-
Notifications
You must be signed in to change notification settings - Fork 54
/
recorder.go
517 lines (437 loc) · 14.5 KB
/
recorder.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
package thrift_rpc
import (
"fmt"
"os"
"path"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/lightstep/lightstep-tracer-go/basictracer"
"github.com/lightstep/lightstep-tracer-go/lightstep_thrift"
"github.com/lightstep/lightstep-tracer-go/thrift_0_9_2/lib/go/thrift"
ot "github.com/opentracing/opentracing-go"
)
const (
collectorPath = "/_rpc/v1/reports/binary"
defaultPlainPort = 80
defaultSecurePort = 443
defaultCollectorHost = "collector.lightstep.com"
defaultAPIHost = "api.lightstep.com"
// See the comment for shouldFlush() for more about these tuning
// parameters.
defaultMaxReportingPeriod = 2500 * time.Millisecond
minReportingPeriod = 500 * time.Millisecond
// ParentSpanGUIDKey is the tag key used to record the relationship
// between child and parent spans.
ParentSpanGUIDKey = "parent_span_guid"
TracerPlatformValue = "go"
TracerVersionValue = "0.9.1"
TracerPlatformKey = "lightstep.tracer_platform"
TracerPlatformVersionKey = "lightstep.tracer_platform_version"
TracerVersionKey = "lightstep.tracer_version"
ComponentNameKey = "lightstep.component_name"
GUIDKey = "lightstep.guid" // <- runtime guid, not span guid
HostnameKey = "lightstep.hostname"
CommandLineKey = "lightstep.command_line"
)
// Endpoint describes a collection or web API host/port and whether or
// not to use plaintext communicatation.
type Endpoint struct {
Host string `yaml:"host" usage:"host on which the endpoint is running"`
Port int `yaml:"port" usage:"port on which the endpoint is listening"`
Plaintext bool `yaml:"plaintext" usage:"whether or not to encrypt data send to the endpoint"`
}
// A set of counter values for a given time window
type counterSet struct {
droppedSpans int64
}
// Options control how the LightStep Tracer behaves.
type Options struct {
// AccessToken is the unique API key for your LightStep project. It is
// available on your account page at https://app.lightstep.com/account
AccessToken string `yaml:"access_token" usage:"access token for reporting to LightStep"`
// Collector is the host, port, and plaintext option to use
// for the collector.
Collector Endpoint `yaml:"collector"`
// Tags are arbitrary key-value pairs that apply to all spans generated by
// this Tracer.
Tags ot.Tags
// LightStep is the host, port, and plaintext option to use
// for the LightStep web API.
LightStepAPI Endpoint `yaml:"lightstep_api"`
// MaxBufferedSpans is the maximum number of spans that will be buffered
// before sending them to a collector.
MaxBufferedSpans int `yaml:"max_buffered_spans"`
// ReportingPeriod is the maximum duration of time between sending spans
// to a collector. If zero, the default will be used.
ReportingPeriod time.Duration `yaml:"reporting_period"`
ReportTimeout time.Duration `yaml:"report_timeout"`
// DropSpanLogs turns log events on all Spans into no-ops.
DropSpanLogs bool `yaml:"drop_span_logs"`
// Set Verbose to true to enable more text logging.
Verbose bool
// In place of Flags
MaxLogMessageLen int
// MaxLogsPerSpan limits the number of logs in a single span.
MaxLogsPerSpan int `yaml:"max_logs_per_span"`
}
// NewTracer returns a new Tracer that reports spans to a LightStep
// collector.
func NewTracer(opts Options) ot.Tracer {
options := basictracer.DefaultOptions()
options.Recorder = NewRecorder(opts)
options.DropAllLogs = opts.DropSpanLogs
options.MaxLogsPerSpan = opts.MaxLogsPerSpan
return basictracer.NewWithOptions(options)
}
func FlushLightStepTracer(lsTracer ot.Tracer) error {
basicTracer, ok := lsTracer.(basictracer.Tracer)
if !ok {
return fmt.Errorf("Not a LightStep Tracer type: %v", reflect.TypeOf(lsTracer))
}
basicRecorder := basicTracer.Options().Recorder
lsRecorder, ok := basicRecorder.(*Recorder)
if !ok {
return fmt.Errorf("Not a LightStep Recorder type: %v", reflect.TypeOf(basicRecorder))
}
lsRecorder.Flush()
return nil
}
// Recorder buffers spans and forwards them to a LightStep collector.
type Recorder struct {
lock sync.Mutex
// auth and runtime information
auth *lightstep_thrift.Auth
attributes map[string]string
startTime time.Time
// Time window of the data to be included in the next report.
reportOldest time.Time
reportYoungest time.Time
// buffered data
buffer spansBuffer
counters counterSet // The unreported count
lastReportAttempt time.Time
maxReportingPeriod time.Duration
reportInFlight bool
// Remote service that will receive reports
backend lightstep_thrift.ReportingService
// apiURL is the base URL of the LightStep web API, used for
// explicit trace collection requests.
apiURL string
// AccessToken is the access token used for explicit trace
// collection requests.
AccessToken string
verbose bool
// We allow our remote peer to disable this instrumentation at any
// time, turning all potentially costly runtime operations into
// no-ops.
disabled bool
closech chan struct{}
// flags replacement
maxLogMessageLen int
}
func NewRecorder(opts Options) *Recorder {
if len(opts.AccessToken) == 0 {
// TODO maybe return a no-op recorder instead?
panic("LightStep Recorder options.AccessToken must not be empty")
}
if opts.Tags == nil {
opts.Tags = make(map[string]interface{})
}
// Set some default attributes if not found in options
if _, found := opts.Tags[ComponentNameKey]; !found {
opts.Tags[ComponentNameKey] = path.Base(os.Args[0])
}
if _, found := opts.Tags[GUIDKey]; !found {
opts.Tags[GUIDKey] = genSeededGUID()
}
if _, found := opts.Tags[HostnameKey]; !found {
hostname, _ := os.Hostname()
opts.Tags[HostnameKey] = hostname
}
if _, found := opts.Tags[CommandLineKey]; !found {
opts.Tags[CommandLineKey] = strings.Join(os.Args, " ")
}
attributes := make(map[string]string)
for k, v := range opts.Tags {
attributes[k] = fmt.Sprint(v)
}
// Don't let the Options override these values. That would be confusing.
attributes[TracerPlatformKey] = TracerPlatformValue
attributes[TracerPlatformVersionKey] = runtime.Version()
attributes[TracerVersionKey] = TracerVersionValue
now := time.Now()
rec := &Recorder{
auth: &lightstep_thrift.Auth{
AccessToken: thrift.StringPtr(opts.AccessToken),
},
attributes: attributes,
startTime: now,
reportOldest: now,
reportYoungest: now,
maxReportingPeriod: defaultMaxReportingPeriod,
verbose: opts.Verbose,
apiURL: getAPIURL(opts),
AccessToken: opts.AccessToken,
maxLogMessageLen: opts.MaxLogMessageLen,
}
rec.buffer.setDefaults()
if opts.MaxBufferedSpans > 0 {
rec.buffer.setMaxBufferSize(opts.MaxBufferedSpans)
}
timeout := 60 * time.Second
if opts.ReportTimeout > 0 {
timeout = opts.ReportTimeout
}
transport, err := thrift.NewTHttpPostClient(getCollectorURL(opts), timeout)
if err != nil {
rec.maybeLogError(err)
return nil
}
rec.backend = lightstep_thrift.NewReportingServiceClientFactory(
transport, thrift.NewTBinaryProtocolFactoryDefault())
rec.closech = make(chan struct{})
go rec.reportLoop(rec.closech)
return rec
}
func (r *Recorder) RecordSpan(raw basictracer.RawSpan) {
r.lock.Lock()
defer r.lock.Unlock()
// Early-out for disabled runtimes.
if r.disabled {
return
}
atomic.AddInt64(&r.counters.droppedSpans, int64(r.buffer.addSpans([]basictracer.RawSpan{raw})))
}
func (r *Recorder) Flush() {
r.lock.Lock()
if r.disabled {
r.lock.Unlock()
return
}
if r.reportInFlight == true {
r.maybeLogError(fmt.Errorf("A previous Report is still in flight; aborting Flush()."))
r.lock.Unlock()
return
}
now := time.Now()
r.lastReportAttempt = now
r.reportYoungest = now
rawSpans := r.buffer.current()
// Convert them to thrift.
recs := make([]*lightstep_thrift.SpanRecord, len(rawSpans))
// TODO: could pool lightstep_thrift.SpanRecords
for i, raw := range rawSpans {
var joinIds []*lightstep_thrift.TraceJoinId
var attributes []*lightstep_thrift.KeyValue
for key, value := range raw.Tags {
if strings.HasPrefix(key, "join:") {
joinIds = append(joinIds, &lightstep_thrift.TraceJoinId{key, fmt.Sprint(value)})
} else {
attributes = append(attributes, &lightstep_thrift.KeyValue{key, fmt.Sprint(value)})
}
}
logs := make([]*lightstep_thrift.LogRecord, len(raw.Logs))
for j, log := range raw.Logs {
thriftLogRecord := &lightstep_thrift.LogRecord{
TimestampMicros: thrift.Int64Ptr(log.Timestamp.UnixNano() / 1000),
}
// In the deprecated thrift case, we can reuse a single "field"
// encoder across all of the N log fields.
lfe := logFieldEncoder{thriftLogRecord, r}
for _, f := range log.Fields {
f.Marshal(&lfe)
}
logs[j] = thriftLogRecord
}
// TODO implement baggage
if raw.ParentSpanID != 0 {
attributes = append(attributes, &lightstep_thrift.KeyValue{ParentSpanGUIDKey,
strconv.FormatUint(raw.ParentSpanID, 16)})
}
recs[i] = &lightstep_thrift.SpanRecord{
SpanGuid: thrift.StringPtr(strconv.FormatUint(raw.Context.SpanID, 16)),
TraceGuid: thrift.StringPtr(strconv.FormatUint(raw.Context.TraceID, 16)),
SpanName: thrift.StringPtr(raw.Operation),
JoinIds: joinIds,
OldestMicros: thrift.Int64Ptr(raw.Start.UnixNano() / 1000),
YoungestMicros: thrift.Int64Ptr(raw.Start.Add(raw.Duration).UnixNano() / 1000),
Attributes: attributes,
LogRecords: logs,
}
}
// TODO the handling of droppedPending / droppedSpans is very
// manual. Add abstraction for the second client-side count to
// avoid duplicating all the atomic ops.
droppedPending := atomic.SwapInt64(&r.counters.droppedSpans, 0)
metrics := lightstep_thrift.Metrics{
Counts: []*lightstep_thrift.MetricsSample{
&lightstep_thrift.MetricsSample{
Name: "spans.dropped",
Int64Value: &droppedPending,
},
},
}
req := &lightstep_thrift.ReportRequest{
OldestMicros: thrift.Int64Ptr(r.reportOldest.UnixNano() / 1000),
YoungestMicros: thrift.Int64Ptr(r.reportYoungest.UnixNano() / 1000),
Runtime: r.thriftRuntime(),
SpanRecords: recs,
InternalMetrics: &metrics,
}
// Do *not* wait until the report RPC finishes to clear the buffer.
// Consider the case of a new span coming in during the RPC: it'll be
// discarded along with the data that was just sent if the buffers are
// cleared later.
r.buffer.reset()
r.reportInFlight = true
r.lock.Unlock() // unlock before making the RPC itself
resp, err := r.backend.Report(r.auth, req)
if err != nil {
r.maybeLogError(err)
} else if len(resp.Errors) > 0 {
// These should never occur, since this library should understand what
// makes for valid logs and spans, but just in case, log it anyway.
for _, err := range resp.Errors {
r.maybeLogError(fmt.Errorf("Remote report returned error: %s", err))
}
} else {
r.maybeLogInfof("Report: resp=%v, err=%v", resp, err)
}
r.lock.Lock()
r.reportInFlight = false
if err != nil {
// Restore the records that did not get sent correctly
atomic.AddInt64(&r.counters.droppedSpans, int64(r.buffer.addSpans(rawSpans))+droppedPending)
r.lock.Unlock()
return
}
// Reset the buffers
r.reportOldest = now
r.reportYoungest = now
// TODO something about timing
r.lock.Unlock()
if droppedPending != 0 {
r.maybeLogInfof("client reported %d dropped spans", droppedPending)
}
for _, c := range resp.Commands {
if c.Disable != nil && *c.Disable {
r.Disable()
}
}
}
func (r *Recorder) Close() error {
r.lock.Lock()
closech := r.closech
r.closech = nil
r.lock.Unlock()
if closech != nil {
close(closech)
}
return nil
}
// caller must hold r.lock
func (r *Recorder) thriftRuntime() *lightstep_thrift.Runtime {
runtimeAttrs := []*lightstep_thrift.KeyValue{}
for k, v := range r.attributes {
runtimeAttrs = append(runtimeAttrs, &lightstep_thrift.KeyValue{k, v})
}
return &lightstep_thrift.Runtime{
StartMicros: thrift.Int64Ptr(r.startTime.UnixNano() / 1000),
Attrs: runtimeAttrs,
}
}
func (r *Recorder) Disable() {
r.lock.Lock()
defer r.lock.Unlock()
if r.disabled {
return
}
fmt.Printf("Disabling Runtime instance: %p", r)
r.buffer.reset()
r.disabled = true
}
// Every minReportingPeriod the reporting loop wakes up and checks to see if
// either (a) the Runtime's max reporting period is about to expire (see
// maxReportingPeriod()), (b) the number of buffered log records is
// approaching kMaxBufferedLogs, or if (c) the number of buffered span records
// is approaching kMaxBufferedSpans. If any of those conditions are true,
// pending data is flushed to the remote peer. If not, the reporting loop waits
// until the next cycle. See Runtime.maybeFlush() for details.
//
// This could alternatively be implemented using flush channels and so forth,
// but that would introduce opportunities for client code to block on the
// runtime library, and we want to avoid that at all costs (even dropping data,
// which can certainly happen with high data rates and/or unresponsive remote
// peers).
func (r *Recorder) shouldFlush() bool {
r.lock.Lock()
defer r.lock.Unlock()
if time.Now().Add(minReportingPeriod).Sub(r.lastReportAttempt) > r.maxReportingPeriod {
// Flush timeout.
r.maybeLogInfof("--> timeout")
return true
} else if r.buffer.len() > r.buffer.cap()/2 {
// Too many queued span records.
r.maybeLogInfof("--> span queue")
return true
}
return false
}
func (r *Recorder) reportLoop(closech chan struct{}) {
// (Thrift really should do this internally, but we saw some too-many-fd's
// errors and thrift is the most likely culprit.)
switch b := r.backend.(type) {
case *lightstep_thrift.ReportingServiceClient:
// TODO This is a bit racy with other calls to Flush, but we're
// currently assuming that no one calls Flush after Disable.
defer b.Transport.Close()
}
tickerChan := time.Tick(minReportingPeriod)
for {
select {
case <-tickerChan:
r.maybeLogInfof("reporting alarm fired")
// Kill the reportLoop() if we've been disabled.
r.lock.Lock()
if r.disabled {
r.lock.Unlock()
break
}
r.lock.Unlock()
if r.shouldFlush() {
r.Flush()
}
case <-closech:
r.Flush()
return
}
}
}
func getCollectorURL(opts Options) string {
return getURL(opts.Collector,
defaultCollectorHost,
collectorPath)
}
func getAPIURL(opts Options) string {
return getURL(opts.LightStepAPI, defaultAPIHost, "")
}
func getURL(e Endpoint, host, path string) string {
if e.Host != "" {
host = e.Host
}
httpProtocol := "https"
port := defaultSecurePort
if e.Plaintext {
httpProtocol = "http"
port = defaultPlainPort
}
if e.Port > 0 {
port = e.Port
}
return fmt.Sprintf("%s://%s:%d%s", httpProtocol, host, port, path)
}