github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/pkg/trace/inject/http-client/http_client.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 traceinject 16 17 import ( 18 "net/http" 19 _ "unsafe" //nolint 20 21 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" 22 "go.opentelemetry.io/otel/trace" 23 24 injectcontext "github.com/erda-project/erda-infra/pkg/trace/inject/context" 25 "github.com/erda-project/erda-infra/pkg/trace/inject/hook" 26 ) 27 28 // RoundTrip . 29 // 30 //go:linkname RoundTrip net/http.(*Transport).RoundTrip 31 //go:noinline 32 func RoundTrip(t *http.Transport, req *http.Request) (*http.Response, error) 33 34 //go:noinline 35 func originalRoundTrip(t *http.Transport, req *http.Request) (*http.Response, error) { 36 return RoundTrip(t, req) 37 } 38 39 type wrappedTransport struct { 40 t *http.Transport 41 } 42 43 //go:noinline 44 func (t *wrappedTransport) RoundTrip(req *http.Request) (*http.Response, error) { 45 return originalRoundTrip(t.t, req) 46 } 47 48 //go:noinline 49 func tracedRoundTrip(t *http.Transport, req *http.Request) (*http.Response, error) { 50 req = contextWithSpan(req) 51 return otelhttp.NewTransport(&wrappedTransport{t: t}).RoundTrip(req) 52 } 53 54 //go:noinline 55 func contextWithSpan(req *http.Request) *http.Request { 56 ctx := req.Context() 57 if span := trace.SpanFromContext(ctx); !span.SpanContext().IsValid() { 58 pctx := injectcontext.GetContext() 59 if pctx != nil { 60 if span := trace.SpanFromContext(pctx); span.SpanContext().IsValid() { 61 ctx = trace.ContextWithSpan(ctx, span) 62 req = req.WithContext(ctx) 63 } 64 } 65 } 66 return req 67 } 68 69 func init() { 70 hook.Hook(RoundTrip, tracedRoundTrip, originalRoundTrip) 71 }