-
Notifications
You must be signed in to change notification settings - Fork 98
/
tracing.ts
200 lines (183 loc) · 6.39 KB
/
tracing.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
// Copyright 2018 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 {StackdriverFormat} from '@opencensus/propagation-stackdriver';
import * as path from 'path';
import {cls, TraceCLSConfig} from './cls';
import {OpenCensusPropagation, TracePolicy} from './config';
import {LEVELS, Logger} from './logger';
import {StackdriverTracer} from './trace-api';
import {pluginLoader, PluginLoaderConfig} from './trace-plugin-loader';
import {traceWriter, TraceWriterConfig} from './trace-writer';
import {BuiltinTracePolicy, TracePolicyConfig} from './tracing-policy';
import {Component, Forceable, packageNameFromPath, Singleton} from './util';
export type TopLevelConfig =
| Forceable<{
enabled: boolean;
logLevel: number;
disableUntracedModulesWarning: boolean;
clsConfig: Forceable<TraceCLSConfig>;
writerConfig: Forceable<TraceWriterConfig>;
pluginLoaderConfig: Forceable<PluginLoaderConfig>;
tracePolicyConfig: TracePolicyConfig;
overrides: {
tracePolicy?: TracePolicy;
propagation?: OpenCensusPropagation;
};
}>
| {
enabled: false;
};
/**
* A class that represents automatic tracing.
*/
export class Tracing implements Component {
/** A logger. */
private readonly logger: Logger;
/** The configuration object for this instance. */
private readonly config: Forceable<TopLevelConfig>;
/**
* Constructs a new Tracing instance.
* @param config The configuration for this instance.
* @param traceAgent An object representing the custom tracing API.
*/
constructor(
config: TopLevelConfig,
private readonly traceAgent: StackdriverTracer
) {
this.config = config;
let logLevel = config.enabled ? config.logLevel : 0;
// Clamp the logger level.
const defaultLevels = LEVELS;
if (logLevel < 0) {
logLevel = 0;
} else if (logLevel >= defaultLevels.length) {
logLevel = defaultLevels.length - 1;
}
this.logger = new Logger({
level: defaultLevels[logLevel],
tag: '@google-cloud/trace-agent',
});
}
/**
* Logs an warning message detailing the list of modules that were loaded
* before the Trace Agent. Loading these modules before the Trace Agent may
* prevent us from monkeypatching those modules for automatic tracing.
* @param filesLoadedBeforeTrace The list of files that were loaded using
* require() before the Stackdriver Trace Agent was required.
*/
logModulesLoadedBeforeTrace(filesLoadedBeforeTrace: string[]) {
const modulesLoadedBeforeTrace: string[] = [];
const traceModuleName = path.join('@google-cloud', 'trace-agent');
for (let i = 0; i < filesLoadedBeforeTrace.length; i++) {
const moduleName = packageNameFromPath(filesLoadedBeforeTrace[i]);
if (
moduleName &&
moduleName !== traceModuleName &&
modulesLoadedBeforeTrace.indexOf(moduleName) === -1
) {
modulesLoadedBeforeTrace.push(moduleName);
}
}
if (modulesLoadedBeforeTrace.length > 0) {
this.logger.warn(
'StackdriverTracer#start: Tracing might not work as the following modules',
'were loaded before the trace agent was initialized:',
`[${modulesLoadedBeforeTrace.sort().join(', ')}]`
);
}
}
/**
* Enables automatic tracing support and the custom span API.
*/
enable(): void {
if (!this.config.enabled) {
return;
}
// Initialize context propagation mechanism configuration.
try {
traceWriter.create(this.config.writerConfig, this.logger);
cls.create(this.config.clsConfig, this.logger);
} catch (e) {
this.logger.error(
'StackdriverTracer#start: Disabling the Trace Agent for the',
`following reason: ${(e as Error).message}`
);
this.disable();
return;
}
traceWriter
.get()
.initialize()
.catch(err => {
this.logger.error(
'StackdriverTracer#start: Disabling the Trace Agent for the',
`following reason: ${err.message}`
);
this.disable();
});
cls.get().enable();
const tracePolicy =
this.config.overrides.tracePolicy ||
new BuiltinTracePolicy(this.config.tracePolicyConfig);
const propagation =
this.config.overrides.propagation || new StackdriverFormat();
const tracerComponents = {logger: this.logger, tracePolicy, propagation};
this.traceAgent.enable(
this.config.pluginLoaderConfig.tracerConfig,
tracerComponents
);
pluginLoader
.create(this.config.pluginLoaderConfig, tracerComponents)
.activate();
// Require http and https again, now that the plugin loader is activated.
// This forces them to be patched.
require('http');
require('https');
if (
typeof this.config.writerConfig.authOptions.projectId !== 'string' &&
typeof this.config.writerConfig.authOptions.projectId !== 'undefined'
) {
this.logger.error(
'StackdriverTracer#start: config.projectId, if provided, must be a string.',
'Disabling trace agent.'
);
this.disable();
return;
}
// Make trace agent available globally without requiring package
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any)._google_trace_agent = this.traceAgent;
this.logger.info('StackdriverTracer#start: Trace Agent activated.');
}
/**
* Disables automatic tracing support. This disables the publicly exposed
* custom span API, as well as any instances passed to plugins. This also
* prevents the Trace Writer from publishing additional traces.
*/
disable() {
if (pluginLoader.exists()) {
pluginLoader.get().deactivate();
}
if (this.traceAgent.isActive()) {
this.traceAgent.disable();
}
if (cls.exists()) {
cls.get().disable();
}
if (traceWriter.exists()) {
traceWriter.get().stop();
}
}
}
export const tracing = new Singleton(Tracing);