-
Notifications
You must be signed in to change notification settings - Fork 1
/
watchdog.py
executable file
·2011 lines (1792 loc) · 68.2 KB
/
watchdog.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
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may abtain 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.
"""WatchDog.
This program monitors resources of Linux systems.
Classes:
Monitor - The Monitor is responsible for managing the overall process of
keeping an updated status of each host.
MonitorThread - a very small threaded class that gets hosts from a queue and
will create a RemoteWorker object for each thread.
RemoteWorker - responsible for SSHing to remote hosts to gather resources.
Resource - maintains all of the resources that are monitored, and methods to
parse their data for consumption by RRDTool.
RRD - maintains all interfaces to RRDTool, including graph definitions, and
methods to create, update, and graph resources.
TestBed - a global class used to hold configuration data and data collected
from each remote host. Additionally, formatted data for RRD will be kept
associated with each host, and some general information about the update
process of each remote host.
TBQueue - a subclass of Queue.Queue(), in order to override method join(),
since we need a timeout in case one of the paramiko ssh sessions hangs.
Dependencies:
WatchDog depends on a few external programs beign installed. Mainly:
- python - written in python, so we're dead without it.
- lshw - uses to get an inventory and determine network devices.
- RRDTool - used to created graphs/charts of monitored resources.
- dmidecode - used to get bios and system info.
You also need to have all of the client machines setup for ssh without a
password (as root). To set that up, simply generate a public keypair:
- ssh-keygen -t rsa
- copy public key to target host and append to .ssh/authorized_keys
- see http://linuxproblem.org/art_9.html for more details.
Usage:
The following options are supported:
--conffile: the name of the configuration file. Default: watchdog.yaml.
--debug: set the debug level. Requires one of the following parameters:
debug
info (default)
warning
error
critical
--graph: boolean, if True, it will create new graphs for resources.
--html: boolean, if set to True it will build html pages.
--log_to_stdout: send program output to stdout as well as logs.
--logfile: set the file name of the log file. Default: watchdog.log
--testbed: the name of the testbed to use. Default: default.
--update: boolean, if True, it will collect new data from all monitored
hosts, and update the RRD databases with the newly collected data.
Arguments should be space separated.
"""
__author__ = '[email protected] (Kelly Lucas)'
__version__ = '2.04'
import logging, logging.handlers, optparse, os, paramiko, Queue, shutil
import subprocess, sys, threading, yaml
from IPy import IP
from time import *
TIMEOUT = 5 # Timeout for accessing remote hosts.
RUNTIME = 240 # Total time to allow the host queue to finish all tasks.
def SetLogger(namespace, logfile, loglevel, log_to_stdout=False):
"""Create a log handler and set log level.
Args:
namespace: name of the logger.
logfile: log file name.
loglevel: debug level of logger.
log_to_stdout: boolean, True = send msgs to stdout and logfile,
False = send msgs to log file only.
Returns:
Logger object.
We use RotatingFileHandler to handle rotating the log files when they reach
maxsize in bytes.
"""
MAXSIZE = 8192000 # Max size to grow log files, in bytes.
levels = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
logger = logging.getLogger(namespace)
c = logging.StreamHandler()
h = logging.handlers.RotatingFileHandler(logfile, maxBytes=MAXSIZE,
backupCount=10)
hf = logging.Formatter('%(asctime)s %(process)d %(levelname)s: %(message)s')
cf = logging.Formatter('%(levelname)s: %(message)s')
logger.addHandler(h)
h.setFormatter(hf)
if log_to_stdout:
logger.addHandler(c)
c.setFormatter(cf)
logger.setLevel(levels.get(loglevel, logging.INFO))
return logger
class MonitorThread(threading.Thread):
"""Get AutoTest hosts from queue and create remote host monitors."""
def __init__(self):
threading.Thread.__init__(self)
self.tb = TB # In case the thread outlives the main program.
def run(self):
host = self.tb.q.get()
worker = RemoteWorker(host.hostname)
try:
worker.run()
except Exception, e:
self.tb.logger.error('Error on remote host: %s\n%s', self.h, e)
# Notify Queue that process is finished.
self.tb.logger.debug('Releasing host %s from queue', host.hostname)
self.tb.q.task_done()
class RemoteWorker(object):
"""SSH into remote hosts to obtain resource data."""
def __init__(self, hostname):
"""
Args:
hostname: string, hostname of AutoTest host.
"""
self.h = hostname
self.cmds = {'bios': ['dmidecode -t 0',
['Vendor', 'Version', 'Release Date']],
'model': ['dmidecode -t 1',
['Manufacturer', 'Product Name']],
}
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.tb = TB # In case the thread outlives the main program.
# Send paramiko messages to our log file.
self.logger = SetLogger('SSH', self.tb.sshlog, self.tb.loglevel)
paramiko.util.log_to_file(self.tb.sshlog, level=30)
def run(self):
try:
self.client.connect(self.h, username='root', key_filename=self.tb.privkey,
timeout=TIMEOUT)
self.logger.info('Connected to host %s', self.h)
self.tb.hosts[self.h]['status'] = True
except Exception, e:
self.logger.error('Host %s: %s', self.h, e)
self.tb.hosts[self.h]['status'] = False
finally:
if self.tb.hosts[self.h]['status']:
try:
self.GetInventory()
self.ReadRelease() # Must be done before UpdateRelease().
for k in self.cmds:
self.RunCommand(k, self.cmds[k][0], self.cmds[k][1])
except Exception, e:
self.logger.error('Error on : %s\n%s', self.h, e)
self.UpdateRelease() # Must be done before ReadResources().
if self.tb.hosts[self.h]['status']:
try:
self.ReadResources()
except Exception, e:
self.tb.logger.error('Error on: %s\n%s', self.h, e)
self.tb.logger.debug('Closing client for %s', self.h)
self.client.close()
self.tb.hosts[self.h]['time'] = strftime('%d%b%Y %H:%M:%S', localtime())
def ReadRelease(self):
"""Get the Linux Release version."""
# The PTR key will mark the current version, version history is preserved.
release = []
cmd = 'cat /etc/issue'
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
for line in stdout:
if len(line) > 2:
release.append(line[:-7].strip())
except Exception, e:
self.tb.logger.error('Error getting release version on %s\n%s', self.h, e)
release.append('-->')
cmd = 'uname -r'
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
for line in stdout:
release.append(line.strip())
except Exception, e:
self.tb.logger.error('Error getting kernel version on %s\n%s', self.h, e)
if release:
self.tb.hosts[self.h]['release']['PTR'] = "".join(release)
def RunCommand(self, item, cmd, targets):
"""Get the Firmware versions."""
# The PTR key will mark the current versions.
val = []
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
for line in stdout:
if any (t in line for t in targets):
fields = line.split(':')
# We must sanitize the string for RRDTool.
val.append(fields[1].strip('\n" '))
self.tb.hosts[self.h][item]['PTR'] = " ".join(val)
except Exception, e:
self.tb.logger.error('Error running remote cmd on %s\n%s', self.h, e)
def GetFS(self):
"""Find filesystems and add device and mount point to Resource.fs
Returns: dictionary of filesystem devices and mount points.
"""
fs = {}
cmd = 'df -P -x tmpfs -x debugfs -x devtmpfs -l'
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
for line in stdout:
if line.startswith('/dev'):
fields = line.split()
if len(fields) > 5:
fs[fields[0]] = fields[5]
except Exception, e:
self.tb.logger.error('Error getting file systems on %s\n%s', self.h, e)
# If we are using LVM, we need to replace the device mapper with the dm
# device used in /proc/diskstats.
for k in fs:
if '/dev/mapper' in k:
cmd = 'ls -l %s' % k
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
for line in stdout:
fields = line.split()
device_minor = fields[5]
device = 'dm-%s' % device_minor
fs[device] = fs[k]
del fs[k]
except Exception, e:
self.tb.logger.error('Error getting device mapper minor number.')
self.tb.logger.error(e)
return fs
def GetNetDevs(self):
"""Get all of the network devices.
Returns: list of network devices.
"""
net_devs = []
cmd = 'lshw -C network -short'
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
for line in stdout:
if line.startswith('/'):
fields = line.split()
net_devs.append(fields[1])
except Exception, e:
self.tb.logger.error('Error getting network devices\n%s', e)
return net_devs
def GetInventory(self):
"""Get the basic hardware details of the system."""
cmd = 'lshw -html'
try:
stdin, stdout, stderr = self.client.exec_command(cmd)
except Exception, e:
self.tb.logger.error('Error taking inventory on host %s\n%s', self.h, e)
self.tb.hosts[self.h]['hwinfo'] = stdout
def UpdateRelease(self):
"""Update Release info with most current release versions.
The PTR key points to the most recent released version. This will also
preserve the last known release version in case the host is down.
"""
rrd_dir = os.path.join(self.tb.home, 'hosts', self.h, 'rrd')
hwinfo_file = os.path.join(rrd_dir, 'hwinfo.html')
# Write the hardware info file
try:
hwf = open(hwinfo_file, 'w')
except IOError, e:
self.tb.logger.error('Error creating hwinfo file.\n%s', e)
for line in self.tb.hosts[self.h]['hwinfo']:
hwf.write(line)
hwf.close()
for v in self.tb.version:
update_file = False
relfile = os.path.join(rrd_dir, v)
tmpfile = os.path.join(rrd_dir, v + '.tmp')
if os.path.isfile(relfile):
try:
rf = open(relfile, 'r')
lines = rf.readlines()
except IOError, e:
self.tb.logger.error('Error parsing release file %s\n%s', relfile, e)
finally:
rf.close()
for line in lines:
fields = line.split('=')
# The correct format will have two strings separated by =.
if len(fields) == 2:
if fields[0] == 'PTR':
if self.tb.hosts[self.h][v]['PTR']:
if self.tb.hosts[self.h][v]['PTR'] != fields[1]:
# Most recent version has changed.
self.tb.logger.info('Release has been updated.')
self.tb.logger.info('New release: %s',
self.tb.hosts[self.h][v]['PTR'])
update_file = True
lines.pop(lines.index(line))
self.tb.hosts[self.h][v][self.tb.time] = (
self.tb.hosts[self.h][v]['PTR'])
else:
# Host is down so use last known value.
self.tb.hosts[self.h][v]['PTR'] = fields[1].srip()
else:
self.tb.hosts[self.h][v][fields[0]] = fields[1].strip()
elif len(line) > 3:
# This means the release file has the wrong format, so
# we'll just write a new one with current values.
update_file = True
lines.pop(lines.index(line))
else:
# If we get here than it's probably a blank line.
update_file = True
lines.pop(lines.index(line))
if update_file:
self.tb.logger.debug('Updating %s', relfile)
shutil.move(relfile, tmpfile)
# Put the most recent update in the new file, and make the
# PTR key to point to it.
lines.append('%s=%s\n' % (self.tb.time,
self.tb.hosts[self.h][v]['PTR']))
lines.append('PTR=%s' % self.tb.hosts[self.h][v]['PTR'])
try:
rf = open(relfile, 'w')
for line in lines:
rf.write(line)
except IOError, e:
self.tb.logger.error('Error writing %s\n%s', relfile, e)
finally:
rf.close()
else:
# Create a new release file, as it does not exist.
if self.tb.hosts[self.h][v]['PTR']:
self.tb.logger.info('Creating new %s', relfile)
try:
rf = open(relfile, 'w')
rf.write('%s=%s\n' % (
self.tb.time,self.tb.hosts[self.h][v]['PTR']))
rf.write('PTR=%s' % self.tb.hosts[self.h][v]['PTR'])
except IOError, e:
self.tb.logger.error('Error writing %s\n%s', relfile, e)
finally:
rf.close()
self.tb.hosts[self.h][v][self.tb.time] = (
self.tb.hosts[self.h][v]['PTR'])
def ReadResources(self):
"""Get resources that we are monitoring on the host."""
filesystems = self.GetFS()
net_devices = self.GetNetDevs()
advisor = Resource(filesystems, net_devices)
if self.tb.update == True:
self.tb.logger.debug('Collecting data on %s', self.h)
cmd = advisor.GetCommands()
for r in advisor.resources:
output = []
try:
stdin, stdout, stderr = self.client.exec_command(cmd[r])
for line in stdout:
output.append(line)
except Exception, e:
self.tb.logger.error('Cannot read %s from %s', r, self.h)
self.tb.hosts[self.h]['data'][r] = "".join(output)
self.tb.logger.debug('Formatting data for %s', self.h)
advisor.FormatData(self.h)
advisor.ProcessRRD(self.h)
if self.tb.html:
self.tb.logger.debug('Building HTML files for %s', self.h)
advisor.BuildHTML(self.h)
class TestBed(object):
"""Used to hold all of the testbed machine data and some global varibles.
This class will be instantiated as a global object so that all of the other
classes in this module will have read/write access to it's variables. It
will also hold some general configuration data as well as all remote hosts
raw and formatted data that was collected.
"""
def __init__(self, conffile, logfile, log_to_stdout, debug, graph, html,
testbed, update):
"""
Args:
conffile: string, name of configuration file.
logfile: string, name of logfile.
log_to_stdout: boolean, True = send log msgs to stdout.
debug: string, the debug log level.
graph: boolean, flag to create graphs.
html: boolean, flag to build html files.
testbed: string, designates which testbed to use.
update: boolean, flag to get update data from remote hosts.
"""
self.version = ['bios', 'model', 'release']
start_time = strftime('%H:%M:%S', localtime())
self.time = int(time())
# Add the watchdog directory to the configuration file, in case this is
# being called from another directory.
self.exec_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
conf_pathname = os.path.join(self.exec_dir, conffile)
# Load configuration data from configuration file.
ydict = self.ReadYamlFile(conf_pathname)
# Get local site data from config file.
confdict = self.ReadConfig(ydict)
self.caption = confdict['caption']
self.home = confdict['homedir']
self.privkey = confdict['privkey']
rundir = confdict['rundir']
self.url = confdict['urlhome']
if not os.path.isdir(rundir):
os.mkdir(rundir)
self.update_runfile = os.path.join(rundir, 'update.running')
self.graph_runfile = os.path.join(rundir, 'graph.running')
self.logfile = os.path.join(self.home, logfile)
self.sshlog = os.path.join(self.home, 'ssh.log')
self.logger = SetLogger('SystemMonitor', self.logfile, debug,
log_to_stdout=log_to_stdout)
self.logger.info('=================================================')
self.logger.info('======== RUN START =========')
self.logger.info('=================================================')
self.logger.info('Script started at: %s', start_time)
self.loglevel = debug
self.graph = graph
self.html = html
self.rrdtimes = ['-1hours', '-4hours', '-24hours', '-1week', '-1month',
'-1year']
self.testbed = testbed
self.update = update
# tbhosts are Host objects from your testbed.. hosts hold the resource data.
self.hosts = {} # Dictionary to hold data from each host.
self.tbhosts = self.LoadHosts(ydict, testbed)
# Create a queue for checking resources on remote hosts.
self.q = TBQueue()
def ReadConfig(self, ydict):
"""Read configuration variables from config file.
Args:
ydict: dictionary of parsed yaml configuration file.
Returns:
dictionary of site values.
"""
sitedict = {}
for k in ydict['site']:
sitedict.update(k)
return sitedict
def LoadHosts(self, ydict, testbed):
"""Load hosts from configuration file.
Args:
ydict: dictionary of parsed yaml configuration file.
testbed: string, defines which testbed to use.
Returns:
list of Host objects.
"""
hostlist = []
if testbed in ydict['testbeds']:
for s in ydict['testbeds'][testbed]:
for k in s:
hostlist.append(Host(k, s[k]))
# Initialize host dictionary to hold data from testbed hosts.
self.hosts[k] = {}
self.hosts[k]['data'] = {} # Raw data from hosts.
self.hosts[k]['rrddata'] = {} # Formatted data.
self.hosts[k]['hwinfo'] = None
self.hosts[k]['status'] = None
self.hosts[k]['time'] = None
for v in self.version:
self.hosts[k][v] = {}
self.hosts[k][v]['PTR'] = None
else:
self.logger.error('Could not find %s testbed in config file', testbed)
return hostlist
def ReadYamlFile(self, yamlfile):
"""Read a yaml file and return a dictionary tree of the data."""
try:
f = open(yamlfile, 'r')
try:
try:
ydict = yaml.load(f)
except IOError, e:
self.logger.error('Error parsing %s\n%s', yamlfile, e)
finally:
f.close()
except IOError, e:
self.logger.error('Cannot open %s', yamlfile)
return ydict
class Monitor(object):
"""Main class used to manage the monitoring of remote hosts.
This class is used to determine the current status of hosts in the testbed.
It will populate a queue from TestBed.tbhosts, and each host will be added
to a Queue and start a threaded operation using the MonitorThread class, to
access each host in the testbed and get resource data.
"""
def __init__(self):
"""Monitor will use config data from TestBed."""
self.threads = []
def UpdateStatus(self):
"""Update data from all monitored hosts."""
# Create new threads of class MonitorThread.
self.hostqty = len(TB.tbhosts)
for i in range(self.hostqty):
t = MonitorThread()
t.setDaemon(True)
self.threads.append(t)
t.start()
# Fill the requests queue with AutoTest host objects.
for host in TB.tbhosts:
TB.logger.debug('Placing %s in host queue.', host.hostname)
TB.q.put(host)
if TB.graph:
# Graphing takes much longer, so increase the max runtime.
maxtime = RUNTIME * 6
else:
maxtime = RUNTIME
# Queue.join() will wait for all jobs in the queue to finish, or
# until the timeout value is reached.
TB.logger.debug('Joining run queue.')
TB.q.join(timeout=maxtime)
TB.logger.info('%s hosts left in host queue', TB.q.qsize())
TB.logger.info('Runtime is %d seconds', (time() - TB.time))
LogLevel = TB.logger.getEffectiveLevel()
if LogLevel == 10:
for host in TB.tbhosts:
TB.logger.debug('%s status is %s', host.hostname,
TB.hosts[host.hostname]['status'])
# If there are any running threads, give them time to finish.
# Since paramiko is multi threaded, this check is needed. A deadline
# will be set since we don't want the process to run indefinitely.
# A deadline needs to be set because one or more of the paramiko
# threads could hang.
deadline = time() + maxtime
running = True
while running:
for t in self.threads:
if t.isAlive():
continue
else:
self.threads.remove(t)
if len(self.threads) == 0:
TB.logger.info('All threads have completed their jobs.')
TB.logger.info('Runtime is %d seconds', (time() - TB.time))
running = False
else:
TB.logger.debug('%d threads still running.', len(self.threads))
sleep(TIMEOUT)
waittime = deadline - time()
if waittime < 0:
TB.logger.info('Deadline reached. Aborting running threads.')
TB.logger.info('%d threads still running!', len(self.threads))
running = False
def CheckStatus(self, hostname):
"""Check the status of one host.
Args:
hostname: hostname or ip address of host to check.
This method is primarily used for debugging purposes.
"""
t = MonitorThread()
t.setDaemon(True)
t.start()
for host in TB.tbhosts:
if host.hostname == hostname:
TB.q.put(host)
break
TB.q.join(timeout=TIMEOUT)
TB.logger.info('%s status is %s', hostname, TB.hosts[hostname]['status'])
def ShowData(self):
"""Show raw data collected from each host."""
for host in TB.tbhosts:
TB.logger.info('Hostname: %s', host.hostname)
for k in TB.hosts[host.hostname]['data']:
TB.logger.info('%s: %s' , k, TB.hosts[host.hostname]['data'][k])
def ValidIP(self, address):
"""Verify address is a valid IP address.
Args:
address: string.
Returns:
boolean: True = valid IP address, False = not valid IP address.
"""
octets = address.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not 0 <= int(octet) <= 255:
return False
return True
def SortAFEHosts(self, afelist):
"""Sort AFE host list by IP address.
Args:
afelist: list of AFE host objects.
Returns:
newlist: list of sorted AFE host objects.
"""
iplist = []
hostlist = []
for h in afelist:
if self.ValidIP(h.hostname):
iplist.append(h)
else:
hostlist.append(h)
templist = [(IP(h.hostname).int(), h) for h in iplist]
templist.sort()
newlist = [h[1] for h in templist]
hostlist.sort()
newlist.extend(hostlist)
return newlist
def BuildLandingPage(self):
"""Build the initial HTML landing page with links to all hosts."""
TB.logger.debug('Building Langing Page')
sorted_ip = []
sorted_hosts = []
downhosts = 0
readyhosts = 0
sorted_ip = self.SortAFEHosts(TB.tbhosts)
# Put host that are down first
for h in sorted_ip:
if not TB.hosts[h.hostname]['status']:
sorted_hosts.insert(downhosts, h)
downhosts = downhosts + 1
else:
sorted_hosts.append(h)
readyhosts = readyhosts + 1
# Create symlink to the log file if it does not exist.
if TB.graph:
log_filename = os.path.join(TB.home, 'graph.txt')
else:
log_filename = os.path.join(TB.home, 'update.txt')
if not os.path.isfile(log_filename):
try:
os.symlink(TB.logfile, log_filename)
except OSError, e:
TB.logger.error('Error linking to logfile\n%s', e)
sshlog = os.path.join(TB.home, 'ssh.txt')
if not os.path.isfile(sshlog):
os.symlink(TB.sshlog, sshlog)
LandPageFile = os.path.join(TB.home, 'index.html')
# The temp file is used so that there will always be viewable html page
# when the new page is being built.
LandPageTemp = os.path.join(TB.home, 'temp.html')
f = open(LandPageTemp, 'w')
f.write('<HTML><HEAD>')
f.write('<LINK REL="stylesheet" TYPE="text/css" HREF="table.css">')
f.write('<center><TITLE>System Health Check</TITLE></HEAD>')
f.write('<BODY>')
f.write('<img src="watchdog.png" style="float:left;"/>')
f.write('<table style="float: right">')
f.write('<TR><TD><em>Total Hosts</em><TD>%d' % (downhosts + readyhosts))
f.write('<TR><TD><em>Inaccessible Hosts</em><TD>%d' % downhosts)
f.write('<TR><TD><em>Accessible Hosts</em><TD>%d' % readyhosts)
f.write('<TR><TD><em>Update Log<em><TD><a href=%s>%s</a>' % ('update.txt',
'log'))
f.write('<TR><TD><em>Graphing Log<em><TD><a href=%s>%s</a>' % ('graph.txt',
'log'))
f.write('<TR><TD><em>Connection Log<em><TD><a href=%s>%s</a>' % ('ssh.txt',
'log'))
f.write('</table>')
f.write('<H1>%s Testbed</H1>' % TB.testbed)
f.write('<H2>System Monitor</H2>')
f.write('<BR><BR>')
f.write('<HR>')
f.write('<table>')
f.write('<CAPTION><EM>%s</EM></CAPTION>' % TB.caption)
f.write('<TR><TH>Hostname<TH>Status<TH>Labels<TH>Last Update')
f.write('<TH>Release<TH>Health</TR>')
for h in sorted_hosts:
link_dir = 'hosts/' + h.hostname + '/rrd'
rrd_dir = os.path.join(TB.home, 'hosts', h.hostname, 'rrd')
downfile = os.path.join(rrd_dir, 'downtime')
hlink = os.path.join(link_dir, 'hwinfo.html')
if not os.path.isdir(rrd_dir):
os.makedirs(rrd_dir)
os.chmod(rrd_dir, 0755)
if TB.hosts[h.hostname]['status']:
if os.path.isfile(downfile):
try:
os.remove(downfile)
except OSError, e:
TB.logger.error('Error deleting %s\n%s', downfile, e)
status = 'Ready'
bgcolor = '#FFFFFF'
else:
if os.path.isfile(downfile):
status = 'Down'
bgcolor = '#FF9999'
df = open(downfile, 'r')
TB.hosts[h.hostname]['time'] = df.read()
df.close()
else:
status = 'Unknown'
bgcolor = '#E8E8E8'
df = open(downfile, 'w')
df.write(TB.hosts[h.hostname]['time'])
df.close()
f.write('<tr bgcolor=%s><th>' % bgcolor)
f.write('<a href="%s">%s</a></th>' % (hlink, h.hostname))
f.write('<td><em>%s</em>' % status)
f.write('<td>')
for label in h.labels:
if 'netbook' in label:
f.write('<em><b>%s</b></em><br>' % label)
else:
f.write('%s<br>' % label)
f.write('<td>%s' % TB.hosts[h.hostname]['time'])
if TB.hosts[h.hostname]['release']['PTR']:
f.write('<td>%s' % TB.hosts[h.hostname]['release']['PTR'])
else:
f.write('<td>Unknown')
index_file = os.path.join(rrd_dir, 'index.html')
if os.path.isfile(index_file):
f.write('<td><a href=%s' % TB.url)
f.write('%s/index.html target="_blank">' % link_dir)
f.write('health</a></td>')
else:
f.write('<td>None</td>')
f.write('</table><p>\n</center>\n</BODY></HTML>')
f.close()
shutil.copyfile(LandPageTemp, LandPageFile)
os.chmod(LandPageFile, 0644)
class Resource(object):
"""Contains structures and methods to collect health data on hosts.
For each resource in self.resources, there must also be a corresponding
method to format the data into what RRDTool expects.
Args:
filesystems: dictionary of file system devices with mountpoints.
net_devices: list of network devices.
"""
def __init__(self, filesystems, net_devices):
self.files = {
'cpu': '/proc/stat',
'load': '/proc/loadavg',
'memory': '/proc/meminfo',
'power': '/proc/acpi/processor/CPU0/throttling',
'temp': '/proc/acpi/thermal_zone/*/temperature',
'uptime': '/proc/uptime',
}
# self.net_devices used when running ParseNetDev().
self.net_dev = net_devices
fs_specs = ['_space', '_inode', '_stats']
### self.fs get populated from df output.
self.fs = {}
for k in filesystems:
fs_dev = os.path.basename(k) # Strip any device directories.
for spec in fs_specs:
key = fs_dev + spec
if spec == '_stats':
self.fs[key] = fs_dev
else:
self.fs[key] = filesystems[k]
self.resources = []
for k in self.files:
self.resources.append(k)
for k in self.fs:
self.resources.append(k)
for k in self.net_dev:
self.resources.append(k)
def FormatData(self, hostname):
"""Convert collected data into the correct format for RRDTool.
Args:
hostname: string, hostname of AutoTest host.
"""
ParseMethod = {
'battery': self.ParseBattery,
'boot': self.ParseBoot,
'fs': self.ParseFS,
'diskstats': self.ParseDiskStats,
'cpu': self.ParseStat,
'load': self.ParseLoadAvg,
'memory': self.ParseMemInfo,
'network': self.ParseNetDev,
'power': self.ParsePower,
'temp': self.ParseTemp,
'uptime': self.ParseUpTime,
}
# method_key is used here because multiple resource keys will use the
# same method to parse them.
for key in TB.hosts[hostname]['data']:
method_key = key
if key in self.fs:
if '_space' in key:
method_key = 'fs'
elif '_inode' in key:
method_key = 'fs'
elif '_stats' in key:
method_key = 'diskstats'
else:
TB.logger.error('Error in key name of %s', key)
if key in self.net_dev:
method_key = 'network'
if method_key in ParseMethod:
if len(TB.hosts[hostname]['data'][key]) > 0:
TB.logger.debug('Parsing %s on %s', key, hostname)
ParseMethod[method_key](hostname, key)
else:
TB.logger.error('No method to parse resource %s', key)
def ProcessRRD(self, hostname):
"""Process formatted data into RRD files.
Args:
hostname: string, hostname or ip address.
"""
hostdir = os.path.join(TB.home, 'hosts', hostname)
rrd_dir = os.path.join(hostdir, 'rrd')
if not os.path.exists(rrd_dir):
os.makedirs(rrd_dir)
os.chmod(rrd_dir, 0755)
os.chmod(hostdir, 0755)
for r in TB.hosts[hostname]['rrddata']:
dk = None # set datakey if it's a file system or network device.
if r in self.fs:
if '_space' in r:
dk = 'fs_space'
elif '_inode' in r:
dk = 'fs_inode'
elif '_stat' in r:
dk = 'fs_stat'
if r in self.net_dev:
dk = 'network'
rrd = RRD(r, hostname, rrd_dir, datakey=dk)
if not os.path.exists(rrd.rrdfile):
rrd.Create()
if TB.update == True:
TB.logger.debug('Updating %s for host %s', r, hostname)
if len(TB.hosts[hostname]['rrddata'][r]) > 0:
rrd.Update()
if TB.graph:
TB.logger.debug('Building %s graphs for %s', r, hostname)
rrd.Graph()
def BuildHTML(self, hostname):
"""Create HTML pages for to display the graphs.
Args:
hostname: string, host of AutoTest host.
"""
mainindex = TB.url + 'index.html'
rrd_dir = os.path.join(TB.home, 'hosts', hostname, 'rrd')
resource_list = []
for r in self.resources:
resource_list.append(r)
resource_list.sort()
index_file = os.path.join(rrd_dir, 'index.html')
html_file = {}
for t in TB.rrdtimes:
html_file[t] = hostname + t + '.html'
pathname = {}
for name in html_file:
pathname[name] = os.path.join(rrd_dir, html_file[name])
# Create HTML files for each time period we are graphing.
for path in pathname:
f = open(pathname[path], 'w')
f.write('<HTML><HEAD>')
f.write('<center><TITLE>%s System Health</TITLE></HEAD>' % hostname)
f.write('<BODY><H1>%s System Health</H1>' % hostname)
for v in TB.version:
f.write('<H4>%s: %s</H4>' % (v, TB.hosts[hostname][v]['PTR']))
for t in TB.rrdtimes:
f.write('<a href="%s">%s</a> <b>|</b>' % (html_file[t], t))
f.write('<a href="%s">SystemHealth Home</a>' % mainindex)
f.write('<p><HR>')
f.write('<b>%s</b><table border=1 bgcolor=#EEEEEE>' % path)
newrow = True
for r in resource_list:
if newrow:
f.write('<tr>')
f.write('<td>%s<br><a href=%s.html>' % (r, r))
f.write('<img src=%s%s.png width=475 height=250></a></td>' % (r, path))
if newrow:
newrow = False
else:
f.write('</tr>\n')
newrow = True
f.write('</table><p>\n')
f.write('</center>\n')
f.write('<H5>Last Update: %s</H5>' % TB.hosts[hostname]['time'])
f.write('</BODY></HTML>')
f.close()
os.chmod(pathname[path], 0644)
if not os.path.isfile(index_file):
os.symlink(pathname[TB.rrdtimes[0]], index_file)
# Create HTML files for each resource for all time periods.