tracing.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package tracing
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "os"
  19. "strconv"
  20. "strings"
  21. "github.com/docker/cli/cli/command"
  22. "github.com/moby/buildkit/util/tracing/detect"
  23. _ "github.com/moby/buildkit/util/tracing/detect/delegated" //nolint:blank-imports
  24. _ "github.com/moby/buildkit/util/tracing/env" //nolint:blank-imports
  25. "go.opentelemetry.io/otel"
  26. "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
  27. "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
  28. "go.opentelemetry.io/otel/propagation"
  29. "go.opentelemetry.io/otel/sdk/resource"
  30. sdktrace "go.opentelemetry.io/otel/sdk/trace"
  31. semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
  32. )
  33. func init() {
  34. detect.ServiceName = "compose"
  35. // do not log tracing errors to stdio
  36. otel.SetErrorHandler(skipErrors{})
  37. }
  38. var Tracer = otel.Tracer("compose")
  39. // OTLPConfig contains the necessary values to initialize an OTLP client
  40. // manually.
  41. //
  42. // This supports a minimal set of options based on what is necessary for
  43. // automatic OTEL configuration from Docker context metadata.
  44. type OTLPConfig struct {
  45. Endpoint string
  46. }
  47. // ShutdownFunc flushes and stops an OTEL exporter.
  48. type ShutdownFunc func(ctx context.Context) error
  49. // envMap is a convenience type for OS environment variables.
  50. type envMap map[string]string
  51. func InitTracing(dockerCli command.Cli) (ShutdownFunc, error) {
  52. // set global propagator to tracecontext (the default is no-op).
  53. otel.SetTextMapPropagator(propagation.TraceContext{})
  54. if v, _ := strconv.ParseBool(os.Getenv("COMPOSE_EXPERIMENTAL_OTEL")); !v {
  55. return nil, nil
  56. }
  57. return InitProvider(dockerCli)
  58. }
  59. func InitProvider(dockerCli command.Cli) (ShutdownFunc, error) {
  60. ctx := context.Background()
  61. var errs []error
  62. var exporters []sdktrace.SpanExporter
  63. envClient, otelEnv := traceClientFromEnv()
  64. if envClient != nil {
  65. if envExporter, err := otlptrace.New(ctx, envClient); err != nil {
  66. errs = append(errs, err)
  67. } else if envExporter != nil {
  68. exporters = append(exporters, envExporter)
  69. }
  70. }
  71. if dcClient, err := traceClientFromDockerContext(dockerCli, otelEnv); err != nil {
  72. errs = append(errs, err)
  73. } else if dcClient != nil {
  74. if dcExporter, err := otlptrace.New(ctx, dcClient); err != nil {
  75. errs = append(errs, err)
  76. } else if dcExporter != nil {
  77. exporters = append(exporters, dcExporter)
  78. }
  79. }
  80. if len(errs) != 0 {
  81. return nil, errors.Join(errs...)
  82. }
  83. res, err := resource.New(
  84. ctx,
  85. resource.WithAttributes(
  86. semconv.ServiceName("compose"),
  87. ),
  88. )
  89. if err != nil {
  90. return nil, fmt.Errorf("failed to create resource: %v", err)
  91. }
  92. muxExporter := MuxExporter{exporters: exporters}
  93. sp := sdktrace.NewSimpleSpanProcessor(muxExporter)
  94. tracerProvider := sdktrace.NewTracerProvider(
  95. sdktrace.WithSampler(sdktrace.AlwaysSample()),
  96. sdktrace.WithResource(res),
  97. sdktrace.WithSpanProcessor(sp),
  98. )
  99. otel.SetTracerProvider(tracerProvider)
  100. // Shutdown will flush any remaining spans and shut down the exporter.
  101. return tracerProvider.Shutdown, nil
  102. }
  103. // traceClientFromEnv creates a GRPC OTLP client based on OS environment
  104. // variables.
  105. //
  106. // https://opentelemetry.io/docs/concepts/sdk-configuration/otlp-exporter-configuration/
  107. func traceClientFromEnv() (otlptrace.Client, envMap) {
  108. hasOtelEndpointInEnv := false
  109. otelEnv := make(map[string]string)
  110. for _, kv := range os.Environ() {
  111. k, v, ok := strings.Cut(kv, "=")
  112. if !ok {
  113. continue
  114. }
  115. if strings.HasPrefix(k, "OTEL_") {
  116. otelEnv[k] = v
  117. if strings.HasSuffix(k, "ENDPOINT") {
  118. hasOtelEndpointInEnv = true
  119. }
  120. }
  121. }
  122. if !hasOtelEndpointInEnv {
  123. return nil, nil
  124. }
  125. client := otlptracegrpc.NewClient()
  126. return client, otelEnv
  127. }