pax_global_header00006660000000000000000000000064131126520040014504gustar00rootroot0000000000000052 comment=48e4d763b2fbcd10e666e6a1742acdf8cc2286ef golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/000077500000000000000000000000001311265200400244605ustar00rootroot00000000000000golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/LICENSE000066400000000000000000000027161311265200400254730ustar00rootroot00000000000000Copyright (c) 2016, opentracing-contrib All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of go-stdlib nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/README.md000066400000000000000000000010431311265200400257350ustar00rootroot00000000000000# go-stdlib This repository contains OpenTracing instrumentation for packages in the Go standard library. For documentation on the packages, [check godoc](https://godoc.org/github.com/opentracing-contrib/go-stdlib/). **The APIs in the various packages are experimental and may change in the future. You should vendor them to avoid spurious breakage.** ## Packages Instrumentation is provided for the following packages, with the following caveats: - **net/http**: Client and server instrumentation. *Only supported with Go 1.7 and later.* golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/nethttp/000077500000000000000000000000001311265200400261465ustar00rootroot00000000000000golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/nethttp/client.go000066400000000000000000000164001311265200400277540ustar00rootroot00000000000000// +build go1.7 package nethttp import ( "context" "io" "net/http" "net/http/httptrace" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" "github.com/opentracing/opentracing-go/log" ) type contextKey int const ( keyTracer contextKey = iota ) const defaultComponentName = "net/http" // Transport wraps a RoundTripper. If a request is being traced with // Tracer, Transport will inject the current span into the headers, // and set HTTP related tags on the span. type Transport struct { // The actual RoundTripper to use for the request. A nil // RoundTripper defaults to http.DefaultTransport. http.RoundTripper } type clientOptions struct { operationName string componentName string disableClientTrace bool } // ClientOption contols the behavior of TraceRequest. type ClientOption func(*clientOptions) // OperationName returns a ClientOption that sets the operation // name for the client-side span. func OperationName(operationName string) ClientOption { return func(options *clientOptions) { options.operationName = operationName } } // ComponentName returns a ClientOption that sets the component // name for the client-side span. func ComponentName(componentName string) ClientOption { return func(options *clientOptions) { options.componentName = componentName } } // ClientTrace returns a ClientOption that turns on or off // extra instrumentation via httptrace.WithClientTrace. func ClientTrace(enabled bool) ClientOption { return func(options *clientOptions) { options.disableClientTrace = !enabled } } // TraceRequest adds a ClientTracer to req, tracing the request and // all requests caused due to redirects. When tracing requests this // way you must also use Transport. // // Example: // // func AskGoogle(ctx context.Context) error { // client := &http.Client{Transport: &nethttp.Transport{}} // req, err := http.NewRequest("GET", "http://google.com", nil) // if err != nil { // return err // } // req = req.WithContext(ctx) // extend existing trace, if any // // req, ht := nethttp.TraceRequest(tracer, req) // defer ht.Finish() // // res, err := client.Do(req) // if err != nil { // return err // } // res.Body.Close() // return nil // } func TraceRequest(tr opentracing.Tracer, req *http.Request, options ...ClientOption) (*http.Request, *Tracer) { opts := &clientOptions{} for _, opt := range options { opt(opts) } ht := &Tracer{tr: tr, opts: opts} ctx := req.Context() if !opts.disableClientTrace { ctx = httptrace.WithClientTrace(ctx, ht.clientTrace()) } req = req.WithContext(context.WithValue(ctx, keyTracer, ht)) return req, ht } type closeTracker struct { io.ReadCloser sp opentracing.Span } func (c closeTracker) Close() error { err := c.ReadCloser.Close() c.sp.LogFields(log.String("event", "ClosedBody")) c.sp.Finish() return err } // RoundTrip implements the RoundTripper interface. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { rt := t.RoundTripper if rt == nil { rt = http.DefaultTransport } tracer, ok := req.Context().Value(keyTracer).(*Tracer) if !ok { return rt.RoundTrip(req) } tracer.start(req) ext.HTTPMethod.Set(tracer.sp, req.Method) ext.HTTPUrl.Set(tracer.sp, req.URL.String()) carrier := opentracing.HTTPHeadersCarrier(req.Header) tracer.sp.Tracer().Inject(tracer.sp.Context(), opentracing.HTTPHeaders, carrier) resp, err := rt.RoundTrip(req) if err != nil { tracer.sp.Finish() return resp, err } ext.HTTPStatusCode.Set(tracer.sp, uint16(resp.StatusCode)) if req.Method == "HEAD" { tracer.sp.Finish() } else { resp.Body = closeTracker{resp.Body, tracer.sp} } return resp, nil } // Tracer holds tracing details for one HTTP request. type Tracer struct { tr opentracing.Tracer root opentracing.Span sp opentracing.Span opts *clientOptions } func (h *Tracer) start(req *http.Request) opentracing.Span { if h.root == nil { parent := opentracing.SpanFromContext(req.Context()) var spanctx opentracing.SpanContext if parent != nil { spanctx = parent.Context() } operationName := h.opts.operationName if operationName == "" { operationName = "HTTP Client" } root := h.tr.StartSpan(operationName, opentracing.ChildOf(spanctx)) h.root = root } ctx := h.root.Context() h.sp = h.tr.StartSpan("HTTP "+req.Method, opentracing.ChildOf(ctx)) ext.SpanKindRPCClient.Set(h.sp) componentName := h.opts.componentName if componentName == "" { componentName = defaultComponentName } ext.Component.Set(h.sp, componentName) return h.sp } // Finish finishes the span of the traced request. func (h *Tracer) Finish() { if h.root != nil { h.root.Finish() } } // Span returns the root span of the traced request. This function // should only be called after the request has been executed. func (h *Tracer) Span() opentracing.Span { return h.root } func (h *Tracer) clientTrace() *httptrace.ClientTrace { return &httptrace.ClientTrace{ GetConn: h.getConn, GotConn: h.gotConn, PutIdleConn: h.putIdleConn, GotFirstResponseByte: h.gotFirstResponseByte, Got100Continue: h.got100Continue, DNSStart: h.dnsStart, DNSDone: h.dnsDone, ConnectStart: h.connectStart, ConnectDone: h.connectDone, WroteHeaders: h.wroteHeaders, Wait100Continue: h.wait100Continue, WroteRequest: h.wroteRequest, } } func (h *Tracer) getConn(hostPort string) { ext.HTTPUrl.Set(h.sp, hostPort) h.sp.LogFields(log.String("event", "GetConn")) } func (h *Tracer) gotConn(info httptrace.GotConnInfo) { h.sp.SetTag("net/http.reused", info.Reused) h.sp.SetTag("net/http.was_idle", info.WasIdle) h.sp.LogFields(log.String("event", "GotConn")) } func (h *Tracer) putIdleConn(error) { h.sp.LogFields(log.String("event", "PutIdleConn")) } func (h *Tracer) gotFirstResponseByte() { h.sp.LogFields(log.String("event", "GotFirstResponseByte")) } func (h *Tracer) got100Continue() { h.sp.LogFields(log.String("event", "Got100Continue")) } func (h *Tracer) dnsStart(info httptrace.DNSStartInfo) { h.sp.LogFields( log.String("event", "DNSStart"), log.String("host", info.Host), ) } func (h *Tracer) dnsDone(httptrace.DNSDoneInfo) { h.sp.LogFields(log.String("event", "DNSDone")) } func (h *Tracer) connectStart(network, addr string) { h.sp.LogFields( log.String("event", "ConnectStart"), log.String("network", network), log.String("addr", addr), ) } func (h *Tracer) connectDone(network, addr string, err error) { if err != nil { h.sp.LogFields( log.String("message", "ConnectDone"), log.String("network", network), log.String("addr", addr), log.String("event", "error"), log.Error(err), ) } else { h.sp.LogFields( log.String("event", "ConnectDone"), log.String("network", network), log.String("addr", addr), ) } } func (h *Tracer) wroteHeaders() { h.sp.LogFields(log.String("event", "WroteHeaders")) } func (h *Tracer) wait100Continue() { h.sp.LogFields(log.String("event", "Wait100Continue")) } func (h *Tracer) wroteRequest(info httptrace.WroteRequestInfo) { if info.Err != nil { h.sp.LogFields( log.String("message", "WroteRequest"), log.String("event", "error"), log.Error(info.Err), ) ext.Error.Set(h.sp, true) } else { h.sp.LogFields(log.String("event", "WroteRequest")) } } golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/nethttp/client_test.go000066400000000000000000000052071311265200400310160ustar00rootroot00000000000000package nethttp import ( "net/http" "net/http/httptest" "testing" opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/mocktracer" ) func makeRequest(t *testing.T, url string, options ...ClientOption) []*mocktracer.MockSpan { tr := &mocktracer.MockTracer{} span := tr.StartSpan("toplevel") client := &http.Client{Transport: &Transport{}} req, err := http.NewRequest("GET", url, nil) if err != nil { t.Fatal(err) } req = req.WithContext(opentracing.ContextWithSpan(req.Context(), span)) req, ht := TraceRequest(tr, req, options...) resp, err := client.Do(req) if err != nil { t.Fatal(err) } _ = resp.Body.Close() ht.Finish() span.Finish() return tr.FinishedSpans() } func TestClientTrace(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {}) mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/ok", http.StatusTemporaryRedirect) }) mux.HandleFunc("/fail", func(w http.ResponseWriter, r *http.Request) { http.Error(w, "failure", http.StatusInternalServerError) }) srv := httptest.NewServer(mux) defer srv.Close() tests := []struct { url string num int opts []ClientOption opName string }{ {url: "/ok", num: 3, opts: nil, opName: "HTTP Client"}, {url: "/redirect", num: 4, opts: []ClientOption{OperationName("client-span")}, opName: "client-span"}, {url: "/fail", num: 3, opts: nil, opName: "HTTP Client"}, } for _, tt := range tests { t.Log(tt.opName) spans := makeRequest(t, srv.URL+tt.url, tt.opts...) if got, want := len(spans), tt.num; got != want { t.Fatalf("got %d spans, expected %d", got, want) } var rootSpan *mocktracer.MockSpan for _, span := range spans { if span.ParentID == 0 { rootSpan = span break } } if rootSpan == nil { t.Fatal("cannot find root span with ParentID==0") } foundClientSpan := false for _, span := range spans { if span.ParentID == rootSpan.SpanContext.SpanID { foundClientSpan = true if got, want := span.OperationName, tt.opName; got != want { t.Fatalf("got %s operation name, expected %s", got, want) } } if span.OperationName == "HTTP GET" { logs := span.Logs() if len(logs) < 6 { t.Fatalf("got %d expected at least %d log events", len(logs), 6) } key := logs[0].Fields[0].Key if key != "event" { t.Fatalf("got %s expected, %s", key, "event") } v := logs[0].Fields[0].ValueString if v != "GetConn" { t.Fatalf("got %s expected, %s", v, "GetConn") } } } if !foundClientSpan { t.Fatal("cannot find client span") } } } golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/nethttp/doc.go000066400000000000000000000001451311265200400272420ustar00rootroot00000000000000// Package nethttp provides OpenTracing instrumentation for the // net/http package. package nethttp golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/nethttp/server.go000066400000000000000000000051101311265200400300000ustar00rootroot00000000000000// +build go1.7 package nethttp import ( "net/http" opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) type statusCodeTracker struct { http.ResponseWriter status int } func (w *statusCodeTracker) WriteHeader(status int) { w.status = status w.ResponseWriter.WriteHeader(status) } type mwOptions struct { opNameFunc func(r *http.Request) string componentName string } // MWOption controls the behavior of the Middleware. type MWOption func(*mwOptions) // OperationNameFunc returns a MWOption that uses given function f // to generate operation name for each server-side span. func OperationNameFunc(f func(r *http.Request) string) MWOption { return func(options *mwOptions) { options.opNameFunc = f } } // MWComponentName returns a MWOption that sets the component name // name for the server-side span. func MWComponentName(componentName string) MWOption { return func(options *mwOptions) { options.componentName = componentName } } // Middleware wraps an http.Handler and traces incoming requests. // Additionally, it adds the span to the request's context. // // By default, the operation name of the spans is set to "HTTP {method}". // This can be overriden with options. // // Example: // http.ListenAndServe("localhost:80", nethttp.Middleware(tracer, http.DefaultServeMux)) // // The options allow fine tuning the behavior of the middleware. // // Example: // mw := nethttp.Middleware( // tracer, // http.DefaultServeMux, // nethttp.OperationName(func(r *http.Request) string { // return "HTTP " + r.Method + ":/api/customers" // }), // ) func Middleware(tr opentracing.Tracer, h http.Handler, options ...MWOption) http.Handler { opts := mwOptions{ opNameFunc: func(r *http.Request) string { return "HTTP " + r.Method }, } for _, opt := range options { opt(&opts) } fn := func(w http.ResponseWriter, r *http.Request) { ctx, _ := tr.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header)) sp := tr.StartSpan(opts.opNameFunc(r), ext.RPCServerOption(ctx)) ext.HTTPMethod.Set(sp, r.Method) ext.HTTPUrl.Set(sp, r.URL.String()) // set component name, use "net/http" if caller does not specify componentName := opts.componentName if componentName == "" { componentName = defaultComponentName } ext.Component.Set(sp, componentName) w = &statusCodeTracker{w, 200} r = r.WithContext(opentracing.ContextWithSpan(r.Context(), sp)) h.ServeHTTP(w, r) ext.HTTPStatusCode.Set(sp, uint16(w.(*statusCodeTracker).status)) sp.Finish() } return http.HandlerFunc(fn) } golang-github-opentracing-contrib-go-stdlib-0.0~git20170528.48e4d76/nethttp/server_test.go000066400000000000000000000021441311265200400310430ustar00rootroot00000000000000package nethttp import ( "net/http" "net/http/httptest" "testing" "github.com/opentracing/opentracing-go/mocktracer" ) func TestOperationNameOption(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/root", func(w http.ResponseWriter, r *http.Request) {}) fn := func(r *http.Request) string { return "HTTP " + r.Method + ": /root" } tests := []struct { options []MWOption opName string }{ {nil, "HTTP GET"}, {[]MWOption{OperationNameFunc(fn)}, "HTTP GET: /root"}, } for _, tt := range tests { testCase := tt t.Run(testCase.opName, func(t *testing.T) { tr := &mocktracer.MockTracer{} mw := Middleware(tr, mux, testCase.options...) srv := httptest.NewServer(mw) defer srv.Close() _, err := http.Get(srv.URL) if err != nil { t.Fatalf("server returned error: %v", err) } spans := tr.FinishedSpans() if got, want := len(spans), 1; got != want { t.Fatalf("got %d spans, expected %d", got, want) } if got, want := spans[0].OperationName, testCase.opName; got != want { t.Fatalf("got %s operation name, expected %s", got, want) } }) } }