google.golang.org/grpc@v1.72.2/stats/opentelemetry/server_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  // traceTagRPC populates context with new span data using the TextMapPropagator
    29  // supplied in trace options and internal itracing.Carrier. It creates a new
    30  // incoming carrier which extracts an existing span context (if present) by
    31  // deserializing from provided context. If valid span context is extracted, it
    32  // is set as parent of the new span otherwise new span remains the root span.
    33  // If TextMapPropagator is not provided in the trace options, it returns context
    34  // as is.
    35  func (h *serverStatsHandler) traceTagRPC(ctx context.Context, ai *attemptInfo) (context.Context, *attemptInfo) {
    36  	mn := strings.Replace(ai.method, "/", ".", -1)
    37  	var span trace.Span
    38  	tracer := h.options.TraceOptions.TracerProvider.Tracer(tracerName, trace.WithInstrumentationVersion(grpc.Version))
    39  	ctx = h.options.TraceOptions.TextMapPropagator.Extract(ctx, otelinternaltracing.NewIncomingCarrier(ctx))
    40  	// If the context.Context provided in `ctx` to tracer.Start(), contains a
    41  	// span then the newly-created Span will be a child of that span,
    42  	// otherwise it will be a root span.
    43  	ctx, span = tracer.Start(ctx, mn, trace.WithSpanKind(trace.SpanKindServer))
    44  	ai.traceSpan = span
    45  	return ctx, ai
    46  }