tracing.go 4.3 KB

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