Skip to content

Commit

Permalink
[distributed tracing] handling is-sampled header
Browse files Browse the repository at this point in the history
  • Loading branch information
ufoot committed Sep 27, 2017
1 parent 9234800 commit 7b1f4bd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
22 changes: 20 additions & 2 deletions tracer/contrib/tracegrpc/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,10 @@ func serverSpan(t *tracer.Tracer, ctx context.Context, method, service string) *
span.SetMeta("gprc.method", method)
span.Type = "go"

traceID, parentID := getIDs(ctx)
traceID, parentID, isSampled := getIDs(ctx)
if traceID != 0 && parentID != 0 {
span.TraceID = traceID
t.Sample(span) // depends on trace ID so needs to be updated to maximize the chances we get complete traces
span.ParentID = parentID
}

Expand All @@ -94,14 +95,17 @@ func setIDs(span *tracer.Span, ctx context.Context) context.Context {
}

// getIDs will return ids embededd an ahe context.
func getIDs(ctx context.Context) (traceID, parentID uint64) {
func getIDs(ctx context.Context) (traceID, parentID uint64, isSampled bool) {
if md, ok := metadata.FromContext(ctx); ok {
if id := getID(md, traceIDKey); id > 0 {
traceID = id
}
if id := getID(md, parentIDKey); id > 0 {
parentID = id
}
if b, found := getBool(md, isSampledKey); found {
parentID = id
}
}
return traceID, parentID
}
Expand All @@ -116,3 +120,17 @@ func getID(md metadata.MD, name string) uint64 {
}
return 0
}

// getBool gets a bool from the metadata (0 or 1 converted to bool).
func getBool(md metadata.MD, name string) (bool, bool) {
for _, str := range md[name] {
if str == "0" {
return false, true
}
n, err := strconv.Atoi(str)
if err == nil && n > 0 {
return true, true
}
}
return true, false
}
9 changes: 7 additions & 2 deletions tracer/tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (t *Tracer) NewRootSpan(name, service, resource string) *Span {
span := NewSpan(name, service, resource, spanID, spanID, 0, t)

span.buffer = newSpanBuffer(t.channels, 0, 0)
t.sampler.Sample(span)
t.Sample(span)
span.buffer.Push(span)

// Add the process id to all root spans
Expand All @@ -198,7 +198,7 @@ func (t *Tracer) NewChildSpan(name string, parent *Span) *Span {
span := NewSpan(name, "", name, spanID, spanID, spanID, t)

span.buffer = newSpanBuffer(t.channels, 0, 0)
t.sampler.Sample(span)
t.Sample(span)
span.buffer.Push(span)

return span
Expand Down Expand Up @@ -339,6 +339,11 @@ func (t *Tracer) ForceFlush() {
<-t.forceFlushOut
}

// Sample samples a span with the internal sampler.
func (t *Tracer) Sample(span *Span) {
t.sampler.Sample(span)
}

// worker periodically flushes traces and services to the transport.
func (t *Tracer) worker() {
defer t.exitWG.Done()
Expand Down

0 comments on commit 7b1f4bd

Please sign in to comment.