tracing.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package tracing
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "net/http"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "github.com/rs/zerolog"
  12. otelContrib "go.opentelemetry.io/contrib/propagators/jaeger"
  13. "go.opentelemetry.io/otel"
  14. "go.opentelemetry.io/otel/attribute"
  15. "go.opentelemetry.io/otel/codes"
  16. "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
  17. "go.opentelemetry.io/otel/propagation"
  18. "go.opentelemetry.io/otel/sdk/resource"
  19. tracesdk "go.opentelemetry.io/otel/sdk/trace"
  20. semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
  21. "go.opentelemetry.io/otel/trace"
  22. )
  23. const (
  24. service = "cloudflared"
  25. tracerInstrumentName = "origin"
  26. TracerContextName = "cf-trace-id"
  27. TracerContextNameOverride = "uber-trace-id"
  28. IntCloudflaredTracingHeader = "cf-int-cloudflared-tracing"
  29. MaxErrorDescriptionLen = 100
  30. traceHttpStatusCodeKey = "upstreamStatusCode"
  31. traceID128bitsWidth = 128 / 4
  32. separator = ":"
  33. )
  34. var (
  35. CanonicalCloudflaredTracingHeader = http.CanonicalHeaderKey(IntCloudflaredTracingHeader)
  36. Http2TransportAttribute = trace.WithAttributes(transportAttributeKey.String("http2"))
  37. QuicTransportAttribute = trace.WithAttributes(transportAttributeKey.String("quic"))
  38. HostOSAttribute = semconv.HostTypeKey.String(runtime.GOOS)
  39. HostArchAttribute = semconv.HostArchKey.String(runtime.GOARCH)
  40. otelVersionAttribute attribute.KeyValue
  41. hostnameAttribute attribute.KeyValue
  42. cloudflaredVersionAttribute attribute.KeyValue
  43. serviceAttribute = semconv.ServiceNameKey.String(service)
  44. transportAttributeKey = attribute.Key("transport")
  45. otelVersionAttributeKey = attribute.Key("jaeger.version")
  46. errNoopTracerProvider = errors.New("noop tracer provider records no spans")
  47. )
  48. func init() {
  49. // Register the jaeger propagator globally.
  50. otel.SetTextMapPropagator(otelContrib.Jaeger{})
  51. otelVersionAttribute = otelVersionAttributeKey.String(fmt.Sprintf("go-otel-%s", otel.Version()))
  52. if hostname, err := os.Hostname(); err == nil {
  53. hostnameAttribute = attribute.String("hostname", hostname)
  54. }
  55. }
  56. func Init(version string) {
  57. cloudflaredVersionAttribute = semconv.ProcessRuntimeVersionKey.String(version)
  58. }
  59. type TracedHTTPRequest struct {
  60. *http.Request
  61. *cfdTracer
  62. ConnIndex uint8 // The connection index used to proxy the request
  63. }
  64. // NewTracedHTTPRequest creates a new tracer for the current HTTP request context.
  65. func NewTracedHTTPRequest(req *http.Request, connIndex uint8, log *zerolog.Logger) *TracedHTTPRequest {
  66. ctx, exists := extractTrace(req)
  67. if !exists {
  68. return &TracedHTTPRequest{req, &cfdTracer{trace.NewNoopTracerProvider(), &NoopOtlpClient{}, log}, connIndex}
  69. }
  70. return &TracedHTTPRequest{req.WithContext(ctx), newCfdTracer(ctx, log), connIndex}
  71. }
  72. func (tr *TracedHTTPRequest) ToTracedContext() *TracedContext {
  73. return &TracedContext{tr.Context(), tr.cfdTracer}
  74. }
  75. type TracedContext struct {
  76. context.Context
  77. *cfdTracer
  78. }
  79. // NewTracedContext creates a new tracer for the current context.
  80. func NewTracedContext(ctx context.Context, traceContext string, log *zerolog.Logger) *TracedContext {
  81. ctx, exists := extractTraceFromString(ctx, traceContext)
  82. if !exists {
  83. return &TracedContext{ctx, &cfdTracer{trace.NewNoopTracerProvider(), &NoopOtlpClient{}, log}}
  84. }
  85. return &TracedContext{ctx, newCfdTracer(ctx, log)}
  86. }
  87. type cfdTracer struct {
  88. trace.TracerProvider
  89. exporter InMemoryClient
  90. log *zerolog.Logger
  91. }
  92. // NewCfdTracer creates a new tracer for the current request context.
  93. func newCfdTracer(ctx context.Context, log *zerolog.Logger) *cfdTracer {
  94. mc := new(InMemoryOtlpClient)
  95. exp, err := otlptrace.New(ctx, mc)
  96. if err != nil {
  97. return &cfdTracer{trace.NewNoopTracerProvider(), &NoopOtlpClient{}, log}
  98. }
  99. tp := tracesdk.NewTracerProvider(
  100. // We want to dump to in-memory exporter immediately
  101. tracesdk.WithSyncer(exp),
  102. // Record information about this application in a Resource.
  103. tracesdk.WithResource(resource.NewWithAttributes(
  104. semconv.SchemaURL,
  105. serviceAttribute,
  106. otelVersionAttribute,
  107. hostnameAttribute,
  108. cloudflaredVersionAttribute,
  109. HostOSAttribute,
  110. HostArchAttribute,
  111. )),
  112. )
  113. return &cfdTracer{tp, mc, log}
  114. }
  115. func (cft *cfdTracer) Tracer() trace.Tracer {
  116. return cft.TracerProvider.Tracer(tracerInstrumentName)
  117. }
  118. // GetSpans returns the spans as base64 encoded string of protobuf otlp traces.
  119. func (cft *cfdTracer) GetSpans() (enc string) {
  120. enc, err := cft.exporter.Spans()
  121. switch err {
  122. case nil:
  123. break
  124. case errNoTraces:
  125. cft.log.Trace().Err(err).Msgf("expected traces to be available")
  126. return
  127. case errNoopTracer:
  128. return // noop tracer has no traces
  129. default:
  130. cft.log.Debug().Err(err)
  131. return
  132. }
  133. return
  134. }
  135. // GetProtoSpans returns the spans as the otlp traces in protobuf byte array.
  136. func (cft *cfdTracer) GetProtoSpans() (proto []byte) {
  137. proto, err := cft.exporter.ExportProtoSpans()
  138. switch err {
  139. case nil:
  140. break
  141. case errNoTraces:
  142. cft.log.Trace().Err(err).Msgf("expected traces to be available")
  143. return
  144. case errNoopTracer:
  145. return // noop tracer has no traces
  146. default:
  147. cft.log.Debug().Err(err)
  148. return
  149. }
  150. return
  151. }
  152. // AddSpans assigns spans as base64 encoded protobuf otlp traces to provided
  153. // HTTP headers.
  154. func (cft *cfdTracer) AddSpans(headers http.Header) {
  155. if headers == nil {
  156. return
  157. }
  158. enc := cft.GetSpans()
  159. // No need to add header if no traces
  160. if enc == "" {
  161. return
  162. }
  163. headers[CanonicalCloudflaredTracingHeader] = []string{enc}
  164. }
  165. // End will set the OK status for the span and then end it.
  166. func End(span trace.Span) {
  167. endSpan(span, -1, codes.Ok, nil)
  168. }
  169. // EndWithErrorStatus will set a status for the span and then end it.
  170. func EndWithErrorStatus(span trace.Span, err error) {
  171. endSpan(span, -1, codes.Error, err)
  172. }
  173. // EndWithStatusCode will set a status for the span and then end it.
  174. func EndWithStatusCode(span trace.Span, statusCode int) {
  175. endSpan(span, statusCode, codes.Ok, nil)
  176. }
  177. // EndWithErrorStatus will set a status for the span and then end it.
  178. func endSpan(span trace.Span, upstreamStatusCode int, spanStatusCode codes.Code, err error) {
  179. if span == nil {
  180. return
  181. }
  182. if upstreamStatusCode > 0 {
  183. span.SetAttributes(attribute.Int(traceHttpStatusCodeKey, upstreamStatusCode))
  184. }
  185. // add error to status buf cap description
  186. errDescription := ""
  187. if err != nil {
  188. errDescription = err.Error()
  189. l := int(math.Min(float64(len(errDescription)), MaxErrorDescriptionLen))
  190. errDescription = errDescription[:l]
  191. }
  192. span.SetStatus(spanStatusCode, errDescription)
  193. span.End()
  194. }
  195. // extractTraceFromString will extract the trace information from the provided
  196. // propagated trace string context.
  197. func extractTraceFromString(ctx context.Context, trace string) (context.Context, bool) {
  198. if trace == "" {
  199. return ctx, false
  200. }
  201. // Jaeger specific separator
  202. parts := strings.Split(trace, separator)
  203. if len(parts) != 4 {
  204. return ctx, false
  205. }
  206. if parts[0] == "" {
  207. return ctx, false
  208. }
  209. // Correctly left pad the trace to a length of 32
  210. if len(parts[0]) < traceID128bitsWidth {
  211. left := traceID128bitsWidth - len(parts[0])
  212. parts[0] = strings.Repeat("0", left) + parts[0]
  213. trace = strings.Join(parts, separator)
  214. }
  215. // Override the 'cf-trace-id' as 'uber-trace-id' so the jaeger propagator can extract it.
  216. traceHeader := map[string]string{TracerContextNameOverride: trace}
  217. remoteCtx := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(traceHeader))
  218. return remoteCtx, true
  219. }
  220. // extractTrace attempts to check for a cf-trace-id from a request and return the
  221. // trace context with the provided http.Request.
  222. func extractTrace(req *http.Request) (context.Context, bool) {
  223. // Only add tracing for requests with appropriately tagged headers
  224. remoteTraces := req.Header.Values(TracerContextName)
  225. if len(remoteTraces) <= 0 {
  226. // Strip the cf-trace-id header
  227. req.Header.Del(TracerContextName)
  228. return nil, false
  229. }
  230. traceHeader := map[string]string{}
  231. for _, t := range remoteTraces {
  232. // Override the 'cf-trace-id' as 'uber-trace-id' so the jaeger propagator can extract it.
  233. // Last entry wins if multiple provided
  234. traceHeader[TracerContextNameOverride] = t
  235. }
  236. // Strip the cf-trace-id header
  237. req.Header.Del(TracerContextName)
  238. if traceHeader[TracerContextNameOverride] == "" {
  239. return nil, false
  240. }
  241. remoteCtx := otel.GetTextMapPropagator().Extract(req.Context(), propagation.MapCarrier(traceHeader))
  242. return remoteCtx, true
  243. }
  244. func NewNoopSpan() trace.Span {
  245. return trace.SpanFromContext(nil)
  246. }