This repository has been archived by the owner on Sep 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 133
/
tracer.js
355 lines (326 loc) Β· 13.4 KB
/
tracer.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
// @flow
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under
// the License.
import * as opentracing from 'opentracing';
import { Tags as otTags } from 'opentracing';
import os from 'os';
import { v4 as uuidv4 } from 'uuid';
import BaggageSetter from './baggage/baggage_setter';
import DefaultBaggageRestrictionManager from './baggage/default_baggage_restriction_manager';
import * as constants from './constants';
import NullLogger from './logger';
import Metrics from './metrics/metrics';
import NoopMetricFactory from './metrics/noop/metric_factory';
import BinaryCodec from './propagators/binary_codec';
import TextMapCodec from './propagators/text_map_codec';
import NoopReporter from './reporters/noop_reporter';
import ConstSampler from './samplers/const_sampler';
import { adaptSamplerOrThrow } from './samplers/_adapt_sampler';
import Span from './span';
import SpanContext from './span_context';
import DefaultThrottler from './throttler/default_throttler';
import Utils from './util';
import version from './version';
export default class Tracer {
_serviceName: string;
_reporter: Reporter;
_sampler: Sampler;
_logger: NullLogger;
_tags: any;
_injectors: any;
_extractors: any;
_metrics: any;
_baggageSetter: BaggageSetter;
_debugThrottler: Throttler & ProcessSetter;
_process: Process;
_traceId128bit: boolean;
_shareRpcSpan: boolean;
/**
* @param {String} [serviceName] - name of the current service or application.
* @param {Object} [reporter] - reporter used to submit finished spans to Jaeger backend.
* @param {Object} [sampler] - sampler used to decide if trace should be sampled when starting a new one.
* @param {Object} [options] - the fields to set on the newly created span.
* @param {Object} [options.tags] - set of key-value pairs which will be set
* as process-level tags on the Tracer itself.
* @param {Object} [options.metrics] - instance of the Metrics class from ./metrics/metrics.js.
* @param {Object} [options.logger] - a logger matching NullLogger API from ./logger.js.
* @param {Object} [options.baggageRestrictionManager] - a baggageRestrictionManager matching
* @param {Object} [options.contextKey] - a name of the key to extract/inject context from headers
* @param {Object} [options.baggagePrefix] - a name of the context baggage key prefix
* @param {boolean} [options.traceId128bit] - generate root span with a 128bit traceId.
* @param {boolean} [options.shareRpcSpan] - share spanIds for rpc servers.
* BaggageRestrictionManager API from ./baggage.js.
*/
constructor(
serviceName: string,
reporter: Reporter = new NoopReporter(),
sampler: LegacySamplerV1 | Sampler = new ConstSampler(false),
options: any = {}
) {
this._tags = options.tags ? Utils.clone(options.tags) : {};
this._tags[constants.JAEGER_CLIENT_VERSION_TAG_KEY] = `Node-${version}`;
this._tags[constants.TRACER_HOSTNAME_TAG_KEY] =
this._tags[constants.TRACER_HOSTNAME_TAG_KEY] || os.hostname();
this._tags[constants.PROCESS_IP] = this._tags[constants.PROCESS_IP] || Utils.myIp();
this._metrics = options.metrics || new Metrics(new NoopMetricFactory());
this._serviceName = serviceName;
this._reporter = reporter;
// TODO(joe): verify we want to throw if the sampler is invalid
this._sampler = adaptSamplerOrThrow(sampler);
this._logger = options.logger || new NullLogger();
this._baggageSetter = new BaggageSetter(
options.baggageRestrictionManager || new DefaultBaggageRestrictionManager(),
this._metrics
);
this._debugThrottler = options.debugThrottler || new DefaultThrottler(false);
this._injectors = {};
this._extractors = {};
let codecOptions = {
contextKey: options.contextKey || null,
baggagePrefix: options.baggagePrefix || null,
urlEncoding: false,
metrics: this._metrics,
};
let textCodec = new TextMapCodec(codecOptions);
this.registerInjector(opentracing.FORMAT_TEXT_MAP, textCodec);
this.registerExtractor(opentracing.FORMAT_TEXT_MAP, textCodec);
codecOptions.urlEncoding = true;
let httpCodec = new TextMapCodec(codecOptions);
this.registerInjector(opentracing.FORMAT_HTTP_HEADERS, httpCodec);
this.registerExtractor(opentracing.FORMAT_HTTP_HEADERS, httpCodec);
let binaryCodec = new BinaryCodec();
this.registerInjector(opentracing.FORMAT_BINARY, binaryCodec);
this.registerExtractor(opentracing.FORMAT_BINARY, binaryCodec);
const uuid = uuidv4();
this._tags[constants.TRACER_CLIENT_ID_TAG_KEY] = uuid;
this._process = {
serviceName: serviceName,
tags: Utils.convertObjectToTags(this._tags),
uuid: uuid,
};
this._debugThrottler.setProcess(this._process);
// TODO update reporter to implement ProcessSetter
this._reporter.setProcess(this._process.serviceName, this._process.tags);
this._traceId128bit = options.traceId128bit;
this._shareRpcSpan = options.shareRpcSpan;
}
_startInternalSpan(
spanContext: SpanContext,
operationName: string,
startTime: number,
userTags: ?{},
internalTags: ?{},
references: Array<Reference>,
hadParent: boolean,
isRpcServer: boolean
): Span {
const span = new Span(this, operationName, spanContext, startTime, references);
if (!span._spanContext.samplingFinalized) {
const decision = this._sampler.onCreateSpan(span);
span._applySamplingDecision(decision);
}
if (userTags) {
span.addTags(userTags);
}
if (internalTags) {
span._appendTags(internalTags); // no need to run internal tags through sampler
}
// emit metrics
if (span.context().isSampled()) {
this._metrics.spansStartedSampled.increment(1);
if (!hadParent) {
this._metrics.tracesStartedSampled.increment(1);
} else if (isRpcServer) {
this._metrics.tracesJoinedSampled.increment(1);
}
} else {
this._metrics.spansStartedNotSampled.increment(1);
if (!hadParent) {
this._metrics.tracesStartedNotSampled.increment(1);
} else if (isRpcServer) {
this._metrics.tracesJoinedNotSampled.increment(1);
}
}
return span;
}
_report(span: Span): void {
this._metrics.spansFinished.increment(1);
this._reporter.report(span);
}
registerInjector(format: string, injector: Injector): void {
this._injectors[format] = injector;
}
registerExtractor(format: string, extractor: Extractor): void {
this._extractors[format] = extractor;
}
/**
* The method for creating a root or child span.
*
* @param {string} operationName - the name of the operation.
* @param {object} [options] - the fields to set on the newly created span.
* @param {string} options.operationName - the name to use for the newly
* created span. Required if called with a single argument.
* @param {SpanContext} [options.childOf] - a parent SpanContext (or Span,
* for convenience) that the newly-started span will be the child of
* (per REFERENCE_CHILD_OF). If specified, `fields.references` must
* be unspecified.
* @param {array} [options.references] - an array of Reference instances,
* each pointing to a causal parent SpanContext. If specified,
* `fields.childOf` must be unspecified.
* @param {object} [options.tags] - set of key-value pairs which will be set
* as tags on the newly created Span. Ownership of the object is
* passed to the created span for efficiency reasons (the caller
* should not modify this object after calling startSpan).
* @param {number} [options.startTime] - a manually specified start time for
* the created Span object. The time should be specified in
* milliseconds as Unix timestamp. Decimal value are supported
* to represent time values with sub-millisecond accuracy.
* @return {Span} - a new Span object.
**/
startSpan(operationName: string, options: ?startSpanOptions): Span {
options = options || {};
let references = options.references || [];
let userTags = options.tags;
let startTime = options.startTime || this.now();
// followsFromIsParent is used to ensure that CHILD_OF reference is preferred
// as a parent even if it comes after FOLLOWS_FROM reference.
let followsFromIsParent = false;
let parent: ?SpanContext = options.childOf instanceof Span ? options.childOf.context() : options.childOf;
// If there is no childOf in options, then search list of references
for (let i = 0; i < references.length; i++) {
let ref: Reference = references[i];
if (ref.type() === opentracing.REFERENCE_CHILD_OF) {
if (!parent || followsFromIsParent) {
parent = ref.referencedContext();
break;
}
} else if (ref.type() === opentracing.REFERENCE_FOLLOWS_FROM) {
if (!parent) {
parent = ref.referencedContext();
followsFromIsParent = true;
}
}
}
let ctx: SpanContext;
let internalTags: any = {};
let hasValidParent = false;
const isRpcServer = Boolean(userTags && userTags[otTags.SPAN_KIND] === otTags.SPAN_KIND_RPC_SERVER);
if (!parent || !parent.isValid) {
if (this._traceId128bit) {
let randomId = Utils.getRandom128();
ctx = new SpanContext(randomId, randomId.slice(-8));
} else {
let randomId = Utils.getRandom64();
ctx = new SpanContext(randomId, randomId);
}
if (parent) {
// fake parent, doesn't contain a parent trace-id, but may contain debug-id/baggage
if (parent.isDebugIDContainerOnly() && this._isDebugAllowed(operationName)) {
ctx._setSampled(true);
ctx._setDebug(true);
internalTags[constants.JAEGER_DEBUG_HEADER] = parent.debugId;
}
// baggage that could have been passed via `jaeger-baggage` header
ctx.baggage = parent.baggage;
}
} else {
hasValidParent = true;
let spanId = this._shareRpcSpan && isRpcServer ? parent.spanId : Utils.getRandom64();
ctx = parent._makeChildContext(spanId);
if (this._shareRpcSpan && isRpcServer) {
ctx.parentId = parent.parentId;
}
if (parent.isRemote()) {
ctx.finalizeSampling(); // will finalize sampling for all spans sharing this traceId
}
}
return this._startInternalSpan(
ctx,
operationName,
startTime,
userTags,
internalTags,
references,
hasValidParent,
isRpcServer
);
}
/**
* Saves the span context into the carrier object for various formats, and encoders.
*
* @param {SpanContext} spanContext - the SpanContext to inject into the
* carrier object. As a convenience, a Span instance may be passed
* in instead (in which case its .context() is used for the
* inject()).
* @param {string} format - the format of the carrier.
* @param {any} carrier - see the documentation for the chosen `format`
* for a description of the carrier object.
**/
inject(spanContext: SpanContext | Span, format: string, carrier: any): void {
if (!spanContext) {
return;
}
const injector = this._injectors[format];
if (!injector) {
throw new Error(`Unsupported format: ${format}`);
}
const _context = spanContext instanceof Span ? spanContext.context() : spanContext;
injector.inject(_context, carrier);
}
/**
* Responsible for extracting a span context from various serialized formats.
*
* @param {string} format - the format of the carrier.
* @param {any} carrier - the type of the carrier object is determined by
* the format.
* @return {SpanContext}
* The extracted SpanContext, or null if no such SpanContext could
* be found in `carrier`
*/
extract(format: string, carrier: any): SpanContext {
let extractor = this._extractors[format];
if (!extractor) {
throw new Error(`Unsupported format: ${format}`);
}
const spanContext = extractor.extract(carrier);
if (spanContext) {
spanContext._setRemote(true);
}
return spanContext;
}
/**
* Closes the tracer, flushes spans, and executes any callbacks if necessary.
*
* @param {Function} [callback] - a callback that runs after the tracer has been closed.
**/
close(callback: Function): void {
let reporter = this._reporter;
this._reporter = new NoopReporter();
reporter.close(() => {
this._sampler.close(callback);
});
this._debugThrottler.close();
}
/**
* Returns the current timestamp in milliseconds since the Unix epoch.
* Fractional values are allowed so that timestamps with sub-millisecond
* accuracy can be represented.
*/
now(): number {
// TODO investigate process.hrtime; verify it is available in all Node versions.
// http://stackoverflow.com/questions/11725691/how-to-get-a-microtime-in-node-js
return Date.now();
}
_isDebugAllowed(operation: string): boolean {
return this._debugThrottler.isAllowed(operation);
}
}