github.com/erda-project/erda-infra@v1.0.9/pkg/trace/inject/http-server/http_server.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  	"context"
    19  	"net/http"
    20  	_ "unsafe" //nolint
    21  
    22  	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
    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  type serverHandler struct {
    29  	srv *http.Server
    30  }
    31  
    32  //go:linkname serveHTTP net/http.serverHandler.ServeHTTP
    33  //go:noinline
    34  func serveHTTP(s *serverHandler, rw http.ResponseWriter, req *http.Request)
    35  
    36  //go:noinline
    37  func originalServeHTTP(s *serverHandler, rw http.ResponseWriter, req *http.Request) {}
    38  
    39  var tracedServerHandler = otelhttp.NewHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
    40  	injectcontext.SetContext(r.Context())
    41  	defer injectcontext.ClearContext()
    42  	s := getServerHandler(r.Context())
    43  	originalServeHTTP(s, rw, r)
    44  }), "", otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
    45  	u := *r.URL
    46  	u.RawQuery = ""
    47  	u.ForceQuery = false
    48  	return r.Method + " " + u.String()
    49  }))
    50  
    51  type _serverHandlerKey int8
    52  
    53  const serverHandlerKey _serverHandlerKey = 0
    54  
    55  func withServerHandler(ctx context.Context, s *serverHandler) context.Context {
    56  	return context.WithValue(ctx, serverHandlerKey, s)
    57  }
    58  
    59  func getServerHandler(ctx context.Context) *serverHandler {
    60  	return ctx.Value(serverHandlerKey).(*serverHandler)
    61  }
    62  
    63  //go:noinline
    64  func wrappedHTTPHandler(s *serverHandler, rw http.ResponseWriter, req *http.Request) {
    65  	req = req.WithContext(withServerHandler(req.Context(), s))
    66  	tracedServerHandler.ServeHTTP(rw, req)
    67  }
    68  
    69  func init() {
    70  	hook.Hook(serveHTTP, wrappedHTTPHandler, originalServeHTTP)
    71  }