forked from DataDog/dd-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
1316 lines (1048 loc) · 48.6 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
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
import ConfigParser
from cStringIO import StringIO
import glob
import imp
import inspect
import itertools
import logging
import logging.config
import logging.handlers
from optparse import OptionParser, Values
import os
import platform
import re
from socket import gaierror, gethostbyname
import string
import sys
import traceback
from urlparse import urlparse
# project
from util import check_yaml, config_to_yaml
from utils.platform import Platform, get_os
from utils.proxy import get_proxy
from utils.service_discovery.config import extract_agent_config
from utils.service_discovery.config_stores import CONFIG_FROM_FILE, TRACE_CONFIG
from utils.service_discovery.sd_backend import get_sd_backend, AUTO_CONFIG_DIR, SD_BACKENDS
from utils.subprocess_output import (
get_subprocess_output,
SubprocessOutputEmptyError,
)
# CONSTANTS
AGENT_VERSION = "5.11.0"
DATADOG_CONF = "datadog.conf"
UNIX_CONFIG_PATH = '/etc/dd-agent'
MAC_CONFIG_PATH = '/opt/datadog-agent/etc'
DEFAULT_CHECK_FREQUENCY = 15 # seconds
LOGGING_MAX_BYTES = 10 * 1024 * 1024
SDK_INTEGRATIONS_DIR = 'integrations'
SD_PIPE_NAME = "dd-service_discovery"
SD_PIPE_UNIX_PATH = '/opt/datadog-agent/run'
SD_PIPE_WIN_PATH = "\\\\.\\pipe\\{pipename}"
log = logging.getLogger(__name__)
OLD_STYLE_PARAMETERS = [
('apache_status_url', "apache"),
('cacti_mysql_server', "cacti"),
('couchdb_server', "couchdb"),
('elasticsearch', "elasticsearch"),
('haproxy_url', "haproxy"),
('hudson_home', "Jenkins"),
('memcache_', "memcached"),
('mongodb_server', "mongodb"),
('mysql_server', "mysql"),
('nginx_status_url', "nginx"),
('postgresql_server', "postgres"),
('redis_urls', "redis"),
('varnishstat', "varnish"),
('WMI', "WMI"),
]
NAGIOS_OLD_CONF_KEYS = [
'nagios_log',
'nagios_perf_cfg'
]
LEGACY_DATADOG_URLS = [
"app.datadoghq.com",
"app.datad0g.com",
]
JMX_SD_CONF_TEMPLATE = '.jmx.{}.yaml'
class PathNotFound(Exception):
pass
def get_parsed_args():
parser = OptionParser()
parser.add_option('-A', '--autorestart', action='store_true', default=False,
dest='autorestart')
parser.add_option('-d', '--dd_url', action='store', default=None,
dest='dd_url')
parser.add_option('-u', '--use-local-forwarder', action='store_true',
default=False, dest='use_forwarder')
parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose',
help='Print out stacktraces for errors in checks')
parser.add_option('-p', '--profile', action='store_true', default=False,
dest='profile', help='Enable Developer Mode')
try:
options, args = parser.parse_args()
except SystemExit:
# Ignore parse errors
options, args = Values({'autorestart': False,
'dd_url': None,
'use_forwarder': False,
'verbose': False,
'profile': False}), []
return options, args
def get_version():
return AGENT_VERSION
# Return url endpoint, here because needs access to version number
def get_url_endpoint(default_url, endpoint_type='app'):
parsed_url = urlparse(default_url)
if parsed_url.netloc not in LEGACY_DATADOG_URLS:
return default_url
subdomain = parsed_url.netloc.split(".")[0]
# Replace https://app.datadoghq.com in https://5-2-0-app.agent.datadoghq.com
return default_url.replace(subdomain,
"{0}-{1}.agent".format(
get_version().replace(".", "-"),
endpoint_type))
def skip_leading_wsp(f):
"Works on a file, returns a file-like object"
return StringIO("\n".join(map(string.strip, f.readlines())))
def _windows_commondata_path():
"""Return the common appdata path, using ctypes
From http://stackoverflow.com/questions/626796/\
how-do-i-find-the-windows-common-application-data-folder-using-python
"""
import ctypes
from ctypes import wintypes, windll
CSIDL_COMMON_APPDATA = 35
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
wintypes.HANDLE,
wintypes.DWORD, wintypes.LPCWSTR]
path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)
_SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)
return path_buf.value
def _windows_config_path():
common_data = _windows_commondata_path()
return _config_path(os.path.join(common_data, 'Datadog'))
def _windows_confd_path():
common_data = _windows_commondata_path()
return _confd_path(os.path.join(common_data, 'Datadog'))
def _windows_checksd_path():
if hasattr(sys, 'frozen'):
# we're frozen - from py2exe
prog_path = os.path.dirname(sys.executable)
return _checksd_path(os.path.join(prog_path, '..'))
else:
cur_path = os.path.dirname(__file__)
return _checksd_path(cur_path)
def _mac_config_path():
return _config_path(MAC_CONFIG_PATH)
def _mac_confd_path():
return _confd_path(MAC_CONFIG_PATH)
def _mac_checksd_path():
return _unix_checksd_path()
def _unix_config_path():
return _config_path(UNIX_CONFIG_PATH)
def _unix_confd_path():
return _confd_path(UNIX_CONFIG_PATH)
def _unix_checksd_path():
# Unix only will look up based on the current directory
# because checks.d will hang with the other python modules
cur_path = os.path.dirname(os.path.realpath(__file__))
return _checksd_path(cur_path)
def _config_path(directory):
path = os.path.join(directory, DATADOG_CONF)
if os.path.exists(path):
return path
raise PathNotFound(path)
def _confd_path(directory):
path = os.path.join(directory, 'conf.d')
if os.path.exists(path):
return path
raise PathNotFound(path)
def _checksd_path(directory):
path = os.path.join(directory, 'checks.d')
if os.path.exists(path):
return path
raise PathNotFound(path)
def _is_affirmative(s):
if s is None:
return False
# int or real bool
if isinstance(s, int):
return bool(s)
# try string cast
return s.lower() in ('yes', 'true', '1')
def get_config_path(cfg_path=None, os_name=None):
# Check if there's an override and if it exists
if cfg_path is not None and os.path.exists(cfg_path):
return cfg_path
# Check if there's a config stored in the current agent directory
try:
path = os.path.realpath(__file__)
path = os.path.dirname(path)
return _config_path(path)
except PathNotFound as e:
pass
if os_name is None:
os_name = get_os()
# Check for an OS-specific path, continue on not-found exceptions
bad_path = ''
try:
if os_name == 'windows':
return _windows_config_path()
elif os_name == 'mac':
return _mac_config_path()
else:
return _unix_config_path()
except PathNotFound as e:
if len(e.args) > 0:
bad_path = e.args[0]
# If all searches fail, exit the agent with an error
sys.stderr.write("Please supply a configuration file at %s or in the directory where "
"the Agent is currently deployed.\n" % bad_path)
sys.exit(3)
def get_default_bind_host():
try:
gethostbyname('localhost')
except gaierror:
log.warning("localhost seems undefined in your hosts file, using 127.0.0.1 instead")
return '127.0.0.1'
return 'localhost'
def get_histogram_aggregates(configstr=None):
if configstr is None:
return None
try:
vals = configstr.split(',')
valid_values = ['min', 'max', 'median', 'avg', 'sum', 'count']
result = []
for val in vals:
val = val.strip()
if val not in valid_values:
log.warning("Ignored histogram aggregate {0}, invalid".format(val))
continue
else:
result.append(val)
except Exception:
log.exception("Error when parsing histogram aggregates, skipping")
return None
return result
def get_histogram_percentiles(configstr=None):
if configstr is None:
return None
result = []
try:
vals = configstr.split(',')
for val in vals:
try:
val = val.strip()
floatval = float(val)
if floatval <= 0 or floatval >= 1:
raise ValueError
if len(val) > 4:
log.warning("Histogram percentiles are rounded to 2 digits: {0} rounded"
.format(floatval))
result.append(float(val[0:4]))
except ValueError:
log.warning("Bad histogram percentile value {0}, must be float in ]0;1[, skipping"
.format(val))
except Exception:
log.exception("Error when parsing histogram percentiles, skipping")
return None
return result
def clean_dd_url(url):
url = url.strip()
if not url.startswith('http'):
url = 'https://' + url
return url[:-1] if url.endswith('/') else url
def remove_empty(string_array):
return filter(lambda x: x, string_array)
def get_config(parse_args=True, cfg_path=None, options=None):
if parse_args:
options, _ = get_parsed_args()
# General config
agentConfig = {
'check_freq': DEFAULT_CHECK_FREQUENCY,
'dogstatsd_port': 8125,
'dogstatsd_target': 'http://localhost:17123',
'graphite_listen_port': None,
'hostname': None,
'listen_port': None,
'tags': None,
'use_ec2_instance_id': False, # DEPRECATED
'version': get_version(),
'watchdog': True,
'additional_checksd': '/etc/dd-agent/checks.d/',
'bind_host': get_default_bind_host(),
'statsd_metric_namespace': None,
'utf8_decoding': False
}
if Platform.is_mac():
agentConfig['additional_checksd'] = '/opt/datadog-agent/etc/checks.d'
# Config handling
try:
# Find the right config file
path = os.path.realpath(__file__)
path = os.path.dirname(path)
config_path = get_config_path(cfg_path, os_name=get_os())
config = ConfigParser.ConfigParser()
config.readfp(skip_leading_wsp(open(config_path)))
# bulk import
for option in config.options('Main'):
agentConfig[option] = config.get('Main', option)
# Store developer mode setting in the agentConfig
if config.has_option('Main', 'developer_mode'):
agentConfig['developer_mode'] = _is_affirmative(config.get('Main', 'developer_mode'))
# Allow an override with the --profile option
if options is not None and options.profile:
agentConfig['developer_mode'] = True
# Core config
#ap
if not config.has_option('Main', 'api_key'):
log.warning(u"No API key was found. Aborting.")
sys.exit(2)
if not config.has_option('Main', 'dd_url'):
log.warning(u"No dd_url was found. Aborting.")
sys.exit(2)
# Endpoints
dd_urls = map(clean_dd_url, config.get('Main', 'dd_url').split(','))
api_keys = map(lambda el: el.strip(), config.get('Main', 'api_key').split(','))
# For collector and dogstatsd
agentConfig['dd_url'] = dd_urls[0]
agentConfig['api_key'] = api_keys[0]
# Forwarder endpoints logic
# endpoints is:
# {
# 'https://app.datadoghq.com': ['api_key_abc', 'api_key_def'],
# 'https://app.example.com': ['api_key_xyz']
# }
endpoints = {}
dd_urls = remove_empty(dd_urls)
api_keys = remove_empty(api_keys)
if len(dd_urls) == 1:
if len(api_keys) > 0:
endpoints[dd_urls[0]] = api_keys
else:
assert len(dd_urls) == len(api_keys), 'Please provide one api_key for each url'
for i, dd_url in enumerate(dd_urls):
endpoints[dd_url] = endpoints.get(dd_url, []) + [api_keys[i]]
agentConfig['endpoints'] = endpoints
# Forwarder or not forwarder
agentConfig['use_forwarder'] = options is not None and options.use_forwarder
if agentConfig['use_forwarder']:
listen_port = 17123
if config.has_option('Main', 'listen_port'):
listen_port = int(config.get('Main', 'listen_port'))
agentConfig['dd_url'] = "http://{}:{}".format(agentConfig['bind_host'], listen_port)
# FIXME: Legacy dd_url command line switch
elif options is not None and options.dd_url is not None:
agentConfig['dd_url'] = options.dd_url
# Forwarder timeout
agentConfig['forwarder_timeout'] = 20
if config.has_option('Main', 'forwarder_timeout'):
agentConfig['forwarder_timeout'] = int(config.get('Main', 'forwarder_timeout'))
# Extra checks.d path
# the linux directory is set by default
if config.has_option('Main', 'additional_checksd'):
agentConfig['additional_checksd'] = config.get('Main', 'additional_checksd')
elif get_os() == 'windows':
# default windows location
common_path = _windows_commondata_path()
agentConfig['additional_checksd'] = os.path.join(common_path, 'Datadog', 'checks.d')
if config.has_option('Main', 'use_dogstatsd'):
agentConfig['use_dogstatsd'] = config.get('Main', 'use_dogstatsd').lower() in ("yes", "true")
else:
agentConfig['use_dogstatsd'] = True
# Service discovery
if config.has_option('Main', 'service_discovery_backend'):
try:
additional_config = extract_agent_config(config)
agentConfig.update(additional_config)
except:
log.error('Failed to load the agent configuration related to '
'service discovery. It will not be used.')
# Concerns only Windows
if config.has_option('Main', 'use_web_info_page'):
agentConfig['use_web_info_page'] = config.get('Main', 'use_web_info_page').lower() in ("yes", "true")
else:
agentConfig['use_web_info_page'] = True
# local traffic only? Default to no
agentConfig['non_local_traffic'] = False
if config.has_option('Main', 'non_local_traffic'):
agentConfig['non_local_traffic'] = config.get('Main', 'non_local_traffic').lower() in ("yes", "true")
# DEPRECATED
if config.has_option('Main', 'use_ec2_instance_id'):
use_ec2_instance_id = config.get('Main', 'use_ec2_instance_id')
# translate yes into True, the rest into False
agentConfig['use_ec2_instance_id'] = (use_ec2_instance_id.lower() == 'yes')
if config.has_option('Main', 'check_freq'):
try:
agentConfig['check_freq'] = int(config.get('Main', 'check_freq'))
except Exception:
pass
# Custom histogram aggregate/percentile metrics
if config.has_option('Main', 'histogram_aggregates'):
agentConfig['histogram_aggregates'] = get_histogram_aggregates(config.get('Main', 'histogram_aggregates'))
if config.has_option('Main', 'histogram_percentiles'):
agentConfig['histogram_percentiles'] = get_histogram_percentiles(config.get('Main', 'histogram_percentiles'))
# Disable Watchdog (optionally)
if config.has_option('Main', 'watchdog'):
if config.get('Main', 'watchdog').lower() in ('no', 'false'):
agentConfig['watchdog'] = False
# Optional graphite listener
if config.has_option('Main', 'graphite_listen_port'):
agentConfig['graphite_listen_port'] = \
int(config.get('Main', 'graphite_listen_port'))
else:
agentConfig['graphite_listen_port'] = None
# Dogstatsd config
dogstatsd_defaults = {
'dogstatsd_port': 8125,
'dogstatsd_target': 'http://' + agentConfig['bind_host'] + ':17123',
}
for key, value in dogstatsd_defaults.iteritems():
if config.has_option('Main', key):
agentConfig[key] = config.get('Main', key)
else:
agentConfig[key] = value
# Create app:xxx tags based on monitored apps
agentConfig['create_dd_check_tags'] = config.has_option('Main', 'create_dd_check_tags') and \
_is_affirmative(config.get('Main', 'create_dd_check_tags'))
# Forwarding to external statsd server
if config.has_option('Main', 'statsd_forward_host'):
agentConfig['statsd_forward_host'] = config.get('Main', 'statsd_forward_host')
if config.has_option('Main', 'statsd_forward_port'):
agentConfig['statsd_forward_port'] = int(config.get('Main', 'statsd_forward_port'))
# Optional config
# FIXME not the prettiest code ever...
if config.has_option('Main', 'use_mount'):
agentConfig['use_mount'] = _is_affirmative(config.get('Main', 'use_mount'))
if options is not None and options.autorestart:
agentConfig['autorestart'] = True
elif config.has_option('Main', 'autorestart'):
agentConfig['autorestart'] = _is_affirmative(config.get('Main', 'autorestart'))
if config.has_option('Main', 'check_timings'):
agentConfig['check_timings'] = _is_affirmative(config.get('Main', 'check_timings'))
if config.has_option('Main', 'exclude_process_args'):
agentConfig['exclude_process_args'] = _is_affirmative(config.get('Main', 'exclude_process_args'))
try:
filter_device_re = config.get('Main', 'device_blacklist_re')
agentConfig['device_blacklist_re'] = re.compile(filter_device_re)
except ConfigParser.NoOptionError:
pass
# Dogstream config
if config.has_option("Main", "dogstream_log"):
# Older version, single log support
log_path = config.get("Main", "dogstream_log")
if config.has_option("Main", "dogstream_line_parser"):
agentConfig["dogstreams"] = ':'.join([log_path, config.get("Main", "dogstream_line_parser")])
else:
agentConfig["dogstreams"] = log_path
elif config.has_option("Main", "dogstreams"):
agentConfig["dogstreams"] = config.get("Main", "dogstreams")
if config.has_option("Main", "nagios_perf_cfg"):
agentConfig["nagios_perf_cfg"] = config.get("Main", "nagios_perf_cfg")
if config.has_option("Main", "use_curl_http_client"):
agentConfig["use_curl_http_client"] = _is_affirmative(config.get("Main", "use_curl_http_client"))
else:
# Default to False as there are some issues with the curl client and ELB
agentConfig["use_curl_http_client"] = False
if config.has_section('WMI'):
agentConfig['WMI'] = {}
for key, value in config.items('WMI'):
agentConfig['WMI'][key] = value
if (config.has_option("Main", "limit_memory_consumption") and
config.get("Main", "limit_memory_consumption") is not None):
agentConfig["limit_memory_consumption"] = int(config.get("Main", "limit_memory_consumption"))
else:
agentConfig["limit_memory_consumption"] = None
if config.has_option("Main", "skip_ssl_validation"):
agentConfig["skip_ssl_validation"] = _is_affirmative(config.get("Main", "skip_ssl_validation"))
agentConfig["collect_instance_metadata"] = True
if config.has_option("Main", "collect_instance_metadata"):
agentConfig["collect_instance_metadata"] = _is_affirmative(config.get("Main", "collect_instance_metadata"))
agentConfig["proxy_forbid_method_switch"] = False
if config.has_option("Main", "proxy_forbid_method_switch"):
agentConfig["proxy_forbid_method_switch"] = _is_affirmative(config.get("Main", "proxy_forbid_method_switch"))
agentConfig["collect_ec2_tags"] = False
if config.has_option("Main", "collect_ec2_tags"):
agentConfig["collect_ec2_tags"] = _is_affirmative(config.get("Main", "collect_ec2_tags"))
agentConfig["utf8_decoding"] = False
if config.has_option("Main", "utf8_decoding"):
agentConfig["utf8_decoding"] = _is_affirmative(config.get("Main", "utf8_decoding"))
agentConfig["gce_updated_hostname"] = False
if config.has_option("Main", "gce_updated_hostname"):
agentConfig["gce_updated_hostname"] = _is_affirmative(config.get("Main", "gce_updated_hostname"))
except ConfigParser.NoSectionError as e:
sys.stderr.write('Config file not found or incorrectly formatted.\n')
sys.exit(2)
except ConfigParser.ParsingError as e:
sys.stderr.write('Config file not found or incorrectly formatted.\n')
sys.exit(2)
except ConfigParser.NoOptionError as e:
sys.stderr.write('There are some items missing from your config file, but nothing fatal [%s]' % e)
# Storing proxy settings in the agentConfig
agentConfig['proxy_settings'] = get_proxy(agentConfig)
if agentConfig.get('ca_certs', None) is None:
agentConfig['ssl_certificate'] = get_ssl_certificate(get_os(), 'datadog-cert.pem')
else:
agentConfig['ssl_certificate'] = agentConfig['ca_certs']
return agentConfig
def get_system_stats(proc_path=None):
systemStats = {
'machine': platform.machine(),
'platform': sys.platform,
'processor': platform.processor(),
'pythonV': platform.python_version(),
}
platf = sys.platform
try:
if Platform.is_linux(platf):
if not proc_path:
proc_path = "/proc"
proc_cpuinfo = os.path.join(proc_path,'cpuinfo')
output, _, _ = get_subprocess_output(['grep', 'model name', proc_cpuinfo], log)
systemStats['cpuCores'] = len(output.splitlines())
if Platform.is_darwin(platf) or Platform.is_freebsd(platf):
output, _, _ = get_subprocess_output(['sysctl', 'hw.ncpu'], log)
systemStats['cpuCores'] = int(output.split(': ')[1])
except SubprocessOutputEmptyError as e:
log.warning("unable to retrieve number of cpuCores. Failed with error %s", e)
if Platform.is_linux(platf):
systemStats['nixV'] = platform.dist()
elif Platform.is_darwin(platf):
systemStats['macV'] = platform.mac_ver()
elif Platform.is_freebsd(platf):
version = platform.uname()[2]
systemStats['fbsdV'] = ('freebsd', version, '') # no codename for FreeBSD
elif Platform.is_win32(platf):
systemStats['winV'] = platform.win32_ver()
return systemStats
def set_win32_cert_path():
"""In order to use tornado.httpclient with the packaged .exe on Windows we
need to override the default ceritifcate location which is based on the path
to tornado and will give something like "C:\path\to\program.exe\tornado/cert-file".
If pull request #379 is accepted (https://github.com/facebook/tornado/pull/379) we
will be able to override this in a clean way. For now, we have to monkey patch
tornado.httpclient._DEFAULT_CA_CERTS
"""
if hasattr(sys, 'frozen'):
# we're frozen - from py2exe
prog_path = os.path.dirname(sys.executable)
crt_path = os.path.join(prog_path, 'ca-certificates.crt')
else:
cur_path = os.path.dirname(__file__)
crt_path = os.path.join(cur_path, 'packaging', 'datadog-agent', 'win32',
'install_files', 'ca-certificates.crt')
import tornado.simple_httpclient
log.info("Windows certificate path: %s" % crt_path)
tornado.simple_httpclient._DEFAULT_CA_CERTS = crt_path
def set_win32_requests_ca_bundle_path():
"""In order to allow `requests` to validate SSL requests with the packaged .exe on Windows,
we need to override the default certificate location which is based on the location of the
requests or certifi libraries.
We override the path directly in requests.adapters so that the override works even when the
`requests` lib has already been imported
"""
import requests.adapters
if hasattr(sys, 'frozen'):
# we're frozen - from py2exe
prog_path = os.path.dirname(sys.executable)
ca_bundle_path = os.path.join(prog_path, 'cacert.pem')
requests.adapters.DEFAULT_CA_BUNDLE_PATH = ca_bundle_path
log.info("Default CA bundle path of the requests library: {0}"
.format(requests.adapters.DEFAULT_CA_BUNDLE_PATH))
def get_confd_path(osname=None):
try:
cur_path = os.path.dirname(os.path.realpath(__file__))
return _confd_path(cur_path)
except PathNotFound as e:
pass
if not osname:
osname = get_os()
bad_path = ''
try:
if osname == 'windows':
return _windows_confd_path()
elif osname == 'mac':
return _mac_confd_path()
else:
return _unix_confd_path()
except PathNotFound as e:
if len(e.args) > 0:
bad_path = e.args[0]
raise PathNotFound(bad_path)
def get_checksd_path(osname=None):
if not osname:
osname = get_os()
if osname == 'windows':
return _windows_checksd_path()
elif osname == 'mac':
return _mac_checksd_path()
else:
return _unix_checksd_path()
def get_sdk_integrations_path(osname=None):
if not osname:
osname = get_os()
if osname in ['windows', 'mac']:
raise PathNotFound()
cur_path = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(cur_path, '..', SDK_INTEGRATIONS_DIR)
if os.path.exists(path):
return path
raise PathNotFound(path)
def get_jmx_pipe_path():
if Platform.is_windows():
pipe_path = SD_PIPE_WIN_PATH
else:
pipe_path = SD_PIPE_UNIX_PATH
if not os.path.isdir(pipe_path):
pipe_path = '/tmp'
return pipe_path
def get_auto_confd_path(osname=None):
"""Used for service discovery which only works for Unix"""
return os.path.join(get_confd_path(osname), AUTO_CONFIG_DIR)
def get_win32service_file(osname, filename):
# This file is needed to log in the event viewer for windows
if osname == 'windows':
if hasattr(sys, 'frozen'):
# we're frozen - from py2exe
prog_path = os.path.dirname(sys.executable)
path = os.path.join(prog_path, filename)
else:
cur_path = os.path.dirname(__file__)
path = os.path.join(cur_path, filename)
if os.path.exists(path):
log.debug("Certificate file found at %s" % str(path))
return path
else:
cur_path = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(cur_path, filename)
if os.path.exists(path):
return path
return None
def get_ssl_certificate(osname, filename):
# The SSL certificate is needed by tornado in case of connection through a proxy
# Also used by flare's requests on Windows
if osname == 'windows':
if hasattr(sys, 'frozen'):
# we're frozen - from py2exe
prog_path = os.path.dirname(sys.executable)
path = os.path.join(prog_path, filename)
else:
cur_path = os.path.dirname(__file__)
path = os.path.join(cur_path, filename)
if os.path.exists(path):
log.debug("Certificate file found at %s" % str(path))
return path
else:
cur_path = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(cur_path, filename)
if os.path.exists(path):
return path
log.info("Certificate file NOT found at %s" % str(path))
return None
def _get_check_class(check_name, check_path):
'''Return the corresponding check class for a check name if available.'''
from checks import AgentCheck
check_class = None
try:
check_module = imp.load_source('checksd_%s' % check_name, check_path)
except Exception as e:
traceback_message = traceback.format_exc()
# There is a configuration file for that check but the module can't be imported
log.exception('Unable to import check module %s.py from checks.d' % check_name)
return {'error': e, 'traceback': traceback_message}
# We make sure that there is an AgentCheck class defined
check_class = None
classes = inspect.getmembers(check_module, inspect.isclass)
for _, clsmember in classes:
if clsmember == AgentCheck:
continue
if issubclass(clsmember, AgentCheck):
check_class = clsmember
if AgentCheck in clsmember.__bases__:
continue
else:
break
return check_class
def _deprecated_configs(agentConfig):
""" Warn about deprecated configs
"""
deprecated_checks = {}
deprecated_configs_enabled = [v for k, v in OLD_STYLE_PARAMETERS if len([l for l in agentConfig if l.startswith(k)]) > 0]
for deprecated_config in deprecated_configs_enabled:
msg = "Configuring %s in datadog.conf is not supported anymore. Please use conf.d" % deprecated_config
deprecated_checks[deprecated_config] = {'error': msg, 'traceback': None}
log.error(msg)
return deprecated_checks
def _file_configs_paths(osname, agentConfig):
""" Retrieve all the file configs and return their paths
"""
try:
confd_path = get_confd_path(osname)
all_file_configs = glob.glob(os.path.join(confd_path, '*.yaml'))
all_default_configs = glob.glob(os.path.join(confd_path, '*.yaml.default'))
except PathNotFound as e:
log.error("No conf.d folder found at '%s' or in the directory where the Agent is currently deployed.\n" % e.args[0])
sys.exit(3)
if all_default_configs:
current_configs = set([_conf_path_to_check_name(conf) for conf in all_file_configs])
for default_config in all_default_configs:
if not _conf_path_to_check_name(default_config) in current_configs:
all_file_configs.append(default_config)
# Compatibility code for the Nagios checks if it's still configured
# in datadog.conf
# FIXME: 6.x, should be removed
if not any('nagios' in config for config in itertools.chain(*all_file_configs)):
# check if it's configured in datadog.conf the old way
if any([nagios_key in agentConfig for nagios_key in NAGIOS_OLD_CONF_KEYS]):
all_file_configs.append('deprecated/nagios')
return all_file_configs
def _service_disco_configs(agentConfig):
""" Retrieve all the service disco configs and return their conf dicts
"""
if agentConfig.get('service_discovery') and agentConfig.get('service_discovery_backend') in SD_BACKENDS:
try:
log.info("Fetching service discovery check configurations.")
sd_backend = get_sd_backend(agentConfig=agentConfig)
service_disco_configs = sd_backend.get_configs()
except Exception:
log.exception("Loading service discovery configurations failed.")
return {}
else:
service_disco_configs = {}
return service_disco_configs
def _conf_path_to_check_name(conf_path):
f = os.path.splitext(os.path.split(conf_path)[1])
if f[1] and f[1] == ".default":
f = os.path.splitext(f[0])
return f[0]
def get_checks_places(osname, agentConfig):
""" Return a list of methods which, when called with a check name, will each return a check path to inspect
"""
try:
checksd_path = get_checksd_path(osname)
except PathNotFound as e:
log.error(e.args[0])
sys.exit(3)
places = [lambda name: os.path.join(agentConfig['additional_checksd'], '%s.py' % name)]
try:
sdk_integrations = get_sdk_integrations_path(osname)
places.append(lambda name: os.path.join(sdk_integrations, name, 'check.py'))
except PathNotFound:
log.debug('No sdk integrations path found')
places.append(lambda name: os.path.join(checksd_path, '%s.py' % name))
return places
def _load_file_config(config_path, check_name, agentConfig):
if config_path == 'deprecated/nagios':
log.warning("Configuring Nagios in datadog.conf is deprecated "
"and will be removed in a future version. "
"Please use conf.d")
check_config = {'instances': [dict((key, value) for (key, value) in agentConfig.iteritems() if key in NAGIOS_OLD_CONF_KEYS)]}
return True, check_config, {}
try:
check_config = check_yaml(config_path)
except Exception as e:
log.exception("Unable to parse yaml config in %s" % config_path)
traceback_message = traceback.format_exc()
return False, None, {check_name: {'error': str(e), 'traceback': traceback_message}}
return True, check_config, {}
def get_valid_check_class(check_name, check_path):
check_class = _get_check_class(check_name, check_path)
if not check_class:
log.error('No check class (inheriting from AgentCheck) found in %s.py' % check_name)
return False, None, {}
# this means we are actually looking at a load failure
elif isinstance(check_class, dict):
return False, None, {check_name: check_class}
return True, check_class, {}
def _initialize_check(check_config, check_name, check_class, agentConfig):
init_config = check_config.get('init_config') or {}
instances = check_config['instances']
try:
try:
check = check_class(check_name, init_config=init_config,
agentConfig=agentConfig, instances=instances)
except TypeError as e:
# Backwards compatibility for checks which don't support the
# instances argument in the constructor.
check = check_class(check_name, init_config=init_config,
agentConfig=agentConfig)
check.instances = instances
except Exception as e:
log.exception('Unable to initialize check %s' % check_name)
traceback_message = traceback.format_exc()
return {}, {check_name: {'error': e, 'traceback': traceback_message}}
else:
return {check_name: check}, {}
def _update_python_path(check_config):
# Add custom pythonpath(s) if available
if 'pythonpath' in check_config:
pythonpath = check_config['pythonpath']
if not isinstance(pythonpath, list):
pythonpath = [pythonpath]
sys.path.extend(pythonpath)
def load_check_from_places(check_config, check_name, checks_places, agentConfig):
'''Find a check named check_name in the given checks_places and try to initialize it with the given check_config.
A failure (`load_failure`) can happen when the check class can't be validated or when the check can't be initialized. '''
load_success, load_failure = {}, {}
for check_path_builder in checks_places:
check_path = check_path_builder(check_name)
if not os.path.exists(check_path):
continue
check_is_valid, check_class, load_failure = get_valid_check_class(check_name, check_path)
if not check_is_valid:
continue
load_success, load_failure = _initialize_check(