-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathnsolid.js
More file actions
1697 lines (1451 loc) · 46.5 KB
/
Copy pathnsolid.js
File metadata and controls
1697 lines (1451 loc) · 46.5 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 {
ArrayIsArray,
Date,
DateNow,
JSONParse,
JSONStringify,
NumberIsFinite,
NumberParseInt,
ObjectAssign,
ObjectDefineProperty,
ObjectGetOwnPropertyNames,
ObjectPrototype,
StringPrototypeTrim,
} = primordials;
/** @module nsolid */
const binding = internalBinding('nsolid_api');
const { getCPUs, getHostname, getTotalMem } = internalBinding('os');
const { cwd } = internalBinding('process_methods');
const { isMainThread } = internalBinding('worker');
const { isNativeError } = internalBinding('types');
const { ARGV, processTitle } = require('internal/nsolid_loader');
const { register, registerInstrumentations } = require('internal/otel/core');
const { URL } = require('internal/url');
const { addPackage, updatePackage, packageList, packagePaths } =
require('internal/nsolid_module');
const { existsSync, readdirSync, realpathSync } = require('fs');
const { dirname, relative, resolve, sep } = require('path');
const { Readable } = require('stream');
const {
validateBoolean,
validateNumber,
validateObject,
} = require('internal/validators');
const { Buffer } = require('buffer');
const debug = require('internal/util/debuglog').debuglog('nsolid');
const grpc = require('internal/agents/grpc/lib/nsolid');
const statsd = require('internal/agents/statsd/lib/nsolid');
const zmq = require('internal/agents/zmq/lib/nsolid');
const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_NSOLID_HEAP_PROFILE_START,
ERR_NSOLID_HEAP_SAMPLING_START,
},
} = require('internal/errors');
const {
clearFatalError,
nsolid_consts,
nsolid_counts,
getKernelVersion,
} = binding;
const DEFAULT_HOSTNAME = getHostname();
const DEFAULT_APPNAME = 'untitled application';
const DEFAULT_INTERVAL = 5000;
const DEFAULT_BLOCKED_LOOP_THRESHOLD = 200;
const DEFAULT_TRACING_SAMPLING_RATE = 1.0;
const DEFAULT_PUBKEY = '^kvy<i^qI<r{=ZDrfK4K<#NtqY+zaH:ksm/YGE6I';
const OBJECT_PROTO_NAMES = ObjectGetOwnPropertyNames(ObjectPrototype);
const OTLP_TYPES = [ 'datadog', 'dynatrace', 'newrelic', 'otlp' ];
const PROCESS_START = +new Date(DateNow() - (process.uptime() * 1000));
const SUPPORTED_TRACING_MODULES = {
dns: nsolid_consts.kSpanDns,
http: nsolid_consts.kSpanHttpClient | nsolid_consts.kSpanHttpServer,
};
let pkg_list_gend = false;
let pause_metrics = false;
let config_version = binding.getConfigVersion();
let config_cache = null;
// Immediately load the package.json and initialize a config object so calls to
// the JS API know what to do before start() runs. The initConfig object will
// no longer be used after start() runs.
const pkgConfig = loadMainPackageJson();
let initConfig = initializeConfig({});
const id = binding.agentId();
// Sometimes backwards compatibility makes me hate the world.
ObjectAssign(start, {
// How horrible is this?
start,
/**
* The time the process started in milliseconds.
* @alias module:nsolid.processStart
*/
processStart: +new Date(DateNow() - (process.uptime() * 1000)),
metrics,
packages,
info,
startupTimes,
pauseMetrics,
resumeMetrics,
/**
* @type {Zmq}
* @alias module:nsolid.zmq
*/
zmq: { status: zmq.status },
/**
* @type {string}
* @description Unique identifier of the NSolid agent.
* @alias module:nsolid.id
*/
id,
saveFatalError,
clearFatalError,
/**
* @type {StatsD}
* @alias module:nsolid.statsd
*/
statsd: {
status: statsd.status,
udpIp: statsd.udpIp,
tcpIp: statsd.tcpIp,
sendRaw: statsd.sendRaw,
counter: statsd.counter,
gauge: statsd.gauge,
set: statsd.set,
timing: statsd.timing,
format: statsd.format,
},
heapProfileStream,
heapProfile,
heapProfileEnd,
heapSamplingStream,
heapSampling,
heapSamplingEnd,
enableAssets,
disableAssets,
enableTraces,
disableTraces,
logger: {
debug: (msg) => { writeLog(msg, 5); },
info: (msg) => { writeLog(msg, 9); },
warn: (msg) => { writeLog(msg, 13); },
error: (msg) => { writeLog(msg, 17); },
fatal: (msg) => { writeLog(msg, 21); },
},
profile,
profileEnd,
snapshot,
on,
getThreadName,
setThreadName,
otel: {
register,
registerInstrumentations,
},
});
const assignObj = assignGetters(start, {
/**
* @member {NSolidConfig} config
* @description current configuration of the agent.
* @static
* @returns {NSolidConfig} current configuration of the agent.
*/
config: () => ObjectAssign({}, getConfig()),
/**
* @member {string} app
* @description application name.
* @static
* @returns {string} application name.
*/
app: () => getConfig('app') || DEFAULT_APPNAME,
/**
* @member {string} appName
* @description application name.
* @static
* @returns {string} application name.
*/
appName: () => getConfig('app') || DEFAULT_APPNAME,
/**
* @member {string} appVersion
* @description application version.
* @static
* @returns {string} application version.
*/
appVersion: () => getConfig('appVersion'),
/**
* @member {string[]} tags
* @description the list of tags associated with your instance,
* which can be used to identify and filter instances in Console views.
* @static
* @returns {string[]} the list of tags associated with your instance.
*/
tags: () =>
(ArrayIsArray(getConfig('tags')) ? getConfig('tags').slice() : []),
/**
* @member {boolean} metricsPaused
* @description whether the agent is currently retrieving metrics or not.
* @static
* @returns {boolean} the value of the pauseMetrics configuration option.
*/
metricsPaused: () => getConfig('pauseMetrics') || false,
/**
* @member {boolean} assetsEnabled
* @description whether the agent is currently retrieving assets or not.
* @static
* @returns {boolean} the value of the assetsEnabled configuration option.
*/
assetsEnabled: () => getConfig('assetsEnabled') ?? true,
/**
* @member {boolean} tracingEnabled
* @description whether tracing is currently enabled for the agent.
* @static
* @returns {boolean} the value of the tracingEnabled configuration option.
*/
tracingEnabled: () => getConfig('tracingEnabled') ?? false,
});
// If the return value is undefined then there was an issue. Return early.
if (assignObj === undefined) {
module.exports.start = function start() { };
return;
}
// Use defineProperty to make them not enumerable.
ObjectDefineProperty(start, 'toJSON', { __proto__: null, value: stringifyStart });
ObjectDefineProperty(start, '_getOnBlockedBody', {
__proto__: null,
value: () => JSONParse(binding._getOnBlockedBody()),
});
/**
* @member {TraceStats} traceStats
* @static
*/
start.traceStats = assignGetters({}, {
httpClientCount: () => nsolid_counts[nsolid_consts.kHttpClientCount],
httpServerCount: () => nsolid_counts[nsolid_consts.kHttpServerCount],
dnsCount: () => nsolid_counts[nsolid_consts.kDnsCount],
httpClientAbortCount: () =>
nsolid_counts[nsolid_consts.kHttpClientAbortCount],
httpServerAbortCount: () =>
nsolid_counts[nsolid_consts.kHttpServerAbortCount],
});
module.exports = start;
function writeLog(msg, sev) {
binding.writeLog(typeof msg === 'string' ? msg : JSONStringify(msg), sev);
}
function stringifyStart() {
const ret = {};
ObjectGetOwnPropertyNames(this).forEach((e) => {
if (e === 'length' || e === 'name' || e === 'prototype' || e === 'start')
return;
ret[e] = this[e];
});
return ret;
}
// Allow regenerating the info object as the `config` object could've changed
// some of the relevant info.
function genInfoObject(regen = false) {
let infoObj = null;
if (!regen) {
infoObj = binding.getProcessInfo();
}
if (infoObj !== null)
return infoObj;
const cpuData = getCPUs();
const nsolidConfig = getConfig();
infoObj = {
id,
app: nsolidConfig.app,
appVersion: nsolidConfig.appVersion,
tags: nsolidConfig.tags,
pid: process.pid,
processStart: PROCESS_START,
nodeEnv: nsolidConfig.env,
execPath: process.execPath,
main: ARGV[1] ? resolve(ARGV[1]) : '',
arch: process.arch,
platform: process.platform,
hostname: getNsolidHostname(),
totalMem: getTotalMem(),
versions: process.versions,
// The os internal binding returns a large array of values. Each group
// of 7 contains all the data for a single CPU. See the cpus() fn in
// lib/os.js for reference.
cpuCores: ArrayIsArray(cpuData) ? cpuData.length / 7 : null,
cpuModel: ArrayIsArray(cpuData) ? cpuData[0] : null,
kernelVersion: getKernelVersion(),
};
// In IISNODE environment, the processes are launched in the following way:
// $ nsolid interceptor.js server.js ...args
// where interceptor.js is a MITM script from iisnode and server.js is the
// main script. Then interceptor.js removes itself from process.argv.
// In this case we want to resolve ARGV[2]
if (nsolidConfig.iisNode) {
infoObj.iisNodeMain = ARGV[2] ? resolve(ARGV[2]) : '';
}
binding.storeProcessInfo(JSONStringify(infoObj));
return infoObj;
}
// eslint-disable-next-line jsdoc/require-returns-check
/**
* It returns relevant information about the running process and platform is
* running on.
* @param {InfoCallback} cb if a callback is passed, it is used to return the info asynchronously
* @example
* const nsolid = require('nsolid');
* nsolid.info((err, info) => {
* if(!err)
* console.log('Info', info);
* });
* @returns {(Info|undefined)} the actual info if no callback, undefined otherwise.
* @alias module:nsolid.info
*/
function info(cb) {
const o = genInfoObject();
if (typeof cb !== 'function')
return o;
process.nextTick(() => cb(null, o));
}
// eslint-disable-next-line jsdoc/require-returns-check
/**
* It retrieves a list of enviroment and process metrics.
* @param {MetricsCallback} cb if a callback is passed, it is used to return the metrics asynchronously
* @example
* nsolid.metrics((err, metrics) => {
* if(!err)
* console.log('Metrics', metrics);
* });
* @returns {(Metrics|undefined)} the actual metrics if no callback, undefined otherwise.
* @alias module:nsolid.metrics
*/
function metrics(cb) {
const envm = JSONParse(binding.getEnvMetrics());
const procm = JSONParse(binding.getProcessMetrics());
const m = ObjectAssign({}, envm, procm);
if (typeof cb !== 'function')
return m;
process.nextTick(() => cb(null, m));
}
/**
* It retrieves the list of packages used by the process.
* @param {PackagesCallback} cb if a callback is passed, it is used to return the packages asynchronously
* @example
* const nsolid = require('nsolid');
* nsolid.packages((err, packages) => {
* if(!err)
* console.log('Packages', packages);
* });
* @returns {Package[]|undefined} the actual packages if no callback, undefined otherwise.
* @alias module:nsolid.packages
*/
function packages(cb) {
if (!getConfig('disablePackageScan'))
genPackageList();
// Make a copy. Would be helpful if this was a deep copy, but eh.
const a = packageList.slice();
if (typeof cb !== 'function')
return a;
process.nextTick(() => cb(null, a));
}
function hasGrpcAssets() {
return !!(getConfig('grpc') || getConfig('saas'));
}
function heapProfile(timeout, trackAllocations, cb) {
if (hasGrpcAssets()) {
return grpc.heapProfile(timeout, trackAllocations, cb);
}
return zmq.heapProfile(timeout, trackAllocations, cb);
}
function heapProfileEnd(cb) {
if (hasGrpcAssets()) {
return grpc.heapProfileEnd(cb);
}
return zmq.heapProfileEnd(cb);
}
/**
* Starts a heap profile in a specific JS thread and returns a readable stream
* of the profile data.
* @param {number} threadId - The ID of the thread for which to start the heap profile.
* @param {number} duration - The duration in milliseconds for which to run the heap profile.
* @param {boolean} trackAllocations - Whether to track allocations during the heap profile.
* @example
* const nsolid = require('nsolid');
* const threadId = 1;
* const duration = 5000; // 5 seconds
* const trackAllocations = true;
* const heapProfileStream = nsolid.heapProfileStream(threadId, duration, trackAllocations);
* heapProfileStream.on('data', (data) => {
* console.log('Heap Profile Data:', data);
* });
* heapProfileStream.on('error', (err) => {
* console.error('Error:', err);
* });
* @returns {Readable} A readable stream of the heap profile data.
* It emits an {ERR_NSOLID_HEAP_PROFILE_START} if there is an error
* starting the heap profile.
* @alias module:nsolid.heapProfileStream
*/
function heapProfileStream(threadId, duration, trackAllocations, options) {
if (getConfig('assetsEnabled') === false)
throw new ERR_NSOLID_HEAP_PROFILE_START();
validateNumber(threadId, 'threadId');
validateNumber(duration, 'duration');
validateBoolean(trackAllocations, 'trackAllocations');
const redacted = getConfig('redactSnapshots') || false;
const readable = new Readable({
read() {
},
destroy(err, cb) {
binding.heapProfileEnd(threadId);
if (typeof cb === 'function')
cb(err);
},
});
const ret = binding.heapProfile(threadId, duration, trackAllocations, redacted, (status, data) => {
if (status !== 0) {
const err = new ERR_NSOLID_HEAP_PROFILE_START();
err.code = status;
readable.destroy(err);
} else if (data === null) {
readable.push(null);
} else {
readable.push(data);
}
});
if (ret !== 0) {
const err = new ERR_NSOLID_HEAP_PROFILE_START();
err.code = ret;
readable.destroy(err);
}
return readable;
}
const defaultHeapSamplingOptions = { sampleInterval: 512 * 1024, stackDepth: 16, flags: 0 };
function heapSampling(duration, options, cb) {
if (hasGrpcAssets()) {
return grpc.heapSampling(duration, options, cb);
}
return zmq.heapSampling(duration, options, cb);
}
function heapSamplingEnd(cb) {
if (hasGrpcAssets()) {
return grpc.heapSamplingEnd(cb);
}
return zmq.heapSamplingEnd(cb);
}
/**
* Starts a heap sampling in a specific JS thread and returns a readable stream
* of the profile data.
* @param {number} threadId - The ID of the thread for which to start the heap sampling.
* @param {number} duration - The duration in milliseconds for which to run the heap sampling.
* @param {object} [options] - Options to pass to the heap sampling.
* Defaults to { sampleInterval: 512 * 1024, stackDepth: 16, flags: 0 }.
* @param {number} options.sampleInterval every allocation will be allocated every `sampleInterval` bytes
* @param {string} options.stackDepth stack depth to capture
* @param {string} options.flags
* flags to pass to the profiler. See:
* https://v8docs.nodesource.com/node-20.3/d7/d76/classv8_1_1_heap_profiler.html#a785d454e7866f222e199d667be567392
* @example
* const nsolid = require('nsolid');
* const threadId = 1;
* const duration = 5000; // 5 seconds
* const trackAllocations = true;
* const heapSamplingStream = nsolid.heapSamplingStream(threadId, duration, {});
* heapSamplingStream.on('data', (data) => {
* console.log('Heap Sampling Data:', data);
* });
* heapSamplingStream.on('error', (err) => {
* console.error('Error:', err);
* });
* @returns {Readable} A readable stream of the heap sampling data. It emits an
* {ERR_NSOLID_HEAP_SAMPLING_START} if there is an error starting the heap sampling.
* @alias module:nsolid.heapSamplingStream
*/
function heapSamplingStream(threadId, duration, options) {
if (getConfig('assetsEnabled') === false)
throw new ERR_NSOLID_HEAP_SAMPLING_START();
validateNumber(threadId, 'threadId');
validateNumber(duration, 'duration', 1);
options ||= {};
validateObject(options, 'options');
options = { ...defaultHeapSamplingOptions, ...options };
validateNumber(options.sampleInterval, 'options.sampleInterval', 1);
validateNumber(options.stackDepth, 'options.stackDepth');
validateNumber(options.flags, 'options.flags');
const readable = new Readable({
read() {
},
destroy(err, cb) {
binding.heapSamplingEnd(threadId);
if (typeof cb === 'function')
cb(err);
},
});
const { sampleInterval, stackDepth, flags } = options;
const ret = binding.heapSampling(threadId, duration, sampleInterval, stackDepth, flags, (status, data) => {
if (status !== 0) {
const err = new ERR_NSOLID_HEAP_SAMPLING_START();
err.code = status;
readable.destroy(err);
} else if (data === null) {
readable.push(null);
} else {
readable.push(data);
}
});
if (ret !== 0) {
const err = new ERR_NSOLID_HEAP_SAMPLING_START();
err.code = ret;
readable.destroy(err);
}
return readable;
}
function profile(timeout, cb) {
if (hasGrpcAssets()) {
return grpc.profile(timeout, cb);
}
return zmq.profile(timeout, cb);
}
function profileEnd(cb) {
if (hasGrpcAssets()) {
return grpc.profileEnd(cb);
}
return zmq.profileEnd(cb);
}
function snapshot(cb) {
if (hasGrpcAssets()) {
return grpc.snapshot(cb);
}
return zmq.snapshot(cb);
}
/**
* It retrieves the startup times of the process.
* @param {StartupTimesCallback} cb if a callback is passed, it is used to
* return the startup times asynchronously
* @example
* nsolid.startupTimes((err, startupTimes) => {
* if(!err)
* console.log(startupTimes);
* });
* @returns {StartupTimes|undefined} the actual startup times if
* no callback, undefined otherwise.
* @alias module:nsolid.startupTimes
*/
function startupTimes(cb) {
const data = JSONParse(binding.getStartupTimes());
if (typeof cb !== 'function')
return data;
process.nextTick(() => cb(null, data));
}
/**
* It pauses the process metrics collection. It works only if called from the
* main thread.
* @alias module:nsolid.pauseMetrics
*/
function pauseMetrics() {
if (!isMainThread)
return;
if (pause_metrics)
return;
pause_metrics = true;
// Update the config only if it's already been generated.
if (binding.getConfigVersion() !== 0)
binding.pauseMetrics();
}
function enableAssets() {
if (getConfig('assetsEnabled') === true)
return;
updateConfig({ assetsEnabled: true });
}
function disableAssets() {
if (getConfig('assetsEnabled') === false)
return;
updateConfig({ assetsEnabled: false });
}
function enableTraces() {
if (getConfig('tracingEnabled') === true)
return;
updateConfig({ tracingEnabled: true });
}
function disableTraces() {
if (getConfig('tracingEnabled') === false)
return;
updateConfig({ tracingEnabled: false });
}
/**
* It resumes the process metrics collection. It works only if called from the
* main thread.
* @alias module:nsolid.resumeMetrics
*/
function resumeMetrics() {
if (!isMainThread)
return;
if (!pause_metrics)
return;
pause_metrics = false;
// Update the config only if it's already been generated.
if (binding.getConfigVersion() !== 0)
binding.resumeMetrics();
}
// eslint-disable-next-line jsdoc/require-returns-check
/**
* Starts the agent with a specific configuration. If the agent was already
* started it updates its configuration.
* @param {NSolidConfig} config
* @returns {module:nsolid} the NSolid object.
* @throws {Error} exception if the configuration is bogus.
* @alias module:nsolid.start
*/
function start(config/* , agentCb */) {
if (!isMainThread)
return;
updateConfig(config);
const nsolidConfig = getConfig();
genInfoObject(true);
if (nsolidConfig.command) {
debug('starting zmq');
debug({
zmq_command_remote: nsolidConfig.command,
zmq_data_remote: nsolidConfig.data,
zmq_bulk_remote: nsolidConfig.bulk,
storage_pubkey: nsolidConfig.pubkey,
disableIpv6: nsolidConfig.disableIpv6,
});
zmq.start();
}
if (nsolidConfig.grpc || nsolidConfig.saas) {
debug('starting grpc');
grpc.start();
}
if (!nsolidConfig.disablePackageScan)
genPackageList();
debug('starting agent name: %s id: %s tags: %s',
nsolidConfig.app,
nsolidConfig.id,
nsolidConfig.tags);
return start;
}
/* These can be set by environment as well as the config object.
* It is possible for this environment to be present, even if it
* was not at process start, such is the case with pm2 in cluster
* mode
*
* Config order:
* 1. configuration object (js API)
* 2. environment variables
* 3. package.json
* 4. (key specific, e.g. app) */
function updateConfig(config = {}) {
const nsolidConfig = {};
// If getConfigVersion() === 0 then binding.updateConfig() hasn't run yet. So
// initialize the object and pass it to the native side.
if (binding.getConfigVersion() === 0) {
initializeConfig(nsolidConfig);
}
for (const key in config) {
// Don't assign names that are part of the default constructor.
if (OBJECT_PROTO_NAMES.includes(key))
continue;
// Assigning tags needs a function call.
if (key === 'tags') {
nsolidConfig.tags = getTags(config.tags);
// These two had a special condition in v3.x so treating it the same.
} else if (key === 'pubkey' || key === 'disableIpv6') {
if (config[key] != null)
nsolidConfig[key] = config[key];
// TODO(santi): Implement validation for every property
} else if ([ 'command', 'data', 'bulk', 'statsd', 'grpc' ].includes(key)) {
let value = config[key];
if (value) {
// Make sure some hostname is always provided if only port was passed.
if (typeof value === 'number')
value = 'localhost:' + value;
if (typeof value !== 'string')
throw new ERR_INVALID_ARG_TYPE(`config.${key}`, 'string', value);
nsolidConfig[key] = value;
} else if (key === 'statsd' || key === 'grpc') {
// The statsd variable can now be set to null to stop the statsd agent.
nsolidConfig[key] = value;
}
} else if (key === 'otlp') {
const otlp = parseOTLPType(config.otlp);
if (otlp !== nsolidConfig.otlp) {
nsolidConfig.otlp = otlp;
nsolidConfig.otlpConfig = null;
}
} else if (key === 'otlpConfig' && nsolidConfig.otlp) {
nsolidConfig.otlpConfig = parseOTLPConfig(config.otlpConfig,
nsolidConfig.otlp);
} else if (key === 'contCpuProfile') {
nsolidConfig.contCpuProfile = envToBool(config.contCpuProfile);
} else if (key === 'contCpuProfileInterval') {
nsolidConfig.contCpuProfileInterval = +config.contCpuProfileInterval;
} else if (key === 'assetsEnabled') {
const normalized = optionToBool(config.assetsEnabled);
if (normalized !== undefined) {
nsolidConfig.assetsEnabled = normalized;
}
} else if (key === 'interval') {
const normalized = parsePositiveFiniteNumber(config.interval);
if (normalized !== undefined) {
nsolidConfig.interval = normalized;
}
} else if (key === 'traceSampleRate') {
const normalized = parseTraceSampleRate(config.traceSampleRate);
if (normalized !== undefined) {
nsolidConfig.traceSampleRate = normalized;
}
} else {
nsolidConfig[key] = config[key];
}
}
if (nsolidConfig.otlpConfig === null &&
!(nsolidConfig.otlp === 'otlp' && !config.otlpConfig)) {
nsolidConfig.otlp = null;
}
if (nsolidConfig.saas) {
if (!config.command) {
nsolidConfig.command = null;
}
if (nsolidConfig.command) {
nsolidConfig.saas = undefined;
} else {
const url = parseSaasEnvVar(nsolidConfig.saas, 0);
if (!url) {
nsolidConfig.saas = undefined;
} else if (config.grpc == null) {
nsolidConfig.grpc = null;
} else {
nsolidConfig.grpc = '' + config.grpc;
}
}
}
if (nsolidConfig.grpc && !nsolidConfig.saas) {
// Make sure it's a valid URL otherwise it might crash in the grpc++
// URLParser implementation
try {
new URL(`http://${nsolidConfig.grpc}`);
} catch {
process._rawDebug(`Invalid grpc url: "${nsolidConfig.grpc}"`);
nsolidConfig.grpc = null;
}
}
binding.updateConfig(JSONStringify(nsolidConfig));
// Now that the config has been set on the native side, can remove the
// initConfig object so it doesn't waste memory.
initConfig = null;
if (typeof nsolidConfig.pubkey === 'string' &&
nsolidConfig.pubkey.length !== 40) {
debug('[updateConfig] invalid pubkey; must be 40 bytes');
}
}
function initializeConfig(nsolidConfig) {
nsolidConfig.pauseMetrics = pause_metrics;
// ZMQ "COMMAND" socket
nsolidConfig.command =
process.env.NSOLID_COMMAND_REMOTE ||
process.env.NSOLID_COMMAND ||
pkgConfig.nsolid.command;
// ZMQ "DATA" socket
nsolidConfig.data =
process.env.NSOLID_DATA_REMOTE ||
process.env.NSOLID_DATA ||
pkgConfig.nsolid.data;
// ZMQ "BULK" socket
nsolidConfig.bulk =
process.env.NSOLID_BULK_REMOTE ||
process.env.NSOLID_BULK ||
pkgConfig.nsolid.bulk;
// Storage ZMQ curve encryption public key
nsolidConfig.pubkey =
process.env.NSOLID_STORAGE_PUBKEY ||
process.env.NSOLID_PUBKEY ||
pkgConfig.nsolid.pubkey ||
DEFAULT_PUBKEY;
// GRPC Agent configuration
nsolidConfig.grpc = process.env.NSOLID_GRPC || pkgConfig.nsolid.grpc;
nsolidConfig.saas = process.env.NSOLID_SAAS || pkgConfig.nsolid.saas;
if (nsolidConfig.saas) {
if (nsolidConfig.command) {
nsolidConfig.saas = undefined;
} else {
const url = parseSaasEnvVar(nsolidConfig.saas, 0);
if (!url) {
nsolidConfig.saas = undefined;
} else if (!nsolidConfig.grpc) {
nsolidConfig.command = url;
}
}
}
// Some kernels will not work if ipv6 is even attempted so allow an out
nsolidConfig.disableIpv6 =
envToBool(process.env.NSOLID_DISABLE_IPV6) ||
pkgConfig.nsolid.disableIpv6;
// StatsD daemon address
nsolidConfig.statsd =
process.env.NSOLID_STATSD ||
pkgConfig.nsolid.statsd;
// StatsD bucket prefix format string
nsolidConfig.statsdBucket =
process.env.NSOLID_STATSD_BUCKET ||
pkgConfig.nsolid.statsdBucket ||
// eslint-disable-next-line no-template-curly-in-string
'nsolid.${env}.${app}.${hostname}.${shortId}';
// StatsD tags extension format string
nsolidConfig.statsdTags =
process.env.NSOLID_STATSD_TAGS ||
pkgConfig.nsolid.statsdTags;
// Hostname override
nsolidConfig.hostname =
process.env.NSOLID_HOSTNAME ||
pkgConfig.nsolid.hostname ||
DEFAULT_HOSTNAME;
// Environment
nsolidConfig.env =
process.env.NODE_ENV ||
pkgConfig.nsolid.env ||
'prod';
// Metrics send interval
const envInterval = parsePositiveFiniteNumber(process.env.NSOLID_INTERVAL);
const pkgInterval = parsePositiveFiniteNumber(pkgConfig.nsolid.interval);
nsolidConfig.interval =
envInterval ??
pkgInterval ??
DEFAULT_INTERVAL;
nsolidConfig.tags = getTags(process.env.NSOLID_TAGS || pkgConfig.nsolid.tags);
nsolidConfig.app =
process.env.NSOLID_APPNAME ||
process.env.NSOLID_APP ||
pkgConfig.nsolid.app ||
pkgConfig.name ||
(processTitle !== process.title && process.title) ||
DEFAULT_APPNAME;
nsolidConfig.blockedLoopThreshold =
+process.env.NSOLID_BLOCKED_LOOP_THRESHOLD ||
+pkgConfig.nsolid.blockedLoopThreshold ||
DEFAULT_BLOCKED_LOOP_THRESHOLD;
// Application version
nsolidConfig.appVersion = pkgConfig.version;
// Allow snapshots to be disabled. This cannot be overridden to false, so if
// any of these are true it remains on.
nsolidConfig.disableSnapshots =
envToBool(process.env.NSOLID_DISABLE_SNAPSHOTS) ||
pkgConfig.nsolid.disableSnapshots;
// Allow snapshots to be redacted. This cannot be overridden to false, so if
// any of these are true it remains on.
nsolidConfig.redactSnapshots =
envToBool(process.env.NSOLID_REDACT_SNAPSHOTS) ||
pkgConfig.nsolid.redactSnapshots;
// Tracing enabled
nsolidConfig.tracingEnabled =
envToBool(process.env.NSOLID_TRACING_ENABLED) ||
!!pkgConfig.nsolid.tracingEnabled;
const envTraceSampleRate =
parseTraceSampleRate(process.env.NSOLID_TRACE_SAMPLE_RATE);
if (envTraceSampleRate !== undefined) {
nsolidConfig.traceSampleRate = envTraceSampleRate;
} else {
const pkgTraceSampleRate =
parseTraceSampleRate(pkgConfig.nsolid.traceSampleRate);
if (pkgTraceSampleRate !== undefined) {
nsolidConfig.traceSampleRate = pkgTraceSampleRate;
} else {
nsolidConfig.traceSampleRate = DEFAULT_TRACING_SAMPLING_RATE;
}
}
// Disable auto-instrumented modules
nsolidConfig.tracingModulesBlacklist =
parseTracingModulesList(process.env.NSOLID_TRACING_MODULES_BLACKLIST ||
pkgConfig.nsolid.tracingModulesBlacklist);
const envAssetsEnabled = optionToBool(process.env.NSOLID_ASSETS_ENABLED);
const pkgAssetsEnabled = optionToBool(pkgConfig.nsolid.assetsEnabled);
if (envAssetsEnabled !== undefined) {
nsolidConfig.assetsEnabled = envAssetsEnabled;
} else if (pkgAssetsEnabled !== undefined) {
nsolidConfig.assetsEnabled = pkgAssetsEnabled;
} else {
nsolidConfig.assetsEnabled = true;
}
// Promise Tracking
nsolidConfig.promiseTracking =
envToBool(process.env.NSOLID_PROMISE_TRACKING) ||
!!pkgConfig.nsolid.promiseTracking;
// IISNODE
nsolidConfig.iisNode =
envToBool(process.env.NSOLID_IISNODE) ||