7 from datetime import datetime,timedelta
12 from pcucontrol import reboot
14 from pcucontrol.util import command
15 from monitor import config
17 from monitor.database.info.model import *
19 from monitor.sources import comon
20 from monitor.wrapper import plc, plccache
23 from monitor.common import nmap_port_status, email_exception
25 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
26 "table=table_nodeview&" + \
27 "dumpcols='name,resptime,sshstatus,uptime,lastcotop,cpuspeed,memsize,disksize'&" + \
30 api = plc.getAuthAPI()
31 plc_lock = threading.Lock()
40 #print "GetPCU from PLC %s" % pcuname
41 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
47 #print "GetPCU from file %s" % pcuname
48 l_pcus = plccache.l_pcus
50 if i['pcu_id'] == pcuname:
59 def get_nodes(node_ids):
63 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
66 plc_nodes = plccache.l_nodes
68 if n['node_id'] in node_ids:
80 def get_plc_pcu_values(pcuname):
82 Try to contact PLC to get the PCU info.
83 If that fails, try a backup copy from the last run.
84 If that fails, return None
88 l_pcu = get_pcu(pcuname)
91 site_id = l_pcu['site_id']
92 node_ids = l_pcu['node_ids']
93 l_node = get_nodes(node_ids)
95 if l_node is not None:
97 values[node['hostname']] = node['ports'][0]
99 values['nodenames'] = [node['hostname'] for node in l_node]
101 # NOTE: this is for a dry run later. It doesn't matter which node.
102 values['node_id'] = l_node[0]['node_id']
110 class ScanInterface(object):
113 primarykey = 'hostname'
115 def __init__(self, round=1):
119 def __getattr__(self, name):
120 if 'collect' in name or 'record' in name:
121 method = getattr(self, name, None)
123 raise Exception("No such method %s" % name)
126 raise Exception("No such method %s" % name)
128 def collect(self, nodename, data):
131 def record(self, request, (nodename, values) ):
138 fbnodesync = self.syncclass.findby_or_create(
139 #if_new_set={'round' : self.round},
140 **{ self.primarykey : nodename})
141 # NOTE: This code will either add a new record for the new self.round,
142 # OR it will find the previous value, and update it with new information.
143 # The data that is 'lost' is not that important, b/c older
144 # history still exists.
145 fbrec = self.recordclass.findby_or_create(
146 **{ self.primarykey:nodename})
148 fbrec.set( **values )
152 fbnodesync.round = self.round
155 print "%d %s %s" % (self.count, nodename, values)
160 email_exception(str(nodename))
161 print traceback.print_exc()
164 class ScanNodeInternal(ScanInterface):
165 recordclass = FindbadNodeRecord
166 #syncclass = FindbadNodeRecordSync
168 primarykey = 'hostname'
170 def collectPorts(self, nodename, port_list=[22,80,806]):
172 for port in port_list:
173 ret = os.system("nc -w 5 -z %s %s > /dev/null" % (nodename, port) )
175 values[str(port)] = "open"
177 values[str(port)] = "closed"
178 return {'port_status' : values }
180 def collectNMAP(self, nodename, cohash):
181 #### RUN NMAP ###############################
182 # NOTE: run the same command three times and take the best of three
183 # runs. NMAP can drop packets, and especially so when it runs many
187 print "nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename
188 (oval1,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename)
189 (oval2,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename)
190 (oval3,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename)
191 # NOTE: an empty / error value for oval, will still work.
192 values['port_status'] = {}
193 (o1,continue_probe) = nmap_port_status(oval1)
194 (o2,continue_probe) = nmap_port_status(oval2)
195 (o3,continue_probe) = nmap_port_status(oval3)
196 for p in ['22', '80', '806']:
197 l = [ o1[p], o2[p], o3[p] ]
198 if len(filter(lambda x: x == 'open', l)) > 1:
199 values['port_status'][p] = 'open'
201 values['port_status'][p] = o1[p]
203 print values['port_status']
204 return (nodename, values)
206 def collectPING(self, nodename, cohash):
209 (oval,errval) = ping.run_noexcept("ping -c 1 -q %s | grep rtt" % nodename)
214 values['ping_status'] = False
216 values['ping_status'] = True
220 def collectTRACEROUTE(self, nodename, cohash):
222 trace = command.CMD()
223 (oval,errval) = trace.run_noexcept("traceroute %s" % nodename)
225 values['traceroute'] = oval
229 def collectSSH(self, nodename, cohash):
232 for port in [22, 806]:
233 ssh = command.SSH('root', nodename, port)
235 (oval, errval) = ssh.run_noexcept2(""" <<\EOF
237 echo ' "kernel_version":"'`uname -a`'",'
238 echo ' "bmlog":"'`ls /tmp/bm.log`'",'
239 echo ' "bootcd_version":"'`cat /mnt/cdrom/bootme/ID`'",'
240 echo ' "nm_status":"'`ps ax | grep nm.py | grep -v grep`'",'
241 echo ' "dns_status":"'`host boot.planet-lab.org 2>&1`'",'
242 echo ' "princeton_comon_dir":"'`ls -d /vservers/princeton_comon`'",'
243 echo ' "uptime":"'`cat /proc/uptime`'",'
245 ID=`grep princeton_comon /etc/passwd | awk -F : '{if ( $3 > 500 ) { print $3}}'`
246 echo ' "princeton_comon_running":"'`ls -d /proc/virtual/$ID`'",'
247 echo ' "princeton_comon_procs":"'`vps ax | grep $ID | grep -v grep | wc -l`'",'
248 echo ' "fs_status":"'`grep proc /proc/mounts | grep ro, ; if [ -x /usr/bin/timeout.pl ] ; then timeout.pl 20 touch /var/log/monitor 2>&1 ; if [ -d /vservers/ ] ; then timeout.pl 20 touch /vservers/monitor.log 2>&1 ; fi ; fi`'",'
249 echo ' "rpm_version":"'`if [ -x /usr/bin/timeout.pl ] ; then timeout.pl 30 rpm -q NodeManager ; fi`'",'
250 echo ' "rpm_versions":"'`if [ -x /usr/bin/timeout.pl ] ; then timeout.pl 45 rpm -q -a ; fi`'",'
254 values['ssh_error'] = errval
256 #print "OVAL: %s" % oval
257 values.update(eval(oval))
258 values['ssh_portused'] = port
261 values.update({'kernel_version': "", 'bmlog' : "", 'bootcd_version' : '',
268 'princeton_comon_dir' : "",
269 'princeton_comon_running' : "",
270 'princeton_comon_procs' : "", 'ssh_portused' : None})
272 oval = values['nm_status']
274 values['nm_status'] = "Y"
276 values['nm_status'] = "N"
278 continue_slice_check = True
279 oval = values['princeton_comon_dir']
280 if "princeton_comon_dir" in oval:
281 values['princeton_comon_dir'] = True
283 values['princeton_comon_dir'] = False
284 continue_slice_check = False
286 if continue_slice_check:
287 oval = values['princeton_comon_running']
288 if len(oval) > len('/proc/virtual/'):
289 values['princeton_comon_running'] = True
291 values['princeton_comon_running'] = False
292 continue_slice_check = False
294 values['princeton_comon_running'] = False
296 if continue_slice_check:
297 oval = values['princeton_comon_procs']
298 values['princeton_comon_procs'] = int(oval)
300 values['princeton_comon_procs'] = None
302 print traceback.print_exc()
307 def collectPLC(self, nodename, cohash):
309 ### GET PLC NODE ######################
310 d_node = plccache.GetNodeByName(nodename)
311 values['plc_node_stats'] = d_node
313 ### GET PLC PCU ######################
316 if d_node and len(d_node['pcu_ids']) > 0:
317 d_pcu = d_node['pcu_ids'][0]
319 site_id = d_node['site_id']
321 values['plc_pcuid'] = d_pcu
323 ### GET PLC SITE ######################
324 print "SITEID: %s" % site_id
325 d_site = plccache.GetSitesById([ site_id ])[0]
326 values['loginbase'] = d_site['login_base']
327 values['plc_site_stats'] = d_site
331 def evaluate(self, nodename, values):
332 # TODO: this section can probably be reduced to a policy statement
333 # using patterns and values collected so far.
334 # NOTE: A node is "DOWN" if
335 # * cannot ssh into it.
336 # * all ports are not open for a 'BOOT' node
337 # * dns for hostname does not exist.
338 b_getbootcd_id = True
340 oval = values['kernel_version']
341 values['ssh_status'] = True
342 if "2.6.17" in oval or "2.6.2" in oval:
343 values['observed_category'] = 'PROD'
344 if "bm.log" in values['bmlog']:
345 values['observed_status'] = 'DEBUG'
347 values['observed_status'] = 'BOOT'
348 elif "2.6.12" in oval or "2.6.10" in oval:
349 values['observed_category'] = 'OLDPROD'
350 if "bm.log" in values['bmlog']:
351 values['observed_status'] = 'DEBUG'
353 values['observed_status'] = 'BOOT'
355 # NOTE: on 2.6.8 kernels, with 4.2 bootstrapfs, the chroot
356 # command fails. I have no idea why.
357 elif "2.4" in oval or "2.6.8" in oval:
358 b_getbootcd_id = False
359 values['observed_category'] = 'OLDBOOTCD'
360 values['observed_status'] = 'DEBUG'
362 values['observed_category'] = 'UNKNOWN'
363 if "bm.log" in values['bmlog']:
364 values['observed_status'] = 'DEBUG'
366 values['observed_status'] = 'BOOT'
369 b_getbootcd_id = False
370 values['ssh_status'] = False
371 values['observed_category'] = 'ERROR'
372 values['observed_status'] = 'DOWN'
373 values['kernel_version'] = ""
375 values['firewall'] = False
377 # NOTE: A node is down if some of the public ports are not open
378 if values['observed_status'] == "BOOT":
379 # verify that all ports are open. Else, report node as down.
380 if not ( values['port_status']['22'] == "open" and \
381 values['port_status']['80'] == "open" and \
382 values['port_status']['806'] == "open") :
383 #email_exception(nodename, "%s FILTERED HOST" % nodename)
384 values['observed_status'] = 'DOWN'
385 values['firewall'] = True
387 #if not values['external_dns_status']:
388 # email_exception("%s DNS down" % nodename)
391 # try to get BootCD for all nodes that are not 2.4 nor inaccessible
392 oval = values['bootcd_version']
394 values['bootcd_version'] = oval
395 if "v2" in oval and \
396 ( nodename is not "planetlab1.cs.unc.edu" and \
397 nodename is not "planetlab2.cs.unc.edu" ):
398 values['observed_category'] = 'OLDBOOTCD'
400 values['bootcd_version'] = ""
402 values['bootcd_version'] = ""
406 def collectDNS(self, nodename, cohash):
409 ipaddr = socket.gethostbyname(nodename)
410 # TODO: check that IP returned matches IP in plc db.
411 values['external_dns_status'] = True
412 except Exception, err:
413 values['external_dns_status'] = False
417 def collectInternal(self, nodename, cohash):
421 v = self.collectPING(nodename, cohash)
424 v = self.collectPorts(nodename)
427 v = self.collectSSH(nodename, cohash)
430 v = self.collectDNS(nodename, cohash)
433 v = self.collectTRACEROUTE(nodename, cohash)
436 v = self.collectPLC(nodename, cohash)
439 if nodename in cohash:
440 values['comon_stats'] = cohash[nodename]
442 values['comon_stats'] = {'resptime': '-1',
450 values['rpms'] = values['rpm_versions']
451 print "ALLVERSIONS: %s %s" % (nodename, values['rpm_versions'])
452 print "RPMVERSION: %s %s" % (nodename, values['rpm_version'])
453 print "UPTIME: %s %s" % (nodename, values['uptime'])
455 values = self.evaluate(nodename, values)
456 values['date_checked'] = datetime.now()
459 print traceback.print_exc()
461 return (nodename, values)
464 def internalprobe(hostname):
465 scannode = ScanNodeInternal()
467 (nodename, values) = scannode.collectInternal(hostname, {})
468 scannode.record(None, (nodename, values))
472 print traceback.print_exc()
475 def externalprobe(hostname):
476 scannode = ScanNodeInternal()
478 values = self.collectPorts(hostname)
479 scannode.record(None, (hostname, values))
483 print traceback.print_exc()
486 class ScanPCU(ScanInterface):
487 recordclass = FindbadPCURecord
489 primarykey = 'plc_pcuid'
491 def collectInternal(self, pcuname, cohash):
493 continue_probe = True
495 values = {'reboot_trial_status' : 'novalue'}
496 ### GET PCU ######################
500 v = get_plc_pcu_values(pcuname)
501 if v['hostname'] is not None: v['hostname'] = v['hostname'].strip()
502 if v['ip'] is not None: v['ip'] = v['ip'].strip()
505 values['plc_pcu_stats'] = v
507 continue_probe = False
510 traceback.print_exc()
511 continue_probe = False
513 if b_except or not continue_probe: return (None, None, None)
515 #### RUN NMAP ###############################
518 print "nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % reboot.pcu_name(values['plc_pcu_stats'])
519 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % reboot.pcu_name(values['plc_pcu_stats']))
520 # NOTE: an empty / error value for oval, will still work.
521 (values['port_status'], continue_probe) = nmap_port_status(oval)
523 values['port_status'] = None
525 #### COMPLETE ENTRY #######################
527 values['entry_complete'] = []
528 #if values['protocol'] is None or values['protocol'] is "":
529 # values['entry_complete'] += ["protocol"]
530 if values['plc_pcu_stats']['model'] is None or values['plc_pcu_stats']['model'] is "":
531 values['entry_complete'] += ["model"]
532 # Cannot continue due to this condition
533 continue_probe = False
535 if values['plc_pcu_stats']['password'] is None or values['plc_pcu_stats']['password'] is "":
536 values['entry_complete'] += ["password"]
537 # Cannot continue due to this condition
538 continue_probe = False
540 if len(values['entry_complete']) > 0:
541 continue_probe = False
543 if values['plc_pcu_stats']['hostname'] is None or values['plc_pcu_stats']['hostname'] is "":
544 values['entry_complete'] += ["hostname"]
545 if values['plc_pcu_stats']['ip'] is None or values['plc_pcu_stats']['ip'] is "":
546 values['entry_complete'] += ["ip"]
548 # If there are no nodes associated with this PCU, then we cannot continue.
549 if len(values['plc_pcu_stats']['node_ids']) == 0:
550 continue_probe = False
551 values['entry_complete'] += ['nodeids']
554 #### DNS and IP MATCH #######################
555 if values['plc_pcu_stats']['hostname'] is not None and values['plc_pcu_stats']['hostname'] is not "" and \
556 values['plc_pcu_stats']['ip'] is not None and values['plc_pcu_stats']['ip'] is not "":
558 ipaddr = socket.gethostbyname(values['plc_pcu_stats']['hostname'])
559 if ipaddr == values['plc_pcu_stats']['ip']:
560 values['dns_status'] = "DNS-OK"
562 values['dns_status'] = "DNS-MISMATCH"
563 values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
565 except Exception, err:
566 values['dns_status'] = "DNS-NOENTRY"
567 values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
569 if values['plc_pcu_stats']['ip'] is not None and values['plc_pcu_stats']['ip'] is not "":
570 values['dns_status'] = "NOHOSTNAME"
571 values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
573 values['dns_status'] = "NO-DNS-OR-IP"
574 values['plc_pcu_stats']['hostname'] = "No_entry_in_DB"
575 continue_probe = False
578 ###### DRY RUN ############################
579 if continue_probe and 'node_ids' in values['plc_pcu_stats'] and \
580 len(values['plc_pcu_stats']['node_ids']) > 0:
581 rb_ret = reboot.reboot_test_new(values['plc_pcu_stats']['nodenames'][0],
584 rb_ret = "Not_Run" # No nodes to test"
586 values['reboot_trial_status'] = rb_ret
589 print "____________________________________"
592 print "____________________________________"
593 errors['traceback'] = traceback.format_exc()
594 print errors['traceback']
595 values['reboot_trial_status'] = str(errors['traceback'])
598 values['entry_complete']=" ".join(values['entry_complete'])
600 values['date_checked'] = datetime.now()
601 return (pcuname, values)