forked from TykTechnologies/tyk
/
manager.go
215 lines (185 loc) · 5.38 KB
/
manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package trace
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"sync"
"sync/atomic"
"github.com/TykTechnologies/tyk/request"
opentracing "github.com/opentracing/opentracing-go"
)
// ErrManagerDisabled is returned when trying to use global trace manager when
// it is disabled.
var ErrManagerDisabled = errors.New("trace: trace is diabled")
// This stores a map of opentracer configurations.
var manager = &sync.Map{}
// This stores a map of service name to initialized Tracer implementation.
var services = &sync.Map{}
// Stores status of tracing.
var enabled atomic.Value
var logger Logger = StdLogger{}
var initializer = Init
// serviceID key used to store the service name in request context.Context.
type serviceID = struct{}
// SetServiceID returns context with service assigned to it.
func SetServiceID(ctx context.Context, service string) context.Context {
return context.WithValue(ctx, serviceID{}, service)
}
// GetServiceID returns service name attched to context returns an empty string
// if the service name key is not found.
func GetServiceID(ctx context.Context) string {
if v := ctx.Value(serviceID{}); v != nil {
return v.(string)
}
return ""
}
// Logger defines api for logging messages by the OpenTracer struct. This is a
// workaround to avoid trying this to logrus
type Logger interface {
Errorf(format string, args ...interface{})
Info(args ...interface{})
Infof(format string, args ...interface{})
}
type StdLogger struct{}
func (StdLogger) Errorf(format string, args ...interface{}) {
log.Println("[ERROR] trace: ", fmt.Sprintf(format, args...))
}
func (StdLogger) Infof(format string, args ...interface{}) {
log.Println("[INFO] trace: ", fmt.Sprintf(format, args...))
}
func (StdLogger) Info(args ...interface{}) {
log.Println("[INFO] trace: ", fmt.Sprint(args...))
}
func (StdLogger) Error(args ...interface{}) {
log.Println("[ERROR] trace: ", fmt.Sprint(args...))
}
type Config struct {
Name string
Opts map[string]interface{}
}
// Get returns a tracer stored on the global trace manager.
func Get(service string) Tracer {
if t, ok := services.Load(service); ok {
return t.(Tracer)
}
return NoopTracer{}
}
// Close calls Close on the global tace manager.
func Close() error {
var s []string
services.Range(func(k, v interface{}) bool {
s = append(s, k.(string))
v.(Tracer).Close()
return true
})
for _, v := range s {
services.Delete(v)
}
Disable()
return nil
}
// IsEnabled returns true if the global trace manager is enabled.
func IsEnabled() bool {
if v := enabled.Load(); v != nil {
return v.(bool)
}
return false
}
// Enable sets the global manager to enabled.
func Enable() {
enabled.Store(true)
}
// Disable disables the global trace manager.
func Disable() {
enabled.Store(false)
}
// AddTracer initialize a tracer for the service.
func AddTracer(tracer, service string) error {
if !IsEnabled() {
return ErrManagerDisabled
}
if _, ok := services.Load(service); !ok {
if v, ok := manager.Load(tracer); ok {
c := v.(Config)
tr, err := initializer(c.Name, service, c.Opts, StdLogger{})
if err != nil {
return err
}
services.Store(service, tr)
}
}
return nil
}
func SetLogger(log Logger) {
logger = log
}
func SetInit(fn InitFunc) {
initializer = fn
}
func SetupTracing(name string, opts map[string]interface{}) {
// We are using empty string as key since we only work with one opentracer at a
// time hence the default.
manager.Store("", Config{
Name: name,
Opts: opts,
})
enabled.Store(true)
}
func Root(service string, r *http.Request) (opentracing.Span, *http.Request) {
tr := Get(service)
mainCtx, err := Extract(tr, r.Header)
tags := opentracing.Tags{
"from_ip": request.RealIP(r),
"method": r.Method,
"endpoint": r.URL.Path,
"raw_url": r.URL.String(),
"size": strconv.Itoa(int(r.ContentLength)),
}
if err != nil {
// TODO log this error?
// We just create a new span here so the log should be a warning.
span, ctx := opentracing.StartSpanFromContextWithTracer(r.Context(),
tr,
service, tags)
return span, r.WithContext(SetServiceID(ctx, service))
}
span, ctx := opentracing.StartSpanFromContextWithTracer(r.Context(),
tr,
service,
opentracing.ChildOf(mainCtx), tags)
return span, r.WithContext(SetServiceID(ctx, service))
}
// Span creates a new span for the given ops. If tracing is disabled in this ctx
// then a noop span is created and the same ctx is returned.
//
// Note that the returned context contains the returned span as active span. So
// any spans created form the returned context will be children of the returned
// span.
func Span(ctx context.Context, ops string, opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context) {
return opentracing.StartSpanFromContextWithTracer(ctx,
Get(GetServiceID(ctx)),
ops, opts...)
}
func Extract(tr Tracer, h http.Header) (opentracing.SpanContext, error) {
return tr.Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(h),
)
}
func ExtractFromContext(ctx context.Context, h http.Header) (opentracing.SpanContext, error) {
return Extract(Get(GetServiceID(ctx)), h)
}
func Inject(service string, span opentracing.Span, h http.Header) error {
tr := Get(service)
return tr.Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(h),
)
}
func InjectFromContext(ctx context.Context, span opentracing.Span, h http.Header) error {
return Inject(GetServiceID(ctx), span, h)
}