-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathconfig.py
3089 lines (2467 loc) · 108 KB
/
config.py
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 2010 New Relic, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import fnmatch
import logging
import os
import sys
import traceback
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import newrelic.api.application
import newrelic.api.background_task
import newrelic.api.database_trace
import newrelic.api.error_trace
import newrelic.api.exceptions
import newrelic.api.external_trace
import newrelic.api.function_profile
import newrelic.api.function_trace
import newrelic.api.generator_trace
import newrelic.api.import_hook
import newrelic.api.memcache_trace
import newrelic.api.object_wrapper
import newrelic.api.profile_trace
import newrelic.api.settings
import newrelic.api.transaction_name
import newrelic.api.wsgi_application
import newrelic.console
import newrelic.core.agent
import newrelic.core.config
import newrelic.core.trace_cache as trace_cache
from newrelic.common.log_file import initialize_logging
from newrelic.common.object_names import expand_builtin_exception_name
from newrelic.core.config import (
Settings,
apply_config_setting,
default_host,
fetch_config_setting,
)
from newrelic.packages import six
__all__ = ["initialize", "filter_app_factory"]
_logger = logging.getLogger(__name__)
# Register our importer which implements post import hooks for
# triggering of callbacks to monkey patch modules before import
# returns them to caller.
sys.meta_path.insert(0, newrelic.api.import_hook.ImportHookFinder())
# The set of valid feature flags that the agent currently uses.
# This will be used to validate what is provided and issue warnings
# if feature flags not in set are provided.
_FEATURE_FLAGS = set(
[
"django.instrumentation.inclusion-tags.r1",
]
)
# Names of configuration file and deployment environment. This
# will be overridden by the load_configuration() function when
# configuration is loaded.
_config_file = None
_environment = None
_ignore_errors = True
# This is the actual internal settings object. Options which
# are read from the configuration file will be applied to this.
_settings = newrelic.api.settings.settings()
# Use the raw config parser as we want to avoid interpolation
# within values. This avoids problems when writing lambdas
# within the actual configuration file for options which value
# can be dynamically calculated at time wrapper is executed.
# This configuration object can be used by the instrumentation
# modules to look up customised settings defined in the loaded
# configuration file.
_config_object = ConfigParser.RawConfigParser()
# Cache of the parsed global settings found in the configuration
# file. We cache these so can dump them out to the log file once
# all the settings have been read.
_cache_object = []
# Mechanism for extracting settings from the configuration for use in
# instrumentation modules and extensions.
def extra_settings(section, types={}, defaults={}):
settings = {}
if _config_object.has_section(section):
settings.update(_config_object.items(section))
settings_object = Settings()
for name, value in defaults.items():
apply_config_setting(settings_object, name, value)
for name, value in settings.items():
if name in types:
value = types[name](value)
apply_config_setting(settings_object, name, value)
return settings_object
# Define some mapping functions to convert raw values read from
# configuration file into the internal types expected by the
# internal configuration settings object.
_LOG_LEVEL = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
}
_RECORD_SQL = {
"off": newrelic.api.settings.RECORDSQL_OFF,
"raw": newrelic.api.settings.RECORDSQL_RAW,
"obfuscated": newrelic.api.settings.RECORDSQL_OBFUSCATED,
}
_COMPRESSED_CONTENT_ENCODING = {
"deflate": newrelic.api.settings.COMPRESSED_CONTENT_ENCODING_DEFLATE,
"gzip": newrelic.api.settings.COMPRESSED_CONTENT_ENCODING_GZIP,
}
def _map_log_level(s):
return _LOG_LEVEL[s.upper()]
def _map_feature_flag(s):
return set(s.split())
def _map_labels(s):
return newrelic.core.config._environ_as_mapping(name="", default=s)
def _map_transaction_threshold(s):
if s == "apdex_f":
return None
return float(s)
def _map_record_sql(s):
return _RECORD_SQL[s]
def _map_compressed_content_encoding(s):
return _COMPRESSED_CONTENT_ENCODING[s]
def _map_split_strings(s):
return s.split()
def _map_console_listener_socket(s):
return s % {"pid": os.getpid()}
def _merge_ignore_status_codes(s):
return newrelic.core.config._parse_status_codes(s, _settings.error_collector.ignore_status_codes)
def _merge_expected_status_codes(s):
return newrelic.core.config._parse_status_codes(s, _settings.error_collector.expected_status_codes)
def _map_browser_monitoring_content_type(s):
return s.split()
def _map_strip_exception_messages_allowlist(s):
return [expand_builtin_exception_name(item) for item in s.split()]
def _map_inc_excl_attributes(s):
return newrelic.core.config._parse_attributes(s)
def _map_default_host_value(license_key):
# If the license key is region aware, we should override the default host
# to be the region aware host
_default_host = default_host(license_key)
_settings.host = os.environ.get("NEW_RELIC_HOST", _default_host)
return license_key
# Processing of a single setting from configuration file.
def _raise_configuration_error(section, option=None):
_logger.error("CONFIGURATION ERROR")
if section:
_logger.error("Section = %s" % section)
if option is None:
options = _config_object.options(section)
_logger.error("Options = %s" % options)
_logger.exception("Exception Details")
if not _ignore_errors:
if section:
raise newrelic.api.exceptions.ConfigurationError(
'Invalid configuration for section "%s". '
"Check New Relic agent log file for further "
"details." % section
)
else:
raise newrelic.api.exceptions.ConfigurationError(
"Invalid configuration. Check New Relic agent log file for further details."
)
else:
_logger.error("Option = %s" % option)
_logger.exception("Exception Details")
if not _ignore_errors:
if section:
raise newrelic.api.exceptions.ConfigurationError(
'Invalid configuration for option "%s" in '
'section "%s". Check New Relic agent log '
"file for further details." % (option, section)
)
else:
raise newrelic.api.exceptions.ConfigurationError(
'Invalid configuration for option "%s". '
"Check New Relic agent log file for further "
"details." % option
)
def _process_setting(section, option, getter, mapper):
try:
# The type of a value is dictated by the getter
# function supplied.
value = getattr(_config_object, getter)(section, option)
# The getter parsed the value okay but want to
# pass this through a mapping function to change
# it to internal value suitable for internal
# settings object. This is usually one where the
# value was a string.
if mapper:
value = mapper(value)
# Now need to apply the option from the
# configuration file to the internal settings
# object. Walk the object path and assign it.
target = _settings
fields = option.split(".", 1)
while True:
if len(fields) == 1:
setattr(target, fields[0], value)
break
else:
target = getattr(target, fields[0])
fields = fields[1].split(".", 1)
# Cache the configuration so can be dumped out to
# log file when whole main configuration has been
# processed. This ensures that the log file and log
# level entries have been set.
_cache_object.append((option, value))
except ConfigParser.NoSectionError:
pass
except ConfigParser.NoOptionError:
pass
except Exception:
_raise_configuration_error(section, option)
# Processing of all the settings for specified section except
# for log file and log level which are applied separately to
# ensure they are set as soon as possible.
def _process_configuration(section):
_process_setting(section, "feature_flag", "get", _map_feature_flag)
_process_setting(section, "app_name", "get", None)
_process_setting(section, "url_regex", "get", None)
_process_setting(section, "url_regex_rep", "get", None)
_process_setting(section, "labels", "get", _map_labels)
_process_setting(section, "license_key", "get", _map_default_host_value)
_process_setting(section, "api_key", "get", None)
_process_setting(section, "host", "get", None)
_process_setting(section, "port", "getint", None)
_process_setting(section, "ssl", "getboolean", None)
_process_setting(section, "proxy_scheme", "get", None)
_process_setting(section, "proxy_host", "get", None)
_process_setting(section, "proxy_port", "getint", None)
_process_setting(section, "proxy_user", "get", None)
_process_setting(section, "proxy_pass", "get", None)
_process_setting(section, "ca_bundle_path", "get", None)
_process_setting(section, "audit_log_file", "get", None)
_process_setting(section, "monitor_mode", "getboolean", None)
_process_setting(section, "developer_mode", "getboolean", None)
_process_setting(section, "high_security", "getboolean", None)
_process_setting(section, "capture_params", "getboolean", None)
_process_setting(section, "ignored_params", "get", _map_split_strings)
_process_setting(section, "capture_environ", "getboolean", None)
_process_setting(section, "include_environ", "get", _map_split_strings)
_process_setting(section, "max_stack_trace_lines", "getint", None)
_process_setting(section, "startup_timeout", "getfloat", None)
_process_setting(section, "shutdown_timeout", "getfloat", None)
_process_setting(section, "compressed_content_encoding", "get", _map_compressed_content_encoding)
_process_setting(section, "attributes.enabled", "getboolean", None)
_process_setting(section, "attributes.exclude", "get", _map_inc_excl_attributes)
_process_setting(section, "attributes.include", "get", _map_inc_excl_attributes)
_process_setting(section, "transaction_name.naming_scheme", "get", None)
_process_setting(section, "gc_runtime_metrics.enabled", "getboolean", None)
_process_setting(section, "gc_runtime_metrics.top_object_count_limit", "getint", None)
_process_setting(section, "thread_profiler.enabled", "getboolean", None)
_process_setting(section, "transaction_tracer.enabled", "getboolean", None)
_process_setting(
section,
"transaction_tracer.transaction_threshold",
"get",
_map_transaction_threshold,
)
_process_setting(section, "transaction_tracer.record_sql", "get", _map_record_sql)
_process_setting(section, "transaction_tracer.stack_trace_threshold", "getfloat", None)
_process_setting(section, "transaction_tracer.explain_enabled", "getboolean", None)
_process_setting(section, "transaction_tracer.explain_threshold", "getfloat", None)
_process_setting(section, "transaction_tracer.function_trace", "get", _map_split_strings)
_process_setting(section, "transaction_tracer.generator_trace", "get", _map_split_strings)
_process_setting(section, "transaction_tracer.top_n", "getint", None)
_process_setting(section, "transaction_tracer.attributes.enabled", "getboolean", None)
_process_setting(
section,
"transaction_tracer.attributes.exclude",
"get",
_map_inc_excl_attributes,
)
_process_setting(
section,
"transaction_tracer.attributes.include",
"get",
_map_inc_excl_attributes,
)
_process_setting(section, "error_collector.enabled", "getboolean", None)
_process_setting(section, "error_collector.capture_events", "getboolean", None)
_process_setting(section, "error_collector.max_event_samples_stored", "getint", None)
_process_setting(section, "error_collector.capture_source", "getboolean", None)
_process_setting(section, "error_collector.ignore_errors", "get", _map_split_strings)
_process_setting(section, "error_collector.ignore_classes", "get", _map_split_strings)
_process_setting(
section,
"error_collector.ignore_status_codes",
"get",
_merge_ignore_status_codes,
)
_process_setting(section, "error_collector.expected_classes", "get", _map_split_strings)
_process_setting(
section,
"error_collector.expected_status_codes",
"get",
_merge_expected_status_codes,
)
_process_setting(section, "error_collector.attributes.enabled", "getboolean", None)
_process_setting(section, "error_collector.attributes.exclude", "get", _map_inc_excl_attributes)
_process_setting(section, "error_collector.attributes.include", "get", _map_inc_excl_attributes)
_process_setting(section, "browser_monitoring.enabled", "getboolean", None)
_process_setting(section, "browser_monitoring.auto_instrument", "getboolean", None)
_process_setting(section, "browser_monitoring.loader", "get", None)
_process_setting(section, "browser_monitoring.debug", "getboolean", None)
_process_setting(section, "browser_monitoring.ssl_for_http", "getboolean", None)
_process_setting(section, "browser_monitoring.content_type", "get", _map_split_strings)
_process_setting(section, "browser_monitoring.attributes.enabled", "getboolean", None)
_process_setting(
section,
"browser_monitoring.attributes.exclude",
"get",
_map_inc_excl_attributes,
)
_process_setting(
section,
"browser_monitoring.attributes.include",
"get",
_map_inc_excl_attributes,
)
_process_setting(section, "slow_sql.enabled", "getboolean", None)
_process_setting(section, "synthetics.enabled", "getboolean", None)
_process_setting(section, "transaction_events.enabled", "getboolean", None)
_process_setting(section, "transaction_events.max_samples_stored", "getint", None)
_process_setting(section, "transaction_events.attributes.enabled", "getboolean", None)
_process_setting(
section,
"transaction_events.attributes.exclude",
"get",
_map_inc_excl_attributes,
)
_process_setting(
section,
"transaction_events.attributes.include",
"get",
_map_inc_excl_attributes,
)
_process_setting(section, "custom_insights_events.enabled", "getboolean", None)
_process_setting(section, "custom_insights_events.max_samples_stored", "getint", None)
_process_setting(section, "distributed_tracing.enabled", "getboolean", None)
_process_setting(section, "distributed_tracing.exclude_newrelic_header", "getboolean", None)
_process_setting(section, "span_events.enabled", "getboolean", None)
_process_setting(section, "span_events.max_samples_stored", "getint", None)
_process_setting(section, "span_events.attributes.enabled", "getboolean", None)
_process_setting(section, "span_events.attributes.exclude", "get", _map_inc_excl_attributes)
_process_setting(section, "span_events.attributes.include", "get", _map_inc_excl_attributes)
_process_setting(section, "transaction_segments.attributes.enabled", "getboolean", None)
_process_setting(
section,
"transaction_segments.attributes.exclude",
"get",
_map_inc_excl_attributes,
)
_process_setting(
section,
"transaction_segments.attributes.include",
"get",
_map_inc_excl_attributes,
)
_process_setting(section, "local_daemon.socket_path", "get", None)
_process_setting(section, "local_daemon.synchronous_startup", "getboolean", None)
_process_setting(section, "agent_limits.transaction_traces_nodes", "getint", None)
_process_setting(section, "agent_limits.sql_query_length_maximum", "getint", None)
_process_setting(section, "agent_limits.slow_sql_stack_trace", "getint", None)
_process_setting(section, "agent_limits.max_sql_connections", "getint", None)
_process_setting(section, "agent_limits.sql_explain_plans", "getint", None)
_process_setting(section, "agent_limits.sql_explain_plans_per_harvest", "getint", None)
_process_setting(section, "agent_limits.slow_sql_data", "getint", None)
_process_setting(section, "agent_limits.merge_stats_maximum", "getint", None)
_process_setting(section, "agent_limits.errors_per_transaction", "getint", None)
_process_setting(section, "agent_limits.errors_per_harvest", "getint", None)
_process_setting(section, "agent_limits.slow_transaction_dry_harvests", "getint", None)
_process_setting(section, "agent_limits.thread_profiler_nodes", "getint", None)
_process_setting(section, "agent_limits.synthetics_events", "getint", None)
_process_setting(section, "agent_limits.synthetics_transactions", "getint", None)
_process_setting(section, "agent_limits.data_compression_threshold", "getint", None)
_process_setting(section, "agent_limits.data_compression_level", "getint", None)
_process_setting(section, "console.listener_socket", "get", _map_console_listener_socket)
_process_setting(section, "console.allow_interpreter_cmd", "getboolean", None)
_process_setting(section, "debug.disable_api_supportability_metrics", "getboolean", None)
_process_setting(section, "debug.log_data_collector_calls", "getboolean", None)
_process_setting(section, "debug.log_data_collector_payloads", "getboolean", None)
_process_setting(section, "debug.log_malformed_json_data", "getboolean", None)
_process_setting(section, "debug.log_transaction_trace_payload", "getboolean", None)
_process_setting(section, "debug.log_thread_profile_payload", "getboolean", None)
_process_setting(section, "debug.log_raw_metric_data", "getboolean", None)
_process_setting(section, "debug.log_normalized_metric_data", "getboolean", None)
_process_setting(section, "debug.log_normalization_rules", "getboolean", None)
_process_setting(section, "debug.log_agent_initialization", "getboolean", None)
_process_setting(section, "debug.log_explain_plan_queries", "getboolean", None)
_process_setting(section, "debug.log_autorum_middleware", "getboolean", None)
_process_setting(section, "debug.log_untrusted_distributed_trace_keys", "getboolean", None)
_process_setting(section, "debug.enable_coroutine_profiling", "getboolean", None)
_process_setting(section, "debug.record_transaction_failure", "getboolean", None)
_process_setting(section, "debug.explain_plan_obfuscation", "get", None)
_process_setting(section, "debug.disable_certificate_validation", "getboolean", None)
_process_setting(section, "debug.disable_harvest_until_shutdown", "getboolean", None)
_process_setting(section, "debug.connect_span_stream_in_developer_mode", "getboolean", None)
_process_setting(section, "cross_application_tracer.enabled", "getboolean", None)
_process_setting(section, "message_tracer.segment_parameters_enabled", "getboolean", None)
_process_setting(section, "process_host.display_name", "get", None)
_process_setting(section, "utilization.detect_aws", "getboolean", None)
_process_setting(section, "utilization.detect_azure", "getboolean", None)
_process_setting(section, "utilization.detect_docker", "getboolean", None)
_process_setting(section, "utilization.detect_kubernetes", "getboolean", None)
_process_setting(section, "utilization.detect_gcp", "getboolean", None)
_process_setting(section, "utilization.detect_pcf", "getboolean", None)
_process_setting(section, "utilization.logical_processors", "getint", None)
_process_setting(section, "utilization.total_ram_mib", "getint", None)
_process_setting(section, "utilization.billing_hostname", "get", None)
_process_setting(section, "strip_exception_messages.enabled", "getboolean", None)
_process_setting(
section,
"strip_exception_messages.allowlist",
"get",
_map_strip_exception_messages_allowlist,
)
_process_setting(section, "datastore_tracer.instance_reporting.enabled", "getboolean", None)
_process_setting(section, "datastore_tracer.database_name_reporting.enabled", "getboolean", None)
_process_setting(section, "heroku.use_dyno_names", "getboolean", None)
_process_setting(section, "heroku.dyno_name_prefixes_to_shorten", "get", _map_split_strings)
_process_setting(section, "serverless_mode.enabled", "getboolean", None)
_process_setting(section, "apdex_t", "getfloat", None)
_process_setting(section, "event_loop_visibility.enabled", "getboolean", None)
_process_setting(section, "event_loop_visibility.blocking_threshold", "getfloat", None)
_process_setting(
section,
"event_harvest_config.harvest_limits.analytic_event_data",
"getint",
None,
)
_process_setting(section, "event_harvest_config.harvest_limits.custom_event_data", "getint", None)
_process_setting(section, "event_harvest_config.harvest_limits.span_event_data", "getint", None)
_process_setting(section, "event_harvest_config.harvest_limits.error_event_data", "getint", None)
_process_setting(section, "event_harvest_config.harvest_limits.log_event_data", "getint", None)
_process_setting(section, "infinite_tracing.trace_observer_host", "get", None)
_process_setting(section, "infinite_tracing.trace_observer_port", "getint", None)
_process_setting(section, "infinite_tracing.span_queue_size", "getint", None)
_process_setting(section, "code_level_metrics.enabled", "getboolean", None)
_process_setting(section, "application_logging.enabled", "getboolean", None)
_process_setting(section, "application_logging.forwarding.max_samples_stored", "getint", None)
_process_setting(section, "application_logging.forwarding.enabled", "getboolean", None)
_process_setting(section, "application_logging.metrics.enabled", "getboolean", None)
_process_setting(section, "application_logging.local_decorating.enabled", "getboolean", None)
# Loading of configuration from specified file and for specified
# deployment environment. Can also indicate whether configuration
# and instrumentation errors should raise an exception or not.
_configuration_done = False
def _process_app_name_setting():
# Do special processing to handle the case where the application
# name was actually a semicolon separated list of names. In this
# case the first application name is the primary and the others are
# linked applications the application also reports to. What we need
# to do is explicitly retrieve the application object for the
# primary application name and link it with the other applications.
# When activating the application the linked names will be sent
# along to the core application where the association will be
# created if the do not exist.
name = _settings.app_name.split(";")[0].strip() or "Python Application"
linked = []
for altname in _settings.app_name.split(";")[1:]:
altname = altname.strip()
if altname:
linked.append(altname)
def _link_applications(application):
for altname in linked:
_logger.debug("link to %s" % ((name, altname),))
application.link_to_application(altname)
if linked:
newrelic.api.application.Application.run_on_initialization(name, _link_applications)
_settings.linked_applications = linked
_settings.app_name = name
def _process_labels_setting(labels=None):
# Do special processing to handle labels. Initially the labels
# setting will be a list of key/value tuples. This needs to be
# converted into a list of dictionaries. It is also necessary
# to eliminate duplicates by taking the last value, plus apply
# length limits and limits on the number collected.
if labels is None:
labels = _settings.labels
length_limit = 255
count_limit = 64
deduped = {}
for key, value in labels:
if len(key) > length_limit:
_logger.warning(
"Improper configuration. Label key %s is too long. Truncating key to: %s" % (key, key[:length_limit])
)
if len(value) > length_limit:
_logger.warning(
"Improper configuration. Label value %s is too "
"long. Truncating value to: %s" % (value, value[:length_limit])
)
if len(deduped) >= count_limit:
_logger.warning(
"Improper configuration. Maximum number of labels reached. Using first %d labels." % count_limit
)
break
key = key[:length_limit]
value = value[:length_limit]
deduped[key] = value
result = []
for key, value in deduped.items():
result.append({"label_type": key, "label_value": value})
_settings.labels = result
def delete_setting(settings_object, name):
"""Delete setting from settings_object.
If passed a 'root' setting, like 'error_collector', it will
delete 'error_collector' and all settings underneath it, such
as 'error_collector.attributes.enabled'
"""
target = settings_object
fields = name.split(".", 1)
while len(fields) > 1:
if not hasattr(target, fields[0]):
break
target = getattr(target, fields[0])
fields = fields[1].split(".", 1)
try:
delattr(target, fields[0])
except AttributeError:
_logger.debug("Failed to delete setting: %r", name)
def translate_deprecated_settings(settings, cached_settings):
# If deprecated setting has been set by user, but the new
# setting has not, then translate the deprecated setting to the
# new one.
#
# If both deprecated and new setting have been applied, ignore
# deprecated setting.
#
# In either case, delete the deprecated one from the settings object.
# Parameters:
#
# settings:
# Settings object
#
# cached_settings:
# A list of (key, value) pairs of the parsed global settings
# found in the config file.
# NOTE:
#
# cached_settings is a list of option key/values and can have duplicate
# keys, if the customer used environment sections in the config file.
# Since options are applied to the settings object in order, so that the
# options at the end of the list will override earlier options with the
# same key, then converting to a dict will result in each option having
# the most recently applied value.
cached = dict(cached_settings)
deprecated_settings_map = [
(
"transaction_tracer.capture_attributes",
"transaction_tracer.attributes.enabled",
),
("error_collector.capture_attributes", "error_collector.attributes.enabled"),
(
"browser_monitoring.capture_attributes",
"browser_monitoring.attributes.enabled",
),
(
"analytics_events.capture_attributes",
"transaction_events.attributes.enabled",
),
("analytics_events.enabled", "transaction_events.enabled"),
(
"analytics_events.max_samples_stored",
"event_harvest_config.harvest_limits.analytic_event_data",
),
(
"transaction_events.max_samples_stored",
"event_harvest_config.harvest_limits.analytic_event_data",
),
(
"span_events.max_samples_stored",
"event_harvest_config.harvest_limits.span_event_data",
),
(
"error_collector.max_event_samples_stored",
"event_harvest_config.harvest_limits.error_event_data",
),
(
"custom_insights_events.max_samples_stored",
"event_harvest_config.harvest_limits.custom_event_data",
),
(
"application_logging.forwarding.max_samples_stored",
"event_harvest_config.harvest_limits.log_event_data",
),
(
"error_collector.ignore_errors",
"error_collector.ignore_classes",
),
(
"strip_exception_messages.whitelist",
"strip_exception_messages.allowlist",
),
]
for (old_key, new_key) in deprecated_settings_map:
if old_key in cached:
_logger.info(
"Deprecated setting found: %r. Please use new setting: %r.",
old_key,
new_key,
)
if new_key in cached:
_logger.info(
"Ignoring deprecated setting: %r. Using new setting: %r.",
old_key,
new_key,
)
else:
apply_config_setting(settings, new_key, cached[old_key])
_logger.info("Applying value of deprecated setting %r to %r.", old_key, new_key)
delete_setting(settings, old_key)
# The 'ignored_params' setting is more complicated than the above
# deprecated settings, so it gets handled separately.
if "ignored_params" in cached:
_logger.info(
"Deprecated setting found: ignored_params. Please use "
"new setting: attributes.exclude. For the new setting, an "
"ignored parameter should be prefaced with "
'"request.parameters.". For example, ignoring a parameter '
'named "foo" should be added added to attributes.exclude as '
'"request.parameters.foo."'
)
# Don't merge 'ignored_params' settings. If user set
# 'attributes.exclude' setting, only use those values,
# and ignore 'ignored_params' settings.
if "attributes.exclude" in cached:
_logger.info("Ignoring deprecated setting: ignored_params. Using new setting: attributes.exclude.")
else:
ignored_params = fetch_config_setting(settings, "ignored_params")
for p in ignored_params:
attr_value = "request.parameters." + p
excluded_attrs = fetch_config_setting(settings, "attributes.exclude")
if attr_value not in excluded_attrs:
settings.attributes.exclude.append(attr_value)
_logger.info(
"Applying value of deprecated setting ignored_params to attributes.exclude: %r.",
attr_value,
)
delete_setting(settings, "ignored_params")
# The 'capture_params' setting is deprecated, but since it affects
# attribute filter default destinations, it is not translated here. We
# log a message, but keep the capture_params setting.
#
# See newrelic.core.transaction:Transaction.agent_attributes to see how
# it is used.
if "capture_params" in cached:
_logger.info(
"Deprecated setting found: capture_params. Please use "
"new setting: attributes.exclude. To disable capturing all "
'request parameters, add "request.parameters.*" to '
"attributes.exclude."
)
if "cross_application_tracer.enabled" in cached:
# CAT Deprecation Warning
_logger.info(
"Deprecated setting found: cross_application_tracer.enabled. Please replace Cross Application Tracing "
"(CAT) with the newer Distributed Tracing by setting 'distributed_tracing.enabled' to True in your agent "
"configuration. For further details on distributed tracing, please refer to our documentation: "
"https://docs.newrelic.com/docs/distributed-tracing/concepts/distributed-tracing-planning-guide/#changes."
)
if not settings.ssl:
settings.ssl = True
_logger.info("Ignoring deprecated setting: ssl. Enabling ssl is now mandatory. Setting ssl=true.")
if settings.agent_limits.merge_stats_maximum is not None:
_logger.info(
"Ignoring deprecated setting: "
"agent_limits.merge_stats_maximum. The agent will now respect "
"server-side commands."
)
return settings
def apply_local_high_security_mode_setting(settings):
# When High Security Mode is activated, certain settings must be
# set to be secure, even if that requires overriding a setting that
# has been individually configured as insecure.
if not settings.high_security:
return settings
log_template = (
"Overriding setting for %r because High "
"Security Mode has been activated. The original "
"setting was %r. The new setting is %r."
)
# capture_params is a deprecated setting for users, and has three
# possible values:
#
# True: For backward compatibility.
# False: For backward compatibility.
# None: The current default setting.
#
# In High Security, capture_params must be False, but we only need
# to log if the customer has actually used the deprecated setting
# and set it to True.
if settings.capture_params:
settings.capture_params = False
_logger.info(log_template, "capture_params", True, False)
elif settings.capture_params is None:
settings.capture_params = False
if settings.transaction_tracer.record_sql == "raw":
settings.transaction_tracer.record_sql = "obfuscated"
_logger.info(log_template, "transaction_tracer.record_sql", "raw", "obfuscated")
if not settings.strip_exception_messages.enabled:
settings.strip_exception_messages.enabled = True
_logger.info(log_template, "strip_exception_messages.enabled", False, True)
if settings.custom_insights_events.enabled:
settings.custom_insights_events.enabled = False
_logger.info(log_template, "custom_insights_events.enabled", True, False)
if settings.message_tracer.segment_parameters_enabled:
settings.message_tracer.segment_parameters_enabled = False
_logger.info(log_template, "message_tracer.segment_parameters_enabled", True, False)
if settings.application_logging.forwarding.enabled:
settings.application_logging.forwarding.enabled = False
_logger.info(log_template, "application_logging.forwarding.enabled", True, False)
return settings
def _load_configuration(
config_file=None,
environment=None,
ignore_errors=True,
log_file=None,
log_level=None,
):
global _configuration_done
global _config_file
global _environment
global _ignore_errors
# Check whether initialisation has been done previously. If
# it has then raise a configuration error if it was against
# a different configuration. Otherwise just return. We don't
# check at this time if an incompatible configuration has
# been read from a different sub interpreter. If this occurs
# then results will be undefined. Use from different sub
# interpreters of the same process is not recommended.
if _configuration_done:
if _config_file != config_file or _environment != environment:
raise newrelic.api.exceptions.ConfigurationError(
"Configuration has already been done against "
"differing configuration file or environment. "
'Prior configuration file used was "%s" and '
'environment "%s".' % (_config_file, _environment)
)
else:
return
_configuration_done = True
# Update global variables tracking what configuration file and
# environment was used, plus whether errors are to be ignored.
_config_file = config_file
_environment = environment
_ignore_errors = ignore_errors
# If no configuration file then nothing more to be done.
if not config_file:
_logger.debug("no agent configuration file")
# Force initialisation of the logging system now in case
# setup provided by environment variables.
if log_file is None:
log_file = _settings.log_file
if log_level is None:
log_level = _settings.log_level
initialize_logging(log_file, log_level)
# Validate provided feature flags and log a warning if get one
# which isn't valid.
for flag in _settings.feature_flag:
if flag not in _FEATURE_FLAGS:
_logger.warning(
"Unknown agent feature flag %r provided. "
"Check agent documentation or release notes, or "
"contact New Relic support for clarification of "
"validity of the specific feature flag.",
flag,
)
# Look for an app_name setting which is actually a semi colon
# list of application names and adjust app_name setting and
# registered linked applications for later handling.
_process_app_name_setting()
# Look for any labels and translate them into required form
# for sending up to data collector on registration.
_process_labels_setting()
return
_logger.debug("agent configuration file was %s" % config_file)
# Now read in the configuration file. Cache the config file
# name in internal settings object as indication of succeeding.
if not _config_object.read([config_file]):
raise newrelic.api.exceptions.ConfigurationError("Unable to open configuration file %s." % config_file)
_settings.config_file = config_file
# Must process log file entries first so that errors with
# the remainder will get logged if log file is defined.
_process_setting("newrelic", "log_file", "get", None)
if environment:
_process_setting("newrelic:%s" % environment, "log_file", "get", None)
if log_file is None:
log_file = _settings.log_file
_process_setting("newrelic", "log_level", "get", _map_log_level)
if environment:
_process_setting("newrelic:%s" % environment, "log_level", "get", _map_log_level)
if log_level is None:
log_level = _settings.log_level
# Force initialisation of the logging system now that we
# have the log file and log level.
initialize_logging(log_file, log_level)