-
Notifications
You must be signed in to change notification settings - Fork 66
/
tracer_imp.js
1354 lines (1184 loc) · 49.1 KB
/
tracer_imp.js
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//============================================================================//
// Imports
//============================================================================//
import EventEmitter from 'eventemitter3';
import * as opentracing from 'opentracing';
import SpanContextImp from './span_context_imp';
import SpanImp from './span_imp';
import _each from '../_each';
import { Platform, ProtoTransport, ThriftTransport } from '../platform_abstraction_layer';
import AuthImp from './auth_imp';
import RuntimeImp from './runtime_imp';
import ReportImp from './report_imp';
import UnsupportedPropagator from './propagator';
import LightStepPropagator from './propagator_ls';
const ClockState = require('./util/clock_state');
const LogBuilder = require('./log_builder');
const coerce = require('./coerce');
const constants = require('../constants');
const globals = require('./globals');
const packageObject = require('../../package.json');
const util = require('./util/util');
const DEFAULT_COLLECTOR_HOSTNAME = 'collector.lightstep.com';
const DEFAULT_COLLECTOR_PORT_TLS = 443;
const DEFAULT_COLLECTOR_PORT_PLAIN = 80;
const DEFAULT_COLLECTOR_PATH = '';
// Internal errors should be rare. Set a low limit to ensure a cascading failure
// does not compound an existing problem by trying to send a great deal of
// internal error data.
const MAX_INTERNAL_LOGS = 20;
let _singleton = null;
export default class Tracer extends opentracing.Tracer {
constructor(opts) {
super();
this._delegateEventEmitterMethods();
opts = opts || {};
if (!_singleton) {
globals.setOptions(opts);
_singleton = this;
}
// Platform abstraction layer
this._platform = new Platform(this);
this._runtimeGUID = opts.guid || this.override_runtime_guid || null; // Set once the group name is set
this._plugins = {};
this._options = {};
this._optionDescs = [];
this._makeOptionsTable();
this._opentracing = opentracing;
if (opts.opentracing_module) {
this._opentracing = opts.opentracing_module;
}
let now = this._platform.nowMicros();
// The thrift authentication and runtime struct are created as soon as
// the necessary initialization options are available.
this._startMicros = now;
this._auth = null;
this._runtime = null;
let logger = {
warn : (msg, payload) => { this._warn(msg, payload); },
error : (err, payload) => { this._error(err, payload); },
};
if (opts) {
this._transport = opts.override_transport;
}
this._propagators = {};
this._propagators[this._opentracing.FORMAT_HTTP_HEADERS] = new LightStepPropagator(this);
this._propagators[this._opentracing.FORMAT_TEXT_MAP] = new LightStepPropagator(this);
this._propagators[this._opentracing.FORMAT_BINARY] = new UnsupportedPropagator(
this,
this._opentracing.FORMAT_BINARY,
);
if (opts && opts.propagators) {
this._propagators = { ...this._propagators, ...opts.propagators };
}
this._reportingLoopActive = false;
this._first_report_has_run = false;
this._reportYoungestMicros = now;
this._reportTimer = null;
this._reportErrorStreak = 0; // Number of consecutive errors
this._lastVisibleErrorMillis = 0;
this._skippedVisibleErrors = 0;
// Set addActiveRootSpan() for detail
this._activeRootSpanSet = {};
this._activeRootSpan = null;
// Span reporting buffer and per-report data
// These data are reset on every successful report.
this._spanRecords = [];
// The counter names need to match those accepted by the collector.
// These are internal counters only.
this._counters = {
'internal.errors' : 0,
'internal.warnings' : 0,
'spans.dropped' : 0,
'logs.dropped' : 0,
'logs.keys.over_limit' : 0,
'logs.values.over_limit' : 0,
'reports.errors.send' : 0,
};
// For internal (not client) logs reported to the collector
this._internalLogs = [];
// Current runtime state / status
this._flushIsActive = false;
// Built-in plugins
this.addPlugin(require('../plugins/log_to_console'));
// Initialize the platform options after the built-in plugins in
// case any of those options affect the built-ins.
this.addPlatformPlugins(opts);
this.setPlatformOptions(opts);
// Set constructor arguments
if (opts) {
this.options(opts);
}
if (typeof this._transport === 'undefined' || this._transport === null) {
switch (this._options.transport) {
case 'proto':
this._transport = new ProtoTransport(logger);
this._info('Using protobuf over HTTP transport per user-defined option.');
break;
case 'thrift':
this._transport = new ThriftTransport(logger);
this._info('Using thrift transport per user-defined option.');
break;
default:
this._transport = new ProtoTransport(logger);
this._info('Using protobuf over HTTP transport as no user-defined option was supplied.');
}
}
// For clock skew adjustment.
// Must be set after options have been set.
this._useClockState = !this._options.disable_clock_skew_correction;
this._clockState = new ClockState({
nowMicros : () => this._platform.nowMicros(),
localStoreGet : () => {
let key = `clock_state/${this._options.collector_host}`;
return this._platform.localStoreGet(key);
},
localStoreSet : (value) => {
let key = `clock_state/${this._options.collector_host}`;
return this._platform.localStoreSet(key, value);
},
});
// This relies on the options being set: call this last.
this._setupReportOnExit();
this._info(`Tracer created with guid ${this._runtimeGUID}`);
if (this._options.access_token.length === 0) {
this._warn(
`Access token not set -
this requires a satellite with access token checking disabled,
such as a developer satellite.`,
);
}
this.startPlugins();
}
// Morally speaking, Tracer also inherits from EventEmmiter, but we must
// fake it via composition.
//
// If not obvious on inspection: a hack.
_delegateEventEmitterMethods() {
let self = this;
this._ee = new EventEmitter();
// The list of methods at https://nodejs.org/api/events.html
_each([
'addListener',
'emit',
'eventNames',
'getMaxListeners',
'listenerCount',
'listeners',
'on',
'once',
'prependListener',
'prependOnceListener',
'removeAllListeners',
'removeListener',
'setMaxListeners',
], (methodName) => {
self[methodName] = function () {
if (self._ee[methodName]) {
// eslint-disable-next-line prefer-spread
self._ee[methodName].apply(self._ee, arguments);
}
};
});
}
_makeOptionsTable() {
/* eslint-disable key-spacing, no-multi-spaces */
// NOTE: make 'verbosity' the first option so it is processed first on
// options changes and takes effect as soon as possible.
this.addOption('verbosity', {
type : 'int', min: 0, max: 9, defaultValue: 1,
});
// Core options
this.addOption('access_token', { type: 'string', defaultValue: '' });
this.addOption('component_name', { type: 'string', defaultValue: '' });
this.addOption('collector_host', { type: 'string', defaultValue: DEFAULT_COLLECTOR_HOSTNAME });
this.addOption('collector_port', { type: 'int', defaultValue: DEFAULT_COLLECTOR_PORT_TLS });
this.addOption('collector_path', { type: 'string', defaultValue: DEFAULT_COLLECTOR_PATH });
this.addOption('collector_encryption', { type: 'string', defaultValue: 'tls' });
this.addOption('tags', { type: 'any', defaultValue: {} });
this.addOption('max_reporting_interval_millis', { type: 'int', defaultValue: 2500 });
this.addOption('disable_clock_skew_correction', { type: 'bool', defaultValue: false });
this.addOption('transport', { type: 'string', defaultValue: 'proto' });
// Non-standard, may be deprecated
this.addOption('disabled', { type: 'bool', defaultValue: false });
this.addOption('max_span_records', { type: 'int', defaultValue: 4096 });
this.addOption('default_span_tags', { type: 'any', defaultValue: {} });
this.addOption('report_timeout_millis', { type: 'int', defaultValue: 30000 });
this.addOption('gzip_json_requests', { type: 'bool', defaultValue: true });
this.addOption('disable_reporting_loop', { type: 'bool', defaultValue: false });
this.addOption('disable_report_on_exit', { type: 'bool', defaultValue: false });
this.addOption('delay_initial_report_millis', { type: 'int', defaultValue: 1000 });
this.addOption('error_throttle_millis', { type: 'int', defaultValue: 60000 });
this.addOption('logger', { type: 'function', defaultValue: this._printToConsole.bind(this) });
this.addOption(
'clear_span_buffer_consecutive_errors',
{ type: 'int', defaultValue: null },
);
// Debugging options
//
// These are not part of the supported public API.
//
// If false, SSL certificate verification is skipped. Useful for testing.
this.addOption('certificate_verification', { type: 'bool', defaultValue: true });
// I.e. report only on explicit calls to flush()
// Unit testing options
this.addOption('override_transport', { type : 'any', defaultValue: null });
this.addOption('silent', { type : 'bool', defaultValue: false });
// Hard upper limits to protect against worst-case scenarios for log field sizes.
this.addOption('log_field_key_hard_limit', { type: 'int', defaultValue: 256 });
this.addOption('log_field_value_hard_limit', { type: 'int', defaultValue: 1024 });
// Meta Event reporting options
this.addOption('disable_meta_event_reporting', { type: 'bool', defaultValue: false });
/* eslint-disable key-spacing, no-multi-spaces */
}
// ---------------------------------------------------------------------- //
// opentracing.Tracer SPI
// ---------------------------------------------------------------------- //
_startSpan(name, fields) {
// First, assemble the SpanContextImp for our SpanImp.
let parentCtxImp = null;
fields = fields || {};
if (fields.references) {
for (let i = 0; i < fields.references.length; i++) {
let ref = fields.references[i];
let type = ref.type();
if (type === this._opentracing.REFERENCE_CHILD_OF
|| type === this._opentracing.REFERENCE_FOLLOWS_FROM) {
let context = ref.referencedContext();
if (!context) {
this._error('Span reference has an invalid context', context);
// eslint-disable-next-line no-continue
continue;
}
parentCtxImp = context;
break;
}
}
}
let traceGUID = parentCtxImp ? parentCtxImp.traceGUID() : this.generateTraceGUIDForRootSpan();
let sampled = parentCtxImp ? parentCtxImp._sampled : true;
let spanCtx = new SpanContextImp(this._platform.generateUUID(), traceGUID, sampled);
let spanImp = new SpanImp(this, name, spanCtx);
spanImp.addTags(this._options.default_span_tags);
_each(fields, (value, key) => {
switch (key) {
case 'references':
// Ignore: handled before constructing the span
break;
case 'startTime':
// startTime is in milliseconds
spanImp.setBeginMicros(Math.floor(value * 1000));
break;
case 'tags':
spanImp.addTags(value);
break;
default:
this._warn(`Ignoring unknown field '${key}'`);
break;
}
});
if (parentCtxImp !== null) {
spanImp.setParentGUID(parentCtxImp._guid);
// Copy baggage items from parent to child
parentCtxImp.forEachBaggageItem((k, v) => spanCtx.setBaggageItem(k, v));
}
this.emit('start_span', spanImp);
if (util.shouldSendMetaSpan(this.options(), spanImp.getTags())) {
this.startSpan(
constants.LS_META_SP_START,
{
tags : {
[constants.LS_META_EVENT_KEY]: true,
[constants.LS_META_TRACE_KEY]: spanImp.traceGUID(),
[constants.LS_META_SPAN_KEY]: spanImp.guid(),
},
},
)
.finish();
}
return spanImp;
}
_inject(spanContext, format, carrier) {
if (this.options().meta_event_reporting === true) {
this.startSpan(
constants.LS_META_INJECT,
{
tags: {
[constants.LS_META_EVENT_KEY]: true,
[constants.LS_META_TRACE_KEY]: spanContext._traceGUID,
[constants.LS_META_SPAN_KEY]: spanContext._guid,
[constants.LS_META_PROPAGATION_KEY]: format,
},
},
)
.finish();
}
switch (format) {
case this._opentracing.FORMAT_HTTP_HEADERS:
this._propagators[this._opentracing.FORMAT_HTTP_HEADERS].inject(spanContext, carrier);
break;
case this._opentracing.FORMAT_TEXT_MAP:
this._propagators[this._opentracing.FORMAT_TEXT_MAP].inject(spanContext, carrier);
break;
case this._opentracing.FORMAT_BINARY:
this._propagators[this._opentracing.FORMAT_BINARY].inject(spanContext, carrier);
break;
default:
this._error(`Unknown format: ${format}`);
break;
}
}
_extract(format, carrier) {
let sc = null;
switch (format) {
case this._opentracing.FORMAT_HTTP_HEADERS:
sc = this._propagators[this._opentracing.FORMAT_HTTP_HEADERS].extract(carrier);
break;
case this._opentracing.FORMAT_TEXT_MAP:
sc = this._propagators[this._opentracing.FORMAT_TEXT_MAP].extract(carrier);
break;
case this._opentracing.FORMAT_BINARY:
sc = this._propagators[this._opentracing.FORMAT_BINARY].extract(carrier);
break;
default:
this._error(`Unsupported format: ${format}`);
return null;
}
if (this.options().meta_event_reporting === true && sc) {
this.startSpan(
constants.LS_META_EXTRACT,
{
tags: {
[constants.LS_META_EVENT_KEY]: true,
[constants.LS_META_TRACE_KEY]: sc._traceGUID,
[constants.LS_META_SPAN_KEY]: sc._guid,
[constants.LS_META_PROPAGATION_KEY]: format,
},
},
)
.finish();
}
return sc;
}
// ---------------------------------------------------------------------- //
// LightStep extensions
// ---------------------------------------------------------------------- //
/**
* Manually sends a report of all buffered data.
*
* @param {Function} done - callback function invoked when the report
* either succeeds or fails.
*/
flush(done) {
if (!done) {
done = function () {};
}
if (this._options.disabled) {
this._warn('Manual flush() called in disabled state.');
return done(null);
}
this._flushReport(true, false, done);
}
//-----------------------------------------------------------------------//
// Options
//-----------------------------------------------------------------------//
guid() {
return this._runtimeGUID;
}
verbosity() {
// The 'undefined' handling below is for logs that may occur before the
// options are initialized.
let v = this._options.verbosity;
return (v === undefined) ? 1 : v;
}
// Call to generate a new Trace GUID
generateTraceGUIDForRootSpan() {
let guid = this._platform.generateUUID();
if (this._activeRootSpan) {
guid = this._activeRootSpan.traceGUID();
}
return guid;
}
setPlatformOptions(userOptions) {
let opts = this._platform.options(this) || {};
_each(userOptions, (val, key) => {
opts[key] = val;
});
this.options(opts);
}
// Register a new option. Used by plug-ins.
addOption(name, desc) {
desc.name = name;
this._optionDescs.push(desc);
this._options[desc.name] = desc.defaultValue;
}
options(opts) {
if (arguments.length === 0) {
console.assert(typeof this._options === 'object', // eslint-disable-line
'Internal error: _options field incorrect',
);
return this._options;
}
if (typeof opts !== 'object') {
throw new Error(`options() must be called with an object: type was ${typeof opts}`);
}
// "collector_port" 0 acts as an alias for "use the default".
if (opts.collector_port === 0) {
delete opts.collector_port;
}
// "collector_encryption" acts an alias for the common cases of 'collector_port'
if (opts.collector_encryption !== undefined && opts.collector_port === undefined) {
opts.collector_port = opts.collector_encryption !== 'none'
? DEFAULT_COLLECTOR_PORT_TLS
: DEFAULT_COLLECTOR_PORT_PLAIN;
}
// set meta event reporting to false by default, it will be enabled by the satellite
this.meta_event_reporting = false;
// Track what options have been modified
let modified = {};
let unchanged = {};
_each(this._optionDescs, (desc) => {
this._setOptionInternal(modified, unchanged, opts, desc);
});
// Check for any invalid options: is there a key in the specified operation
// that didn't result either in a change or a reset to the existing value?
Object.keys(opts).forEach((key) => {
if (modified[key] === undefined && unchanged[key] === undefined) {
this._warn(`Invalid option ${key} with value ${opts[key]}`);
}
});
//
// Update the state information based on the changes
//
this._initReportingDataIfNeeded(modified);
if (!this._reportingLoopActive) {
this._startReportingLoop();
}
if (this.verbosity() >= 3) {
let optionsString = '';
let count = 0;
_each(modified, (val, key) => {
optionsString += `\t${JSON.stringify(key)}: ${JSON.stringify(val.newValue)}\n`;
count++;
});
if (count > 0) {
this._debug(`Options modified:\n${optionsString}`);
}
}
this.emit('options', modified, this._options, this);
}
_setOptionInternal(modified, unchanged, opts, desc) {
let { name } = desc;
let value = opts[name];
let valueType = typeof value;
if (value === undefined) {
return;
}
// Parse the option (and check constraints)
switch (desc.type) {
case 'any':
break;
case 'bool':
if (value !== true && value !== false) {
this._error(`Invalid boolean option '${name}' '${value}'`);
return;
}
break;
case 'function':
if (typeof value !== 'function') {
this._error(`Invalid function option '${name}' '${value}'`);
return;
}
break;
case 'int':
if (valueType !== 'number' || Math.floor(value) !== value) {
this._error(`Invalid int option '${name}' '${value}'`);
return;
}
if (desc.min !== undefined && desc.max !== undefined) {
if (!(value >= desc.min && value <= desc.max)) {
this._error(`Option '${name}' out of range '${value}' is not between ${desc.min} and ${desc.max}`); // eslint-disable-line max-len
return;
}
}
break;
case 'string':
switch (valueType) {
case 'string':
break;
case 'number':
value = coerce.toString(value);
break;
default:
this._error(`Invalid string option ${name} ${value}`);
return;
}
break;
case 'array':
// Per http://stackoverflow.com/questions/4775722/check-if-object-is-array
if (Object.prototype.toString.call(value) !== '[object Array]') {
this._error(`Invalid type for array option ${name}: found '${valueType}'`);
return;
}
break;
default:
this._error(`Unknown option type '${desc.type}'`);
return;
}
// Set the new value, recording any modifications
let oldValue = this._options[name];
if (oldValue === undefined) {
throw new Error(`Attempt to set unknown option ${name}`);
}
// Ignore no-op changes for types that can be checked quickly
if (valueType !== 'object' && oldValue === value) {
unchanged[name] = true;
return;
}
modified[name] = {
oldValue : oldValue,
newValue : value,
};
this._options[name] = value;
}
// The authorization and runtime information is initialized as soon
// as it is available. This allows logs and spans to be buffered before
// the library is initialized, which can be helpul in a complex setup with
// many subsystems.
//
_initReportingDataIfNeeded(modified) {
// Ignore redundant initialization; complaint on inconsistencies
if (this._auth !== null) {
if (!this._runtime) {
return this._error('Inconsistent state: auth initialized without runtime.');
}
if (modified.access_token) {
throw new Error('Cannot change access_token after it has been set.');
}
if (modified.component_name) {
throw new Error('Cannot change component_name after it has been set.');
}
if (modified.collector_host) {
throw new Error('Cannot change collector_host after the connection is established');
}
if (modified.collector_port) {
throw new Error('Cannot change collector_port after the connection is established');
}
if (modified.collector_path) {
throw new Error('Cannot change collector_path after the connection is established');
}
if (modified.collector_encryption) {
throw new Error('Cannot change collector_encryption after the connection is established');
}
return;
}
this._runtimeGUID = this._platform.runtimeGUID(this._options.component_name);
this._auth = new AuthImp(this._options.access_token);
//
// Assemble the tracer tags from the user-specified and automatic,
// internal tags.
//
let tags = {};
_each(this._options.tags, (value, key) => {
if (typeof value !== 'string') {
this._error(`Tracer tag value is not a string: key=${key}`);
return;
}
tags[key] = value;
});
tags['lightstep.tracer_version'] = packageObject.version;
let platformTags = this._platform.tracerTags();
_each(platformTags, (val, key) => {
tags[key] = val;
});
this._runtime = new RuntimeImp(this._runtimeGUID, this._startMicros, this._options.component_name, tags);
this._info('Initializing reporting data', {
component_name : this._options.component_name,
access_token : this._auth.getAccessToken(),
});
this.emit('reporting_initialized');
}
getLogFieldKeyHardLimit() {
return this._options.log_field_key_hard_limit;
}
getLogFieldValueHardLimit() {
return this._options.log_field_value_hard_limit;
}
//-----------------------------------------------------------------------//
// Plugins
//-----------------------------------------------------------------------//
addPlatformPlugins(opts) {
let pluginSet = this._platform.plugins(opts);
_each(pluginSet, (val) => {
this.addPlugin(val);
});
}
addPlugin(plugin) {
// Don't add plug-ins twice
let name = plugin.name();
if (this._plugins[name]) {
return;
}
this._plugins[name] = plugin;
plugin.addOptions(this);
}
startPlugins() {
_each(this._plugins, (val, key) => {
this._plugins[key].start(this);
});
}
//-----------------------------------------------------------------------//
// Spans
//-----------------------------------------------------------------------//
// This is a LightStep-specific feature that should be used sparingly. It
// sets a "global" root span such that spans that would *otherwise* be root
// span instead inherit the trace GUID of the active root span. This is
// best clarified by example:
//
// On document load in the browser, an "active root span" is created for
// the page load process. Any spans started without an explicit parent
// will the document load trace GUID instead of starting a trace GUID.
// This implicit root remains active only until the page is done loading.
//
// Any span adding itself as a root span *must* remove itself along with
// calling finish(). This will *not* be done automatically.
//
// NOTE: currently, only the trace GUID is transferred; it may or may not
// make sure to make this a proper parent.
//
// NOTE: the root span tracking is handled as a set rather than a single
// global to avoid conflicts between libraries.
addActiveRootSpan(span) {
this._activeRootSpanSet[span._guid] = span;
this._setActiveRootSpanToYoungest();
}
removeActiveRootSpan(span) {
delete this._activeRootSpanSet[span._guid];
this._setActiveRootSpanToYoungest();
}
_setActiveRootSpanToYoungest() {
// Set the _activeRootSpan to the youngest of the roots in case of
// multiple.
this._activeRootSpan = null;
_each(this._activeRootSpanSet, (span) => {
if (!this._activeRootSpan
|| span._beginMicros > this._activeRootSpan._beginMicros) {
this._activeRootSpan = span;
}
});
}
//-----------------------------------------------------------------------//
// Encoding / decoding
//-----------------------------------------------------------------------//
_objectToUint8Array(obj) {
let jsonString;
try {
// encodeURIComponent() is a *very* inefficient, but simple and
// well-supported way to avoid having to think about Unicode in
// in the conversion to a UInt8Array.
//
// Writing multiple bytes for String.charCodeAt and
// String.codePointAt would be an alternate approach; again,
// simplicitly is being preferred over efficiency for the moment.
jsonString = encodeURIComponent(JSON.stringify(obj));
} catch (e) {
this._error('Could not binary encode carrier data.');
return null;
}
let buffer = new ArrayBuffer(jsonString.length);
let view = new Uint8Array(buffer);
for (let i = 0; i < jsonString.length; i++) {
let code = jsonString.charCodeAt(i);
if (!(code >= 0 && code <= 255)) {
this._error('Unexpected character code');
return null;
}
view[i] = code;
}
return view;
}
_uint8ArrayToObject(arr) {
if (!arr) {
this._error('Array is null');
return null;
}
let jsonString = '';
for (let i = 0; i < arr.length; i++) {
jsonString += String.fromCharCode(arr[i]);
}
try {
return JSON.parse(decodeURIComponent(jsonString));
} catch (e) {
this._error('Could not decode binary data.');
return null;
}
}
//-----------------------------------------------------------------------//
// Logging
//-----------------------------------------------------------------------//
log() {
let b = new LogBuilder(this);
return b;
}
//-----------------------------------------------------------------------//
// Buffers
//-----------------------------------------------------------------------//
_clearBuffers() {
this._spanRecords = [];
this._internalLogs = [];
// Create a new object to avoid overwriting the values in any references
// to the old object
let counters = {};
_each(this._counters, (unused, key) => {
counters[key] = 0;
});
this._counters = counters;
}
_buffersAreEmpty() {
if (this._spanRecords.length > 0) {
return false;
}
if (this._internalLogs.length > 0) {
return false;
}
let countersAllZero = true;
_each(this._counters, (val) => {
if (val > 0) {
countersAllZero = false;
}
});
return countersAllZero;
}
_addSpanRecord(record) {
this._internalAddSpanRecord(record);
this.emit('span_added', record);
}
_internalAddSpanRecord(record) {
if (!record) {
this._error('Attempt to add null record to buffer');
return;
}
if (this._spanRecords.length >= this._options.max_span_records) {
let index = Math.floor(this._spanRecords.length * Math.random());
this._spanRecords[index] = record;
this._counters['spans.dropped']++;
} else {
this._spanRecords.push(record);
}
}
_restoreRecords(spans, internalLogs, counters) {
_each(spans, (span) => {
this._internalAddSpanRecord(span);
});
let currentInternalLogs = this._internalLogs;
this._internalLogs = [];
let toAdd = internalLogs.concat(currentInternalLogs);
_each(toAdd, (log) => {
this._pushInternalLog(log);
});
_each(counters, (value, key) => {
if (key in this._counters) {
this._counters[key] += value;
} else {
this._error(`Bad counter name: ${key}`);
}
});
}
/**
* clearSpanRecordsIfMaxErrors checks to see if the tracer was configured to
* empty the span buffer after a fixed amount of errors. If it is configured,
* and there has been an error streak equal to the configured value,
* it will empty spanRecords and record that the spans were dropped.
*
* @private
*/
_clearSpanRecordsIfMaxErrors() {
const maxErrorsToEmpty = this.options().clear_span_buffer_consecutive_errors;
if (maxErrorsToEmpty === null || this._reportErrorStreak < maxErrorsToEmpty) {
return;
}
// spanRecords is configured to be emptied
// the number of dropped spans and reporting errors should still be maintained since
// the loop may still in the process of a report.
const numSpansToDrop = this._spanRecords.length;
this._counters['spans.dropped'] += numSpansToDrop;
this._spanRecords = [];
this._warn('Span buffer flushed, max consecutive errors reached', {
max_consecutive_errors: maxErrorsToEmpty,
spans_dropped: numSpansToDrop,
});
}
//-----------------------------------------------------------------------//
// Reporting loop
//-----------------------------------------------------------------------//
_setupReportOnExit() {
if (this._options.disable_report_on_exit) {
this._debug('report-on-exit is disabled.');
return;
}
// Do a final explicit flush. Note that the final flush may enqueue
// asynchronous callbacks that cause the 'beforeExit' event to be
// re-emitted when those callbacks finish.
let finalFlushOnce = 0;
let finalFlush = () => {
if (finalFlushOnce++ > 0) { return; }
this._info('Final flush before exit.');
this._flushReport(false, true, (err) => {
if (err) {
this._warn('Final report before exit failed', {
error : err,
unflushed_spans : this._spanRecords.length,
buffer_youngest_micros : this._reportYoungestMicros,
});
}
});
};
this._platform.onBeforeExit(finalFlush);
}
_startReportingLoop() {
if (this._options.disabled) {
this._info('Not starting reporting loop: instrumentation is disabled.');
return;
}
if (this._options.disable_reporting_loop) {
this._info('Not starting reporting loop: reporting loop is disabled.');
return;
}
if (this._auth === null) {
// Don't start the loop until the thrift data necessary to do the
// report is set up.
return;
}
if (this._reportingLoopActive) {
this._info('Reporting loop already started!');
return;
}
this._info('Starting reporting loop:', this._runtime);
this._reportingLoopActive = true;
// Stop the reporting loop so the Node.js process does not become a
// zombie waiting for the timers.
let stopReportingOnce = 0;
let stopReporting = () => {
if (stopReportingOnce++ > 0) { return; }
this._stopReportingLoop();
};
this._platform.onBeforeExit(stopReporting);
// Begin the asynchronous reporting loop
let loop = () => {
this._enqueueNextReport((err) => {
if (this._reportingLoopActive) {
loop();
}
});
};
const delay = Math.floor(Math.random() * this._options.delay_initial_report_millis);