google.golang.org/grpc@v1.72.2/stats/opentelemetry/client_tracing.go (about)

     1  /*
     2   * Copyright 2024 gRPC 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 opentelemetry
    18  
    19  import (
    20  	"context"
    21  	"strings"
    22  
    23  	"go.opentelemetry.io/otel/trace"
    24  	"google.golang.org/grpc"
    25  	otelinternaltracing "google.golang.org/grpc/stats/opentelemetry/internal/tracing"
    26  )
    27  
    28  const tracerName = "grpc-go"
    29  
    30  // traceTagRPC populates provided context with a new span using the
    31  // TextMapPropagator supplied in trace options and internal itracing.carrier.
    32  // It creates a new outgoing carrier which serializes information about this
    33  // span into gRPC Metadata, if TextMapPropagator is provided in the trace
    34  // options. if TextMapPropagator is not provided, it returns the context as is.
    35  func (h *clientStatsHandler) traceTagRPC(ctx context.Context, ai *attemptInfo) (context.Context, *attemptInfo) {
    36  	mn := "Attempt." + strings.Replace(ai.method, "/", ".", -1)
    37  	tracer := h.options.TraceOptions.TracerProvider.Tracer(tracerName, trace.WithInstrumentationVersion(grpc.Version))
    38  	ctx, span := tracer.Start(ctx, mn)
    39  	carrier := otelinternaltracing.NewOutgoingCarrier(ctx)
    40  	h.options.TraceOptions.TextMapPropagator.Inject(ctx, carrier)
    41  	ai.traceSpan = span
    42  	return carrier.Context(), ai
    43  }
    44  
    45  // createCallTraceSpan creates a call span to put in the provided context using
    46  // provided TraceProvider. If TraceProvider is nil, it returns context as is.
    47  func (h *clientStatsHandler) createCallTraceSpan(ctx context.Context, method string) (context.Context, trace.Span) {
    48  	if h.options.TraceOptions.TracerProvider == nil {
    49  		logger.Error("TraceProvider is not provided in trace options")
    50  		return ctx, nil
    51  	}
    52  	mn := strings.Replace(removeLeadingSlash(method), "/", ".", -1)
    53  	tracer := h.options.TraceOptions.TracerProvider.Tracer(tracerName, trace.WithInstrumentationVersion(grpc.Version))
    54  	ctx, span := tracer.Start(ctx, mn, trace.WithSpanKind(trace.SpanKindClient))
    55  	return ctx, span
    56  }