-
Notifications
You must be signed in to change notification settings - Fork 223
/
config.test.js
1384 lines (1224 loc) · 38.8 KB
/
config.test.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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
var cp = require('child_process')
var fs = require('fs')
var IncomingMessage = require('http').IncomingMessage
var os = require('os')
var path = require('path')
var util = require('util')
var isRegExp = require('core-util-is').isRegExp
var mkdirp = require('mkdirp')
var pFinally = require('p-finally')
var rimraf = require('rimraf')
var semver = require('semver')
var test = require('tape')
const Agent = require('../lib/agent')
const { MockAPMServer } = require('./_mock_apm_server')
const { NoopTransport } = require('../lib/noop-transport')
var config = require('../lib/config')
var Instrumentation = require('../lib/instrumentation')
var apmVersion = require('../package').version
var apmName = require('../package').name
var isHapiIncompat = require('./_is_hapi_incompat')
// Options to pass to `agent.start()` to turn off some default agent behavior
// that is unhelpful for these tests.
const agentOpts = {
centralConfig: false,
captureExceptions: false,
metricsInterval: '0s',
cloudProvider: 'none',
spanFramesMinDuration: -1, // Never discard fast spans.
logLevel: 'warn'
}
const agentOptsNoopTransport = Object.assign(
{},
agentOpts,
{
transport: function createNoopTransport () {
// Avoid accidentally trying to send data to an APM server.
return new NoopTransport()
}
}
)
var optionFixtures = [
['abortedErrorThreshold', 'ABORTED_ERROR_THRESHOLD', 25],
['active', 'ACTIVE', true],
['apiKey', 'API_KEY'],
['apiRequestSize', 'API_REQUEST_SIZE', 768 * 1024],
['apiRequestTime', 'API_REQUEST_TIME', 10],
['asyncHooks', 'ASYNC_HOOKS', true],
['captureBody', 'CAPTURE_BODY', 'off'],
['captureErrorLogStackTraces', 'CAPTURE_ERROR_LOG_STACK_TRACES', config.CAPTURE_ERROR_LOG_STACK_TRACES_MESSAGES],
['captureExceptions', 'CAPTURE_EXCEPTIONS', true],
['captureSpanStackTraces', 'CAPTURE_SPAN_STACK_TRACES', true],
['centralConfig', 'CENTRAL_CONFIG', true],
['containerId', 'CONTAINER_ID'],
['disableSend', 'DISABLE_SEND', false],
['disableInstrumentations', 'DISABLE_INSTRUMENTATIONS', []],
['environment', 'ENVIRONMENT', 'development'],
['errorMessageMaxLength', 'ERROR_MESSAGE_MAX_LENGTH', undefined],
['errorOnAbortedRequests', 'ERROR_ON_ABORTED_REQUESTS', false],
['filterHttpHeaders', 'FILTER_HTTP_HEADERS', true],
['frameworkName', 'FRAMEWORK_NAME'],
['frameworkVersion', 'FRAMEWORK_VERSION'],
['hostname', 'HOSTNAME'],
['instrument', 'INSTRUMENT', true],
['instrumentIncomingHTTPRequests', 'INSTRUMENT_INCOMING_HTTP_REQUESTS', true],
['kubernetesNamespace', 'KUBERNETES_NAMESPACE'],
['kubernetesNodeName', 'KUBERNETES_NODE_NAME'],
['kubernetesPodName', 'KUBERNETES_POD_NAME'],
['kubernetesPodUID', 'KUBERNETES_POD_UID'],
['logLevel', 'LOG_LEVEL', 'info'],
['logUncaughtExceptions', 'LOG_UNCAUGHT_EXCEPTIONS', false],
['longFieldMaxLength', 'LONG_FIELD_MAX_LENGTH', 10000],
['maxQueueSize', 'MAX_QUEUE_SIZE', 1024],
['metricsInterval', 'METRICS_INTERVAL', 30],
['metricsLimit', 'METRICS_LIMIT', 1000],
['secretToken', 'SECRET_TOKEN'],
['serverCaCertFile', 'SERVER_CA_CERT_FILE'],
['serverTimeout', 'SERVER_TIMEOUT', 30],
['serverUrl', 'SERVER_URL'],
['serviceName', 'SERVICE_NAME', apmName],
['serviceNodeName', 'SERVICE_NODE_NAME'],
['serviceVersion', 'SERVICE_VERSION', apmVersion],
['sourceLinesErrorAppFrames', 'SOURCE_LINES_ERROR_APP_FRAMES', 5],
['sourceLinesErrorLibraryFrames', 'SOURCE_LINES_ERROR_LIBRARY_FRAMES', 5],
['sourceLinesSpanAppFrames', 'SOURCE_LINES_SPAN_APP_FRAMES', 0],
['sourceLinesSpanLibraryFrames', 'SOURCE_LINES_SPAN_LIBRARY_FRAMES', 0],
['stackTraceLimit', 'STACK_TRACE_LIMIT', 50],
['transactionMaxSpans', 'TRANSACTION_MAX_SPANS', 500],
['transactionSampleRate', 'TRANSACTION_SAMPLE_RATE', 1.0],
['usePathAsTransactionName', 'USE_PATH_AS_TRANSACTION_NAME', false],
['verifyServerCert', 'VERIFY_SERVER_CERT', true]
]
var falsyValues = [false, 'false']
var truthyValues = [true, 'true']
optionFixtures.forEach(function (fixture) {
if (fixture[1]) {
var type
if (typeof fixture[2] === 'boolean') {
type = 'bool'
} else if (fixture[0] === 'serverUrl') {
// special case for url's so they can be parsed using url.parse()
type = 'url'
} else if (fixture[0] === 'serverCaCertFile') {
// special case for files, so a temp file can be written
type = 'file'
} else if (typeof fixture[2] === 'number' || fixture[0] === 'errorMessageMaxLength') {
type = 'number'
} else if (Array.isArray(fixture[2])) {
type = 'array'
} else {
type = 'string'
}
var envName = 'ELASTIC_APM_' + fixture[1]
var existingValue = process.env[envName]
test(`should be configurable by environment variable ${envName}`, function (t) {
var agent = new Agent()
var value
switch (type) {
case 'bool':
value = !fixture[2]
break
case 'number':
value = 1
break
case 'url':
value = 'http://custom-value'
break
case 'file':
var tmpdir = path.join(os.tmpdir(), 'elastic-apm-node-test', String(Date.now()))
var tmpfile = path.join(tmpdir, 'custom-file')
t.on('end', function () { rimraf.sync(tmpdir) })
mkdirp.sync(tmpdir)
fs.writeFileSync(tmpfile, tmpfile)
value = tmpfile
break
case 'array':
value = ['custom-value']
break
case 'string':
value = 'custom-value'
break
default:
t.fail(`missing handling for config var type "${type}"`)
}
process.env[envName] = value.toString()
agent.start(agentOptsNoopTransport)
switch (type) {
case 'bool':
t.strictEqual(agent._conf[fixture[0]], !fixture[2])
break
case 'array':
t.deepEqual(agent._conf[fixture[0]], value)
break
default:
t.strictEqual(agent._conf[fixture[0]], value)
}
// Restore process.env state.
if (existingValue) {
process.env[envName] = existingValue
} else {
delete process.env[envName]
}
agent.destroy()
t.end()
})
test(`should overwrite option property ${fixture[0]} by ${envName}`, function (t) {
var agent = new Agent()
var opts = {}
var value1, value2
switch (type) {
case 'bool':
value1 = !fixture[2]
value2 = fixture[2]
break
case 'number':
value1 = 2
value2 = 1
break
case 'url':
value1 = 'http://overwriting-value'
value2 = 'http://custom-value'
break
case 'file':
var tmpdir = path.join(os.tmpdir(), 'elastic-apm-node-test', String(Date.now()))
var tmpfile = path.join(tmpdir, 'custom-file')
t.on('end', function () { rimraf.sync(tmpdir) })
mkdirp.sync(tmpdir)
fs.writeFileSync(tmpfile, tmpfile)
value1 = path.join(tmpdir, 'does-not-exist')
value2 = tmpfile
break
case 'array':
value1 = ['overwriting-value']
value2 = ['custom-value']
break
case 'string':
value1 = 'overwriting-value'
value2 = 'custom-value'
break
default:
t.fail(`missing handling for config var type "${type}"`)
}
opts[fixture[0]] = value1
process.env[envName] = value2.toString()
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
switch (type) {
case 'array':
t.deepEqual(agent._conf[fixture[0]], value2)
break
default:
t.strictEqual(agent._conf[fixture[0]], value2)
}
if (existingValue) {
process.env[envName] = existingValue
} else {
delete process.env[envName]
}
agent.destroy()
t.end()
})
}
test('should default ' + fixture[0] + ' to ' + fixture[2], function (t) {
if (existingValue) {
delete process.env[envName]
}
var opts = Object.assign({}, agentOptsNoopTransport)
if (fixture[0] in opts) {
delete opts[fixture[0]]
}
var agent = new Agent().start(opts)
switch (type) {
case 'array':
t.deepEqual(agent._conf[fixture[0]], fixture[2])
break
default:
t.strictEqual(agent._conf[fixture[0]], fixture[2])
}
if (existingValue) {
process.env[envName] = existingValue
}
agent.destroy()
t.end()
})
})
falsyValues.forEach(function (val) {
test('should be disabled by environment variable ELASTIC_APM_ACTIVE set to: ' + util.inspect(val), function (t) {
var agent = new Agent()
process.env.ELASTIC_APM_ACTIVE = val
agent.start(Object.assign({}, agentOptsNoopTransport, { serviceName: 'foo', secretToken: 'baz' }))
t.strictEqual(agent._conf.active, false)
delete process.env.ELASTIC_APM_ACTIVE
agent.destroy()
t.end()
})
})
truthyValues.forEach(function (val) {
test('should be enabled by environment variable ELASTIC_APM_ACTIVE set to: ' + util.inspect(val), function (t) {
var agent = new Agent()
process.env.ELASTIC_APM_ACTIVE = val
agent.start(Object.assign({}, agentOptsNoopTransport, { serviceName: 'foo', secretToken: 'baz' }))
t.strictEqual(agent._conf.active, true)
delete process.env.ELASTIC_APM_ACTIVE
agent.destroy()
t.end()
})
})
test('should log invalid booleans', function (t) {
var agent = new Agent()
var logger = new CaptureLogger()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{
serviceName: 'foo',
secretToken: 'baz',
active: 'nope',
logger
}
))
t.strictEqual(logger.calls.length, 2)
var warning = logger.calls.shift()
t.strictEqual(warning.message, 'unrecognized boolean value "nope" for "active"')
var debug = logger.calls.shift()
t.strictEqual(debug.message, 'Elastic APM agent disabled (`active` is false)')
agent.destroy()
t.end()
})
var MINUS_ONE_EQUAL_INFINITY = [
'transactionMaxSpans'
]
MINUS_ONE_EQUAL_INFINITY.forEach(function (key) {
test(key + ' should be Infinity if set to -1', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = -1
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf[key], Infinity)
agent.destroy()
t.end()
})
})
var bytesValues = [
'apiRequestSize',
'errorMessageMaxLength'
]
bytesValues.forEach(function (key) {
test(key + ' should be converted to a number', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = '1mb'
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf[key], 1024 * 1024)
agent.destroy()
t.end()
})
})
var POSITIVE_TIME_OPTS = [
'abortedErrorThreshold',
'apiRequestTime',
'metricsInterval',
'serverTimeout'
]
// Time options allowing negative values.
var TIME_OPTS = [
'spanFramesMinDuration'
]
POSITIVE_TIME_OPTS.forEach(function (key) {
test(key + ' should guard against a negative time', function (t) {
var agent = new Agent()
var logger = new CaptureLogger()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{
[key]: '-1s',
logger
}
))
t.strictEqual(agent._conf[key], config.secondsFromTimeStr(config.DEFAULTS[key]),
'fell back to default value')
const warning = logger.calls[0]
t.equal(warning.type, 'warn', 'got a log.warn')
t.ok(warning.message.indexOf('-1s') !== -1, 'warning message includes the invalid value')
t.ok(warning.message.indexOf(key) !== -1, 'warning message includes the invalid key')
agent.destroy()
t.end()
})
test(key + ' should guard against a bogus non-time', function (t) {
var agent = new Agent()
var logger = new CaptureLogger()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{
[key]: 'bogusvalue',
logger
}
))
t.strictEqual(agent._conf[key], config.secondsFromTimeStr(config.DEFAULTS[key]),
'fell back to default value')
const warning = logger.calls[0]
t.equal(warning.type, 'warn', 'got a log.warn')
t.ok(warning.message.indexOf('bogusvalue') !== -1, 'warning message includes the invalid value')
t.ok(warning.message.indexOf(key) !== -1, 'warning message includes the invalid key')
agent.destroy()
t.end()
})
})
POSITIVE_TIME_OPTS.concat(TIME_OPTS).forEach(function (key) {
test(key + ' should convert minutes to seconds', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = '1m'
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf[key], 60)
agent.destroy()
t.end()
})
test(key + ' should convert milliseconds to seconds', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = '2000ms'
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf[key], 2)
agent.destroy()
t.end()
})
test(key + ' should parse seconds', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = '5s'
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf[key], 5)
agent.destroy()
t.end()
})
test(key + ' should support bare numbers', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = 10
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf[key], 10)
agent.destroy()
t.end()
})
})
var keyValuePairValues = [
'addPatch',
'globalLabels'
]
keyValuePairValues.forEach(function (key) {
var string = 'foo=bar,baz=buz'
var object = { foo: 'bar', baz: 'buz' }
var pairs = [
[
'foo',
'bar'
],
[
'baz',
'buz'
]
]
test(key + ' should support string form', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = string
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.deepEqual(agent._conf[key], pairs)
agent.destroy()
t.end()
})
test(key + ' should support object form', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = object
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.deepEqual(agent._conf[key], pairs)
agent.destroy()
t.end()
})
test(key + ' should support pair form', function (t) {
var agent = new Agent()
var opts = {}
opts[key] = pairs
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.deepEqual(agent._conf[key], pairs)
agent.destroy()
t.end()
})
})
var noPrefixValues = [
['kubernetesNodeName', 'KUBERNETES_NODE_NAME'],
['kubernetesNamespace', 'KUBERNETES_NAMESPACE'],
['kubernetesPodName', 'KUBERNETES_POD_NAME'],
['kubernetesPodUID', 'KUBERNETES_POD_UID']
]
noPrefixValues.forEach(function (pair) {
const [key, envVar] = pair
test(`maps ${envVar} to ${key}`, (t) => {
var agent = new Agent()
process.env[envVar] = 'test'
agent.start(agentOptsNoopTransport)
delete process.env[envVar]
t.strictEqual(agent._conf[key], 'test')
agent.destroy()
t.end()
})
})
test('should overwrite option property active by ELASTIC_APM_ACTIVE', function (t) {
var agent = new Agent()
var opts = { serviceName: 'foo', secretToken: 'baz', active: true }
process.env.ELASTIC_APM_ACTIVE = 'false'
agent.start(Object.assign({}, agentOptsNoopTransport, opts))
t.strictEqual(agent._conf.active, false)
delete process.env.ELASTIC_APM_ACTIVE
agent.destroy()
t.end()
})
test('should default serviceName to package name', function (t) {
var agent = new Agent()
agent.start()
t.strictEqual(agent._conf.serviceName, 'elastic-apm-node')
agent.destroy()
t.end()
})
test('should default to empty request blacklist arrays', function (t) {
var agent = new Agent()
agent.start(agentOptsNoopTransport)
t.strictEqual(agent._conf.ignoreUrlStr.length, 0)
t.strictEqual(agent._conf.ignoreUrlRegExp.length, 0)
t.strictEqual(agent._conf.ignoreUserAgentStr.length, 0)
t.strictEqual(agent._conf.ignoreUserAgentRegExp.length, 0)
t.strictEqual(agent._conf.transactionIgnoreUrlRegExp.length, 0)
agent.destroy()
t.end()
})
test('should separate strings and regexes into their own blacklist arrays', function (t) {
var agent = new Agent()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{
ignoreUrls: ['str1', /regex1/],
ignoreUserAgents: ['str2', /regex2/]
}
))
t.deepEqual(agent._conf.ignoreUrlStr, ['str1'])
t.deepEqual(agent._conf.ignoreUserAgentStr, ['str2'])
t.strictEqual(agent._conf.ignoreUrlRegExp.length, 1)
t.ok(isRegExp(agent._conf.ignoreUrlRegExp[0]))
t.strictEqual(agent._conf.ignoreUrlRegExp[0].toString(), '/regex1/')
t.strictEqual(agent._conf.ignoreUserAgentRegExp.length, 1)
t.ok(isRegExp(agent._conf.ignoreUserAgentRegExp[0]))
t.strictEqual(agent._conf.ignoreUserAgentRegExp[0].toString(), '/regex2/')
agent.destroy()
t.end()
})
test('should compile wildcards from string', function (t) {
var agent = new Agent()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{
transactionIgnoreUrls: ['foo', '/str1', '/wil*card']
}
))
t.strictEqual(
agent._conf.transactionIgnoreUrlRegExp.length,
3,
'was everything added?'
)
agent.destroy()
t.end()
})
test('invalid serviceName => inactive', function (t) {
var agent = new Agent()
agent.start(Object.assign({}, agentOptsNoopTransport, { serviceName: 'foo&bar' }))
t.strictEqual(agent._conf.active, false)
agent.destroy()
t.end()
})
test('valid serviceName => active', function (t) {
var agent = new Agent()
agent.start(Object.assign({}, agentOptsNoopTransport, { serviceName: 'fooBAR0123456789_- ' }))
t.strictEqual(agent._conf.active, true)
agent.destroy()
t.end()
})
test('serviceName defaults to package name', function (t) {
var mkdirpPromise = util.promisify(mkdirp)
var rimrafPromise = util.promisify(rimraf)
var writeFile = util.promisify(fs.writeFile)
var symlink = util.promisify(fs.symlink)
var exec = util.promisify(cp.exec)
function testServiceConfig (pkg, handle) {
var tmp = path.join(os.tmpdir(), 'elastic-apm-node-test', String(Date.now()))
var files = [
{
action: 'mkdirp',
dir: tmp
},
{
action: 'create',
path: path.join(tmp, 'package.json'),
contents: JSON.stringify(pkg)
},
{
action: 'create',
path: path.join(tmp, 'index.js'),
contents: `
var apm = require('elastic-apm-node').start({
centralConfig: false,
metricsInterval: '0s',
logLevel: 'off'
})
console.log(JSON.stringify(apm._conf))
`
},
{
action: 'mkdirp',
dir: path.join(tmp, 'node_modules')
}
]
if (process.platform === 'win32') {
files.push({
action: 'npm link',
from: path.resolve(__dirname, '..'),
to: tmp
})
} else {
files.push({
action: 'symlink',
from: path.resolve(__dirname, '..'),
to: path.join(tmp, 'node_modules/elastic-apm-node')
})
}
// NOTE: Reduce the sequence to a promise chain rather
// than using Promise.all(), as the tasks are dependent.
let promise = files.reduce((p, file) => {
return p.then(() => {
switch (file.action) {
case 'create': {
return writeFile(file.path, file.contents)
}
case 'mkdirp': {
return mkdirpPromise(file.dir)
}
case 'symlink': {
return symlink(file.from, file.to)
}
case 'npm link': {
return exec('npm link', {
cwd: file.from
}).then(() => {
return exec('npm link elastic-apm-node', {
cwd: file.to
})
})
}
}
})
}, Promise.resolve())
promise = promise
.then(() => {
return exec('node index.js', {
cwd: tmp
})
})
.then(result => {
return JSON.parse(result.stdout)
})
.catch(err => {
t.error(err)
})
return pFinally(promise, () => {
return rimrafPromise(tmp)
})
}
t.test('should be active when valid', function (t) {
var pkg = {
name: 'valid'
}
return testServiceConfig(pkg).then(conf => {
t.strictEqual(conf.active, true)
t.strictEqual(conf.serviceName, pkg.name)
t.end()
})
})
t.test('should be inactive when blank', function (t) {
var pkg = {
name: ''
}
return testServiceConfig(pkg).then(conf => {
t.strictEqual(conf.active, false)
t.strictEqual(conf.serviceName, pkg.name)
t.end()
})
})
t.test('should be inactive when missing', function (t) {
var pkg = {}
return testServiceConfig(pkg).then(conf => {
t.strictEqual(conf.active, false)
t.end()
})
})
t.test('serviceVersion should default to package version', function (t) {
var pkg = {
version: '1.2.3'
}
return testServiceConfig(pkg).then(conf => {
t.strictEqual(conf.serviceVersion, pkg.version)
t.end()
})
})
})
var captureBodyTests = [
{ value: 'off', errors: '[REDACTED]', transactions: '[REDACTED]' },
{ value: 'transactions', errors: '[REDACTED]', transactions: 'test' },
{ value: 'errors', errors: 'test', transactions: '[REDACTED]' },
{ value: 'all', errors: 'test', transactions: 'test' }
]
captureBodyTests.forEach(function (captureBodyTest) {
test('captureBody => ' + captureBodyTest.value, function (t) {
const apmServer = new MockAPMServer()
apmServer.start(function (serverUrl) {
const agent = new Agent().start(Object.assign(
{},
agentOpts,
{
serverUrl,
captureBody: captureBodyTest.value
}
))
var req = new IncomingMessage()
req.socket = { remoteAddress: '127.0.0.1' }
req.headers['transfer-encoding'] = 'chunked'
req.headers['content-length'] = 4
req.body = 'test'
var trans = agent.startTransaction()
trans.req = req
trans.end()
agent.captureError(new Error('wat'), { request: req },
function () {
t.equal(apmServer.events.length, 3, 'apmServer got 3 events')
let data = apmServer.events[1].transaction
t.ok(data, 'event 1 is a transaction')
t.strictEqual(data.context.request.body, captureBodyTest.transactions,
'transaction.context.request.body is ' + captureBodyTest.transactions)
data = apmServer.events[2].error
t.ok(data, 'event 2 is an error')
t.strictEqual(data.context.request.body, captureBodyTest.errors,
'error.context.request.body is ' + captureBodyTest.errors)
agent.destroy()
apmServer.close()
t.end()
}
)
})
})
})
var usePathAsTransactionNameTests = [
{ value: true, url: '/foo/bar?baz=2', transactionName: 'GET /foo/bar' },
{ value: false, url: '/foo/bar?baz=2', transactionName: 'GET unknown route' }
]
usePathAsTransactionNameTests.forEach(function (usePathAsTransactionNameTest) {
test('usePathAsTransactionName => ' + usePathAsTransactionNameTest.value, function (t) {
var sentTrans
var agent = new Agent()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{
usePathAsTransactionName: usePathAsTransactionNameTest.value,
transport () {
return {
sendTransaction (trans, cb) {
sentTrans = trans
if (cb) process.nextTick(cb)
},
flush (cb) {
if (cb) process.nextTick(cb)
}
}
}
}
))
var req = new IncomingMessage()
req.socket = { remoteAddress: '127.0.0.1' }
req.url = usePathAsTransactionNameTest.url
req.method = 'GET'
var trans = agent.startTransaction()
trans.req = req
trans.end()
agent.flush(function () {
t.ok(sentTrans, 'sent a transaction')
t.strictEqual(sentTrans.name, usePathAsTransactionNameTest.transactionName,
'transaction.name is ' + usePathAsTransactionNameTest.transactionName)
agent.destroy()
t.end()
})
})
})
test('disableInstrumentations', function (t) {
var expressGraphqlVersion = require('express-graphql/package.json').version
var esVersion = require('@elastic/elasticsearch/package.json').version
// require('apollo-server-core') is a hard crash on nodes < 12.0.0
const apolloServerCoreVersion = require('apollo-server-core/package.json').version
var flattenedModules = Instrumentation.modules.reduce((acc, val) => acc.concat(val), [])
var modules = new Set(flattenedModules)
if (isHapiIncompat('hapi')) {
modules.delete('hapi')
}
if (isHapiIncompat('@hapi/hapi')) {
modules.delete('@hapi/hapi')
}
if (semver.lt(process.version, '7.6.0') && semver.gte(expressGraphqlVersion, '0.9.0')) {
modules.delete('express-graphql')
}
if (semver.lt(process.version, '10.0.0') && semver.gte(esVersion, '7.12.0')) {
modules.delete('@elastic/elasticsearch')
}
// As of mongodb@4 only supports node >=v12.
const mongodbVersion = require('../node_modules/mongodb/package.json').version
if (semver.gte(mongodbVersion, '4.0.0') && semver.lt(process.version, '12.0.0')) {
modules.delete('mongodb')
}
if (semver.gte(apolloServerCoreVersion, '3.0.0') && semver.lt(process.version, '12.0.0')) {
modules.delete('apollo-server-core')
}
function testSlice (t, name, selector) {
var selection = selector(modules)
var selectionSet = new Set(typeof selection === 'string' ? selection.split(',') : selection)
t.test(name + ' -> ' + Array.from(selectionSet).join(','), function (t) {
var agent = new Agent()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{ disableInstrumentations: selection }
))
var found = new Set()
agent._instrumentation._patchModule = function (exports, name, version, enabled) {
if (!enabled) found.add(name)
return exports
}
for (const mod of modules) {
require(mod)
}
t.deepEqual(selectionSet, found, 'disabled all selected modules')
agent.destroy()
t.end()
})
}
for (const mod of modules) {
testSlice(t, 'individual modules', () => new Set([mod]))
}
testSlice(t, 'multiple modules by array', modules => {
return Array.from(modules).filter((value, index) => index % 2)
})
testSlice(t, 'multiple modules by csv string', modules => {
return Array.from(modules).filter((value, index) => !(index % 2))
})
t.end()
})
test('custom transport', function (t) {
class MyTransport {
constructor () {
this.transactions = []
this.spans = []
this.errors = []
}
sendTransaction (data, cb) {
this.transactions.push(data)
if (cb) setImmediate(cb)
}
sendSpan (data, cb) {
this.spans.push(data)
if (cb) setImmediate(cb)
}
sendError (data, cb) {
this.errors.push(data)
if (cb) setImmediate(cb)
}
config () {}
flush (cb) {
if (cb) setImmediate(cb)
}
}
const myTransport = new MyTransport()
var agent = new Agent()
agent.start(Object.assign({}, agentOpts, { transport: () => myTransport }))
var error = new Error('error')
var trans = agent.startTransaction('transaction')
var span = agent.startSpan('span')
agent.captureError(error)
span.end()
trans.end()
setTimeout(function () {
t.equal(myTransport.transactions.length, 1, 'received correct number of transactions')
assertEncodedTransaction(t, trans, myTransport.transactions[0])
t.equal(myTransport.spans.length, 1, 'received correct number of spans')
assertEncodedSpan(t, span, myTransport.spans[0])
t.equal(myTransport.errors.length, 1, 'received correct number of errors')
assertEncodedError(t, error, myTransport.errors[0], trans, span)
agent.destroy()
t.end()
}, 200) // Hack wait for ended span and captured error to be sent to transport.
})
test('addPatch', function (t) {
const before = require('express')
const patch = require('./_patch')
delete require.cache[require.resolve('express')]
const agent = new Agent()
agent.start(Object.assign(
{},
agentOptsNoopTransport,
{