| 1 |
package opencensus |
| 2 |
|
| 3 |
// Copyright 2018 Microsoft Corporation |
| 4 |
// |
| 5 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
// you may not use this file except in compliance with the License. |
| 7 |
// You may obtain a copy of the License at |
| 8 |
// |
| 9 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
// |
| 11 |
// Unless required by applicable law or agreed to in writing, software |
| 12 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
// See the License for the specific language governing permissions and |
| 15 |
// limitations under the License. |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"fmt" |
| 20 |
"net/http" |
| 21 |
"os" |
| 22 |
|
| 23 |
"contrib.go.opencensus.io/exporter/ocagent" |
| 24 |
"github.com/Azure/go-autorest/tracing" |
| 25 |
"go.opencensus.io/plugin/ochttp" |
| 26 |
"go.opencensus.io/plugin/ochttp/propagation/tracecontext" |
| 27 |
"go.opencensus.io/stats/view" |
| 28 |
"go.opencensus.io/trace" |
| 29 |
_ "gopkg.in/yaml.v2" // allows us to explicitly update the version without updating other dependencies |
| 30 |
) |
| 31 |
|
| 32 |
func init() { |
| 33 |
enableFromEnv() |
| 34 |
} |
| 35 |
|
| 36 |
// split out for testing purposes |
| 37 |
func enableFromEnv() { |
| 38 |
if _, ok := os.LookupEnv("AZURE_SDK_TRACING_ENABLED"); ok { |
| 39 |
agentEndpoint, ok := os.LookupEnv("OCAGENT_TRACE_EXPORTER_ENDPOINT") |
| 40 |
if ok { |
| 41 |
EnableWithAIForwarding(agentEndpoint) |
| 42 |
} else { |
| 43 |
Enable() |
| 44 |
} |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
var defaultTracer = newocTracer() |
| 49 |
|
| 50 |
type ocTracer struct { |
| 51 |
// Sampler is the tracing sampler. If tracing is disabled it will never sample. Otherwise |
| 52 |
// it will be using the parent sampler or the default. |
| 53 |
sampler trace.Sampler |
| 54 |
|
| 55 |
// Views for metric instrumentation. |
| 56 |
views map[string]*view.View |
| 57 |
|
| 58 |
// the trace exporter |
| 59 |
traceExporter trace.Exporter |
| 60 |
} |
| 61 |
|
| 62 |
func newocTracer() *ocTracer { |
| 63 |
return &ocTracer{ |
| 64 |
sampler: trace.NeverSample(), |
| 65 |
views: map[string]*view.View{}, |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
// NewTransport returns a new instance of a tracing-aware RoundTripper. |
| 70 |
func (oct ocTracer) NewTransport(base *http.Transport) http.RoundTripper { |
| 71 |
return &ochttp.Transport{ |
| 72 |
Base: base, |
| 73 |
Propagation: &tracecontext.HTTPFormat{}, |
| 74 |
GetStartOptions: func(*http.Request) trace.StartOptions { |
| 75 |
return trace.StartOptions{ |
| 76 |
Sampler: oct.sampler, |
| 77 |
} |
| 78 |
}, |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
// StartSpan starts a trace span |
| 83 |
func (oct ocTracer) StartSpan(ctx context.Context, name string) context.Context { |
| 84 |
ctx, _ = trace.StartSpan(ctx, name, trace.WithSampler(oct.sampler)) |
| 85 |
return ctx |
| 86 |
} |
| 87 |
|
| 88 |
// EndSpan ends a previously started span stored in the context |
| 89 |
func (oct ocTracer) EndSpan(ctx context.Context, httpStatusCode int, err error) { |
| 90 |
span := trace.FromContext(ctx) |
| 91 |
|
| 92 |
if span == nil { |
| 93 |
return |
| 94 |
} |
| 95 |
|
| 96 |
if err != nil { |
| 97 |
span.SetStatus(trace.Status{Message: err.Error(), Code: toTraceStatusCode(httpStatusCode)}) |
| 98 |
} |
| 99 |
span.End() |
| 100 |
} |
| 101 |
|
| 102 |
// Enable will start instrumentation for metrics and traces. |
| 103 |
func Enable() error { |
| 104 |
defaultTracer.sampler = nil |
| 105 |
|
| 106 |
// register the views for HTTP metrics |
| 107 |
clientViews := []*view.View{ |
| 108 |
ochttp.ClientCompletedCount, |
| 109 |
ochttp.ClientRoundtripLatencyDistribution, |
| 110 |
ochttp.ClientReceivedBytesDistribution, |
| 111 |
ochttp.ClientSentBytesDistribution, |
| 112 |
} |
| 113 |
for _, cv := range clientViews { |
| 114 |
vn := fmt.Sprintf("Azure/go-autorest/tracing/opencensus-%s", cv.Name) |
| 115 |
defaultTracer.views[vn] = cv.WithName(vn) |
| 116 |
err := view.Register(defaultTracer.views[vn]) |
| 117 |
if err != nil { |
| 118 |
return err |
| 119 |
} |
| 120 |
} |
| 121 |
tracing.Register(defaultTracer) |
| 122 |
return nil |
| 123 |
} |
| 124 |
|
| 125 |
// Disable will disable instrumentation for metrics and traces. |
| 126 |
func Disable() { |
| 127 |
// unregister any previously registered metrics |
| 128 |
for _, v := range defaultTracer.views { |
| 129 |
view.Unregister(v) |
| 130 |
} |
| 131 |
defaultTracer.sampler = trace.NeverSample() |
| 132 |
if defaultTracer.traceExporter != nil { |
| 133 |
trace.UnregisterExporter(defaultTracer.traceExporter) |
| 134 |
} |
| 135 |
tracing.Register(nil) |
| 136 |
} |
| 137 |
|
| 138 |
// EnableWithAIForwarding will start instrumentation and will connect to app insights forwarder |
| 139 |
// exporter making the metrics and traces available in app insights. |
| 140 |
func EnableWithAIForwarding(agentEndpoint string) error { |
| 141 |
err := Enable() |
| 142 |
if err != nil { |
| 143 |
return err |
| 144 |
} |
| 145 |
|
| 146 |
defaultTracer.traceExporter, err = ocagent.NewExporter(ocagent.WithInsecure(), ocagent.WithAddress(agentEndpoint)) |
| 147 |
if err != nil { |
| 148 |
return err |
| 149 |
} |
| 150 |
trace.RegisterExporter(defaultTracer.traceExporter) |
| 151 |
return nil |
| 152 |
} |
| 153 |
|
| 154 |
// toTraceStatusCode converts HTTP Codes to OpenCensus codes as defined |
| 155 |
// at https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/HTTP.md#status |
| 156 |
func toTraceStatusCode(httpStatusCode int) int32 { |
| 157 |
switch { |
| 158 |
case http.StatusOK <= httpStatusCode && httpStatusCode < http.StatusBadRequest: |
| 159 |
return trace.StatusCodeOK |
| 160 |
case httpStatusCode == http.StatusBadRequest: |
| 161 |
return trace.StatusCodeInvalidArgument |
| 162 |
case httpStatusCode == http.StatusUnauthorized: // 401 is actually unauthenticated. |
| 163 |
return trace.StatusCodeUnauthenticated |
| 164 |
case httpStatusCode == http.StatusForbidden: |
| 165 |
return trace.StatusCodePermissionDenied |
| 166 |
case httpStatusCode == http.StatusNotFound: |
| 167 |
return trace.StatusCodeNotFound |
| 168 |
case httpStatusCode == http.StatusTooManyRequests: |
| 169 |
return trace.StatusCodeResourceExhausted |
| 170 |
case httpStatusCode == 499: |
| 171 |
return trace.StatusCodeCancelled |
| 172 |
case httpStatusCode == http.StatusNotImplemented: |
| 173 |
return trace.StatusCodeUnimplemented |
| 174 |
case httpStatusCode == http.StatusServiceUnavailable: |
| 175 |
return trace.StatusCodeUnavailable |
| 176 |
case httpStatusCode == http.StatusGatewayTimeout: |
| 177 |
return trace.StatusCodeDeadlineExceeded |
| 178 |
default: |
| 179 |
return trace.StatusCodeUnknown |
| 180 |
} |
| 181 |
} |