-
Notifications
You must be signed in to change notification settings - Fork 384
/
http.js
713 lines (617 loc) · 21.9 KB
/
http.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
'use strict'
const shimmer = require('../../shimmer')
const logger = require('../../logger').child({component: 'http'})
const recordWeb = require('../../metrics/recorders/http')
const hashes = require('../../util/hashes')
const cat = require('../../util/cat')
const instrumentOutbound = require('./http-outbound')
const util = require('util')
const url = require('url')
const urltils = require('../../util/urltils')
const properties = require('../../util/properties')
const psemver = require('../../util/process-version')
const headerAttributes = require('../../header-attributes')
const headerProcessing = require('../../header-processing')
const NAMES = require('../../metrics/names')
const DESTS = require('../../config/attribute-filter').DESTINATIONS
/*
*
* CONSTANTS
*
*/
const SHOULD_WRAP_HTTPS = psemver.satisfies('>=9.0.0 || 8.9.0')
const NR_CONNECTION_PROP = '__NR__connection'
const NEWRELIC_ID_HEADER = 'x-newrelic-id'
const NEWRELIC_APP_DATA_HEADER = 'x-newrelic-app-data'
const NEWRELIC_TRANSACTION_HEADER = 'x-newrelic-transaction'
const NEWRELIC_SYNTHETICS_HEADER = 'x-newrelic-synthetics'
const TRANSACTION_INFO_KEY = '__NR_transactionInfo'
// For incoming requests this instrumentation functions by wrapping
// `http.createServer` and `http.Server#addListener`. The former merely sets the
// agent dispatcher to 'http' and the latter wraps any event handlers bound to
// `request`.
//
// The `request` event listener wrapper creates a transaction proxy which will
// start a new transaction whenever a new request comes in. It also scans the
// headers of the incoming request looking for CAT and synthetics headers.
function wrapEmitWithTransaction(agent, emit, isHTTPS) {
const tracer = agent.tracer
const transport = isHTTPS ? 'HTTPS' : 'HTTP'
let serverPort = null
return tracer.transactionProxy(function wrappedHandler(evnt, request, response) {
var transaction = tracer.getTransaction()
if (!transaction) return emit.apply(this, arguments)
transaction.nameState.setPrefix(NAMES.NODEJS.PREFIX)
transaction.nameState.setDelimiter(NAMES.ACTION_DELIMITER)
// Store the transaction information on the request and response.
const txInfo = storeTxInfo(transaction, request, response)
// Hook for web framework instrumentations that don't have easy access to
// the request entry point.
if (properties.hasOwn(this, '__NR_onRequestStarted')) {
this.__NR_onRequestStarted(request, response)
}
if (request) {
initializeRequest(transaction, request)
}
// Create the transaction segment using the request URL for now. Once a
// better name can be determined this segment will be renamed to that.
const segment = tracer.createSegment(request.url, recordWeb)
segment.start()
if (txInfo) {
// Seed segment stack to enable parenting logic leveraged by
// web framework instrumentations.
txInfo.segmentStack.push(segment)
}
transaction.type = 'web'
transaction.baseSegment = segment
/* Needed for Connect and Express middleware that monkeypatch request
* and response via listeners.
*/
tracer.bindEmitter(request, segment)
tracer.bindEmitter(response, segment)
// the error tracer needs a URL for tracing, even though naming overwrites
transaction.parsedUrl = url.parse(request.url, true)
transaction.url = transaction.parsedUrl.pathname
transaction.verb = request.method
// URL is sent as an agent attribute with transaction events
transaction.trace.attributes.addAttribute(
DESTS.TRANS_EVENT | DESTS.ERROR_EVENT,
'request.uri',
transaction.url
)
// store the port on which this transaction runs
if (this.address instanceof Function) {
var address = this.address()
if (address) {
serverPort = address.port
}
}
transaction.port = serverPort
// need to set any config-driven names early for RUM
logger.trace({url: request.url, transaction: transaction.id},
'Applying user naming rules for RUM.')
transaction.applyUserNamingRules(request.url)
const queueTimeStamp = headerProcessing.getQueueTime(logger, request.headers)
if (queueTimeStamp) {
transaction.queueTime = Date.now() - queueTimeStamp
}
if (agent.config.distributed_tracing.enabled) {
// Node http headers are automatically lowercase
transaction.acceptDistributedTraceHeaders(transport, request.headers)
} else if (agent.config.cross_application_tracer.enabled) {
var encKey = agent.config.encoding_key
var incomingCatId = request.headers[NEWRELIC_ID_HEADER]
var obfTransaction = request.headers[NEWRELIC_TRANSACTION_HEADER]
var synthHeader = request.headers[NEWRELIC_SYNTHETICS_HEADER]
if (encKey) {
cat.handleCatHeaders(incomingCatId, obfTransaction, encKey, transaction)
if (transaction.incomingCatId) {
logger.trace('Got inbound request CAT headers in transaction %s',
transaction.id)
}
if (synthHeader && agent.config.trusted_account_ids) {
handleSyntheticsHeader(
synthHeader,
encKey,
agent.config.trusted_account_ids,
transaction
)
}
}
}
function instrumentedFinish() {
// Remove listeners so this doesn't get called twice.
response.removeListener('finish', instrumentedFinish)
request.removeListener('aborted', instrumentedFinish)
// Naming must happen before the segment and transaction are ended,
// because metrics recording depends on naming's side effects.
transaction.finalizeNameFromUri(transaction.parsedUrl, response.statusCode)
if (response) {
if (response.statusCode != null) {
var responseCode = String(response.statusCode)
transaction.trace.attributes.addAttribute(
DESTS.TRANS_COMMON,
'httpResponseCode',
responseCode
)
if (/^\d+$/.test(responseCode)) {
transaction.trace.attributes.addAttribute(
DESTS.TRANS_COMMON,
'response.status',
responseCode
)
}
}
if (response.statusMessage !== undefined) {
transaction.trace.attributes.addAttribute(
DESTS.TRANS_COMMON,
'httpResponseMessage',
response.statusMessage
)
}
var headers = response.getHeaders()
if (headers) {
headerAttributes.collectResponseHeaders(headers, transaction)
}
}
// And we are done! End the segment and transaction.
segment.end()
transaction.end()
}
response.once('finish', instrumentedFinish)
request.once('aborted', instrumentedFinish)
return tracer.bindFunction(emit, segment).apply(this, arguments)
})
}
function storeTxInfo(transaction, request, response) {
if (!request || !response) {
logger.debug('Missing request or response object! Not storing transaction info.')
return
}
var hideInternal = transaction.agent.config.transaction_tracer.hide_internals
var txInfo = {
transaction: transaction,
segmentStack: [],
errorHandled: false,
error: null
}
if (hideInternal) {
properties.setInternal(request, TRANSACTION_INFO_KEY, txInfo)
properties.setInternal(response, TRANSACTION_INFO_KEY, txInfo)
} else {
request[TRANSACTION_INFO_KEY] = response[TRANSACTION_INFO_KEY] = txInfo
}
logger.trace(
'Stored transaction %s information on request and response',
transaction.id
)
return txInfo
}
function initializeRequest(transaction, request) {
headerAttributes.collectRequestHeaders(request.headers, transaction)
if (request.method != null) {
transaction.trace.attributes.addAttribute(
DESTS.TRANS_COMMON,
'request.method',
request.method
)
transaction.nameState.setVerb(request.method)
}
}
function wrapResponseEnd(agent, proto) {
var tracer = agent.tracer
// On end, we must freeze the current name state to maintain the route that
// responded and also end the current segment (otherwise it may become truncated).
shimmer.wrapMethod(proto, 'Response.prototype', 'end', function wrapResEnd(end) {
if (typeof end !== 'function') {
logger.debug('Response#end is not a function?')
return end
}
return function wrappedResEnd() {
var txInfo = this && this[TRANSACTION_INFO_KEY]
if (!txInfo) {
return end.apply(this, arguments)
}
// If an error happend, add it to the aggregator.
if (txInfo.error) {
if (!txInfo.errorHandled || urltils.isError(agent.config, this.statusCode)) {
agent.errors.add(txInfo.transaction, txInfo.error)
}
}
// End all the segments leading up to and including this one.
for (var i = txInfo.segmentStack.length - 1; i >= 0; --i) {
txInfo.segmentStack[i].end()
}
var segment = tracer.getSegment()
if (segment) {
segment.end()
}
// Freeze the name state to prevent further changes.
txInfo.transaction.nameState.freeze()
return end.apply(this, arguments)
}
})
}
// CAT this wont be used unless CAT is enabled, see below where we actually do
// the shimmer stuff if you'd like to verify.
function wrapWriteHead(agent, writeHead) {
return function wrappedWriteHead() {
var transaction = agent.tracer.getTransaction()
if (!transaction) {
logger.trace('No transaction - not adding response CAT headers')
return writeHead.apply(this, arguments)
}
if (transaction.syntheticsHeader) {
this.setHeader(NEWRELIC_SYNTHETICS_HEADER, transaction.syntheticsHeader)
}
if (!transaction.incomingCatId) {
logger.trace('No incoming CAT ID - not adding response CAT headers')
return writeHead.apply(this, arguments)
}
if (!agent.config.trusted_account_ids) {
logger.trace(
'No account IDs in config.trusted_account_ids - not adding response CAT headers'
)
return writeHead.apply(this, arguments)
}
var accountId = transaction.incomingCatId.split('#')[0]
accountId = parseInt(accountId, 10)
if (agent.config.trusted_account_ids.indexOf(accountId) === -1) {
logger.trace(
'Request from untrusted account id: %s - not adding response CAT headers',
accountId
)
return writeHead.apply(this, arguments)
}
// Not sure this could ever happen, but should guard against it anyway
// otherwise exception we blow up the user's app.
if (!agent.config.cross_process_id || !agent.config.encoding_key) {
logger.trace(
'Managed to have %s but not cross_process_id (%s) or encoding_key (%s) - %s',
'agent.config.trusted_account_ids',
agent.config.cross_process_id,
agent.config.encoding_key,
'not adding response CAT headers'
)
return writeHead.apply(this, arguments)
}
// -1 means no content length header was sent. We should only send this
// value in the appData if the header is set.
var contentLength = -1
var new_headers = arguments[arguments.length - 1]
if (typeof new_headers === 'object') {
contentLength = headerProcessing.getContentLengthFromHeaders(new_headers)
}
const currentHeaders = this.getHeaders()
if (contentLength === -1 && currentHeaders) {
contentLength = headerProcessing.getContentLengthFromHeaders(currentHeaders)
}
// Stored on the tx so we can push a metric with this time instead of
// actual duration.
transaction.catResponseTime = transaction.timer.getDurationInMillis()
var appData = null
var txName = transaction.getFullName() || ''
try {
appData = JSON.stringify([
agent.config.cross_process_id, // cross_process_id
txName, // transaction name
transaction.queueTime / 1000, // queue time (s)
transaction.catResponseTime / 1000, // response time (s)
contentLength, // content length (if content-length header is also being sent)
transaction.id, // TransactionGuid
false // force a transaction trace to be recorded
])
} catch (err) {
logger.trace(
err,
'Failed to serialize transaction: %s - not adding CAT response headers',
txName
)
return writeHead.apply(this, arguments)
}
var encKey = agent.config.encoding_key
var obfAppData = hashes.obfuscateNameUsingKey(appData, encKey)
this.setHeader(NEWRELIC_APP_DATA_HEADER, obfAppData)
logger.trace('Added outbound response CAT headers in transaction %s', transaction.id)
return writeHead.apply(this, arguments)
}
}
function wrapRequest(agent, request) {
return function wrappedRequest() {
let _url
let options
let cb
if (
typeof arguments[0] === "string" ||
(global.URL && arguments[0] instanceof global.URL)
) {
_url = arguments[0]
if (arguments[2]) {
options = arguments[1]
cb = arguments[2]
} else {
cb = arguments[1]
}
} else {
options = arguments[0]
cb = arguments[1]
}
// Don't pollute metrics and calls with NR connections
const internalOnly = options && options[NR_CONNECTION_PROP]
if (internalOnly) {
delete options[NR_CONNECTION_PROP]
}
const reqArgs = _url ? [_url, options, cb] : [options, cb]
// If this is not a request we're recording, exit early.
const transaction = agent.tracer.getTransaction()
if (!transaction || internalOnly) {
if (!internalOnly && logger.traceEnabled()) {
const logOpts = typeof options === 'string' ? url.parse(options) : options
logger.trace(
'No transaction, not recording external to %s:%s',
logOpts.hostname || logOpts.host,
logOpts.port
)
}
return request.apply(this, reqArgs)
}
const args = agent.tracer.slice(reqArgs)
const context = this
// hostname & port logic pulled directly from node's 0.10 lib/http.js
return instrumentOutbound(agent, _url, options, function makeRequest(opts) {
if (_url) {
args[1] = opts
} else {
args[0] = opts
}
return request.apply(context, args)
})
}
}
function wrapLegacyRequest(agent, request) {
return function wrappedLegacyRequest(method, path, headers) {
var makeRequest = request.bind(this, method, path, headers)
if (agent.tracer.getTransaction()) {
return instrumentOutbound(agent, undefined, this, makeRequest)
}
logger.trace('No transaction, not recording external to %s:%s', this.host, this.port)
return makeRequest()
}
}
function wrapLegacyClient(agent, proto) {
shimmer.wrapMethod(
proto,
'http.Client.prototype',
'request',
wrapLegacyRequest.bind(null, agent)
)
}
module.exports = function initialize(agent, http, moduleName) {
if (!http) {
logger.debug('Did not get http module, not instrumenting!')
return false
}
const IS_HTTPS = moduleName === 'https'
// FIXME: will this ever not be called?
shimmer.wrapMethod(http, 'http', 'createServer', function cb_wrapMethod(createServer) {
return function setDispatcher(requestListener) { // eslint-disable-line no-unused-vars
agent.environment.setDispatcher('http')
return createServer.apply(this, arguments)
}
})
// It's not a great idea to monkeypatch EventEmitter methods given how hot
// they are, but this method is simple and works with all versions of node
// supported by the module.
shimmer.wrapMethod(
http.Server && http.Server.prototype,
'http.Server.prototype',
'emit',
function wrapEmit(emit) {
var txStarter = wrapEmitWithTransaction(agent, emit, IS_HTTPS)
return function wrappedEmit(evnt) {
if (evnt === 'request') {
return txStarter.apply(this, arguments)
}
return emit.apply(this, arguments)
}
}
)
wrapResponseEnd(agent, http.ServerResponse && http.ServerResponse.prototype)
// If CAT is enabled we'll wrap `writeHead` to inject our headers.
if (agent.config.cross_application_tracer.enabled) {
shimmer.wrapMethod(
http.ServerResponse && http.ServerResponse.prototype,
'http.ServerResponse.prototype',
'writeHead',
wrapWriteHead.bind(null, agent)
)
}
var agentProto = http && http.Agent && http.Agent.prototype
// As of node 0.8, http.request() is the right way to originate outbound
// requests. From 0.11 until 9, the `https` module simply called through to
// the `http` methods, so to prevent double-instrumenting we need to check
// what module we're instrumenting and what version of Node we're on. This
// change originally also appeared in 8.9.0 but was reverted in 8.9.1.
//
// TODO: Remove `SHOULD_WRAP_HTTPS` after deprecating Node <9.
if (SHOULD_WRAP_HTTPS) {
shimmer.wrapMethod(
http,
'http',
'request',
wrapRequest.bind(null, agent)
)
shimmer.wrapMethod(
http,
'http',
'get',
wrapRequest.bind(null, agent)
)
}
shimmer.wrapMethod(
agentProto,
'http.Agent.prototype',
'createConnection',
function wrapCreateConnection(original) {
return function wrappedCreateConnection() {
if (!agent.getTransaction()) {
return original.apply(this, arguments)
}
var segment = agent.tracer.createSegment('http.Agent#createConnection')
var args = agent.tracer.slice(arguments)
if (typeof args[1] === 'function') {
args[1] = agent.tracer.bindFunction(args[1], segment, true)
}
var sock = agent.tracer.bindFunction(original, segment, true).apply(this, args)
return sock
}
}
)
// http.Client is deprecated, but still in use
// TODO: Remove this once Node <7 is deprecated.
var DeprecatedClient, deprecatedCreateClient
function clearGetters() {
if (DeprecatedClient) {
delete http.Client
http.Client = DeprecatedClient
}
if (deprecatedCreateClient) {
delete http.createClient
http.createClient = deprecatedCreateClient
}
}
// TODO: Remove this once Node <7 is deprecated.
DeprecatedClient = shimmer.wrapDeprecated(
http,
'http',
'Client',
{
get: function get() {
var example = new DeprecatedClient(80, 'localhost')
wrapLegacyClient(agent, example.constructor.prototype)
clearGetters()
return DeprecatedClient
},
set: function set(NewClient) {
DeprecatedClient = NewClient
}
}
)
// TODO: Remove this once Node <7 is deprecated.
deprecatedCreateClient = shimmer.wrapDeprecated(
http,
'http',
'createClient',
{
get: function get() {
var example = deprecatedCreateClient(80, 'localhost')
wrapLegacyClient(agent, example.constructor.prototype)
clearGetters()
return deprecatedCreateClient
},
set: function set(newCreateClient) {
deprecatedCreateClient = newCreateClient
}
}
)
}
/**
* Take the X-NewRelic-Synthetics header and apply any appropriate data to the
* transaction for later use. This is the gate keeper for attributes being
* added onto the transaction object for synthetics.
*
* @param {string} header - The raw X-NewRelic-Synthetics header
* @param {string} encKey - Encoding key handed down from the server
* @param {Array.<number>} trustedIds - Array of accounts to trust the header from.
* @param {Transaction} transaction - Where the synthetics data is attached to.
*/
function handleSyntheticsHeader(header, encKey, trustedIds, transaction) {
var synthData = parseSyntheticsHeader(header, encKey, trustedIds)
if (!synthData) {
return
}
transaction.syntheticsData = synthData
transaction.syntheticsHeader = header
}
/**
* Parse out and verify the the pieces of the X-NewRelic-Synthetics header.
*
* @param {string} header - The raw X-NewRelic-Synthetics header
* @param {string} encKey - Encoding key handed down from the server
* @param {Array.<number>} trustedIds - Array of accounts to trust the header from.
* @return {Object|null} - On successful parse and verification an object of
* synthetics data is returned, otherwise null is
* returned.
*/
function parseSyntheticsHeader(header, encKey, trustedIds) {
// Eagerly declare this object because we know what it should look like and
// can use that for header verification.
var parsedData = {
version: null,
accountId: null,
resourceId: null,
jobId: null,
monitorId: null
}
var synthData = null
try {
synthData = JSON.parse(
hashes.deobfuscateNameUsingKey(header, encKey)
)
} catch (e) {
logger.trace(e, 'Got unparsable synthetics header: %s', header)
return
}
if (!util.isArray(synthData)) {
logger.trace(
'Synthetics data is not an array: %s (%s)',
synthData,
typeof synthData
)
return
}
if (synthData.length < Object.keys(parsedData).length) {
logger.trace(
'Synthetics header length is %s, expected at least %s',
synthData.length,
Object.keys(parsedData).length
)
}
parsedData.version = synthData[0]
if (parsedData.version !== 1) {
logger.trace(
'Synthetics header version is not 1, got: %s (%s)',
parsedData.version,
synthData
)
return
}
parsedData.accountId = synthData[1]
if (parsedData.accountId) {
if (trustedIds.indexOf(parsedData.accountId) === -1) {
logger.trace(
'Synthetics header account ID is not in trusted account IDs: %s (%s)',
parsedData.accountId,
trustedIds
)
return
}
} else {
logger.trace('Synthetics header account ID missing.')
return
}
parsedData.resourceId = synthData[2]
if (!parsedData.resourceId) {
logger.trace('Synthetics resource ID is missing.')
return
}
parsedData.jobId = synthData[3]
if (!parsedData.jobId) {
logger.trace('Synthetics job ID is missing.')
}
parsedData.monitorId = synthData[4]
if (!parsedData.monitorId) {
logger.trace('Synthetics monitor ID is missing.')
}
return parsedData
}