-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathruntime_metrics.spec.js
More file actions
1576 lines (1338 loc) · 60.6 KB
/
Copy pathruntime_metrics.spec.js
File metadata and controls
1576 lines (1338 loc) · 60.6 KB
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'
const assert = require('node:assert')
const os = require('node:os')
const { performance } = require('node:perf_hooks')
const { setImmediate, setTimeout } = require('node:timers/promises')
const util = require('node:util')
const { describe, it, beforeEach, afterEach } = require('mocha')
const proxyquire = require('proxyquire')
const sinon = require('sinon')
const { metrics } = require('@opentelemetry/api')
require('./setup/core')
const { NODE_MAJOR, NODE_MINOR } = require('../../../version')
const { DogStatsDClient } = require('../src/dogstatsd')
// On Node versions that support `monitorEventLoopDelay({ samplePerIteration })`
// (available in v24.19.0 and v26.5.0) the runtime metrics module unconditionally skips the
// @datadog/native-metrics path, so the "with native metrics" variant is unreachable.
const SAMPLE_PER_ITERATION_AVAILABLE = NODE_MAJOR > 26 ||
(NODE_MAJOR === 26 && NODE_MINOR >= 5) ||
(NODE_MAJOR === 24 && NODE_MINOR >= 19)
const NATIVE_METRICS_VARIANTS = SAMPLE_PER_ITERATION_AVAILABLE ? [false] : [true, false]
// Only runs on a real runtime that actually supports the per-iteration sampler.
const describeSamplePerIteration = SAMPLE_PER_ITERATION_AVAILABLE ? describe : describe.skip
const { assertObjectContains } = require('../../../integration-tests/helpers')
const MeterProvider = require('../src/opentelemetry/metrics/meter_provider')
const PeriodicMetricReader = require('../src/opentelemetry/metrics/periodic_metric_reader')
const OtlpTransformer = require('../src/opentelemetry/metrics/otlp_transformer')
const otlpRuntimeMetrics = require('../src/runtime_metrics/otlp_runtime_metrics')
function createGarbage (count = 50) {
let last = {}
const obj = last
for (let i = 0; i < count; i++) {
last.next = { circular: obj, last, obj: { a: 1, b: 2, c: true } }
// @ts-expect-error - Difficult to define type
last = last.next
// @ts-expect-error - Difficult to define type
last.map = new Map([['a', 1], ['b', 2], ['c', true]])
obj[i] = last
}
return util.inspect(obj, { depth: Infinity })
}
NATIVE_METRICS_VARIANTS.forEach((nativeMetrics) => {
describe(`runtimeMetrics ${nativeMetrics ? 'with' : 'without'} native metrics`, () => {
describe('runtimeMetrics (proxy)', () => {
let runtimeMetrics
let proxy
let config
before(() => {
require('../src/process-tags').initialize()
})
beforeEach(() => {
config = {
runtimeMetrics: {
enabled: false,
},
}
runtimeMetrics = sinon.spy({
start () {},
stop () {},
track () {},
boolean () {},
histogram () {},
count () {},
gauge () {},
increment () {},
decrement () {},
})
proxy = proxyquire('../src/runtime_metrics', {
'./runtime_metrics': runtimeMetrics,
})
})
it('should be noop when disabled', () => {
proxy.start()
proxy.track()
proxy.boolean()
proxy.histogram()
proxy.count()
proxy.gauge()
proxy.increment()
proxy.decrement()
proxy.stop()
sinon.assert.notCalled(runtimeMetrics.start)
sinon.assert.notCalled(runtimeMetrics.track)
sinon.assert.notCalled(runtimeMetrics.boolean)
sinon.assert.notCalled(runtimeMetrics.histogram)
sinon.assert.notCalled(runtimeMetrics.count)
sinon.assert.notCalled(runtimeMetrics.gauge)
sinon.assert.notCalled(runtimeMetrics.increment)
sinon.assert.notCalled(runtimeMetrics.decrement)
sinon.assert.notCalled(runtimeMetrics.stop)
})
it('should proxy when enabled', () => {
config.runtimeMetrics.enabled = true
proxy.start(config)
proxy.track()
proxy.boolean()
proxy.histogram()
proxy.count()
proxy.gauge()
proxy.increment()
proxy.decrement()
proxy.stop()
sinon.assert.calledWith(runtimeMetrics.start, config)
sinon.assert.called(runtimeMetrics.track)
sinon.assert.called(runtimeMetrics.boolean)
sinon.assert.called(runtimeMetrics.histogram)
sinon.assert.called(runtimeMetrics.count)
sinon.assert.called(runtimeMetrics.gauge)
sinon.assert.called(runtimeMetrics.increment)
sinon.assert.called(runtimeMetrics.decrement)
sinon.assert.called(runtimeMetrics.stop)
})
it('should be noop when disabled after being enabled', () => {
config.runtimeMetrics.enabled = true
proxy.start(config)
proxy.stop()
config.runtimeMetrics.enabled = false
proxy.start(config)
proxy.track()
proxy.boolean()
proxy.histogram()
proxy.count()
proxy.gauge()
proxy.increment()
proxy.decrement()
proxy.stop()
sinon.assert.calledOnce(runtimeMetrics.start)
sinon.assert.notCalled(runtimeMetrics.track)
sinon.assert.notCalled(runtimeMetrics.boolean)
sinon.assert.notCalled(runtimeMetrics.histogram)
sinon.assert.notCalled(runtimeMetrics.count)
sinon.assert.notCalled(runtimeMetrics.gauge)
sinon.assert.notCalled(runtimeMetrics.increment)
sinon.assert.notCalled(runtimeMetrics.decrement)
sinon.assert.calledOnce(runtimeMetrics.stop)
})
})
describe('runtimeMetrics', () => {
let runtimeMetrics
let config
let clock
let client
let Client
beforeEach(() => {
// This is needed because sinon spies keep references to arguments which
// breaks tests because the tags parameter is now mutated right after the
// call.
const wrapSpy = (client, spy) => {
return function (stat, value, tags) {
return spy.call(client, stat, value, [].concat(tags))
}
}
Client = sinon.spy(function () {
return {
gauge: wrapSpy(client, client.gauge),
increment: wrapSpy(client, client.increment),
histogram: wrapSpy(client, client.histogram),
flush: client.flush.bind(client),
}
})
Client.generateClientConfig = DogStatsDClient.generateClientConfig
client = {
gauge: sinon.spy(),
increment: sinon.spy(),
histogram: sinon.spy(),
flush: sinon.spy(),
}
const proxiedObject = {
// Exercise the real client factory (incl. process tags) but with the spy DogStatsD client.
'./client': proxyquire('../src/runtime_metrics/client', {
'../dogstatsd': { DogStatsDClient: Client },
}),
}
if (!nativeMetrics) {
proxiedObject['@datadog/native-metrics'] = {
start () {
throw new Error('Native metrics are not supported in this environment')
},
}
} else {
// The log is called in case native metrics fail to load.
proxiedObject['../log'] = {
error () {
throw new Error('Native metrics should load properly')
},
}
}
runtimeMetrics = proxyquire('../src/runtime_metrics/runtime_metrics', proxiedObject)
config = {
url: new URL('http://localhost:8126'),
dogstatsd: {
hostname: 'localhost',
port: 8125,
},
runtimeMetrics: {
enabled: true,
eventLoop: true,
gc: true,
},
tags: {
str: 'bar',
obj: {},
invalid: 't{e*s#t5-:./',
},
DD_RUNTIME_METRICS_FLUSH_INTERVAL: 10000,
getOrigin: () => {
return 'default'
},
}
clock = sinon.useFakeTimers({
toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'],
})
runtimeMetrics.start(config)
})
afterEach(() => {
clock.restore()
runtimeMetrics.stop()
})
describe('start', () => {
it('it should initialize the Dogstatsd client with the correct options', function () {
runtimeMetrics.stop()
runtimeMetrics.start(config)
sinon.assert.calledWithMatch(Client, {
metricsProxyUrl: new URL('http://localhost:8126'),
host: 'localhost',
tags: [
'str:bar',
'invalid:t_e_s_t5-:./',
],
})
})
it('it should initialize the Dogstatsd client with an IPv6 URL', function () {
config.url = new URL('http://[::1]:8126')
runtimeMetrics.stop()
runtimeMetrics.start(config)
sinon.assert.calledWithMatch(Client, {
metricsProxyUrl: new URL('http://[::1]:8126'),
host: 'localhost',
tags: [
'str:bar',
'invalid:t_e_s_t5-:./',
],
})
})
it('should include process tags when propagateProcessTags is enabled', function () {
config.DD_EXPERIMENTAL_PROPAGATE_PROCESS_TAGS_ENABLED = true
runtimeMetrics.stop()
runtimeMetrics.start(config)
const call = Client.lastCall
const tags = call.args[0].tags
assert.ok(tags.some(tag => tag.startsWith('entrypoint.type:')), 'expected entrypoint.type tag')
})
it('should not include process tags when propagateProcessTags is disabled', function () {
config.DD_EXPERIMENTAL_PROPAGATE_PROCESS_TAGS_ENABLED = false
runtimeMetrics.stop()
runtimeMetrics.start(config)
const call = Client.lastCall
const tags = call.args[0].tags
assert.ok(!tags.some(tag => tag.startsWith('entrypoint.')), 'expected no entrypoint tags')
})
it('should start collecting runtimeMetrics every 10 seconds', async () => {
runtimeMetrics.stop()
runtimeMetrics.start(config)
client.gauge.resetHistory()
client.increment.resetHistory()
client.histogram.resetHistory()
createGarbage()
createGarbage()
// Wait for GC observer to trigger.
const startTime = Date.now()
const waitTime = 200 + (nativeMetrics ? 0 : 200)
let iterations = 0
while (Date.now() - startTime < waitTime) {
// Need ticks for the event loop delay
if (iterations++ % 10000 === 0) {
await setTimeout(1)
clock.tick(1)
}
}
global.gc()
await setImmediate()
await setImmediate()
clock.tick(10000 - waitTime)
const isFiniteNumber = sinon.match((value) => {
return value > 0 && Number.isFinite(value)
})
const isIntegerNumber = sinon.match((value) => {
return value > 0 && Number.isInteger(value)
})
const isGC95Percentile = sinon.match((value) => {
// Nanoseconds, 1µs to 100ms. These bounds guard the unit conversion, not the timing:
// a sub-microsecond value means the ms→ns conversion (`entry.duration * 1e6`) was
// dropped, and a value over 100ms means it was left in milliseconds or seconds. The
// floor used to be 0.1ms, which flaked on fast/idle runners where a single scavenge
// pause is the only sample for a gc_type and its p95 sits below that.
return value >= 1e3 && value < 1e8
})
const isHeapSpace = sinon.match((metricName) => {
return /^heap_space:[a-z_]+$/.test(metricName)
})
// These return percentages as strings and are tested later.
sinon.assert.calledWith(client.gauge, 'runtime.node.cpu.user')
sinon.assert.calledWith(client.gauge, 'runtime.node.cpu.system')
sinon.assert.calledWith(client.gauge, 'runtime.node.cpu.total')
sinon.assert.calledWith(client.gauge, 'runtime.node.mem.rss', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.mem.heap_total', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.mem.heap_used', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.process.uptime')
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.total_heap_size', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.total_heap_size_executable', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.total_physical_size', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.total_available_size', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.total_heap_size', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.heap_size_limit', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.malloced_memory', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.peak_malloced_memory', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.delay.max', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.delay.min', sinon.match((value) => {
return value >= 0 && Number.isFinite(value)
}))
sinon.assert.calledWith(client.increment, 'runtime.node.event_loop.delay.sum', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.delay.avg', isFiniteNumber)
if (nativeMetrics) {
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.delay.median', isFiniteNumber)
} else {
sinon.assert.neverCalledWith(client.gauge, 'runtime.node.event_loop.delay.median')
}
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.delay.95percentile', isFiniteNumber)
sinon.assert.calledWith(client.increment, 'runtime.node.event_loop.delay.count', isIntegerNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.utilization', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.max', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.min', isFiniteNumber)
sinon.assert.calledWith(client.increment, 'runtime.node.gc.pause.sum', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.avg', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.median', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.95percentile', isFiniteNumber)
sinon.assert.calledWith(client.increment, 'runtime.node.gc.pause.count', isIntegerNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.by.type.max', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.by.type.min', isFiniteNumber)
sinon.assert.calledWith(client.increment, 'runtime.node.gc.pause.by.type.sum', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.by.type.avg', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.by.type.median', isFiniteNumber)
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.by.type.95percentile', isGC95Percentile)
sinon.assert.calledWith(client.increment, 'runtime.node.gc.pause.by.type.count', isIntegerNumber)
sinon.assert.calledWith(client.increment,
'runtime.node.gc.pause.by.type.count', sinon.match.any, sinon.match(val => {
return val && /^gc_type:[a-z_]+$/.test(val[0])
})
)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.size.by.space', isFiniteNumber, isHeapSpace)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.used_size.by.space', isFiniteNumber, isHeapSpace)
sinon.assert.calledWith(
client.gauge,
'runtime.node.heap.available_size.by.space',
isFiniteNumber,
isHeapSpace
)
sinon.assert.calledWith(client.gauge, 'runtime.node.heap.physical_size.by.space', isFiniteNumber, isHeapSpace)
sinon.assert.called(client.flush)
})
it('should collect individual metrics only once every 10 seconds', async () => {
runtimeMetrics.stop()
runtimeMetrics.start(config)
global.gc()
// Wait for GC observer to trigger.
await setImmediate()
await setImmediate()
clock.tick(60 * 60 * 1000)
// If a metric is leaking, it will leak exponentially because it will
// be sent one more time each flush, in addition to the previous
// flushes that also had the metric multiple times in them, so after
// 1 hour even if a single metric is leaking it would get over
// 64980 calls on its own without any other metric. A slightly lower
// value is used here to be on the safer side.
assert.ok(client.gauge.callCount < 60000, `Expected ${client.gauge.callCount} < 60000`)
assert.ok(client.increment.callCount < 60000, `Expected ${client.increment.callCount} < 60000`)
})
it('should handle configuration changes correctly', async () => {
// Test with GC disabled
const configWithoutGC = { ...config, runtimeMetrics: { ...config.runtimeMetrics, gc: false } }
runtimeMetrics.stop()
runtimeMetrics.start(configWithoutGC)
createGarbage()
// Wait for event loop delay observer to trigger.
let startTime = Date.now()
const waitTime = 60
while (Date.now() - startTime < waitTime) {
// Need ticks for the event loop delay
await setTimeout(1)
clock.tick(1)
}
global.gc()
await setTimeout(1)
clock.tick(10000 - waitTime)
// Should still collect basic metrics
sinon.assert.calledWith(client.gauge, 'runtime.node.mem.rss')
sinon.assert.calledWith(client.gauge, 'runtime.node.cpu.user')
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.utilization')
sinon.assert.calledWith(client.gauge, 'runtime.node.event_loop.delay.95percentile')
sinon.assert.neverCalledWith(client.gauge, 'runtime.node.gc.pause.95percentile')
// Test with event loop disabled
const configWithoutEL = { ...config, runtimeMetrics: { ...config.runtimeMetrics, eventLoop: false } }
// Calling start again should stop any former metric collection
runtimeMetrics.start(configWithoutEL)
client.gauge.resetHistory()
createGarbage()
// Wait for GC observer to trigger.
startTime = Date.now()
while (Date.now() - startTime < waitTime) {
// Need ticks for the event loop delay
await setTimeout(1)
clock.tick(1)
}
global.gc()
await setTimeout(1)
clock.tick(10000 - waitTime)
// Should still collect other metrics
sinon.assert.calledWith(client.gauge, 'runtime.node.mem.rss')
sinon.assert.calledWith(client.gauge, 'runtime.node.cpu.user')
sinon.assert.calledWith(client.gauge, 'runtime.node.gc.pause.95percentile')
sinon.assert.neverCalledWith(client.gauge, 'runtime.node.event_loop.utilization')
sinon.assert.neverCalledWith(client.gauge, 'runtime.node.event_loop.delay.95percentile')
})
it('should not load native metrics when native is false, even if eventLoop or gc are enabled', () => {
// Stop the default runtimeMetrics instance started in beforeEach
runtimeMetrics.stop()
const nativeMetricsStart = sinon.spy()
const nativeMetricsModule = {
start: nativeMetricsStart,
stop: sinon.spy(),
stats: sinon.stub().returns({ cpu: { user: 0, system: 0 }, heap: { spaces: [] }, eventLoop: {}, gc: {} }),
}
const localClient = {
gauge: sinon.spy(),
increment: sinon.spy(),
histogram: sinon.spy(),
flush: sinon.spy(),
}
const LocalClient = sinon.spy(function () {
return {
gauge: localClient.gauge,
increment: localClient.increment,
histogram: localClient.histogram,
flush: localClient.flush,
}
})
LocalClient.generateClientConfig = DogStatsDClient.generateClientConfig
const localRuntimeMetrics = proxyquire('../src/runtime_metrics/runtime_metrics', {
'./client': proxyquire('../src/runtime_metrics/client', {
'../dogstatsd': { DogStatsDClient: LocalClient },
}),
'@datadog/native-metrics': nativeMetricsModule,
})
const configNativeDisabled = {
...config,
runtimeMetrics: { ...config.runtimeMetrics, eventLoop: true, gc: true, native: false },
}
localRuntimeMetrics.start(configNativeDisabled)
// Native metrics should not have been started despite eventLoop and gc being enabled
sinon.assert.notCalled(nativeMetricsStart)
// Should still collect basic metrics via the JS fallback path
clock.tick(10000)
sinon.assert.calledWith(localClient.gauge, 'runtime.node.mem.rss')
sinon.assert.calledWith(localClient.gauge, 'runtime.node.cpu.user')
localRuntimeMetrics.stop()
})
it('should not require native metrics when samplePerIteration is available, even if native is true', () => {
// Stop the default runtimeMetrics instance started in beforeEach
runtimeMetrics.stop()
const localClient = {
gauge: sinon.spy(),
increment: sinon.spy(),
histogram: sinon.spy(),
flush: sinon.spy(),
}
const LocalClient = sinon.spy(function () {
return {
gauge: localClient.gauge,
increment: localClient.increment,
histogram: localClient.histogram,
flush: localClient.flush,
}
})
LocalClient.generateClientConfig = DogStatsDClient.generateClientConfig
const localRuntimeMetrics = proxyquire('../src/runtime_metrics/runtime_metrics', {
'./client': proxyquire('../src/runtime_metrics/client', {
'../dogstatsd': { DogStatsDClient: LocalClient },
}),
'../../../../version': { NODE_MAJOR: 24, NODE_MINOR: 19 },
'@datadog/native-metrics': {
start () {
throw new Error('Native metrics should not even be required')
},
},
})
const configNativeEnabled = {
...config,
runtimeMetrics: { ...config.runtimeMetrics, eventLoop: true, gc: true, native: true },
}
localRuntimeMetrics.start(configNativeEnabled)
// Should still collect metrics via the JS fallback path
clock.tick(10000)
sinon.assert.calledWith(localClient.gauge, 'runtime.node.mem.rss')
sinon.assert.calledWith(localClient.gauge, 'runtime.node.cpu.user')
localRuntimeMetrics.stop()
})
})
describe('Event Loop Utilization', () => {
it('should calculate utilization correctly with delta values', () => {
const firstElu = { idle: 80000000, active: 20000000, utilization: 0.2 }
const secondElu = { idle: 100000000, active: 80000000, utilization: 0.4444444444444444 }
let diff = performance.eventLoopUtilization(firstElu, secondElu)
assert.strictEqual(diff.utilization, 0.75)
const thirdElu = { idle: 200000000, active: 80000000, utilization: 0.2857142857142857 }
diff = performance.eventLoopUtilization(secondElu, thirdElu)
assert.strictEqual(diff.utilization, -0)
const eventLoopUtilizationStub = sinon.stub(performance, 'eventLoopUtilization')
.onFirstCall().returns(firstElu)
.onSecondCall().returns(secondElu)
.onThirdCall().returns(thirdElu)
clock.tick(10000) // First collection
clock.tick(10000) // Second collection with delta
clock.tick(10000) // Second collection with delta
eventLoopUtilizationStub.restore()
const eluCalls = client.gauge.getCalls().filter(call =>
call.args[0] === 'runtime.node.event_loop.utilization'
)
assert.strictEqual(eluCalls.length, 3)
assert.strictEqual(eluCalls[0].args[1], 0.2)
assert.strictEqual(eluCalls[1].args[1], 0.75)
assert.strictEqual(eluCalls[2].args[1], 0)
})
})
describe('CPU Usage Calculations', () => {
it('should report CPU percentages matching real process usage', () => {
const outerStartCpuUsage = process.cpuUsage()
const outerStartTime = performance.now()
clock.tick(10000)
client.gauge.resetHistory()
const innerStartTime = performance.now()
const innerStartCpuUsage = process.cpuUsage()
let iterations = 0
let userCpuUsage = 0
while (userCpuUsage < 100_000) {
if (++iterations % 1_000_000 === 0) {
userCpuUsage = process.cpuUsage(innerStartCpuUsage).user
}
}
const innerEndCpuUsage = process.cpuUsage()
const innerEndTime = performance.now()
clock.tick(10000)
const outerEndTime = performance.now()
const outerEndCpuUsage = process.cpuUsage()
const cpuCalls = client.gauge.getCalls().filter(call => call.args[0].startsWith('runtime.node.cpu.'))
const cpuMetrics = new Map(cpuCalls.map(call => [call.args[0], call.args[1]]))
assert.deepStrictEqual([...cpuMetrics.keys()].sort(), [
'runtime.node.cpu.system',
'runtime.node.cpu.total',
'runtime.node.cpu.user',
])
assert.strictEqual(cpuCalls.length, cpuMetrics.size, 'CPU metrics should be reported exactly once')
for (const value of cpuMetrics.values()) {
assert.match(value, /^\d+\.\d{2}$/)
}
const userPercent = Number(cpuMetrics.get('runtime.node.cpu.user'))
const systemPercent = Number(cpuMetrics.get('runtime.node.cpu.system'))
const totalPercent = Number(cpuMetrics.get('runtime.node.cpu.total'))
const totalDiff = Math.abs(totalPercent - userPercent - systemPercent)
assert(totalDiff <= 0.02, `Total CPU percentage sanity check failed: ${totalDiff} > 0.02`)
// The collector reads its counters between the outer and inner samples on each side.
const minimumElapsedTime = innerEndTime - innerStartTime
const maximumElapsedTime = outerEndTime - outerStartTime
const minimumUserPercent = (innerEndCpuUsage.user - innerStartCpuUsage.user) / (maximumElapsedTime * 10)
const maximumUserPercent = (outerEndCpuUsage.user - outerStartCpuUsage.user) / (minimumElapsedTime * 10)
const minimumSystemPercent = (innerEndCpuUsage.system - innerStartCpuUsage.system) / (maximumElapsedTime * 10)
const maximumSystemPercent = (outerEndCpuUsage.system - outerStartCpuUsage.system) / (minimumElapsedTime * 10)
const minimumTotalPercent = minimumUserPercent + minimumSystemPercent
const maximumTotalPercent = maximumUserPercent + maximumSystemPercent
assert(
userPercent >= minimumUserPercent - 0.01 && userPercent <= maximumUserPercent + 0.01,
`Expected real user CPU percentage ${minimumUserPercent} <= ${userPercent} <= ${maximumUserPercent}`
)
assert(
systemPercent >= minimumSystemPercent - 0.01 && systemPercent <= maximumSystemPercent + 0.01,
`Expected real system CPU percentage ${minimumSystemPercent} <= ${systemPercent} <= ${maximumSystemPercent}`
)
assert(
totalPercent >= minimumTotalPercent - 0.01 && totalPercent <= maximumTotalPercent + 0.01,
`Expected real total CPU percentage ${minimumTotalPercent} <= ${totalPercent} <= ${maximumTotalPercent}`
)
})
})
describe('Memory and Heap Metrics', () => {
it('should ensure heap_used <= heap_total', () => {
clock.tick(10000)
const heapUsedCalls = client.gauge.getCalls().filter(call => call.args[0] === 'runtime.node.mem.heap_used')
const heapTotalCalls = client.gauge.getCalls().filter(call => call.args[0] === 'runtime.node.mem.heap_total')
assert.strictEqual(heapUsedCalls.length, 1)
assert.strictEqual(heapTotalCalls.length, 1)
const heapUsed = heapUsedCalls[0].args[1]
const heapTotal = heapTotalCalls[0].args[1]
assert(heapUsed <= heapTotal, `Expected ${heapUsed} <= ${heapTotal}`)
})
})
describe('Process Uptime', () => {
it('should show increasing uptime over time', () => {
// On linux performance.now() would return a negative value due to the mocked time.
// This is a workaround to ensure the test is deterministic.
const startPerformanceNow = Math.max(performance.now(), Math.random() * 1_000_000)
const nowStub = sinon.stub(performance, 'now').returns(startPerformanceNow)
clock.tick(10000)
nowStub.restore()
const firstUptimeCalls = client.gauge.getCalls()
.filter(call => call.args[0] === 'runtime.node.process.uptime')
const firstUptime = firstUptimeCalls[0].args[1]
client.gauge.resetHistory()
const nowStub2 = sinon.stub(performance, 'now').returns(startPerformanceNow + 10_000)
clock.tick(10000) // Advance another 10 seconds
nowStub2.restore()
let nextUptimeCall = client.gauge.getCalls().filter(call => call.args[0] === 'runtime.node.process.uptime')
assert.strictEqual(nextUptimeCall.length, 1)
let nextUptime = nextUptimeCall[0].args[1]
// Uptime should be 10 seconds more
assert.strictEqual(
nextUptime - firstUptime,
10,
`Uptime diff should be 10 seconds, got ${nextUptime} - ${firstUptime}, start: ${startPerformanceNow}`
)
client.gauge.resetHistory()
const nowStub3 = sinon.stub(performance, 'now').returns(startPerformanceNow + 20_000)
clock.tick(10000) // Advance another 10 seconds
nowStub3.restore()
nextUptimeCall = client.gauge.getCalls().filter(call => call.args[0] === 'runtime.node.process.uptime')
assert.strictEqual(nextUptimeCall.length, 1)
nextUptime = nextUptimeCall[0].args[1]
// Uptime should be 10 seconds more
assert.strictEqual(
nextUptime - firstUptime,
20,
`Uptime diff should be 20 seconds, got ${nextUptime} - ${firstUptime}, start: ${startPerformanceNow}`
)
})
})
describe('Metric Consistency and Reliability', () => {
it('should produce consistent metrics across multiple flushes', () => {
runtimeMetrics.start(config)
const flushCount = 3
for (let i = 0; i < flushCount; i++) {
client.gauge.resetHistory()
client.increment.resetHistory()
client.histogram.resetHistory()
clock.tick(10000)
const metrics = client.gauge.getCalls().reduce((acc, call) => {
acc.set(call.args[0], call.args[1])
return acc
}, new Map())
// If event loop count or gc count is zero, the metrics are not reported.
assert.strictEqual(metrics.size, 22)
assert.strictEqual(client.histogram.getCalls().length, 0)
assert.strictEqual(client.increment.getCalls().length, 0)
}
})
it('should report expected memory usage values', () => {
const stats = process.memoryUsage()
const totalmem = os.totalmem()
const freemem = os.freemem()
sinon.stub(process, 'memoryUsage').returns(stats)
sinon.stub(os, 'totalmem').returns(totalmem)
sinon.stub(os, 'freemem').returns(freemem)
clock.tick(10000)
sinon.restore()
const metrics = client.gauge.getCalls().reduce((acc, call) => {
acc[call.args[0]] = call.args[1]
return acc
}, {})
assertObjectContains(metrics, {
'runtime.node.mem.heap_total': stats.heapTotal,
'runtime.node.mem.heap_used': stats.heapUsed,
'runtime.node.mem.rss': stats.rss,
'runtime.node.mem.total': totalmem,
'runtime.node.mem.free': freemem,
'runtime.node.mem.external': stats.external,
})
})
})
describe('when started', () => {
describe('stop', () => {
it('should stop collecting runtimeMetrics every 10 seconds', () => {
runtimeMetrics.stop()
clock.tick(10000)
sinon.assert.notCalled(client.gauge)
})
})
describe('histogram', () => {
it('should add a record to a histogram', () => {
runtimeMetrics.histogram('test', 0)
runtimeMetrics.histogram('test', 1)
runtimeMetrics.histogram('test', 2)
runtimeMetrics.histogram('test', 3)
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test.max', 3)
sinon.assert.calledWith(client.gauge, 'test.min', 0)
sinon.assert.calledWith(client.increment, 'test.sum', 6)
sinon.assert.calledWith(client.increment, 'test.total', 6)
sinon.assert.calledWith(client.gauge, 'test.avg', 1.5)
sinon.assert.calledWith(client.gauge, 'test.median', sinon.match.number)
sinon.assert.calledWith(client.gauge, 'test.95percentile', sinon.match.number)
sinon.assert.calledWith(client.increment, 'test.count', 4)
})
})
describe('increment', () => {
it('should increment a gauge', () => {
runtimeMetrics.increment('test')
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', 1)
})
it('should increment a gauge with a tag', () => {
runtimeMetrics.increment('test', 'foo:bar')
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', 1, ['foo:bar'])
})
it('should increment a monotonic counter', () => {
runtimeMetrics.increment('test', true)
clock.tick(10000)
sinon.assert.calledWith(client.increment, 'test', 1)
client.increment.resetHistory()
clock.tick(10000)
sinon.assert.neverCalledWith(client.increment, 'test')
})
it('should increment a monotonic counter with a tag', () => {
runtimeMetrics.increment('test', 'foo:bar', true)
clock.tick(10000)
sinon.assert.calledWith(client.increment, 'test', 1, ['foo:bar'])
client.increment.resetHistory()
clock.tick(10000)
sinon.assert.neverCalledWith(client.increment, 'test')
})
})
describe('decrement', () => {
it('should increment a gauge', () => {
runtimeMetrics.decrement('test')
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', -1)
})
it('should decrement a gauge with a tag', () => {
runtimeMetrics.decrement('test', 'foo:bar')
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', -1, ['foo:bar'])
})
})
describe('gauge', () => {
it('should set a gauge', () => {
runtimeMetrics.gauge('test', 10)
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', 10)
})
it('should set a gauge with a tag', () => {
runtimeMetrics.gauge('test', 10, 'foo:bar')
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', 10, ['foo:bar'])
})
})
describe('boolean', () => {
it('should set a gauge', () => {
runtimeMetrics.boolean('test', true)
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', 1)
})
it('should set a gauge with a tag', () => {
runtimeMetrics.boolean('test', true, 'foo:bar')
clock.tick(10000)
sinon.assert.calledWith(client.gauge, 'test', 1, ['foo:bar'])
})
})
})
})
})
})
describeSamplePerIteration('runtimeMetrics event loop delay via samplePerIteration (Node 24.19+ or >= 26.5)', () => {
let clock
let localClient
let nativeMetricsStart
let localRuntimeMetrics
let config
beforeEach(() => {
localClient = {
gauge: sinon.spy(),
increment: sinon.spy(),
histogram: sinon.spy(),
flush: sinon.spy(),
}
const LocalClient = sinon.spy(function () {
return {
gauge: localClient.gauge,
increment: localClient.increment,
histogram: localClient.histogram,
flush: localClient.flush,
}
})
LocalClient.generateClientConfig = DogStatsDClient.generateClientConfig
// If the native addon is ever started on a runtime that has the per-iteration
// sampler, this throws and fails the test loudly.
nativeMetricsStart = sinon.spy(() => {
throw new Error('Native metrics must not be started when samplePerIteration is available')
})
localRuntimeMetrics = proxyquire('../src/runtime_metrics/runtime_metrics', {
'./client': proxyquire('../src/runtime_metrics/client', {
'../dogstatsd': { DogStatsDClient: LocalClient },
}),
'@datadog/native-metrics': { start: nativeMetricsStart, stop () {} },
})
config = {
url: new URL('http://localhost:8126'),
dogstatsd: { hostname: 'localhost', port: 8125 },
// native is explicitly true to prove the real version gate wins over it.
runtimeMetrics: { enabled: true, eventLoop: true, gc: true, native: true },
tags: {},
DD_RUNTIME_METRICS_FLUSH_INTERVAL: 10000,
getOrigin: () => 'default',
}
clock = sinon.useFakeTimers({
toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'],
})
})