|
| 1 | +// Copyright 2019, OpenCensus Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package tracesamplerprocessor |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "errors" |
| 20 | + "fmt" |
| 21 | + |
| 22 | + tracepb "github.com/census-instrumentation/opencensus-proto/gen-go/trace/v1" |
| 23 | + "github.com/spf13/viper" |
| 24 | + |
| 25 | + "github.com/open-telemetry/opentelemetry-service/consumer" |
| 26 | + "github.com/open-telemetry/opentelemetry-service/data" |
| 27 | + "github.com/open-telemetry/opentelemetry-service/processor" |
| 28 | +) |
| 29 | + |
| 30 | +const ( |
| 31 | + // The constants below are tags used to read the configuration via viper. |
| 32 | + samplingPercentageCfgTag = "sampling-percentage" |
| 33 | + hashSeedCfgTag = "hash-seed" |
| 34 | + |
| 35 | + // The constants help translate user friendly percentages to numbers direct used in sampling. |
| 36 | + numHashBuckets = 0x4000 // Using a power of 2 to avoid division. |
| 37 | + bitMaskHashBuckets = numHashBuckets - 1 |
| 38 | + percentageScaleFactor = numHashBuckets / 100.0 |
| 39 | +) |
| 40 | + |
| 41 | +// TraceSamplerCfg has the configuration guiding the trace sampler processor. |
| 42 | +type TraceSamplerCfg struct { |
| 43 | + // SamplingPercentage is the percentage rate at which traces are going to be sampled. Defaults to zero, i.e.: no sample. |
| 44 | + // Values greater or equal 100 are treated as "sample all traces". |
| 45 | + SamplingPercentage float32 |
| 46 | + // HashSeed allows one to configure the hashing seed. This is important in scenarios where multiple layers of collectors |
| 47 | + // have different sampling rates: if they use the same seed all passing one layer may pass the other even if they have |
| 48 | + // different sampling rates, configuring different seeds avoids that. |
| 49 | + HashSeed uint32 |
| 50 | +} |
| 51 | + |
| 52 | +// InitFromViper updates TraceSamplerCfg according to the viper configuration. |
| 53 | +func (tsc *TraceSamplerCfg) InitFromViper(v *viper.Viper) (*TraceSamplerCfg, error) { |
| 54 | + if v == nil { |
| 55 | + return nil, errors.New("v is nil") |
| 56 | + } |
| 57 | + if err := v.UnmarshalKey(samplingPercentageCfgTag, &tsc.SamplingPercentage); err != nil { |
| 58 | + return nil, fmt.Errorf("failed to unmarshal %q: %v", samplingPercentageCfgTag, err) |
| 59 | + } |
| 60 | + if err := v.UnmarshalKey(hashSeedCfgTag, &tsc.HashSeed); err != nil { |
| 61 | + return nil, fmt.Errorf("failed to unmarshal %q: %v", hashSeedCfgTag, err) |
| 62 | + } |
| 63 | + return tsc, nil |
| 64 | +} |
| 65 | + |
| 66 | +type tracesamplerprocessor struct { |
| 67 | + nextConsumer consumer.TraceConsumer |
| 68 | + scaledSamplingRate uint32 |
| 69 | + hashSeed uint32 |
| 70 | +} |
| 71 | + |
| 72 | +var _ processor.TraceProcessor = (*tracesamplerprocessor)(nil) |
| 73 | + |
| 74 | +// NewTraceProcessor returns a processor.TraceProcessor that will perform head sampling according to the given |
| 75 | +// configuration. |
| 76 | +func NewTraceProcessor(nextConsumer consumer.TraceConsumer, cfg TraceSamplerCfg) (processor.TraceProcessor, error) { |
| 77 | + if nextConsumer == nil { |
| 78 | + return nil, errors.New("nextConsumer is nil") |
| 79 | + } |
| 80 | + |
| 81 | + return &tracesamplerprocessor{ |
| 82 | + nextConsumer: nextConsumer, |
| 83 | + // Adjust sampling percentage on private so recalculations are avoided. |
| 84 | + scaledSamplingRate: uint32(cfg.SamplingPercentage * percentageScaleFactor), |
| 85 | + hashSeed: cfg.HashSeed, |
| 86 | + }, nil |
| 87 | +} |
| 88 | + |
| 89 | +func (tsp *tracesamplerprocessor) ConsumeTraceData(ctx context.Context, td data.TraceData) error { |
| 90 | + scaledSamplingRate := tsp.scaledSamplingRate |
| 91 | + if scaledSamplingRate >= numHashBuckets { |
| 92 | + return tsp.nextConsumer.ConsumeTraceData(ctx, td) |
| 93 | + } |
| 94 | + |
| 95 | + sampledTraceData := data.TraceData{ |
| 96 | + Node: td.Node, |
| 97 | + Resource: td.Resource, |
| 98 | + SourceFormat: td.SourceFormat, |
| 99 | + } |
| 100 | + |
| 101 | + sampledSpans := make([]*tracepb.Span, 0, len(td.Spans)) |
| 102 | + for _, span := range td.Spans { |
| 103 | + // If one assumes random trace ids hashing may seems avoidable, however, traces can be coming from sources |
| 104 | + // with various different criterias to generate trace id and perhaps were already sampled without hashing. |
| 105 | + // Hashing here prevents bias due to such systems. |
| 106 | + if hash(span.TraceId, tsp.hashSeed)&bitMaskHashBuckets < scaledSamplingRate { |
| 107 | + sampledSpans = append(sampledSpans, span) |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + sampledTraceData.Spans = sampledSpans |
| 112 | + |
| 113 | + return tsp.nextConsumer.ConsumeTraceData(ctx, sampledTraceData) |
| 114 | +} |
| 115 | + |
| 116 | +// hash is a murmur3 hash function, see http://en.wikipedia.org/wiki/MurmurHash. |
| 117 | +func hash(key []byte, seed uint32) (hash uint32) { |
| 118 | + const ( |
| 119 | + c1 = 0xcc9e2d51 |
| 120 | + c2 = 0x1b873593 |
| 121 | + c3 = 0x85ebca6b |
| 122 | + c4 = 0xc2b2ae35 |
| 123 | + r1 = 15 |
| 124 | + r2 = 13 |
| 125 | + m = 5 |
| 126 | + n = 0xe6546b64 |
| 127 | + ) |
| 128 | + |
| 129 | + hash = seed |
| 130 | + iByte := 0 |
| 131 | + for ; iByte+4 <= len(key); iByte += 4 { |
| 132 | + k := uint32(key[iByte]) | uint32(key[iByte+1])<<8 | uint32(key[iByte+2])<<16 | uint32(key[iByte+3])<<24 |
| 133 | + k *= c1 |
| 134 | + k = (k << r1) | (k >> (32 - r1)) |
| 135 | + k *= c2 |
| 136 | + hash ^= k |
| 137 | + hash = (hash << r2) | (hash >> (32 - r2)) |
| 138 | + hash = hash*m + n |
| 139 | + } |
| 140 | + |
| 141 | + // TraceId and SpanId have lengths that are multiple of 4 so the code below is never expected to |
| 142 | + // be hit when sampling traces. However, it is preserved here to keep it as a correct murmur3 implementation. |
| 143 | + // This is enforced via tests. |
| 144 | + var remainingBytes uint32 |
| 145 | + switch len(key) - iByte { |
| 146 | + case 3: |
| 147 | + remainingBytes += uint32(key[iByte+2]) << 16 |
| 148 | + fallthrough |
| 149 | + case 2: |
| 150 | + remainingBytes += uint32(key[iByte+1]) << 8 |
| 151 | + fallthrough |
| 152 | + case 1: |
| 153 | + remainingBytes += uint32(key[iByte]) |
| 154 | + remainingBytes *= c1 |
| 155 | + remainingBytes = (remainingBytes << r1) | (remainingBytes >> (32 - r1)) |
| 156 | + remainingBytes = remainingBytes * c2 |
| 157 | + hash ^= remainingBytes |
| 158 | + } |
| 159 | + |
| 160 | + hash ^= uint32(len(key)) |
| 161 | + hash ^= hash >> 16 |
| 162 | + hash *= c3 |
| 163 | + hash ^= hash >> 13 |
| 164 | + hash *= c4 |
| 165 | + hash ^= hash >> 16 |
| 166 | + |
| 167 | + return |
| 168 | +} |
0 commit comments