|
| 1 | +/* |
| 2 | + Copyright The containerd Authors. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package tracing |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "time" |
| 22 | + |
| 23 | + "github.com/containerd/containerd/v2/pkg/shutdown" |
| 24 | + cplugins "github.com/containerd/containerd/v2/plugins" |
| 25 | + "github.com/containerd/log" |
| 26 | + "github.com/containerd/otelttrpc" |
| 27 | + "github.com/containerd/plugin" |
| 28 | + "github.com/containerd/plugin/registry" |
| 29 | + "github.com/containerd/ttrpc" |
| 30 | + "go.opentelemetry.io/otel" |
| 31 | + "go.opentelemetry.io/otel/propagation" |
| 32 | + sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 33 | + |
| 34 | + "github.com/containerd/nerdbox/internal/tracing" |
| 35 | + "github.com/containerd/nerdbox/plugins" |
| 36 | +) |
| 37 | + |
| 38 | +func init() { |
| 39 | + registry.Register(&plugin.Registration{ |
| 40 | + Type: plugins.TTRPCPlugin, |
| 41 | + ID: "tracing", |
| 42 | + Requires: []plugin.Type{ |
| 43 | + cplugins.InternalPlugin, |
| 44 | + }, |
| 45 | + InitFn: func(ic *plugin.InitContext) (interface{}, error) { |
| 46 | + ctx := ic.Context |
| 47 | + |
| 48 | + otel.SetTextMapPropagator(propagation.TraceContext{}) |
| 49 | + |
| 50 | + exp := tracing.NewRelayExporter(ctx) |
| 51 | + if exp == nil { |
| 52 | + log.G(ctx).Debug("OTEL_EXPORTER_OTLP_ENDPOINT not set, shim tracing disabled") |
| 53 | + return &interceptor{}, nil |
| 54 | + } |
| 55 | + |
| 56 | + tp := sdktrace.NewTracerProvider( |
| 57 | + sdktrace.WithBatcher(exp, |
| 58 | + sdktrace.WithBatchTimeout(100*time.Millisecond), |
| 59 | + ), |
| 60 | + ) |
| 61 | + otel.SetTracerProvider(tp) |
| 62 | + |
| 63 | + ss, err := ic.GetByID(cplugins.InternalPlugin, "shutdown") |
| 64 | + if err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + ss.(shutdown.Service).RegisterCallback(func(ctx context.Context) error { |
| 68 | + return tp.Shutdown(ctx) |
| 69 | + }) |
| 70 | + |
| 71 | + return &interceptor{}, nil |
| 72 | + }, |
| 73 | + }) |
| 74 | +} |
| 75 | + |
| 76 | +type interceptor struct{} |
| 77 | + |
| 78 | +func (i *interceptor) UnaryServerInterceptor() ttrpc.UnaryServerInterceptor { |
| 79 | + return otelttrpc.UnaryServerInterceptor() |
| 80 | +} |
0 commit comments