-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathtrace-writer.ts
390 lines (355 loc) · 12.1 KB
/
trace-writer.ts
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
// Copyright 2015 Google LLC
//
// 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 gcpMetadata from 'gcp-metadata';
import {OutgoingHttpHeaders} from 'http';
import * as os from 'os';
import {Constants} from './constants';
import {Logger} from './logger';
import {SpanKind, Trace} from './trace';
import {TraceLabels} from './trace-labels';
import {Singleton} from './util';
import {
DecorateRequestOptions,
GoogleAuthOptions,
Service,
} from '@google-cloud/common';
import {GaxiosError} from 'gaxios';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pjson = require('../../package.json');
// TODO(kjin): This value should be exported from @g-c/c.
const NO_PROJECT_ID_TOKEN = '{{projectId}}';
const onUncaughtExceptionValues = ['ignore', 'flush', 'flushAndExit'];
const headers: OutgoingHttpHeaders = {};
headers[Constants.TRACE_AGENT_REQUEST_HEADER] = 1;
/* A list of scopes needed to operate with the trace API */
const SCOPES: string[] = ['https://www.googleapis.com/auth/trace.append'];
/* The API endpoint of the Stackdriver Trace service */
const TRACE_API_ENDPOINT = 'cloudtrace.googleapis.com';
export interface TraceWriterConfig {
authOptions: GoogleAuthOptions;
onUncaughtException: string;
bufferSize: number;
flushDelaySeconds: number;
stackTraceLimit: number;
maximumLabelValueSize: number;
serviceContext: {service?: string; version?: string; minorVersion?: string};
}
export interface LabelObject {
[key: string]: string;
}
export class TraceBuffer {
/**
* Buffered traces.
*/
private traces: Trace[] = [];
/**
* Number of buffered spans; this number must be at least as large as
* buffer.length.
*/
private numSpans = 0;
/**
* Add a new trace to the buffer.
* @param trace The trace to add.
*/
add(trace: Trace) {
this.traces.push(trace);
this.numSpans += trace.spans.length;
}
/**
* Gets the number of spans contained within buffered traces.
*/
getNumSpans() {
return this.numSpans;
}
/**
* Clears the buffer, returning its original contents.
*/
drain(): Trace[] {
const result = this.traces;
this.traces = [];
this.numSpans = 0;
return result;
}
}
/**
* A class representing a service that publishes traces in the background.
*/
export class TraceWriter extends Service {
/** Traces to be published */
protected buffer: TraceBuffer;
/** Default labels to be attached to written spans */
defaultLabels: LabelObject;
/** Reference to global unhandled exception handler */
private unhandledException?: () => void;
/** Whether the trace writer is active */
isActive: boolean;
/**
* Constructs a new TraceWriter instance.
* @param config A config object containing information about
* authorization credentials.
* @param logger The Trace Agent's logger object.
* @constructor
*/
constructor(
private readonly config: TraceWriterConfig,
private readonly logger: Logger
) {
super(
{
packageJson: pjson,
projectIdRequired: false,
apiEndpoint: TRACE_API_ENDPOINT,
baseUrl: `https://${TRACE_API_ENDPOINT}/v1`,
scopes: SCOPES,
},
config.authOptions
);
this.logger = logger;
this.buffer = new TraceBuffer();
this.defaultLabels = {};
this.isActive = true;
if (onUncaughtExceptionValues.indexOf(config.onUncaughtException) === -1) {
logger.error(
`TraceWriter#constructor: The value of config.onUncaughtException [${
config.onUncaughtException
}] should be one of [${onUncaughtExceptionValues.join(', ')}].`
);
// TODO(kjin): Either log an error or throw one, but not both
throw new Error('Invalid value for onUncaughtException configuration.');
}
const onUncaughtException = config.onUncaughtException;
if (onUncaughtException !== 'ignore') {
this.unhandledException = () => {
this.flushBuffer();
if (onUncaughtException === 'flushAndExit') {
setTimeout(() => {
// eslint-disable-next-line n/no-process-exit
process.exit(1);
}, 2000);
}
};
process.on('uncaughtException', this.unhandledException);
}
}
stop(): void {
this.isActive = false;
}
getConfig(): TraceWriterConfig {
return this.config;
}
async initialize(): Promise<void> {
// Schedule periodic flushing of the buffer, but only if we are able to get
// the project number (potentially from the network.)
const getProjectIdAndScheduleFlush = async () => {
try {
await this.getProjectId();
} catch (err) {
this.logger.error(
'TraceWriter#initialize: Unable to acquire the project number',
'automatically from the GCP metadata service. Please provide a',
'valid project ID as environmental variable GCLOUD_PROJECT, or',
`as config.projectId passed to start. Original error: ${err}`
);
throw err;
}
this.scheduleFlush();
};
// getProjectIdAndScheduleFlush has no return value, so no need to capture
// it on the left-hand side.
const [hostname, instanceId] = await Promise.all([
this.getHostname(),
this.getInstanceId(),
getProjectIdAndScheduleFlush(),
]);
const addDefaultLabel = (key: string, value: string | number) => {
this.defaultLabels[key] = `${value}`;
};
this.defaultLabels = {};
addDefaultLabel(
TraceLabels.AGENT_DATA,
`node ${pjson.name} v${pjson.version}`
);
addDefaultLabel(TraceLabels.GCE_HOSTNAME, hostname!);
if (instanceId) {
addDefaultLabel(TraceLabels.GCE_INSTANCE_ID, instanceId);
}
const moduleName = this.config.serviceContext.service || hostname;
addDefaultLabel(TraceLabels.GAE_MODULE_NAME, moduleName!);
const moduleVersion = this.config.serviceContext.version;
if (moduleVersion) {
addDefaultLabel(TraceLabels.GAE_MODULE_VERSION, moduleVersion);
const minorVersion = this.config.serviceContext.minorVersion;
if (minorVersion) {
let versionLabel = '';
if (moduleName !== 'default') {
versionLabel = moduleName + ':';
}
versionLabel += moduleVersion + '.' + minorVersion;
addDefaultLabel(TraceLabels.GAE_VERSION, versionLabel);
}
}
Object.freeze(this.defaultLabels);
}
private async getHostname(): Promise<string> {
try {
return await gcpMetadata.instance({property: 'hostname', headers});
} catch (err) {
if ((err as GaxiosError).code !== 'ENOTFOUND') {
// We are running on GCP.
this.logger.warn(
'TraceWriter#getHostname: Encountered an error while',
'retrieving GCE hostname from the GCP metadata service',
`(metadata.google.internal): ${err}`
);
}
return os.hostname();
}
}
private async getInstanceId(): Promise<number | null> {
try {
return await gcpMetadata.instance({property: 'id', headers});
} catch (err) {
if ((err as GaxiosError).code !== 'ENOTFOUND') {
// We are running on GCP.
this.logger.warn(
'TraceWriter#getInstanceId: Encountered an error while',
'retrieving GCE instance ID from the GCP metadata service',
`(metadata.google.internal): ${err}`
);
}
return null;
}
}
getProjectId() {
// super.getProjectId writes to projectId, but doesn't check it first
// before going through the flow of obtaining it. So we add that logic
// first.
if (this.projectId !== NO_PROJECT_ID_TOKEN) {
return Promise.resolve(this.projectId);
}
return super.getProjectId();
}
/**
* Queues a trace to be published. Spans with no end time are excluded.
*
* @param trace The trace to be queued.
*/
writeTrace(trace: Trace) {
const publishableSpans = trace.spans.filter(span => !!span.endTime);
publishableSpans.forEach(spanData => {
if (spanData.kind === SpanKind.RPC_SERVER) {
// Copy properties from the default labels.
Object.assign(spanData.labels, this.defaultLabels);
}
});
this.buffer.add({
traceId: trace.traceId,
projectId: trace.projectId,
spans: publishableSpans,
});
this.logger.info(
`TraceWriter#writeTrace: number of buffered spans = ${this.buffer.getNumSpans()}`
);
// Publish soon if the buffer is getting big
if (this.buffer.getNumSpans() >= this.config.bufferSize) {
this.logger.info('TraceWriter#writeTrace: Trace buffer full, flushing.');
setImmediate(() => this.flushBuffer());
}
}
/**
* Flushes the buffer of traces at a regular interval controlled by the
* flushDelay property of this TraceWriter's config.
*/
private scheduleFlush() {
this.logger.info('TraceWriter#scheduleFlush: Performing periodic flush.');
this.flushBuffer();
// Do it again after delay
if (this.isActive) {
// 'global.setTimeout' avoids TS2339 on this line.
// It helps disambiguate the Node runtime setTimeout function from
// WindowOrWorkerGlobalScope.setTimeout, which returns an integer.
global
.setTimeout(
this.scheduleFlush.bind(this),
this.config.flushDelaySeconds * 1000
)
.unref();
}
}
/**
* Serializes the buffered traces to be published asynchronously.
*/
private flushBuffer() {
// Privatize and clear the buffer.
const flushedTraces = this.buffer.drain();
if (flushedTraces.length === 0) {
return;
}
const afterProjectId = (projectId: string) => {
flushedTraces.forEach(trace => (trace.projectId = projectId));
this.logger.debug(
'TraceWriter#flushBuffer: Flushing traces',
flushedTraces
);
this.publish(JSON.stringify({traces: flushedTraces}));
};
// TODO(kjin): We should always be following the 'else' path.
// Any test that doesn't mock the Trace Writer will assume that traces get
// buffered synchronously. We need to refactor those tests to remove that
// assumption before we can make this fix.
if (this.projectId !== NO_PROJECT_ID_TOKEN) {
afterProjectId(this.projectId);
} else {
this.getProjectId().then(afterProjectId, () => {
// Because failing to get a project ID means that the trace agent will
// get disabled, there is a very small window for this code path to be
// taken. For this reason we don't do anything more complex than just
// notifying that we are dropping the current traces.
this.logger.info(
'TraceWriter#flushBuffer: No project ID, dropping traces.'
);
});
}
}
/**
* Publishes flushed traces to the network.
* @param json The stringified json representation of the queued traces.
*/
protected publish(json: string) {
const hostname = 'cloudtrace.googleapis.com';
const uri = `https://${hostname}/v1/projects/${this.projectId}/traces`;
const options: DecorateRequestOptions = {
method: 'PATCH',
uri,
body: json,
headers,
};
this.logger.info('TraceWriter#publish: Publishing to ' + uri);
this.request(options, (err, body?, response?) => {
const statusCode = response && response.statusCode;
if (err) {
this.logger.error(
`TraceWriter#publish: Received error ${
statusCode ? `with status code ${statusCode}` : ''
} while publishing traces to ${hostname}: ${err}`
);
} else {
this.logger.info(
`TraceWriter#publish: Published w/ status code: ${statusCode}`
);
}
});
}
}
export const traceWriter = new Singleton(TraceWriter);