forked from cloudviz/agentless-system-crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawlutils.py
executable file
·2733 lines (2425 loc) · 117 KB
/
crawlutils.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
#!/usr/bin/python
#
# (c) Copyright IBM Corp.2014,2015
#
# Collection of crawlers that extract specific types of features from
# the host machine. This code is portable across OS platforms (Linux, Windows)
#
import sys
import platform
import os
import stat
import logging
from collections import namedtuple,OrderedDict
import socket
import codecs
import subprocess
import tempfile
import gzip
import shutil
import fnmatch
import re
import time
import csv
import commands
from datetime import datetime
import copy
#from mtgraphite import MTGraphiteClient
import cPickle as pickle
import multiprocessing
import errno
#from timeout import timeout
# Additional modules
import platform_outofband
# External dependencies that must be easy_install'ed separately
import simplejson as json
import psutil
import requests
from netifaces import interfaces, ifaddresses, AF_INET
logger = logging.getLogger("crawlutils")
OSFeature = namedtuple('OSFeature', ["boottime", "ipaddr", "osdistro", "osname", "osplatform", "osrelease", "ostype", "osversion"])
FileFeature = namedtuple('FileFeature', ["atime", "ctime", "gid", "linksto", "mode", "mtime", "name", "path", "size", "type", "uid"])
ConfigFeature = namedtuple('ConfigFeature', ["name", "content", "path"])
DiskFeature = namedtuple('DiskFeature', ["partitionname", "freepct", "fstype", "mountpt", "mountopts", "partitionsize"])
ProcessFeature = namedtuple('ProcessFeature', ["cmd", "created", "cwd", "pname", "openfiles", "pid", "ppid", "threads", "user"])
MetricFeature = namedtuple('MetricFeature', ["cpupct", "mempct", "pname", "pid", "read", "rss", "status", "user", "vms", "write"])
ConnectionFeature = namedtuple('ConnectionFeature', ["localipaddr", "localport", "pname", "pid", "remoteipaddr", "remoteport", "connstatus"])
PackageFeature = namedtuple('PackageFeature', ["installed", "pkgname", "pkgsize", "pkgversion"])
MemoryFeature = namedtuple('MemoryFeature', ["memory_used", "memory_buffered", "memory_cached", "memory_free"])
CpuFeature = namedtuple('CpuFeature', ["cpu_idle", "cpu_nice", "cpu_user", "cpu_wait", "cpu_system", "cpu_interrupt", "cpu_steal"])
InterfaceFeature = namedtuple('InterfaceFeature', ["if_octets_tx", "if_octets_rx", "if_packets_tx", "if_packets_rx", "if_errors_tx", "if_errors_rx"])
LoadFeature = namedtuple('LoadFeature', ["shortterm", "midterm", "longterm"])
DockerPSFeature = namedtuple('DockerPSFeature', ["Status", "Created", "Image", "Ports", "Command", "Names", "Id" ])
DockerHistoryFeature = namedtuple('DockerHistoryFeature', ["history" ])
Container = namedtuple('Container', ['pid', 'short_id', 'long_id', 'name', 'image', 'namespace'])
FEATURE_SCHEMA = {
'os' : OSFeature._fields,
'file' : FileFeature._fields,
'config' : ConfigFeature._fields,
'disk' : DiskFeature._fields,
'process' : ProcessFeature._fields,
'connection' : ConnectionFeature._fields,
'metric' : MetricFeature._fields,
'package' : PackageFeature._fields,
'memory' : MemoryFeature._fields,
'cpu' : CpuFeature._fields,
'interface' : InterfaceFeature._fields,
'load' : LoadFeature._fields,
'dockerps' : DockerPSFeature._fields,
'dockerhistory' : DockerHistoryFeature._fields
}
class CrawlException(Exception):
def __init__(self, e):
pass
# try to determine this host's IP address
def get_host_ipaddr():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('www.ibm.com', 9))
return s.getsockname()[0]
except socket.error:
return None
finally:
del s
def get_host_ip4_addresses():
ip_list = []
for interface in interfaces():
if AF_INET in ifaddresses(interface):
for link in ifaddresses(interface)[AF_INET]:
ip_list.append(link['addr'])
return ip_list
class Crawler:
@staticmethod
def get_feature_schema():
return FEATURE_SCHEMA
# feature_epoch must be a UTC timestamp. If > 0 only features accessed/modified/created since this time are crawled
def __init__(self, feature_epoch=0, ignore_exceptions=True,
config_file_discovery_heuristic=None, crawl_mode='INVM',
vm=None, container_long_id=None, namespace=None):
logger.info('Initilizing crawler: feature_epoch={0}, ignore_exceptions={1}, config_file_discovery_heuristic={2}'.format(
feature_epoch, ignore_exceptions, config_file_discovery_heuristic))
self.feature_epoch = feature_epoch
self.ignore_exceptions = ignore_exceptions
self.is_config_file = config_file_discovery_heuristic or Crawler._is_config_file
#TODO: Define crawl mode as custom type!! #'INVM', 'MOUNTPOINT', 'DEVICE', 'FILE', etc.
self.crawl_mode = crawl_mode
# Used for OUTCONTAINER crawl mode
self.container_long_id = container_long_id
# Used by crawl_interface
self.namespace = namespace
# Used for OUTVM crawl mode
self.vm = vm # tuple like ('instance-00000172', 'x86_64', '3.3.3')
#crawl the OS information
# mountpoint only used for out-of-band crawling
def crawl_os(self, mountpoint=None):
# os attributes: ["boottime", "osdistro", "ipaddr", "osname", "osplatform", "osrelease", "ostype", "osversion"]
# os "linux" --> platform.system().lower()
# {"boottime":1394049039.0, --> psutil.boot_time()
# "ipaddr":"10.154.163.164", --> get_host_ipaddr()
# "osdistro":"Ubuntu", --> platform_outofband.linux_distribution(prefix=mountpoint)[0],
# "osname":"Linux-3.11.0-12-generic-i686-with-Ubuntu-13.10-saucy", --> platform_outofband.platform(),
# "osplatform":"i686", --> platform_outofband.machine(prefix=mountpoint),
# "osrelease":"3.11.0-12-generic", --> platform_outofband.release(prefix=mountpoint),
# "ostype":"linux", --> platform_outofband.system(prefix=mountpoint).lower(),
# "osversion":"#19-Ubuntu SMP Wed Oct 9 16:12:00 UTC 2013"} --> platform_outofband.version(prefix=mountpoint)
logger.debug('Crawling OS')
if self.crawl_mode == 'INVM':
logger.debug('Using in-VM state information (crawl mode: ' + self.crawl_mode + ')')
feature_key = platform.system().lower()
try: ips = get_host_ip4_addresses()
except Exception, e: ips = 'unknown'
try: distro = platform.linux_distribution()[0]
except Exception, e: distro = 'unknown'
try: osname = platform.platform()
except Exception, e: osname = 'unknown'
boot_time = (psutil.boot_time() if hasattr(psutil, "boot_time")
else psutil.BOOT_TIME)
feature_attributes = OSFeature(boot_time, ips, distro, osname,
platform.machine(), platform.release(),
platform.system().lower(), platform.version())
elif self.crawl_mode == 'MOUNTPOINT':
logger.debug('Using disk image information (crawl mode: ' + self.crawl_mode + ')')
if (mountpoint is None) or (not os.path.exists(mountpoint)):
logger.error('Mountpoint: ' + mountpoint + ' does not exist.')
feature_key = 'unknown'
feature_attributes = OSFeature('unknown', 'unknown', 'unknown', 'unknown',
'unknown', 'unknown', 'unknown', 'unknown')
else:
feature_key = platform_outofband.system(prefix=mountpoint).lower()
feature_attributes = OSFeature("unsupported", # boot time unknown for img
"0.0.0.0", # live IP unknown for img
platform_outofband.linux_distribution(prefix=mountpoint)[0],
platform_outofband.platform(prefix=mountpoint),
platform_outofband.machine(prefix=mountpoint),
platform_outofband.release(prefix=mountpoint),
platform_outofband.system(prefix=mountpoint).lower(),
platform_outofband.version(prefix=mountpoint)
)
elif self.crawl_mode == 'OUTVM':
domain_name, kernel_version, distro, arch = self.vm
from psvmi import system_info
sys = system_info(domain_name, kernel_version, distro, arch)
feature_attributes = OSFeature(sys.boottime, sys.ipaddr,
sys.osdistro, sys.osname,sys.osplatform,sys.osrelease,
sys.ostype,sys.osversion)
feature_key = sys.ostype
else:
logger.error('Unsupported crawl mode: ' + self.crawl_mode + '. Returning unknown OS key and attributes.')
feature_key = 'unknown'
feature_attributes = OSFeature('unknown', 'unknown', 'unknown', 'unknown',
'unknown', 'unknown', 'unknown', 'unknown')
try:
yield feature_key, feature_attributes
except Exception, e:
logger.error('Error crawling OS', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl the directory hierarchy under root_dir
def crawl_files(self, root_dir='/', exclude_dirs=['proc','mnt','dev','tmp'], root_dir_alias=None):
accessed_since = self.feature_epoch
logger.debug('Crawling Files: root_dir={0}, exclude_dirs={1}, root_dir_alias={2}, accessed_since={3}'.format(
root_dir, exclude_dirs, root_dir_alias, accessed_since))
try:
assert os.path.isdir(root_dir)
if root_dir_alias is None:
root_dir_alias = root_dir
exclude_dirs = [os.path.join(root_dir, d) for d in exclude_dirs]
exclude_regex = r'|'.join([fnmatch.translate(d) for d in exclude_dirs]) or r'$.'
# walk the directory hierarchy starting at 'root_dir' in BFS order
feature = self._crawl_file(root_dir, root_dir, root_dir_alias)
if feature and (feature.ctime > accessed_since or feature.atime > accessed_since):
yield feature.path, feature
for root_dirpath, dirs, files in os.walk(root_dir):
dirs[:] = [os.path.join(root_dirpath, d) for d in dirs]
dirs[:] = [d for d in dirs if not re.match(exclude_regex, d)]
files = [os.path.join(root_dirpath, f) for f in files]
files = [f for f in files if not re.match(exclude_regex, f)]
for fpath in files:
feature = self._crawl_file(root_dir, fpath, root_dir_alias)
if feature and (feature.ctime > accessed_since or feature.atime > accessed_since):
yield feature.path, feature
for fpath in dirs:
feature = self._crawl_file(root_dir, fpath, root_dir_alias)
if feature and (feature.ctime > accessed_since or feature.atime > accessed_since):
yield feature.path, feature
except Exception, e:
logger.error('Error crawling root_dir %s' % root_dir, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
def _filetype(self, fpath, fperm):
modebit = fperm[0]
ftype = {
'l': 'link',
'-': 'file',
'b': 'block',
'd': 'dir',
'c': 'char',
'p': 'pipe'
}.get(modebit)
return ftype
_filemode_table = (
((stat.S_IFLNK, "l"), (stat.S_IFREG, "-"), (stat.S_IFBLK, "b"), (stat.S_IFDIR, "d"), (stat.S_IFCHR, "c"), (stat.S_IFIFO, "p")),
((stat.S_IRUSR, "r"),),
((stat.S_IWUSR, "w"),),
((stat.S_IXUSR|stat.S_ISUID, "s"), (stat.S_ISUID, "S"), (stat.S_IXUSR, "x")),
((stat.S_IRGRP, "r"),),
((stat.S_IWGRP, "w"),),
((stat.S_IXGRP|stat.S_ISGID, "s"), (stat.S_ISGID, "S"), (stat.S_IXGRP, "x"),),
((stat.S_IROTH, "r"),),
((stat.S_IWOTH, "w"),),
((stat.S_IXOTH|stat.S_ISVTX, "t"), (stat.S_ISVTX, "T"), (stat.S_IXOTH, "x"))
)
def _fileperm(self, mode):
# Convert a file's mode to a string of the form '-rwxrwxrwx'
perm = []
for table in self._filemode_table:
for bit, char in table:
if mode & bit == bit:
perm.append(char)
break
else:
perm.append("-")
return "".join(perm)
def _is_executable(self, fpath):
return os.access(self, fpath, os.X_OK)
# crawl a single file
def _crawl_file(self, root_dir, fpath, root_dir_alias):
# file attributes: ["atime", "ctime", "group", "linksto", "mode", "mtime", "name", "path", "size", "type", "user"]
try:
lstat = os.lstat(fpath)
fmode = lstat.st_mode
fperm = self._fileperm(fmode)
ftype = self._filetype(fpath, fperm)
flinksto = None
if ftype == 'link':
try:
flinksto = os.readlink(fpath) # this has to be an absolute path, not a root-relative path
except:
logger.error('Error reading linksto info for file %s' % fpath, exc_info=True)
fgroup = lstat.st_gid
fuser = lstat.st_uid
frelpath = fpath.replace(root_dir, root_dir_alias, 1) # root_dir relative path
_, fname = os.path.split(frelpath)
return FileFeature(lstat.st_atime, lstat.st_ctime, fgroup, flinksto,
fmode, lstat.st_mtime, fname, frelpath, lstat.st_size, ftype, fuser)
#Doing below temporarily to get rid of atime pollution
# return FileFeature(0, lstat.st_ctime, fgroup, flinksto,
# fmode, lstat.st_mtime, fname, frelpath, lstat.st_size, ftype, fuser)
except Exception, e:
logger.error('Error crawling file %s' % fpath, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# default config file discovery heuristic
@staticmethod
def _is_config_file(fpath):
_, ext = os.path.splitext(fpath)
if os.path.isfile(fpath) and ext in ['.xml', '.ini', '.properties', '.conf', '.cnf', '.cfg', '.cf', '.config', '.allow', '.deny', '.lst'] and os.path.getsize(fpath) <= 204800:
return True
return False
# crawl the given list of configuration files
def crawl_config_files(self, root_dir='/', exclude_dirs=['proc','mnt','dev','tmp'], root_dir_alias=None, known_config_files=[], discover_config_files=False):
# config attributes: ["name", "content", "path"]
accessed_since = self.feature_epoch
logger.debug('Crawling Config files: root_dir={0}, exclude_dirs={1}, root_dir_alias={2}, accessd_since={3}, known_config_files={4}, discover_config_files={5}'.format(
root_dir, exclude_dirs, root_dir_alias, accessed_since, known_config_files, discover_config_files))
try:
assert os.path.isdir(root_dir)
if root_dir_alias is None:
root_dir_alias = root_dir
exclude_dirs = [os.path.join(root_dir, d) for d in exclude_dirs]
exclude_regex = r'|'.join([fnmatch.translate(d) for d in exclude_dirs]) or r'$.'
known_config_files[:] = [os.path.join(root_dir, f) for f in known_config_files]
known_config_files[:] = [f for f in known_config_files if not re.match(exclude_regex, f)]
config_file_set = set()
for fpath in known_config_files:
if os.path.exists(fpath):
lstat = os.lstat(fpath)
if lstat.st_atime > accessed_since or lstat.st_ctime > accessed_since:
config_file_set.add(fpath)
except Exception, e:
logger.error('Error examining %s' % root_dir, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
try:
if discover_config_files:
# walk the directory hierarchy starting at 'root_dir' in BFS order looking for config files
for root_dirpath, dirs, files in os.walk(root_dir):
dirs[:] = [os.path.join(root_dirpath, d) for d in dirs]
dirs[:] = [d for d in dirs if not re.match(exclude_regex, d)]
files = [os.path.join(root_dirpath, f) for f in files]
files = [f for f in files if not re.match(exclude_regex, f)]
for fpath in files:
if os.path.exists(fpath) and self.is_config_file(fpath):
lstat = os.lstat(fpath)
if lstat.st_atime > accessed_since or lstat.st_ctime > accessed_since:
config_file_set.add(fpath)
except Exception, e:
logger.error('Error examining %s' % root_dir, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
try:
for fpath in config_file_set:
try:
_, fname = os.path.split(fpath)
frelpath = fpath.replace(root_dir, root_dir_alias, 1) # root_dir relative path
# copy this config_file into / before reading it, so we don't change its atime attribute
(th, temppath) = tempfile.mkstemp(prefix='config.', dir='/')
os.close(th)
shutil.copyfile(fpath, temppath)
with codecs.open(filename=fpath, mode='r', encoding='utf-8', errors='ignore') as config_file: # encode the contents of config_file as utf-8
yield frelpath, ConfigFeature(fname, config_file.read(), frelpath)
os.remove(temppath)
except IOError, e:
print "Unable to copy file. %s" % e
if not self.ignore_exceptions:
raise CrawlException(e)
except Exception, e:
print fpath, temppath, frelpath
logger.error('Error crawling config file %s' % fpath, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
except Exception, e:
logger.error('Error examining %s' % root_dir, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl disk partition information
def crawl_disk_partitions(self):
# disk attributes: ["device", "freepct", "fstype", "mountpt", "options", "size"]
logger.debug('Crawling Disk partitions')
for partition in psutil.disk_partitions():
try:
pdiskusage = psutil.disk_usage(partition.mountpoint)
yield partition.mountpoint, DiskFeature(partition.device, (100.0 - pdiskusage.percent), partition.fstype,
partition.mountpoint, partition.opts, pdiskusage.total)
except Exception, e:
logger.error("Error crawling disk partition %s" % partition.mountpoint, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl process metadata
def crawl_processes(self):
# process attributes: ["cmd", "created", "cwd", "pname", "openfiles", "pid", "ppid", "threads", "user"]
# Always do a full crawl since epoch:
#created_since = self.feature_epoch
created_since = 0
logger.debug('Crawling Processes: created_since={0}'.format(created_since))
if self.crawl_mode == 'INVM':
list = psutil.process_iter()
elif self.crawl_mode == 'OUTVM':
domain_name, kernel_version, distro, arch = self.vm
from psvmi import process_iter
list = process_iter(domain_name, kernel_version, distro, arch)
for p in list:
create_time = p.create_time() if hasattr(p.create_time, '__call__') \
else p.create_time
if create_time > created_since:
name = p.name() if hasattr(p.name, '__call__') else p.name
cmdline = p.cmdline() if hasattr(p.cmdline, '__call__') else p.cmdline
pid = p.pid() if hasattr(p.pid, '__call__') else p.pid
status = p.status() if hasattr(p.status, '__call__') else p.status
if status == psutil.STATUS_ZOMBIE:
cwd = "unknown" # invalid
else:
try:
cwd = p.cwd() if hasattr(p, "cwd") and hasattr(p.cwd, '__call__') else p.getcwd()
except Exception, e:
logger.error('Error crawling process %s for cwd' % pid, exc_info=True)
cwd = 'unknown'
ppid = p.ppid() if hasattr(p.ppid, '__call__') else p.ppid
num_threads = p.num_threads() if hasattr(p, "num_threads") and hasattr(p.num_threads, '__call__') \
else p.get_num_threads()
try:
username = p.username() if hasattr(p, "username") and hasattr(p.username, '__call__') else p.username
except Exception, e:
logger.error('Error crawling process %s for username' % pid, exc_info=True)
username = 'unknown'
try:
openfiles = []
for f in p.get_open_files():
openfiles.append(f.path)
openfiles.sort()
default_key = '{0}/{1}'.format(name, pid)
yield default_key, ProcessFeature(str(' '.join(cmdline)), create_time, cwd, name,
openfiles, pid, ppid, num_threads, username)
except Exception, e:
logger.error('Error crawling process %s' % pid, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl network connection metadata
def crawl_connections(self):
# connection attributes: ["localipaddr", "localport", "pname", "pid", "remoteipaddr", "remoteport", "status"]
# Always do a full crawl since epoch:
#created_since = self.feature_epoch
created_since = 0
logger.debug('Crawling Connections: created_since={0}'.format(created_since))
if self.crawl_mode == 'INVM':
list = psutil.process_iter()
elif self.crawl_mode == 'OUTVM':
domain_name, kernel_version, distro, arch = self.vm
from psvmi import process_iter
list = process_iter(domain_name, kernel_version, distro, arch)
for p in list:
pid = p.pid() if hasattr(p.pid, '__call__') else p.pid
status = p.status() if hasattr(p.status, '__call__') else p.status
if status == psutil.STATUS_ZOMBIE: continue
create_time = p.create_time() if hasattr(p.create_time, '__call__') \
else p.create_time
name = p.name() if hasattr(p.name, '__call__') else p.name
if create_time <= created_since:
continue
try:
for c in p.get_connections():
try:
localipaddr, localport = c.laddr[:]
except: # older version of psutil uses local_address instead of laddr
localipaddr, localport = c.local_address[:]
try:
if c.raddr:
remoteipaddr, remoteport = c.raddr[:]
else:
remoteipaddr, remoteport = None, None
except: # older version of psutil uses remote_address instead of raddr
if c.remote_address:
remoteipaddr, remoteport = c.remote_address[:]
else:
remoteipaddr, remoteport = None, None
default_key = '{0}/{1}/{2}'.format(pid, localipaddr, localport)
yield default_key, ConnectionFeature(localipaddr, localport, name, pid, remoteipaddr, remoteport, str(c.status))
except Exception, e:
logger.error('Error crawling connection for process %s' % pid, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl performance metric data
def crawl_metrics(self):
# metric attributes: ["cpupct", "mempct", "name", "pid", "read", "rss", "status", "user", "vms", "write"]
# Always do a full crawl since epoch:
#created_since = self.feature_epoch
created_since = 0
logger.debug('Crawling Metrics')
for p in psutil.process_iter():
create_time = p.create_time() if hasattr(p.create_time, '__call__') else p.create_time
if create_time <= created_since:
continue
try:
name = p.name() if hasattr(p.name, '__call__') else p.name
pid = p.pid() if hasattr(p.pid, '__call__') else p.pid
status = p.status() if hasattr(p.status, '__call__') else p.status
if status == psutil.STATUS_ZOMBIE:
continue
username = p.username() if hasattr(p.username, '__call__') else p.username
meminfo = p.get_memory_info() if hasattr(p.get_memory_info, '__call__') else p.memory_info
ioinfo = p.get_io_counters() if hasattr(p.get_io_counters, '__call__') else p.io_counters
cpu_percent = p.get_cpu_percent(interval=0) if hasattr(p.get_cpu_percent, '__call__') else p.cpu_percent
memory_percent = p.get_memory_percent() if hasattr(p.get_memory_percent, '__call__') else p.memory_percent
default_key = '{0}/{1}'.format(name, pid)
yield default_key, \
MetricFeature(round(cpu_percent, 2),
round(memory_percent, 2),
name, pid, ioinfo.read_bytes,
meminfo.rss, str(status),
username, meminfo.vms, ioinfo.write_bytes)
except Exception, e:
logger.error('Error crawling metric for process %s' % pid, exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl Linux package database
def crawl_packages(self, dbpath=None, root_dir='/'):
# package attributes: ["installed", "name", "size", "version"]
(installtime, name, version, size) = (None, None, None, None)
if self.crawl_mode == 'INVM':
logger.debug('Using in-VM state information (crawl mode: ' + self.crawl_mode + ')')
system_type = platform.system().lower()
distro = platform.linux_distribution()[0].lower()
elif self.crawl_mode == 'MOUNTPOINT':
logger.debug('Using disk image information (crawl mode: ' + self.crawl_mode + ')')
system_type = platform_outofband.system(prefix=root_dir).lower()
distro = platform_outofband.linux_distribution(prefix=root_dir)[0].lower()
else:
logger.error('Unsupported crawl mode: ' + self.crawl_mode + '. Skipping package crawl.')
system_type = 'unknown'
distro = 'unknown'
installed_since = self.feature_epoch
if system_type != 'linux':
raise StopIteration() # package feature is only valid for Linux platforms
logger.debug('Crawling Packages')
pkg_manager = 'unknown'
if distro in ['ubuntu', 'debian']:
pkg_manager = 'dpkg'
elif distro.startswith('red hat') or distro in ['redhat', 'fedora', 'centos']:
pkg_manager = 'rpm'
elif os.path.exists(os.path.join(root_dir, 'var/lib/dpkg')):
pkg_manager = 'dpkg'
elif os.path.exists(os.path.join(root_dir, 'var/lib/rpm')):
pkg_manager ='rpm'
try:
if pkg_manager == 'dpkg':
if not dbpath:
dbpath = 'var/lib/dpkg'
if os.path.isabs(dbpath):
logger.warning("dbpath: " + dbpath + " is defined absolute. Crawler will ignore prefix: " + root_dir + ".")
dbpath = os.path.join(root_dir, dbpath) #update for a different route
if installed_since > 0:
logger.warning('dpkg does not provide install-time, defaulting to all packages installed since epoch')
try:
dpkg = subprocess.Popen(["dpkg-query", "-W",
"--admindir={0}".format(dbpath),
"-f=${Package}|${Version}|${Installed-Size}\n"],
stdout=subprocess.PIPE)
dpkglist = dpkg.stdout.read().strip('\n')
except OSError, e:
logger.error('Failed to launch dpkg query for packages. Check if dpkg-query is installed: '
+ ('[Errno: %d] ' % e.errno) + e.strerror + ' [Exception: ' + type(e).__name__ + ']')
dpkglist = None
if dpkglist:
for dpkginfo in dpkglist.split('\n'):
(name, version, size) = dpkginfo.split('|')
# NOTE: dpkg does not provide any installtime field
#default_key = '{0}/{1}'.format(name, version) --> changed to below per Suriya's request
default_key = '{0}'.format(name, version)
yield default_key, PackageFeature(None, name, size, version)
elif pkg_manager == 'rpm':
if not dbpath:
dbpath = 'var/lib/rpm'
if os.path.isabs(dbpath):
logger.warning("dbpath: " + dbpath + " is defined absolute. Crawler will ignore prefix: " + root_dir + ".")
dbpath = os.path.join(root_dir, dbpath) #update for a different route
try:
rpm = subprocess.Popen(["rpm", "--dbpath", dbpath,
"-qa", "--queryformat",
"%{installtime}|%{name}|%{version}|%{size}\n"],
stdout=subprocess.PIPE)
rpmlist = rpm.stdout.read().strip('\n')
except OSError, e:
logger.error('Failed to launch rpm query for packages. Check if rpm is installed: '
+ ('[Errno: %d] ' % e.errno) + e.strerror + ' [Exception: ' + type(e).__name__ + ']')
rpmlist = None
if rpmlist:
for rpminfo in rpmlist.split('\n'):
(installtime, name, version, size) = rpminfo.split('|')
# if int(installtime) <= installed_since:
# --> this barfs for sth like: 1376416422. Consider try: xxx except ValueError: pass
if installtime <= installed_since:
continue
#default_key = '{0}/{1}'.format(name, version) --> changed to below per Suriya's request
default_key = '{0}'.format(name, version)
yield default_key, PackageFeature(installtime, name, size, version)
else:
raise CrawlException(Exception("Unsupported package manager for Linux distro %s" % distro))
except Exception, e:
logger.error('Error crawling package %s' % (name if name else "Unknown"), exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# Find the mount point of the specified cgroup
def get_cgroup_dir(self, dev=""):
paths = [os.path.join("/cgroup/", dev),
os.path.join("/sys/fs/cgroup/", dev)]
for p in paths:
if os.path.ismount(p):
return p
# Try getting the mount point from /proc/mounts
try:
proc = subprocess.Popen(
"grep \"cgroup/" + dev + " \" /proc/mounts | awk '{print $2}'",
shell=True, stdout=subprocess.PIPE)
return proc.stdout.read().strip()
except Exception, e:
logger.exception(e)
raise
# crawl virtual memory information
def crawl_memory(self, mountpoint=None):
# memory attributes: ["used", "buffered", "cached", "free"]
logger.debug('Crawling memory')
feature_key = "memory"
if self.crawl_mode == 'INVM':
try: used = psutil.virtual_memory().used
except Exception, e: used = 'unknown'
try: buffered = psutil.virtual_memory().buffers
except Exception, e: buffered = 'unknown'
try: cached = psutil.virtual_memory().cached
except Exception, e: cached = 'unknown'
try: free = psutil.virtual_memory().free
except Exception, e: free = 'unknown'
feature_attributes = MemoryFeature(used, buffered, cached, free)
elif self.crawl_mode == 'OUTVM':
domain_name, kernel_version, distro, arch = self.vm
from psvmi import system_info
sys = system_info(domain_name, kernel_version, distro, arch)
feature_attributes = MemoryFeature(sys.memory_used,
sys.memory_buffered, sys.memory_cached, sys.memory_free)
elif self.crawl_mode == 'OUTCONTAINER':
container_long_id = self.container_long_id
used = buffered = cached = free = 'unknown'
try:
d = os.path.join(self.get_cgroup_dir("memory"), "docker",
container_long_id, "memory.stat")
with open(d, "r") as f:
for line in f:
key, value = line.strip().split(' ')
if key == 'total_cache': cached = int(value)
if key == 'total_active_file': buffered = int(value)
d = os.path.join(self.get_cgroup_dir("memory"), "docker",
container_long_id, "memory.limit_in_bytes")
with open(d, "r") as f:
limit = int(f.readline().strip())
d = os.path.join(self.get_cgroup_dir("memory"), "docker",
container_long_id, "memory.usage_in_bytes")
with open(d, "r") as f:
used = int(f.readline().strip())
host_free = psutil.virtual_memory().free
container_total = used + min(host_free, limit - used)
free = container_total - used
feature_attributes = MemoryFeature(used, buffered, cached, free)
except Exception, e:
logger.error('Error crawling memory', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
return
else:
logger.error('Unsupported crawl mode: ' + self.crawl_mode +
'. Returning unknown memory key and attributes.')
feature_attributes = MemoryFeature('unknown', 'unknown',
'unknown', 'unknown')
try:
yield feature_key, feature_attributes
except Exception, e:
logger.error('Error crawling memory', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
"""
Static cache of cpu_times. This is needed because for container cgroups
we only get the total accumulated cpu time spent in a container. Then,
to get a percentage utilization we need to have two cpu measurements.
Instead of sleeping between the two measurements we use the previous
crawled values. We use these variables to store those previous values.
XXX Issue #272 need to be careful about this when we parallelize the crawls
"""
container_cpu_times = dict()
container_last_crawl_time = dict()
@staticmethod
def save_container_cpu_times(container_long_id, times):
Crawler.container_cpu_times[container_long_id] = times
now = time.time()
Crawler.container_last_crawl_time[container_long_id] = now
@staticmethod
def get_prev_container_cpu_times(container_long_id):
if Crawler.container_cpu_times.has_key(container_long_id):
return [Crawler.container_cpu_times[container_long_id],
Crawler.container_last_crawl_time[container_long_id]]
else:
return [None, None]
# crawl per CPU information
def crawl_cpu(self, mountpoint=None, per_cpu=False):
# cpu attributes: ["idle", "nice", "user", "wait", "system", "interrupt", "steal"]
logger.debug('Crawling cpu information')
if self.crawl_mode not in ['INVM', 'OUTCONTAINER', 'OUTVM']:
logger.error('Unsupported crawl mode: ' + self.crawl_mode +
'. Returning unknown memory key and attributes.')
feature_attributes = CpuFeature('unknown', 'unknown', 'unknown', 'unknown',
'unknown', 'unknown', 'unknown')
host_cpu_feature = {}
if self.crawl_mode in ['INVM', 'OUTCONTAINER']:
for index, cpu in enumerate(psutil.cpu_times_percent(percpu=True)):
try: idle = cpu.idle
except Exception, e: idle = 'unknown'
try: nice = cpu.nice
except Exception, e: nice = 'unknown'
try: user = cpu.user
except Exception, e: user = 'unknown'
try: wait = cpu.iowait
except Exception, e: wait = 'unknown'
try: system = cpu.system
except Exception, e: system = 'unknown'
try: interrupt = cpu.irq
except Exception, e: interrupt = 'unknown'
try: steal = cpu.steal
except Exception, e: steal = 'unknown'
default_key = '{0}-{1}'.format("cpu", index)
feature_attributes = CpuFeature(idle, nice, user, wait,
system, interrupt, steal)
host_cpu_feature[index] = feature_attributes
if self.crawl_mode == 'INVM':
try:
yield default_key, feature_attributes
except Exception, e:
logger.error('Error crawling cpu information', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
elif self.crawl_mode == 'OUTVM':
# XXX dummy data
default_key = 'cpu-0'
feature_attributes = CpuFeature(10, 10, 10, 10, 10, 10, 10)
try:
yield default_key, feature_attributes
except Exception, e:
logger.error('Error crawling cpu information', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
if self.crawl_mode == 'OUTCONTAINER':
if per_cpu:
filename = "cpuacct.usage_percpu"
else:
filename = "cpuacct.usage"
container_long_id = self.container_long_id
"""
1. We first try to get the previous CPU times but if this fails
because thisis the first crawl we sleep for 100ms.
"""
cpu_usage = {}
try:
cpu_usage_t1, prev_time = self.get_prev_container_cpu_times(
container_long_id)
if cpu_usage_t1:
logger.info("Using previous cpu times for container %s"
% (container_long_id))
interval = time.time() - prev_time
if not cpu_usage_t1 or interval == 0:
logger.info("There are no previous cpu times for container %s"
" so we will be sleeping for 100 milliseconds"
% (container_long_id))
d = os.path.join(self.get_cgroup_dir("cpuacct"), "docker",
container_long_id, filename)
with open(d, "r") as f:
cpu_usage_t1= f.readline().strip().split(' ')
interval = 0.1 # sleep for 100ms
time.sleep(interval)
d = os.path.join(self.get_cgroup_dir("cpuacct"), "docker",
container_long_id, filename)
with open(d, "r") as f:
cpu_usage_t2= f.readline().strip().split(' ')
# Store the cpu times for the next crawl
self.save_container_cpu_times(container_long_id, cpu_usage_t2)
except Exception, e:
logger.error('Error crawling cpu information', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
return
"""
2. get container system and user usage to split the per CPU usage
time accordingly. This is just an approximation!
"""
cpu_user_system = {}
try:
d = os.path.join(self.get_cgroup_dir("cpuacct"), "docker",
container_long_id, "cpuacct.stat")
with open(d, "r") as f:
for line in f:
m = re.search(r"(system|user)\s+(\d+)", line)
if m:
cpu_user_system[m.group(1)] = float(m.group(2))
except Exception, e:
logger.error('Error crawling cpu information', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
return
"""
3. Approximations:
1. user and system per cpu percentages are approximated using the
container cpu usage and the container user versus sustem time for
all the cpus of the container.
2. nice, wait, interrupt, and steal are just host values.
"""
for index, cpu_usage_ns in enumerate(cpu_usage_t1):
usage_secs = ((float(cpu_usage_t2[index]) - float(cpu_usage_ns))
/ float(1e9))
# Interval is never 0 because of step 0 (forcing a sleep)
usage_percent = (usage_secs / interval) * 100.0
if usage_percent > 100.0: usage_percent = 100.0
idle = 100.0 - usage_percent
# Approximation 1
user_plus_sys_hz = (cpu_user_system['user'] +
cpu_user_system['system'])
if (user_plus_sys_hz == 0):
user_plus_sys_hz = 0.1 # Fake value to avoid divide by zero
user = usage_percent * (cpu_user_system['user'] / user_plus_sys_hz)
system = usage_percent * (cpu_user_system['system'] / user_plus_sys_hz)
# Approximation 2
nice = host_cpu_feature[index][1]
wait = host_cpu_feature[index][3]
interrupt = host_cpu_feature[index][5]
steal = host_cpu_feature[index][6]
default_key = '{0}-{1}'.format("cpu", index)
feature_attributes = CpuFeature(idle, nice, user, wait,
system, interrupt, steal)
try:
yield default_key, feature_attributes
except Exception, e:
logger.error('Error crawling cpu information', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
temp_changes_to_cache = {}
def store_temp_change(self, key, value):
self.temp_changes_to_cache[key] = value
def get_temp_changes(self):
return self.temp_changes_to_cache
cached_values = {}
@staticmethod
def cache_apply_changes(changes):
if not changes:
return
for key,value in changes.iteritems():
Crawler.cached_values[key] = value
@staticmethod
def cache_get_value(key):
if Crawler.cached_values.has_key(key):
return Crawler.cached_values[key]
else:
return None
# crawl per network interface information
def crawl_interface(self, mountpoint=None):
# interface attributes: ["if_octets.tx", "if_octets.rx", "if_packets.tx", "if_packets.rx", "if_errors.tx", "if_errors.rx"]
logger.debug('Crawling interface information')
for ifname in psutil.net_io_counters(pernic=True):
try:
interface = psutil.net_io_counters(pernic=True)[ifname]
except:
continue
try: bytes_sent = interface.bytes_sent
except Exception, e: bytes_sent = 'unknown'
try: bytes_recv = interface.bytes_recv
except Exception, e: bytes_recv = 'unknown'
try: packets_sent = interface.packets_sent
except Exception, e: packets_sent = 'unknown'
try: packets_recv = interface.packets_recv
except Exception, e: packets_recv = 'unknown'
try: errout = interface.errout
except Exception, e: errout = 'unknown'
try: errin = interface.errin
except Exception, e: errin = 'unknown'
default_key = '{0}-{1}'.format("interface", ifname)
store_key = '{0}-{1}'.format(self.namespace, default_key)
prev_time_key = '{0}-{1}-last_crawl'.format(
self.namespace, default_key)
prev_count = self.cache_get_value(store_key)
prev_time = self.cache_get_value(prev_time_key)
curr_count = [bytes_sent, bytes_recv, packets_sent,
packets_recv, errout, errin]
self.store_temp_change(store_key, curr_count)
self.store_temp_change(prev_time_key, time.time())
if prev_count and prev_time:
d = time.time() - prev_time
diff = [(a - b) / d for a, b in zip(curr_count, prev_count)]
else:
# first measurement
diff = [0,0,0,0,0,0]
feature_attributes = InterfaceFeature._make(diff)
try:
yield default_key, feature_attributes
except Exception, e:
logger.error('Error crawling interface information', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
# crawl virtual system load (this is based on the libc getloadavg API)
def crawl_load(self, mountpoint=None):
# memory attributes: ["shortterm", "midterm", "longterm"]
logger.debug('Crawling system load')
feature_key = "load"
try: shortterm = os.getloadavg()[0]
except Exception, e: shortterm = 'unknown'
try: midterm = os.getloadavg()[1]
except Exception, e: midterm = 'unknown'
try: longterm = os.getloadavg()[2]
except Exception, e: longterm = 'unknown'
feature_attributes = LoadFeature(shortterm, midterm, longterm)
try:
yield feature_key, feature_attributes
except Exception, e:
logger.error('Error crawling memory', exc_info=True)
if not self.ignore_exceptions:
raise CrawlException(e)
def crawl_dockerps(self, mountpoint=None):
logger.debug('Crawling docker ps results')
# Let's try Docker API first
try:
from docker import Client
client = Client(base_url='unix://var/run/docker.sock')