-
Notifications
You must be signed in to change notification settings - Fork 404
/
Copy pathindex.js
1865 lines (1661 loc) · 57.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
'use strict'
const AttributeFilter = require('./attribute-filter')
const CollectorResponse = require('../collector/response')
const copy = require('../util/copy')
const { config: defaultConfig, definition, setNestedKey } = require('./default')
const EventEmitter = require('events').EventEmitter
const featureFlag = require('../feature_flags')
const flatten = require('../util/flatten')
const fs = require('../util/unwrapped-core').fs
const hashes = require('../util/hashes')
const os = require('os')
const parseKey = require('../collector/key-parser').parseKey
const path = require('path')
const stringify = require('json-stringify-safe')
const util = require('util')
const MergeServerConfig = require('./merge-server-config')
const harvestConfigValidator = require('./harvest-config-validator')
const mergeServerConfig = new MergeServerConfig()
const { boolean: isTruthular } = require('./formatters')
const configDefinition = definition()
const parseLabels = require('../util/label-parser')
/**
* CONSTANTS -- we gotta lotta 'em
*/
const AZURE_APP_NAME = 'APP_POOL_ID'
const DEFAULT_MAX_PAYLOAD_SIZE_IN_BYTES = 1_000_000
const BASE_CONFIG_PATH = require.resolve('../../newrelic')
const HAS_ARBITRARY_KEYS = new Set(['ignore_messages', 'expected_messages', 'labels'])
const LASP_MAP = require('./lasp').LASP_MAP
const HSM = require('./hsm')
const REMOVE_BEFORE_SEND = new Set(['attributeFilter'])
const SSL_WARNING = 'SSL config key can no longer be disabled, not updating.'
const SERVERLESS_DT_KEYS = ['account_id', 'primary_application_id', 'trusted_account_key']
const exists = fs.existsSync
let logger = null // Lazy-loaded in `initialize`.
let _configInstance = null
const getConfigFileNames = () =>
[process.env.NEW_RELIC_CONFIG_FILENAME, 'newrelic.js', 'newrelic.cjs', 'newrelic.mjs'].filter(
Boolean
)
const getConfigFileLocations = () =>
[
process.env.NEW_RELIC_HOME,
process.cwd(),
process.env.HOME,
path.join(__dirname, '../../../..'), // above node_modules
// the REPL has no main module
process.mainModule && process.mainModule.filename
? path.dirname(process.mainModule.filename)
: undefined
].filter(Boolean)
function _findConfigFile() {
const configFileCandidates = getConfigFileLocations().reduce((files, configPath) => {
const configFiles = getConfigFileNames().map((filename) =>
path.join(path.resolve(configPath), filename)
)
return files.concat(configFiles)
}, [])
return configFileCandidates.find(exists)
}
/**
* Indicates if the agent should be enabled or disabled based upon the
* processed configuration.
*
* @event Config#agent_enabled
* @param {boolean} indication
*/
/**
* Indicates that the configuration has changed due to some external factor,
* e.g. the configuration from the New Relic server has overridden some
* local setting.
*
* @event Config#change
* @param {Config} currentConfig
*/
/**
* Parses and manages the agent configuration.
*
* @param {object} config Configuration object as read from a `newrelic.js`
* file. This is used as the baseline, which is the overridden by environment
* variables and feature flags.
*
* @class
*/
function Config(config) {
EventEmitter.call(this)
// 1. start by cloning the defaults
Object.assign(this, defaultConfig())
// 2. initialize undocumented, internal-only default values
// feature flags are mostly private settings for gating unreleased features
// flags are set in the feature_flags.js file
this.feature_flag = copy.shallow(featureFlag.prerelease)
// set by environment
this.newrelic_home = null
// set by configuration file loader
this.config_file_path = null
// set by collector on handshake
this.run_id = null
this.account_id = null
this.application_id = null
this.web_transactions_apdex = Object.create(null)
this.cross_process_id = null
this.encoding_key = null
this.obfuscatedId = null
this.primary_application_id = null
this.trusted_account_ids = null
this.trusted_account_key = null
this.sampling_target = 10
this.sampling_target_period_in_seconds = 60
this.max_payload_size_in_bytes = DEFAULT_MAX_PAYLOAD_SIZE_IN_BYTES
// this value is arbitrary
this.max_trace_segments = 900
this.entity_guid = null
// feature level of this account
this.product_level = 0
// product-level related
this.collect_traces = true
this.collect_errors = true
this.collect_span_events = true
this.browser_monitoring.loader = 'rum'
this.browser_monitoring.loader_version = ''
// Settings to play nice with DLPs (see NODE-1044).
this.simple_compression = false // Disables subcomponent compression
this.put_for_data_send = false // Changes http verb for harvest
// 3. override defaults with values from the loaded / passed configuration
this._fromPassed(config)
// 3.5. special values (only Azure environment APP_POOL_ID for now)
this._fromSpecial()
// 4. override config with environment variables
this._featureFlagsFromEnv()
this._fromEnvironment()
// 5. clean up anything that requires postprocessing
this._canonicalize()
// 6. put the version in the config
this.version = require('../../package.json').version
// TODO: this may belong in canonicalize.
if (!this.event_harvest_config) {
this.event_harvest_config = {
report_period_ms: 60000,
harvest_limits: {
analytic_event_data: this.transaction_events.max_samples_stored,
custom_event_data: this.custom_insights_events.max_samples_stored,
error_event_data: this.error_collector.max_event_samples_stored,
span_event_data: this.span_events.max_samples_stored,
log_event_data: this.application_logging.forwarding.max_samples_stored
}
}
}
// 7. serverless_mode specific settings
this._enforceServerless(config)
// 8. apply high security overrides
if (this.high_security) {
if (this.security_policies_token) {
throw new Error(
'Security Policies and High Security Mode cannot both be present ' +
'in the agent configuration. If Security Policies have been set ' +
'for your account, please ensure the security_policies_token is ' +
'set but high_security is disabled (default).'
)
}
this._applyHighSecurity()
}
// 9. Set instance attribute filter using updated context
this.attributeFilter = new AttributeFilter(this)
// 10. Setup labels for both `collector/facts` and application logging
this.parsedLabels = parseLabels(this.labels, logger)
this.loggingLabels = this._setApplicationLoggingLabels()
}
util.inherits(Config, EventEmitter)
/**
* Compares the labels list to the application logging excluded label list and removes any labels that need to be excluded.
* Then prefixing each label with "tags."
*
* assigns labels to `config.loggingLabels`
*/
Config.prototype._setApplicationLoggingLabels = function setApplicationLoggingLabels() {
if (this.application_logging.forwarding.labels.enabled === false) {
return
}
this.application_logging.forwarding.labels.exclude =
this.application_logging.forwarding.labels.exclude.map((k) => k.toLowerCase())
return this.parsedLabels.reduce((filteredLabels, label) => {
if (
!this.application_logging.forwarding.labels.exclude.includes(label.label_type.toLowerCase())
) {
filteredLabels[`tags.${label.label_type}`] = label.label_value
}
return filteredLabels
}, {})
}
/**
* Because this module and logger depend on each other, the logger needs
* a way to inject the actual logger instance once it's constructed.
* It's kind of a Rube Goldberg device, but it works.
*
* @param {Logger} bootstrapped The actual, configured logger.
*/
Config.prototype.setLogger = function setLogger(bootstrapped) {
logger = bootstrapped
}
/**
* helper object for merging server side values
*/
Config.prototype.mergeServerConfig = mergeServerConfig
/**
* Accept any configuration passed back from the server. Will log all
* recognized, unsupported, and unknown parameters.
*
* @param {object} json The config blob sent by New Relic.
* @param {boolean} recursion flag indicating coming from server side config
*
* @fires Config#agent_enabled When there is a conflict between the local
* setting of high security mode and what the New Relic server has returned.
* @fires Config#change
*/
Config.prototype.onConnect = function onConnect(json, recursion) {
json = json || Object.create(null)
if (this.high_security && recursion !== true && !json.high_security) {
this.agent_enabled = false
this.emit('agent_enabled', false)
return
}
if (Object.keys(json).length === 0) {
return
}
Object.keys(json).forEach(function updateProp(key) {
this._fromServer(json, key)
}, this)
this._warnDeprecations()
this.emit('change', this)
}
Config.prototype._getMostSecure = function getMostSecure(key, currentVal, newVal) {
const filter = LASP_MAP[key] && LASP_MAP[key].filter
if (!this.security_policies_token || !filter) {
// If we aren't applying something vetted by security policies we
// just return the new value.
return newVal
}
// Return the most secure if we have a filter to apply
return filter(currentVal, newVal)
}
/**
* Helper that checks if value from server is false
* then updates the corresponding configuration enabled flag.
* We never allow server-side config to enable a feature but you can disable
*
* @param {*} serverValue value from server
* @param {string} key within configuration to disable its enabled flag
*/
Config.prototype._disableOption = function _disableOption(serverValue, key) {
if (serverValue === false) {
this[key].enabled = false
}
}
/**
* Updates harvest_limits for event_harvest_config if they are valid values
*
* @param {object} serverConfig harvest config from server
* @param {string} key value from server side config that stores the event harvest config
*/
Config.prototype._updateHarvestConfig = function _updateHarvestConfig(serverConfig, key) {
const val = serverConfig[key]
const isValidConfig = harvestConfigValidator.isValidHarvestConfig(val)
if (!isValidConfig) {
this.emit(key, null)
return
}
logger.info('Valid event_harvest_config received. Updating harvest cycles.', val)
const limits = Object.keys(val.harvest_limits).reduce((acc, k) => {
const v = val.harvest_limits[k]
if (harvestConfigValidator.isValidHarvestValue(v)) {
acc[k] = v
} else {
logger.info(`Omitting limit for ${k} due to invalid value ${v}`)
}
return acc
}, {})
val.harvest_limits = limits
this[key] = val
this.emit(key, val)
}
/**
* The guts of the logic about how to deal with server-side configuration.
*
* @param {object} params A configuration dictionary.
* @param {string} key The particular configuration parameter to set.
*
* @fires Config#change
*/
Config.prototype._fromServer = function _fromServer(params, key) {
/* eslint-disable-next-line sonarjs/max-switch-cases */
switch (key) {
// handled by the connection
case 'messages':
break
// per the spec this is the key where all server side configuration values will come from.
case 'agent_config':
if (this.ignore_server_configuration) {
this.logDisabled(params, key)
} else {
this.onConnect(params[key], true)
}
break
// if it's undefined or null, so be it
case 'agent_run_id':
this.run_id = params.agent_run_id
break
// if it's undefined or null, so be it
case 'request_headers_map':
this.request_headers_map = params.request_headers_map
break
// handled by config.onConnect
case 'high_security':
break
// interpret AI Monitoring account setting
case 'collect_ai':
this._disableOption(params.collect_ai, 'ai_monitoring')
this.emit('change', this)
break
// always accept these settings
case 'cross_process_id':
case 'encoding_key':
this._alwaysUpdateIfChanged(params, key)
if (this.cross_process_id && this.encoding_key) {
this.obfuscatedId = hashes.obfuscateNameUsingKey(this.cross_process_id, this.encoding_key)
}
break
// always accept these settings
case 'account_id':
case 'application_id':
case 'collect_errors':
case 'collect_traces':
case 'primary_application_id':
case 'product_level':
case 'max_payload_size_in_bytes':
case 'sampling_target':
case 'sampling_target_period_in_seconds':
case 'trusted_account_ids':
case 'trusted_account_key':
this._alwaysUpdateIfChanged(params, key)
break
case 'collect_error_events':
if (params.collect_error_events === false) {
this._updateNestedIfChanged(params, this.error_collector, key, 'capture_events')
}
break
// also accept these settings
case 'url_rules':
case 'metric_name_rules':
case 'transaction_name_rules':
case 'transaction_segment_terms':
this._emitIfSet(params, key)
break
case 'ssl':
if (!isTruthular(params.ssl)) {
logger.warn(SSL_WARNING)
}
break
case 'apdex_t':
case 'web_transactions_apdex':
this._updateIfChanged(params, key)
break
case 'event_harvest_config':
this._updateHarvestConfig(params, key)
break
case 'collect_analytics_events':
this._disableOption(params.collect_analytics_events, 'transaction_events')
break
case 'collect_custom_events':
this._disableOption(params.collect_custom_events, 'custom_insights_events')
break
case 'collect_span_events':
this._disableOption(params.collect_span_events, 'span_events')
break
case 'allow_all_headers':
this._updateIfChanged(params, key)
this._canonicalize()
break
//
// Browser Monitoring
//
case 'browser_monitoring.loader':
this._updateNestedIfChangedRaw(params, this.browser_monitoring, key, 'loader')
break
// these are used by browser_monitoring
// and the api.getRUMHeader() method
case 'js_agent_file':
case 'js_agent_loader_file':
case 'beacon':
case 'error_beacon':
case 'browser_key':
case 'js_agent_loader':
this._updateNestedIfChangedRaw(params, this.browser_monitoring, key, key)
break
//
// Cross Application Tracer
//
case 'cross_application_tracer.enabled':
this._updateNestedIfChanged(params, this.cross_application_tracer, key, 'enabled')
break
//
// Error Collector
//
case 'error_collector.enabled':
this._updateNestedIfChanged(
params,
this.error_collector,
'error_collector.enabled',
'enabled'
)
break
case 'error_collector.ignore_status_codes':
this._validateThenUpdateStatusCodes(
params,
this.error_collector,
'error_collector.ignore_status_codes',
'ignore_status_codes'
)
this._canonicalize()
break
case 'error_collector.expected_status_codes':
this._validateThenUpdateStatusCodes(
params,
this.error_collector,
'error_collector.expected_status_codes',
'expected_status_codes'
)
this._canonicalize()
break
case 'error_collector.ignore_classes':
this._validateThenUpdateErrorClasses(
params,
this.error_collector,
'error_collector.ignore_classes',
'ignore_classes'
)
break
case 'error_collector.expected_classes':
this._validateThenUpdateErrorClasses(
params,
this.error_collector,
'error_collector.expected_classes',
'expected_classes'
)
break
case 'error_collector.ignore_messages':
this._validateThenUpdateErrorMessages(
params,
this.error_collector,
'error_collector.ignore_messages',
'ignore_messages'
)
break
case 'error_collector.expected_messages':
this._validateThenUpdateErrorMessages(
params,
this.error_collector,
'error_collector.expected_messages',
'expected_messages'
)
break
case 'error_collector.capture_events':
this._updateNestedIfChanged(
params,
this.error_collector,
'error_collector.capture_events',
'capture_events'
)
break
case 'error_collector.max_event_samples_stored':
this._updateNestedIfChanged(
params,
this.error_collector,
'error_collector.max_event_samples_stored',
'max_event_samples_stored'
)
break
//
// Slow SQL
//
case 'slow_sql.enabled':
this._updateNestedIfChanged(params, this.slow_sql, key, 'enabled')
break
//
// Transaction Events
//
case 'transaction_events.enabled':
this._updateNestedIfChanged(params, this.transaction_events, key, 'enabled')
break
//
// Transaction Tracer
//
case 'transaction_tracer.enabled':
this._updateNestedIfChanged(
params,
this.transaction_tracer,
'transaction_tracer.enabled',
'enabled'
)
break
case 'transaction_tracer.transaction_threshold':
this._updateNestedIfChanged(
params,
this.transaction_tracer,
'transaction_tracer.transaction_threshold',
'transaction_threshold'
)
break
// Entity GUID
case 'entity_guid':
this.entity_guid = params[key]
break
// These settings aren't supported by the agent (yet).
case 'sampling_rate':
case 'episodes_file':
case 'episodes_url':
case 'rum.load_episodes_file':
// Ensure the most secure setting is applied to the settings below
// when enabling them.
case 'attributes.include_enabled': // eslint-disable-line no-fallthrough
case 'strip_exception_messages.enabled':
case 'transaction_tracer.record_sql':
this.logUnsupported(params, key)
break
// DT span event harvest config limits
case 'span_event_harvest_config':
this.span_event_harvest_config = {
...params[key]
}
break
// These settings are not allowed from the server.
case 'attributes.enabled':
case 'attributes.exclude':
case 'attributes.include':
case 'browser_monitoring.attributes.enabled':
case 'browser_monitoring.attributes.exclude':
case 'browser_monitoring.attributes.include':
case 'error_collector.attributes.enabled':
case 'error_collector.attributes.exclude':
case 'error_collector.attributes.include':
case 'transaction_events.attributes.enabled':
case 'transaction_events.attributes.exclude':
case 'transaction_events.attributes.include':
case 'transaction_events.max_samples_stored':
case 'transaction_tracer.attributes.enabled':
case 'transaction_tracer.attributes.exclude':
case 'transaction_tracer.attributes.include':
case 'serverless_mode.enabled':
break
default:
this.logUnknown(params, key)
}
}
/**
* Change a value sent by the collector if and only if it's different from the
* value we already have. Emit an event with the key name and the new value,
* and log that the value has changed.
*
* @param {object} json Config blob sent by collector.
* @param {string} key Value we're looking to set.
*/
Config.prototype._alwaysUpdateIfChanged = function _alwaysUpdateIfChanged(json, key) {
const value = json[key]
if (value != null && this[key] !== value) {
if (Array.isArray(value) && Array.isArray(this[key])) {
value.forEach(function pushIfNew(element) {
if (this[key].indexOf(element) === -1) {
this[key].push(element)
}
}, this)
} else {
this[key] = value
}
this.emit(key, value)
logger.debug('Configuration of %s was changed to %s by New Relic.', key, value)
}
}
/**
* Change a value sent by the collector if and only if it's different from the
* value we already have. Emit an event with the key name and the new value,
* and log that the value has changed.
*
* @param {object} json Config blob sent by collector.
* @param {string} key Value we're looking to set.
*/
Config.prototype._updateIfChanged = function _updateIfChanged(json, key) {
this._updateNestedIfChanged(json, this, key, key)
}
/**
* Expected and Ignored status code configuration values should look like this
*
* [500,'501','503-507']
*
* If the server side config is not in this format, it might put the agent
* in a world of hurt. So, before we pass everything on to
* _updateNestedIfChanged, we'll do some validation.
*
* @param {object} remote JSON sent from New Relic.
* @param {object} local A portion of this configuration object.
* @param {string} remoteKey The name sent by New Relic.
* @param {string} localKey The local name.
*/
Config.prototype._validateThenUpdateStatusCodes = _validateThenUpdateStatusCodes
function _validateThenUpdateStatusCodes(remote, local, remoteKey, localKey) {
const valueToTest = remote[remoteKey]
if (!Array.isArray(valueToTest)) {
logger.warn(
'Saw SSC (ignore|expect)_status_codes that is not an array, will not merge: %s',
valueToTest
)
return
}
let valid = true
valueToTest.forEach(function validateArray(thingToTest) {
if (!(typeof thingToTest === 'string' || typeof thingToTest === 'number')) {
logger.warn(
'Saw SSC (ignore|expect)_status_code that is not a number or string,' +
'will not merge: %s',
thingToTest
)
valid = false
}
})
if (!valid) {
return
}
return this._updateNestedIfChanged(remote, local, remoteKey, localKey)
}
/**
* Expected and Ignored classes configuration values should look like this
*
* ['Error','Again']
*
* If the server side config is not in this format, it might put the agent
* in a world of hurt. So, before we pass everything on to
* _updateNestedIfChanged, we'll do some validation.
*
* @param {object} remote JSON sent from New Relic.
* @param {object} local A portion of this configuration object.
* @param {string} remoteKey The name sent by New Relic.
* @param {string} localKey The local name.
*/
Config.prototype._validateThenUpdateErrorClasses = _validateThenUpdateErrorClasses
function _validateThenUpdateErrorClasses(remote, local, remoteKey, localKey) {
const valueToTest = remote[remoteKey]
if (!Array.isArray(valueToTest)) {
logger.warn(
'Saw SSC (ignore|expect)_classes that is not an array, will not merge: %s',
valueToTest
)
return
}
let valid = true
Object.keys(valueToTest).forEach(function validateArray(key) {
const thingToTest = valueToTest[key]
if (typeof thingToTest !== 'string') {
logger.warn(
'Saw SSC (ignore|expect)_class that is not a string, will not merge: %s',
thingToTest
)
valid = false
}
})
if (!valid) {
return
}
return this._updateNestedIfChanged(remote, local, remoteKey, localKey)
}
/**
* Expected and Ignore messages configuration values should look like this
*
* {'ErrorType':['Error Message']}
*
* If the server side config is not in this format, it might put the agent
* in a world of hurt. So, before we pass everything on to
* _updateNestedIfChanged, we'll do some validation.
*
* @param {object} remote JSON sent from New Relic.
* @param {object} local A portion of this configuration object.
* @param {string} remoteKey The name sent by New Relic.
* @param {string} localKey The local name.
*/
Config.prototype._validateThenUpdateErrorMessages = _validateThenUpdateErrorMessages
function _validateThenUpdateErrorMessages(remote, local, remoteKey, localKey) {
const valueToTest = remote[remoteKey]
if (Array.isArray(valueToTest)) {
logger.warn('Saw SSC (ignore|expect)_message that is an Array, will not merge: %s', valueToTest)
return
}
if (!valueToTest) {
logger.warn('SSC ignore|expect_message is null or undefined, will not merge')
return
}
if (typeof valueToTest !== 'object') {
logger.warn(
'Saw SSC (ignore|expect)_message that is primitive/scaler, will not merge: %s',
valueToTest
)
return
}
let valid = true
Object.keys(valueToTest).forEach(function validateArray(key) {
const arrayToTest = valueToTest[key]
if (!Array.isArray(arrayToTest)) {
logger.warn('Saw SSC message array that is not an array, will not merge: %s', arrayToTest)
valid = false
}
})
if (!valid) {
return
}
return this._updateNestedIfChanged(remote, local, remoteKey, localKey)
}
/**
* Some parameter values are nested, need a simple way to change them as well.
* Will merge local and remote if and only if both are arrays.
*
* @param {object} remote JSON sent from New Relic.
* @param {object} local A portion of this configuration object.
* @param {string} remoteKey The name sent by New Relic.
* @param {string} localKey The local name.
*/
Config.prototype._updateNestedIfChanged = _updateNestedIfChanged
function _updateNestedIfChanged(remote, local, remoteKey, localKey) {
// if high-sec mode is enabled, we do not accept server changes to high-sec
if (this.high_security && HSM.HIGH_SECURITY_KEYS.indexOf(remoteKey) !== -1) {
return this.logDisabled(remote, remoteKey)
}
return this._updateNestedIfChangedRaw(remote, local, remoteKey, localKey)
}
Config.prototype._updateNestedIfChangedRaw = _updateNestedIfChangedRaw
function _updateNestedIfChangedRaw(remote, local, remoteKey, localKey) {
return this.mergeServerConfig.updateNestedIfChanged(
this,
remote,
local,
remoteKey,
localKey,
logger
)
}
/**
* Some parameter values are just to be passed on.
*
* @param {object} json Config blob sent by collector.
* @param {string} key Value we're looking to set.
*/
Config.prototype._emitIfSet = function _emitIfSet(json, key) {
const value = json[key]
if (value != null) {
this.emit(key, value)
}
}
/**
* The agent would normally do something with this parameter, but server-side
* configuration is disabled via local settings or HSM.
*
* @param {object} json Config blob sent by collector.
* @param {string} key Value the agent won't set.
*/
Config.prototype.logDisabled = function logDisabled(json, key) {
const value = json[key]
if (value != null) {
logger.debug(
'Server-side configuration of %s is currently disabled by local configuration. ' +
'(Server sent value of %s.)',
key,
value
)
}
}
/**
* Help support out by putting in the logs the fact that we don't currently
* support the provided configuration key, and including the sent value.
*
* @param {object} json Config blob sent by collector.
* @param {string} key Value the agent doesn't set.
*/
Config.prototype.logUnsupported = function logUnsupported(json, key) {
const value = json[key]
if (value !== null && value !== undefined) {
logger.debug(
'Server-side configuration of %s is currently not supported by the ' +
'Node.js agent. (Server sent value of %s.)',
key,
value
)
this.emit(key, value)
}
}
/**
* The agent knows nothing about this parameter.
*
* @param {object} json Config blob sent by collector.
* @param {string} key Value the agent knows nothing about.
*/
Config.prototype.logUnknown = function logUnknown(json, key) {
const value = json[key]
logger.debug('New Relic sent unknown configuration parameter %s with value %s.', key, value)
}
/**
* Gets the user set host display name. If not provided, it returns the default value.
*
* This function is written in this strange way because of the use of caching variables.
* I wanted to cache the DisplayHost, but if I attached the variable to the config object,
* it sends the extra variable to New Relic, which is not desired.
*
* @returns {string} display host name
*/
Config.prototype.getDisplayHost = getDisplayHost
Config.prototype.clearDisplayHostCache = function clearDisplayHostCache() {
this.getDisplayHost = getDisplayHost
}
function getDisplayHost() {
let _displayHost
this.getDisplayHost = function getCachedDisplayHost() {
return _displayHost
}
if (this.process_host.display_name === '') {
_displayHost = this.getHostnameSafe()
return _displayHost
}
const stringBuffer = Buffer.from(this.process_host.display_name, 'utf8')
const numBytes = stringBuffer.length
if (numBytes > 255) {
logger.warn('Custom host display name must be less than 255 bytes')
_displayHost = this.getHostnameSafe()
return _displayHost
}
_displayHost = this.process_host.display_name
return _displayHost
}
/**
* Gets the system's host name. If that fails, it just returns ipv4/6 based on the user's
* process_host.ipv_preference setting.
*
* This function is written is this strange way because of the use of caching variables.
* I wanted to cache the Hostname, but if I attached the variable to the config object,
* it sends the extra variable to New Relic, which is not desired.
*
* @returns {string} host name
*/
Config.prototype.getHostnameSafe = getHostnameSafe
Config.prototype.clearHostnameCache = function clearHostnameCache() {
this.getHostnameSafe = getHostnameSafe
}
Config.prototype.getIPAddresses = function getIPAddresses() {
const addresses = Object.create(null)
const interfaces = os.networkInterfaces()
for (const interfaceKey in interfaces) {
if (interfaceKey.match(/^lo/)) {
continue
}
const interfaceDescriptions = interfaces[interfaceKey]
for (let i = 0; i < interfaceDescriptions.length; i++) {
const description = interfaceDescriptions[i]
const family = description.family.toLowerCase()
addresses[family] = description.address
}
}
return addresses
}
function getHostnameSafe() {
let _hostname
const config = this
this.getHostnameSafe = function getCachedHostname() {
return _hostname
}
try {
if (config.heroku.use_dyno_names) {
const dynoName = process.env.DYNO
_hostname = dynoName || os.hostname()
} else {
_hostname = os.hostname()
}
return _hostname
} catch {
const addresses = this.getIPAddresses()
if (this.process_host.ipv_preference === '6' && addresses.ipv6) {
_hostname = addresses.ipv6
} else if (addresses.ipv4) {
logger.info('Defaulting to ipv4 address for host name')
_hostname = addresses.ipv4
} else if (addresses.ipv6) {
logger.info('Defaulting to ipv6 address for host name')
_hostname = addresses.ipv6
} else {