github.com/erda-project/erda-infra@v1.0.9/pkg/trace/trace.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     2  //
     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  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package trace
    16  
    17  import (
    18  	"context"
    19  
    20  	"go.opentelemetry.io/otel/trace"
    21  
    22  	injectcontext "github.com/erda-project/erda-infra/pkg/trace/inject/context"
    23  )
    24  
    25  // Go .
    26  func Go(ctx context.Context, fn func()) {
    27  	GoWithContext(ctx, func(ctx context.Context) {
    28  		fn()
    29  	})
    30  }
    31  
    32  // GoWithContext .
    33  func GoWithContext(ctx context.Context, fn func(ctx context.Context)) {
    34  	if ctx == nil {
    35  		ctx = context.Background()
    36  	}
    37  	if span := trace.SpanFromContext(ctx); !span.SpanContext().IsValid() {
    38  		pctx := injectcontext.GetContext()
    39  		if pctx != nil {
    40  			if span := trace.SpanFromContext(pctx); span.SpanContext().IsValid() {
    41  				ctx = trace.ContextWithSpan(ctx, span)
    42  			}
    43  		}
    44  	}
    45  	go injectcontext.RunWithContext(ctx, fn)
    46  }
    47  
    48  // ContextWithSpan .
    49  func ContextWithSpan(ctx context.Context) context.Context {
    50  	if ctx == nil {
    51  		ctx = context.Background()
    52  	}
    53  	if span := trace.SpanFromContext(ctx); !span.SpanContext().IsValid() {
    54  		pctx := injectcontext.GetContext()
    55  		if pctx != nil {
    56  			if span := trace.SpanFromContext(pctx); span.SpanContext().IsValid() {
    57  				ctx = trace.ContextWithSpan(ctx, span)
    58  			}
    59  		}
    60  	}
    61  	return ctx
    62  }
    63  
    64  // RunWithTrace .
    65  func RunWithTrace(ctx context.Context, fn func(ctx context.Context)) {
    66  	injectcontext.RunWithContext(ctx, fn)
    67  }