forked from googleapis/cloud-trace-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
255 lines (221 loc) · 7.45 KB
/
index.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
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
'use strict';
var filesLoadedBeforeTrace = Object.keys(require.cache);
// Load continuation-local-storage first to ensure the core async APIs get
// patched before any user-land modules get loaded.
require('continuation-local-storage');
var common = require('@google-cloud/common');
var constants = require('./src/constants.js');
var gcpMetadata = require('gcp-metadata');
var semver = require('semver');
var traceUtil = require('./src/util.js');
var SpanData = require('./src/span-data.js');
var util = require('util');
var modulesLoadedBeforeTrace = [];
for (var i = 0; i < filesLoadedBeforeTrace.length; i++) {
var moduleName = traceUtil.packageNameFromPath(filesLoadedBeforeTrace[i]);
if (moduleName && moduleName !== '@google/cloud-trace' &&
modulesLoadedBeforeTrace.indexOf(moduleName) === -1) {
modulesLoadedBeforeTrace.push(moduleName);
}
}
var onUncaughtExceptionValues = ['ignore', 'flush', 'flushAndExit'];
/**
* Phantom implementation of the trace agent. This allows API users to decouple
* the enable/disable logic from the calls to the tracing API. The phantom API
* has a lower overhead than isEnabled checks inside the API functions.
* @private
*/
var phantomTraceAgent = {
startSpan: function() { return SpanData.nullSpan; },
endSpan: function(spanData) { spanData.close(); },
runInSpan: function(name, labels, fn) {
if (typeof(labels) === 'function') {
fn = labels;
}
fn(function() {});
},
runInRootSpan: function(name, labels, fn) {
if (typeof(labels) === 'function') {
fn = labels;
}
fn(function() {});
},
setTransactionName: function() {},
addTransactionLabel: function() {}
};
/** @private */
var agent = phantomTraceAgent;
var initConfig = function(projectConfig) {
var config = {};
util._extend(config, require('./config.js').trace);
util._extend(config, projectConfig);
if (process.env.hasOwnProperty('GCLOUD_TRACE_LOGLEVEL')) {
var envLogLevel = parseInt(process.env.GCLOUD_TRACE_LOGLEVEL, 10);
if (!isNaN(envLogLevel)) {
config.logLevel = envLogLevel;
} else {
console.error('Warning: Ignoring env var GCLOUD_TRACE_LOGLEVEL as it ' +
'contains an non-integer log level: ' +
process.env.GCLOUD_TRACE_LOGLEVEL);
}
}
if (process.env.hasOwnProperty('GCLOUD_PROJECT')) {
config.projectId = process.env.GCLOUD_PROJECT;
}
return config;
};
/**
* The singleton public agent. This is the public API of the module.
*/
var publicAgent = {
isActive: function() {
return agent !== phantomTraceAgent;
},
startSpan: function(name, labels) {
return agent.startSpan(name, labels);
},
endSpan: function(spanData, labels) {
return agent.endSpan(spanData, labels);
},
runInSpan: function(name, labels, fn) {
return agent.runInSpan(name, labels, fn);
},
runInRootSpan: function(name, labels, fn) {
return agent.runInRootSpan(name, labels, fn);
},
setTransactionName: function(name) {
return agent.setTransactionName(name);
},
addTransactionLabel: function(key, value) {
return agent.addTransactionLabel(key, value);
},
start: function(projectConfig) {
var config = initConfig(projectConfig);
if (this.isActive() && !config.forceNewAgent_) { // already started.
throw new Error('Cannot call start on an already started agent.');
}
if (!config.enabled) {
return this;
}
var logLevel = config.logLevel;
if (logLevel < 0) {
logLevel = 0;
} else if (logLevel >= common.logger.LEVELS.length) {
logLevel = common.logger.LEVELS.length - 1;
}
var logger = common.logger({
level: common.logger.LEVELS[logLevel],
tag: '@google/cloud-trace'
});
if (!semver.satisfies(process.versions.node, '>=0.12')) {
logger.error('Tracing is only supported on Node versions >=0.12');
return this;
}
if (config.projectId) {
logger.info('Locally provided ProjectId: ' + config.projectId);
}
if (onUncaughtExceptionValues.indexOf(config.onUncaughtException) === -1) {
logger.error('The value of onUncaughtException should be one of ',
onUncaughtExceptionValues);
throw new Error('Invalid value for onUncaughtException configuration.');
}
var headers = {};
headers[constants.TRACE_AGENT_REQUEST_HEADER] = 1;
if (modulesLoadedBeforeTrace.length > 0) {
logger.warn('Tracing might not work as the following modules ' +
'were loaded before the trace agent was initialized: ' +
JSON.stringify(modulesLoadedBeforeTrace));
}
if (typeof config.projectId === 'undefined') {
var that = this;
// Queue the work to acquire the projectId (potentially from the
// network.)
gcpMetadata.project({
property: 'project-id',
headers: headers
}, function(err, response, projectId) {
if (response && response.statusCode !== 200) {
if (response.statusCode === 503) {
err = new Error('Metadata service responded with a 503 status ' +
'code. This may be due to a temporary server error; please try ' +
'again later.');
} else {
err = new Error('Metadata service responded with the following ' +
'status code: ' + response.statusCode);
}
}
if (err) {
logger.error('Unable to acquire the project number from metadata ' +
'service. Please provide a valid project number as an env. ' +
'variable, or through config.projectId passed to start(). ' + err);
if (that.isActive()) {
agent.stop();
agent = phantomTraceAgent;
}
return;
}
config.projectId = projectId;
});
} else if (typeof config.projectId !== 'string') {
logger.error('config.projectId, if provided, must be a string. ' +
'Disabling trace agent.');
return this;
}
agent = require('./src/trace-agent.js').get(config, logger);
return this; // for chaining
},
get: function() {
if (this.isActive()) {
return this;
}
throw new Error('The agent must be initialized by calling start.');
},
/**
* For use in tests only.
* @private
*/
private_: function() { return agent; }
};
/**
* Start the Trace agent that will make your application available for
* tracing with Stackdriver Trace.
*
* @param {object=} config - Trace configuration
*
* @resource [Introductory video]{@link
* https://www.youtube.com/watch?v=NCFDqeo7AeY}
*
* @example
* trace.start();
*/
function start(config) {
publicAgent.start(config);
return publicAgent;
}
function get() {
return publicAgent.get();
}
global._google_trace_agent = publicAgent;
module.exports = {
start: start,
get: get
};
// If the module was --require'd from the command line, start the agent.
if (module.parent && module.parent.id === 'internal/preload') {
module.exports.start();
}