github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/tracing/util.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package tracing 15 16 import ( 17 "context" 18 19 "github.com/opentracing/basictracer-go" 20 "github.com/opentracing/opentracing-go" 21 ) 22 23 // MilevaDBTrace is set as Baggage on traces which are used for milevadb tracing. 24 const MilevaDBTrace = "tr" 25 26 // A CallbackRecorder immediately invokes itself on received trace spans. 27 type CallbackRecorder func(sp basictracer.RawSpan) 28 29 // RecordSpan implements basictracer.SpanRecorder. 30 func (cr CallbackRecorder) RecordSpan(sp basictracer.RawSpan) { 31 cr(sp) 32 } 33 34 // NewRecordedTrace returns a Span which records directly via the specified 35 // callback. 36 func NewRecordedTrace(opName string, callback func(sp basictracer.RawSpan)) opentracing.Span { 37 tr := basictracer.New(CallbackRecorder(callback)) 38 opentracing.SetGlobalTracer(tr) 39 sp := tr.StartSpan(opName) 40 sp.SetBaggageItem(MilevaDBTrace, "1") 41 return sp 42 } 43 44 // noopSpan returns a Span which discards all operations. 45 func noopSpan() opentracing.Span { 46 return (opentracing.NoopTracer{}).StartSpan("DefaultSpan") 47 } 48 49 // SpanFromContext returns the span obtained from the context or, if none is found, a new one started through tracer. 50 func SpanFromContext(ctx context.Context) (sp opentracing.Span) { 51 if sp = opentracing.SpanFromContext(ctx); sp == nil { 52 return noopSpan() 53 } 54 return sp 55 } 56 57 // ChildSpanFromContxt return a non-nil span. If span can be got from ctx, then returned span is 58 // a child of such span. Otherwise, returned span is a noop span. 59 func ChildSpanFromContxt(ctx context.Context, opName string) (opentracing.Span, context.Context) { 60 if sp := opentracing.SpanFromContext(ctx); sp != nil { 61 if _, ok := sp.Tracer().(opentracing.NoopTracer); !ok { 62 child := opentracing.StartSpan(opName, opentracing.ChildOf(sp.Context())) 63 return child, opentracing.ContextWithSpan(ctx, child) 64 } 65 } 66 return noopSpan(), ctx 67 }