-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathconfiguration.py
5013 lines (4381 loc) · 187 KB
/
configuration.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 2014-2024 Scalyr 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.
from __future__ import unicode_literals
from __future__ import absolute_import
from scalyr_agent.scalyr_monitor import MonitorInformation
if False:
from typing import Tuple
from typing import Dict
from typing import List
import os
import re
import sys
import socket
import time
import logging
import copy
import json
import stat
import platform
import six
import six.moves.urllib.parse
from six.moves import range
try:
import win32file
except ImportError:
# Likely not running on Windows
win32file = None
import scalyr_agent.util as scalyr_util
from scalyr_agent.json_lib import JsonConversionException, JsonMissingFieldException
from scalyr_agent.json_lib.objects import (
JsonObject,
JsonArray,
ArrayOfStrings,
SpaceAndCommaSeparatedArrayOfStrings,
)
from scalyr_agent.monitor_utils.blocking_rate_limiter import BlockingRateLimiter
from scalyr_agent.config_util import BadConfiguration, get_config_from_env
from scalyr_agent.__scalyr__ import get_install_root
from scalyr_agent.compat import os_environ_unicode
from scalyr_agent import compat
FILE_WRONG_OWNER_ERROR_MSG = """
File \"%s\" is not readable by the current user (%s).
You need to make sure that the file is owned by the same account which is used to run the agent.
Original error: %s
""".strip()
MASKED_CONFIG_ITEM_VALUE = "********** MASKED **********"
# prefix for the worker session log file name.
AGENT_WORKER_SESSION_LOG_NAME_PREFIX = "agent-worker-session-"
DEFAULT_WORKER_ID = "default"
def ensure_https_url(server):
parts = six.moves.urllib.parse.urlparse(server)
# use index-based addressing for 2.4 compatibility
scheme = parts[0]
if not scheme:
return "https://" + server
elif scheme == "http":
return re.sub("^http://", "https://", server)
else:
return server
class Configuration(object):
"""Encapsulates the results of a single read of the configuration file.
An instance of this object can be used to read and validate the configuration file. It supports
reading the main contents of the configuration, as well as configuration fragments in the 'configs.d'
directory. It handles merging the contents of the configuration files together and filling in any default
values for fields not set. You can also use the equivalent method to determine if two instances of this
object have the same configuration content.
You may also use environment variable substitution in any string value in the configuration file. You just
need to define the ``import_vars`` configuration field to be a list of variable names to import from the
shell and then use the $VAR_NAME in any string field. Each entry in ``import_vars`` may also be a dict with
two entries: ``var`` for the name of the environment variable and ``default`` for the value to use if the
the environment variable is not set or is empty.
This also handles reporting status information about the configuration state, including what time it was
read and what error (if any) was raised.
Note:
UNDOCUMENTED_CONFIG: These are undocumented config params, meaning they are not described in the public online docs
in order to simplify the mental model. In rare cases, a customer may need to tune these params under direct
guidance from support.
"""
DEFAULT_K8S_IGNORE_NAMESPACES = ["kube-system"]
DEFAULT_K8S_INCLUDE_NAMESPACES = ["*"]
def __init__(
self, file_path, default_paths, logger, extra_config_dir=None, log_warnings=True
):
# Captures all environment aware variables for testing purposes
self._environment_aware_map = {}
self.__file_path = os.path.abspath(file_path)
# Paths for additional configuration files that were read (from the config directory).
self.__additional_paths = []
# The JsonObject holding the contents of the configuration file, along with any default
# values filled in.
self.__config = None
# The number of seconds past epoch when the file was read.
self.__read_time = None
# The exception, if any, that was raised when the state was read. This will be a BadConfiguration exception.
self.__last_error = None
# The log configuration objects from the configuration file. This does not include logs required by
# the monitors.
self.__log_configs = []
# Optional configuration for journald monitor logging
self.__journald_log_configs = []
# Optional configuration for k8s monitor logging
self.__k8s_log_configs = []
# The monitor configuration objects from the configuration file. This does not include monitors that
# are created by default by the platform.
self.__monitor_configs = []
self.__worker_configs = []
# The DefaultPaths object that specifies the default paths for things like the data and log directory
# based on platform.
self.__default_paths = default_paths
# FIX THESE:
# Add documentation, verify, etc.
self.max_retry_time = 15 * 60
# An additional directory to look for config snippets
self.__extra_config_directory = extra_config_dir
# True to emit warnings on parse. In some scenarios such as when parsing config for agent
# status command we don't want to emit / log warnings since they will interleve with the
# status output
self.__log_warnings = log_warnings
self.__logger = logger
def parse(self):
self.__read_time = time.time()
try:
try:
# First read the file. This makes sure it exists and can be parsed.
self.__config = scalyr_util.read_config_file_as_json(self.__file_path)
# What implicit entries do we need to add? metric monitor, agent.log, and then logs from all monitors.
except Exception as e:
# Special case - file is not readable, likely means a permission issue so return a
# more user-friendly error
msg = str(e).lower()
if (
"file is not readable" in msg
or "error reading" in msg
or "failed while reading"
):
from scalyr_agent.platform_controller import PlatformController
platform_controller = PlatformController.new_platform()
current_user = platform_controller.get_current_user()
msg = FILE_WRONG_OWNER_ERROR_MSG % (
self.__file_path,
current_user,
six.text_type(e),
)
raise BadConfiguration(msg, None, "fileParseError")
raise BadConfiguration(six.text_type(e), None, "fileParseError")
# Import any requested variables from the shell and use them for substitutions.
self.__perform_substitutions(self.__config)
self._check_config_file_permissions_and_warn(self.__file_path)
# get initial list of already seen config keys (we need to do this before
# defaults have been applied)
already_seen = {}
for k in self.__config.keys():
already_seen[k] = self.__file_path
self.__verify_main_config_and_apply_defaults(
self.__config, self.__file_path
)
api_key, api_config_file = self.__check_field(
"api_key", self.__config, self.__file_path
)
scalyr_server, scalyr_server_config_file = self.__check_field(
"scalyr_server", self.__config, self.__file_path
)
self.__verify_logs_and_monitors_configs_and_apply_defaults(
self.__config, self.__file_path
)
# these variables are allowed to appear in multiple files
allowed_multiple_keys = (
"import_vars",
"logs",
"journald_logs",
"k8s_logs",
"monitors",
"server_attributes",
"workers",
)
# map keys to their deprecated versions to replace them later.
allowed_multiple_keys_deprecated_synonyms = {"workers": ["api_keys"]}
# Get any configuration snippets in the config directory
extra_config = self.__list_files(self.config_directory)
# Plus any configuration snippets in the additional config directory
extra_config.extend(self.__list_files(self.extra_config_directory))
# Now, look for any additional configuration in the config fragment directory.
for fp in extra_config:
self.__additional_paths.append(fp)
content = scalyr_util.read_config_file_as_json(fp)
if not isinstance(content, (dict, JsonObject)):
raise BadConfiguration(
'Invalid content inside configuration fragment file "%s". '
"Expected JsonObject (dictionary), got %s."
% (fp, type(content).__name__),
"multiple",
"invalidConfigFragmentType",
)
# if deprecated key names are used, then replace them with their current versions.
for k, v in list(content.items()):
for (
key,
key_synonyms,
) in allowed_multiple_keys_deprecated_synonyms.items():
if k in key_synonyms:
# replace deprecated key.
content[key] = v
del content[k]
break
for k in content.keys():
if k not in allowed_multiple_keys:
if k in already_seen:
self.__last_error = BadConfiguration(
'Configuration fragment file "%s" redefines the config key "%s", first seen in "%s". '
"The only config items that can be defined in multiple config files are: %s."
% (fp, k, already_seen[k], allowed_multiple_keys),
k,
"multipleKeys",
)
raise self.__last_error
else:
already_seen[k] = fp
self._check_config_file_permissions_and_warn(fp)
self.__perform_substitutions(content)
self.__verify_main_config(content, self.__file_path)
self.__verify_logs_and_monitors_configs_and_apply_defaults(content, fp)
for (key, value) in six.iteritems(content):
if key not in allowed_multiple_keys:
self.__config.put(key, value)
self.__add_elements_from_array("logs", content, self.__config)
self.__add_elements_from_array("journald_logs", content, self.__config)
self.__add_elements_from_array("k8s_logs", content, self.__config)
self.__add_elements_from_array("monitors", content, self.__config)
self.__add_elements_from_array(
"workers", content, self.__config, deprecated_names=["api_keys"]
)
self.__merge_server_attributes(fp, content, self.__config)
self.__set_api_key(self.__config, api_key)
if scalyr_server is not None:
self.__config.put("scalyr_server", scalyr_server)
self.__verify_or_set_optional_string(
self.__config,
"scalyr_server",
"https://agent.scalyr.com",
"configuration file %s" % self.__file_path,
env_name="SCALYR_SERVER",
)
self.__config["raw_scalyr_server"] = self.__config["scalyr_server"]
# force https unless otherwise instructed not to
if not self.__config["allow_http"]:
server = self.__config["scalyr_server"].strip()
https_server = ensure_https_url(server)
if https_server != server:
self.__config["scalyr_server"] = https_server
# Set defaults based on `max_send_rate_enforcement` value
if (
not self.__config["disable_max_send_rate_enforcement_overrides"]
and not self.__config["max_send_rate_enforcement"] == "legacy"
):
self._warn_of_override_due_to_rate_enforcement(
"max_allowed_request_size", 1024 * 1024
)
self._warn_of_override_due_to_rate_enforcement(
"pipeline_threshold", 1.1
)
self._warn_of_override_due_to_rate_enforcement(
"min_request_spacing_interval", 1.0
)
self._warn_of_override_due_to_rate_enforcement(
"max_request_spacing_interval", 5.0
)
self._warn_of_override_due_to_rate_enforcement(
"max_log_offset_size", 5 * 1024 * 1024
)
self._warn_of_override_due_to_rate_enforcement(
"max_existing_log_offset_size", 100 * 1024 * 1024
)
self.__config["max_allowed_request_size"] = 5900000
self.__config["pipeline_threshold"] = 0
self.__config["min_request_spacing_interval"] = 0.0
self.__config["max_request_spacing_interval"] = 5.0
self.__config["max_log_offset_size"] = 200000000
self.__config["max_existing_log_offset_size"] = 200000000
# Parse `max_send_rate_enforcement`
if (
self.__config["max_send_rate_enforcement"] != "unlimited"
and self.__config["max_send_rate_enforcement"] != "legacy"
):
try:
self.__config[
"parsed_max_send_rate_enforcement"
] = scalyr_util.parse_data_rate_string(
self.__config["max_send_rate_enforcement"]
)
except ValueError as e:
raise BadConfiguration(
six.text_type(e), "max_send_rate_enforcement", "notDataRate"
)
# Add in 'serverHost' to server_attributes if it is not set. We must do this after merging any
# server attributes from the config fragments.
if "serverHost" not in self.server_attributes:
self.__config["server_attributes"][
"serverHost"
] = self.__get_default_hostname()
# Add in implicit entry to collect the logs generated by this agent and its worker sessions.
agent_log = None
worker_session_agent_logs = None
if self.implicit_agent_log_collection:
# set path as glob to handle log files from the multiprocess worker sessions.
config = JsonObject(
path="agent.log",
parser="scalyrAgentLog",
)
# add log config for the worker session agent log files.
worker_session_logs_config = JsonObject(
path="%s*.log" % AGENT_WORKER_SESSION_LOG_NAME_PREFIX,
# exclude debug files for the worker session debug logs.
# NOTE: the glob for the excluded files has to be restrictive enough,
# so it matches only worker session debug logs.
exclude=JsonArray(
"*%s*_debug.log" % AGENT_WORKER_SESSION_LOG_NAME_PREFIX
),
parser="scalyrAgentLog",
)
self.__verify_log_entry_and_set_defaults(
config, description="implicit rule"
)
self.__verify_log_entry_and_set_defaults(
worker_session_logs_config, description="implicit rule"
)
agent_log = config
worker_session_agent_logs = worker_session_logs_config
self.__log_configs = list(self.__config.get_json_array("logs"))
if agent_log is not None:
self.__log_configs.append(agent_log)
if worker_session_agent_logs is not None:
self.__log_configs.append(worker_session_agent_logs)
self.__journald_log_configs = list(
self.__config.get_json_array("journald_logs")
)
self.__k8s_log_configs = list(self.__config.get_json_array("k8s_logs"))
if (
self.__log_warnings
and self.instrumentation_stats_log_interval > 0
and self.instrumentation_stats_log_interval < (30 * 60 * 60)
):
self.__logger.info(
"Instrumentation logging is enabled (instrumentation_stats_log_interval config "
"option), but logging interval is "
"set lower than 30 minutes. To avoid overhead you are advised to "
"set this interval to 30 minutes or more in production.",
limit_once_per_x_secs=86400,
limit_key="instrumentation-interval-too-low",
)
enable_cpu_profiling = self.enable_profiling or self.enable_cpu_profiling
enable_memory_profiling = (
self.enable_profiling or self.enable_memory_profiling
)
# add in the profile logs if we have enabled profiling
# 1. CPU profiling
if enable_cpu_profiling:
if self.__log_warnings:
log_path = os.path.join(self.agent_log_path, self.profile_log_name)
self.__logger.info(
"CPU profiling is enabled, will ingest CPU profiling (%s) data."
% (log_path),
limit_once_per_x_secs=86400,
limit_key="cpu-profiling-enabled-ingest",
)
profile_config = JsonObject(
path=self.profile_log_name,
copy_from_start=True,
staleness_threshold_secs=20 * 60,
parser="scalyrAgentCpuProfiling",
)
self.__verify_log_entry_and_set_defaults(
profile_config, description="CPU profile log config"
)
self.__log_configs.append(profile_config)
# 2. Memory profiling
if enable_memory_profiling:
if self.__log_warnings:
log_path = os.path.join(
self.agent_log_path, self.memory_profile_log_name
)
self.__logger.info(
"Memory profiling is enabled, will ingest memory "
"profiling (%s) data by default. Using %s memory profiler."
% (
log_path,
self.__config["memory_profiler"],
),
limit_once_per_x_secs=86400,
limit_key="memory-profiling-enabled-ingest",
)
profile_config = JsonObject(
path=self.memory_profile_log_name,
copy_from_start=True,
staleness_threshold_secs=20 * 60,
parser="scalyrAgentMemoryProfiling",
)
self.__verify_log_entry_and_set_defaults(
profile_config, description="CPU profile log config"
)
self.__log_configs.append(profile_config)
self.__monitor_configs = self.__get_monitors_config()
# Perform validation for k8s_logs option
self._check_k8s_logs_config_option_and_warn()
# NOTE do this verifications only after all config fragments were added into configurations.
self.__verify_workers()
self.__verify_and_match_workers_in_logs()
self.__worker_configs = list(self.__config.get_json_array("workers"))
except BadConfiguration as e:
self.__last_error = e
raise e
def __get_monitors_config(self):
monitors_config = list(self.__config.get_json_array("monitors"))
if not self.allow_http_monitors:
return list(map(self.force_http_monitor_config, monitors_config))
return monitors_config
@staticmethod
def force_http_monitor_config(monitor_config):
# Loads a monitor module, checks for options marked as allow_http=False and forces https scheme there.
__import__(monitor_config["module"])
monitor_info = MonitorInformation.get_monitor_info(monitor_config["module"])
for name, value in monitor_config.iteritems():
monitor_config_option = monitor_info.config_option(name)
if monitor_config_option and not monitor_config_option.allow_http:
monitor_config[name] = ensure_https_url(value)
return monitor_config
def __verify_workers(self):
"""
Verify all worker config entries from the "workers" list in config.
"""
workers = list(self.__config.get_json_array("workers"))
unique_worker_ids = {}
# Apply other defaults to all worker entries
for i, worker_entry in enumerate(workers):
self.__verify_workers_entry_and_set_defaults(worker_entry, entry_index=i)
worker_id = worker_entry["id"]
if worker_id in unique_worker_ids:
raise BadConfiguration(
"There are multiple workers with the same '%s' id. Worker id's must remain unique."
% worker_id,
"workers",
"workerIdDuplication",
)
else:
unique_worker_ids[worker_id] = worker_entry
default_worker_entry = unique_worker_ids.get(DEFAULT_WORKER_ID)
if default_worker_entry is None:
default_worker_entry = JsonObject(
api_key=self.api_key, id=DEFAULT_WORKER_ID
)
self.__verify_workers_entry_and_set_defaults(default_worker_entry)
workers.insert(0, default_worker_entry)
self.__config.put("workers", JsonArray(*workers))
def __verify_and_match_workers_in_logs(self):
"""
Check if every log file entry contains a valid reference to the worker.
Each log file config entry has to have a field "worker_id" which refers to some entry in the "workers" list.
If such "worker_id" field is not specified, then the id of the default worker is used.
If "worker_id" is specified but there is no such api key, then the error is raised.
"""
# get the set of all worker ids.
worker_ids = set()
for worker_config in self.__config.get_json_array("workers"):
worker_ids.add(worker_config["id"])
# get all lists where log files entries may be defined and require worker_id param.
# __k8s_log_configs is left out because it interferes with the kubernetes monitor container checker and CopyingManager itself sets default worker_id while adding logs.
log_config_lists_worker_id_required = [
self.__log_configs,
self.__journald_log_configs,
]
for log_config_list in log_config_lists_worker_id_required:
for log_file_config in log_config_list:
log_file_config["worker_id"] = log_file_config.get(
"worker_id", default_value=DEFAULT_WORKER_ID
)
# get all lists where log files entries may be defined.
log_config_lists = [
self.__log_configs,
self.__k8s_log_configs,
self.__journald_log_configs,
]
for log_config_list in log_config_lists:
for log_file_config in log_config_list:
worker_id = log_file_config.get("worker_id", none_if_missing=True)
if worker_id is not None:
# if log file entry has worker_id which is not defined in the 'workers' list, then throw an error.
if worker_id not in worker_ids:
valid_worker_ids = ", ".join(sorted(worker_ids))
raise BadConfiguration(
"The log entry '%s' refers to a non-existing worker with id '%s'. Valid worker ids: %s."
% (
six.text_type(log_file_config),
worker_id,
valid_worker_ids,
),
"logs",
"invalidWorkerReference",
)
def _check_config_file_permissions_and_warn(self, file_path):
# type: (str) -> None
"""
Check config file permissions and log a warning is it's readable or writable by "others".
"""
if not self.__log_warnings:
return None
if not os.path.isfile(file_path) or not self.__logger:
return None
st_mode = os.stat(file_path).st_mode
if bool(st_mode & stat.S_IROTH) or bool(st_mode & stat.S_IWOTH):
file_permissions = str(oct(st_mode)[4:])
if file_permissions.startswith("0") and len(file_permissions) == 4:
file_permissions = file_permissions[1:]
limit_key = "config-permissions-warn-%s" % (file_path)
self.__logger.warn(
"Config file %s is readable or writable by others (permissions=%s). Config "
"files can "
"contain secrets so you are strongly encouraged to change the config "
"file permissions so it's not readable by others."
% (file_path, file_permissions),
limit_once_per_x_secs=86400,
limit_key=limit_key,
)
def _check_k8s_logs_config_option_and_warn(self):
# type: () -> None
"""
Check if k8s_logs attribute is configured, but kubernetes monitor is not and warn.
k8s_logs is a top level config option, but it's utilized by Kubernetes monitor which means
it will have no affect if kubernetes monitor is not configured as well.
"""
if (
self.__k8s_log_configs
and not self._is_kubernetes_monitor_configured()
and self.__log_warnings
):
self.__logger.warn(
'"k8s_logs" config options is defined, but Kubernetes monitor is '
"not configured / enabled. That config option applies to "
"Kubernetes monitor so for it to have an affect, Kubernetes "
"monitor needs to be enabled and configured",
limit_once_per_x_secs=86400,
limit_key="k8s_logs_k8s_monitor_not_enabled",
)
def _is_kubernetes_monitor_configured(self):
# type: () -> bool
"""
Return true if Kubernetes monitor is configured, false otherwise.
"""
monitor_configs = self.monitor_configs or []
for monitor_config in monitor_configs:
if (
monitor_config.get("module", "")
== "scalyr_agent.builtin_monitors.kubernetes_monitor"
):
return True
return False
def _warn_of_override_due_to_rate_enforcement(self, config_option, default):
if self.__log_warnings and self.__config[config_option] != default:
self.__logger.warn(
"Configured option %s is being overridden due to max_send_rate_enforcement setting."
% config_option,
limit_once_per_x_secs=86400,
limit_key="max_send_rate_enforcement_override",
)
def apply_config(self):
"""
Apply global configuration object based on the configuration values.
At this point this only applies to the JSON library which is used and maxstdio settings on
Windows.
"""
if not self.__config:
# parse() hasn't been called yet. We should probably throw here
return
# Set json library based on the config value. If "auto" is provided this means we use
# default behavior which is try to use orjson and if that's not available fall back to
# stdlib json
json_library = self.json_library
current_json_library = scalyr_util.get_json_lib()
if json_library != "auto" and json_library != current_json_library:
self.__logger.debug(
'Changing JSON library from "%s" to "%s"'
% (current_json_library, json_library)
)
scalyr_util.set_json_lib(json_library)
# Call method which applies Windows specific global config options
self.__apply_win32_global_config_options()
def __apply_win32_global_config_options(self):
"""
Method which applies Windows specific global configuration options.
"""
if not sys.platform.startswith("win"):
# Not a Windows platformn
return
# Change the value for maxstdio process specific option
if not win32file:
# win32file module not available
return None
# TODO: We should probably use platform Windows module for this
max_open_fds = self.win32_max_open_fds
current_max_open_fds = win32file._getmaxstdio()
if (max_open_fds and current_max_open_fds) and (
max_open_fds != current_max_open_fds
):
self.__logger.debug(
'Changing limit for max open fds (maxstdio) from "%s" to "%s"'
% (current_max_open_fds, max_open_fds)
)
try:
win32file._setmaxstdio(max_open_fds)
except Exception:
self.__logger.exception("Failed to change the value of maxstdio")
def print_useful_settings(self, other_config=None):
"""
Prints various useful configuration settings to the agent log, so we have a record
in the log of the settings that are currently in use.
@param other_config: Another configuration option. If not None, this function will
only print configuration options that are different between the two objects.
"""
# TODO/NOTE: This code doesn't handle JsonArray's correctly
options = [
"verify_server_certificate",
"ca_cert_path",
"compression_type",
"compression_level",
"pipeline_threshold",
"max_send_rate_enforcement",
"disable_max_send_rate_enforcement_overrides",
"min_allowed_request_size",
"max_allowed_request_size",
"min_request_spacing_interval",
"max_request_spacing_interval",
"read_page_size",
"max_line_size",
"internal_parse_max_line_size",
"line_completion_wait_time",
"max_log_offset_size",
"max_existing_log_offset_size",
"json_library",
"docker_py_version",
"requests_version",
"use_requests_lib",
"use_multiprocess_workers",
"default_sessions_per_worker",
"default_worker_session_status_message_interval",
"enable_worker_session_process_metrics_gather",
# NOTE: It's important we use sanitzed_ version of this method which masks the API key
"sanitized_worker_configs",
]
# get options (if any) from the other configuration object
other_options = None
if other_config is not None:
other_options = {}
for option in options:
other_options[option] = getattr(other_config, option, None)
first = True
for option in options:
value = getattr(self, option, None)
print_value = False
# check to see if we should be printing this option which will will
# be True if other_config is None or if the other_config had a setting
# that was different from our current setting
if other_config is None:
print_value = True
elif (
other_options is not None
and option in other_options
and other_options[option] != value
):
print_value = True
# For json_library config option, we also print actual library which is being used in
# case the value is set to "auto"
if option == "json_library" and value == "auto":
json_lib = scalyr_util.get_json_lib()
value = "%s (%s)" % (value, json_lib)
elif option == "docker_py_version":
try:
import docker
except Exception:
value = "none"
else:
value = getattr(docker, "__version__", None)
elif option == "requests_version":
try:
import requests
except Exception:
value = "none"
else:
value = getattr(requests, "__version__", None)
if print_value:
# if this is the first option we are printing, output a header
if first:
self.__logger.info("Configuration settings")
first = False
if isinstance(value, (list, dict)):
# We remove u"" prefix to ensure consistent output between Python 2 and 3
value = six.text_type(value).replace("u'", "'")
self.__logger.info("\t%s: %s" % (option, value))
# Print additional useful Windows specific information on Windows
win32_max_open_fds_previous_value = getattr(
other_config, "win32_max_open_fds", None
)
win32_max_open_fds_current_value = getattr(self, "win32_max_open_fds", None)
if (
sys.platform.startswith("win")
and win32file
and (
win32_max_open_fds_current_value != win32_max_open_fds_previous_value
or other_config is None
)
):
try:
win32_max_open_fds_actual_value = win32file._getmaxstdio()
except Exception:
win32_max_open_fds_actual_value = "unknown"
if first:
self.__logger.info("Configuration settings")
self.__logger.info(
"\twin32_max_open_fds(maxstdio): %s (%s)"
% (win32_max_open_fds_current_value, win32_max_open_fds_actual_value)
)
# If debug level 5 is set also log the raw config JSON excluding the api_key
# This makes various troubleshooting easier.
if self.debug_level >= 5:
try:
raw_config = self.__get_sanitized_raw_config()
self.__logger.info("Raw config value: %s" % (json.dumps(raw_config)))
except Exception:
# If for some reason we fail to serialize the config, this should not be fatal
pass
def __get_sanitized_raw_config(self):
# type: () -> dict
"""
Return raw config values as a dictionary, masking any secret values such as "api_key".
"""
if not self.__config:
return {}
values_to_mask = [
"api_key",
]
raw_config = copy.deepcopy(self.__config.to_dict())
for key in values_to_mask:
if key in raw_config:
raw_config[key] = MASKED_CONFIG_ITEM_VALUE
# Ensure we also sanitize api_key values in workers dictionaries
if "workers" in raw_config:
raw_config["workers"] = self.sanitized_worker_configs
return raw_config
def __get_default_hostname(self):
"""Returns the default hostname for this host.
@return: The default hostname for this host.
@rtype: str
"""
result = six.ensure_text(socket.gethostname())
if result is not None and self.strip_domain_from_default_server_host:
result = result.split(".")[0]
return result
@staticmethod
def get_session_ids_of_the_worker(worker_config): # type: (Dict) -> List
"""
Generate the list of IDs of all sessions for the specified worker.
:param worker_config: config entry for the worker.
:return: List of worker session IDs.
"""
result = []
for i in range(worker_config["sessions"]):
# combine the id of the worker and session's position in the list to get a session id.
worker_session_id = "%s-%s" % (worker_config["id"], i)
result.append(worker_session_id)
return result
def get_session_ids_from_all_workers(self): # type: () -> List[six.text_type]
"""
Get session ids for all workers.
:return: List of worker session ids.
"""
result = []
for worker_config in self.worker_configs:
result.extend(self.get_session_ids_of_the_worker(worker_config))
return result
def get_worker_session_agent_log_path(
self, worker_session_id
): # type: (six.text_type) -> six.text_type
"""
Generate the name of the log file path for the worker session based on its id.
:param worker_session_id: ID of the worker session.
:return: path for the worker session log file.
"""
return os.path.join(
self.agent_log_path,
"%s%s.log" % (AGENT_WORKER_SESSION_LOG_NAME_PREFIX, worker_session_id),
)
def parse_log_config(
self,
log_config,
default_parser=None,
context_description="uncategorized log entry",
):
"""Parses a given configuration stanza for a log file and returns the complete config with all the
default values filled in.
This is useful for parsing a log configuration entry that was not originally included in the configuration
but whose contents still must be verified. For example, a log configuration entry from a monitor.
@param log_config: The configuration entry for the log.
@param default_parser: If the configuration entry does not have a ``parser`` entry, set this as the default.
@param context_description: The context of where this entry came from, used when creating an error message
for the user.
@type log_config: dict|JsonObject
@type default_parser: str
@type context_description: str
@return: The full configuration for the log.
@rtype: JsonObject
"""
if type(log_config) is dict:
log_config = JsonObject(content=log_config)
log_config = log_config.copy()
if default_parser is not None:
self.__verify_or_set_optional_string(
log_config, "parser", default_parser, context_description
)
self.__verify_log_entry_and_set_defaults(
log_config, description=context_description
)
return log_config
def parse_monitor_config(
self, monitor_config, context_description="uncategorized monitor entry"
):
"""Parses a given monitor configuration entry and returns the complete config with all default values
filled in.
This is useful for parsing a monitor configuration entry that was not originally included in the
configuration but whose contents still must be verified. For example, a default monitor supplied by the
platform.
@param monitor_config: The configuration entry for the monitor.
@param context_description: The context of where this entry came from, used when creating an error message
for the user.
@type monitor_config: dict|JsonObject
@type context_description: str
@return: The full configuration for the monitor.
@rtype: JsonObject