tracing.go 4.2 KB

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