controllers should allow refreshes while findall is running.
[monitor.git] / monitor / scanapi.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import string
6 import time
7 from datetime import datetime,timedelta
8 import threadpool
9 import threading
10
11 import socket
12 from pcucontrol import reboot
13
14 from pcucontrol.util import command
15 from monitor import config
16
17 from monitor.database.info.model import *
18
19 from monitor.sources import comon
20 from monitor.wrapper import plc, plccache
21
22 import traceback
23 from monitor.common import nmap_port_status, email_exception
24
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'&" + \
28                         "formatcsv"
29
30 api = plc.getAuthAPI()
31 plc_lock = threading.Lock()
32 round = 1
33 global_round = round
34 count = 0
35
36
37 def get_pcu(pcuname):
38         plc_lock.acquire()
39         try:
40                 #print "GetPCU from PLC %s" % pcuname
41                 l_pcu  = plc.GetPCUs({'pcu_id' : pcuname})
42                 #print l_pcu
43                 if len(l_pcu) > 0:
44                         l_pcu = l_pcu[0]
45         except:
46                 try:
47                         #print "GetPCU from file %s" % pcuname
48                         l_pcus = plccache.l_pcus
49                         for i in l_pcus:
50                                 if i['pcu_id'] == pcuname:
51                                         l_pcu = i
52                 except:
53                         traceback.print_exc()
54                         l_pcu = None
55
56         plc_lock.release()
57         return l_pcu
58
59 def get_nodes(node_ids):
60         plc_lock.acquire()
61         l_node = []
62         try:
63                 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
64         except:
65                 try:
66                         plc_nodes = plccache.l_plcnodes
67                         for n in plc_nodes:
68                                 if n['node_id'] in node_ids:
69                                         l_node.append(n)
70                 except:
71                         traceback.print_exc()
72                         l_node = None
73
74         plc_lock.release()
75         if l_node == []:
76                 l_node = None
77         return l_node
78         
79
80 def get_plc_pcu_values(pcuname):
81         """
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
85         """
86         values = {}
87
88         l_pcu = get_pcu(pcuname)
89         
90         if l_pcu is not None:
91                 site_id = l_pcu['site_id']
92                 node_ids = l_pcu['node_ids']
93                 l_node = get_nodes(node_ids) 
94                                 
95                 if l_node is not None:
96                         for node in l_node:
97                                 values[node['hostname']] = node['ports'][0]
98
99                         values['nodenames'] = [node['hostname'] for node in l_node]
100
101                         # NOTE: this is for a dry run later. It doesn't matter which node.
102                         values['node_id'] = l_node[0]['node_id']
103
104                 values.update(l_pcu)
105         else:
106                 values = None
107         
108         return values
109
110 class ScanInterface(object):
111         recordclass = None
112         syncclass = None
113         primarykey = 'hostname'
114
115         def __init__(self, round=1):
116                 self.round = round
117                 self.count = 1
118
119         def __getattr__(self, name):
120                 if 'collect' in name or 'record' in name:
121                         method = getattr(self, name, None)
122                         if method is None:
123                                 raise Exception("No such method %s" % name)
124                         return method
125                 else:
126                         raise Exception("No such method %s" % name)
127
128         def collect(self, nodename, data):
129                 pass
130
131         def record(self, request, (nodename, values) ):
132
133                 try:
134                         if values is None:
135                                 return
136                         
137                         if self.syncclass:
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})
147
148                         fbrec.set( **values ) 
149
150                         fbrec.flush()
151                         if self.syncclass:
152                                 fbnodesync.round = self.round
153                                 fbnodesync.flush()
154
155                         print "%d %s %s" % (self.count, nodename, values)
156                         self.count += 1
157
158                 except:
159                         print "ERROR:"
160                         email_exception(str(nodename))
161                         print traceback.print_exc()
162                         pass
163
164 class ScanNodeInternal(ScanInterface):
165         recordclass = FindbadNodeRecord
166         #syncclass = FindbadNodeRecordSync
167         syncclass = None
168         primarykey = 'hostname'
169
170         def collectNMAP(self, nodename, cohash):
171                 #### RUN NMAP ###############################
172                 values = {}
173                 nmap = command.CMD()
174                 print "nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename
175                 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename)
176                 # NOTE: an empty / error value for oval, will still work.
177                 (values['port_status'], continue_probe) = nmap_port_status(oval)
178
179                 values['date_checked'] = datetime.now()
180                                 
181                 return (nodename, values)
182
183         def collectInternal(self, nodename, cohash):
184                 ### RUN PING ######################
185                 ping = command.CMD()
186                 (oval,errval) = ping.run_noexcept("ping -c 1 -q %s | grep rtt" % nodename)
187
188                 try:
189                         values = {}
190
191                         if oval == "":
192                                 # An error occurred
193                                 values['ping_status'] = False
194                         else:
195                                 values['ping_status'] = True
196
197                         try:
198                                 for port in [22, 806]: 
199                                         ssh = command.SSH('root', nodename, port)
200
201                                         (oval, errval) = ssh.run_noexcept2(""" <<\EOF
202                                                 echo "{"
203                                                 echo '  "kernel_version":"'`uname -a`'",'
204                                                 echo '  "bmlog":"'`ls /tmp/bm.log`'",'
205                                                 echo '  "bootcd_version":"'`cat /mnt/cdrom/bootme/ID`'",'
206                                                 echo '  "nm_status":"'`ps ax | grep nm.py | grep -v grep`'",'
207                                                 echo '  "fs_status":"'`touch /var/log/monitor 2>&1 ; if [ -d /vservers/ ] ; then touch /vservers/monitor.log 2>&1 ; fi ; grep proc /proc/mounts | grep ro,`'",'
208                                                 echo '  "dns_status":"'`host boot.planet-lab.org 2>&1`'",'
209                                                 echo '  "princeton_comon_dir":"'`ls -d /vservers/princeton_comon`'",'
210
211                                                 ID=`grep princeton_comon /etc/passwd | awk -F : '{if ( $3 > 500 ) { print $3}}'` 
212                                                 echo '  "princeton_comon_running":"'`ls -d /proc/virtual/$ID`'",'
213                                                 echo '  "princeton_comon_procs":"'`vps ax | grep $ID | grep -v grep | wc -l`'",'
214                                                 echo '  "rpm_version":"'`rpm -q NodeManager`'",'
215                                                 echo '  "rpm_versions":"'`rpm -q -a`'",'
216                                                 echo "}"
217 EOF                             """)
218                                         
219                                         values['ssh_error'] = errval
220                                         if len(oval) > 0:
221                                                 #print "OVAL: %s" % oval
222                                                 values.update(eval(oval))
223                                                 values['ssh_portused'] = port
224                                                 break
225                                         else:
226                                                 values.update({'kernel_version': "", 'bmlog' : "", 'bootcd_version' : '', 
227                                                                                 'nm_status' : '', 
228                                                                                 'fs_status' : '',
229                                                                                 'dns_status' : '',
230                                                                                 'rpm_version' : '',
231                                                                                 'rpm_versions' : '',
232                                                                                 'princeton_comon_dir' : "", 
233                                                                                 'princeton_comon_running' : "", 
234                                                                                 'princeton_comon_procs' : "", 'ssh_portused' : None})
235                         except:
236                                 print traceback.print_exc()
237                                 sys.exit(1)
238
239                         print "ALLVERSIONS: %s %s" % (nodename, values['rpm_versions'])
240
241                         print "RPMVERSION: %s %s" % (nodename, values['rpm_version'])
242                         ### RUN SSH ######################
243                         b_getbootcd_id = True
244
245                         oval = values['kernel_version']
246                         if "2.6.17" in oval or "2.6.2" in oval:
247                                 values['ssh_status'] = True
248                                 values['observed_category'] = 'PROD'
249                                 if "bm.log" in values['bmlog']:
250                                         values['observed_status'] = 'DEBUG'
251                                 else:
252                                         values['observed_status'] = 'BOOT'
253                         elif "2.6.12" in oval or "2.6.10" in oval:
254                                 values['ssh_status'] = True
255                                 values['observed_category'] = 'OLDPROD'
256                                 if "bm.log" in values['bmlog']:
257                                         values['observed_status'] = 'DEBUG'
258                                 else:
259                                         values['observed_status'] = 'BOOT'
260                         
261                         # NOTE: on 2.6.8 kernels, with 4.2 bootstrapfs, the chroot 
262                         #       command fails.  I have no idea why.
263                         elif "2.4" in oval or "2.6.8" in oval:
264                                 b_getbootcd_id = False
265                                 values['ssh_status'] = True
266                                 values['observed_category'] = 'OLDBOOTCD'
267                                 values['observed_status'] = 'DEBUG'
268                         elif oval != "":
269                                 values['ssh_status'] = True
270                                 values['observed_category'] = 'UNKNOWN'
271                                 if "bm.log" in values['bmlog']:
272                                         values['observed_status'] = 'DEBUG'
273                                 else:
274                                         values['observed_status'] = 'BOOT'
275                         else:
276                                 # An error occurred.
277                                 b_getbootcd_id = False
278                                 values['ssh_status'] = False
279                                 values['observed_category'] = 'ERROR'
280                                 values['observed_status'] = 'DOWN'
281                                 val = errval.strip()
282                                 values['ssh_error'] = val
283                                 values['kernel_version'] = ""
284
285                         if b_getbootcd_id:
286                                 # try to get BootCD for all nodes that are not 2.4 nor inaccessible
287                                 oval = values['bootcd_version']
288                                 if "BootCD" in oval:
289                                         values['bootcd_version'] = oval
290                                         if "v2" in oval and \
291                                                 ( nodename is not "planetlab1.cs.unc.edu" and \
292                                                   nodename is not "planetlab2.cs.unc.edu" ):
293                                                 values['observed_category'] = 'OLDBOOTCD'
294                                 else:
295                                         values['bootcd_version'] = ""
296                         else:
297                                 values['bootcd_version'] = ""
298
299                         oval = values['nm_status']
300                         if "nm.py" in oval:
301                                 values['nm_status'] = "Y"
302                         else:
303                                 values['nm_status'] = "N"
304
305                         continue_slice_check = True
306                         oval = values['princeton_comon_dir']
307                         if "princeton_comon_dir" in oval:
308                                 values['princeton_comon_dir'] = True
309                         else:
310                                 values['princeton_comon_dir'] = False
311                                 continue_slice_check = False
312
313                         if continue_slice_check:
314                                 oval = values['princeton_comon_running']
315                                 if len(oval) > len('/proc/virtual/'):
316                                         values['princeton_comon_running'] = True
317                                 else:
318                                         values['princeton_comon_running'] = False
319                                         continue_slice_check = False
320                         else:
321                                 values['princeton_comon_running'] = False
322                                 
323                         if continue_slice_check:
324                                 oval = values['princeton_comon_procs']
325                                 values['princeton_comon_procs'] = int(oval)
326                         else:
327                                 values['princeton_comon_procs'] = None
328
329                                 
330                         if nodename in cohash: 
331                                 values['comon_stats'] = cohash[nodename]
332                         else:
333                                 values['comon_stats'] = {'resptime':  '-1', 
334                                                                                 'uptime':    '-1',
335                                                                                 'sshstatus': '-1', 
336                                                                                 'lastcotop': '-1',
337                                                                                 'cpuspeed' : "null",
338                                                                                 'disksize' : 'null',
339                                                                                 'memsize'  : 'null'}
340                         # include output value
341                         ### GET PLC NODE ######################
342                         plc_lock.acquire()
343                         d_node = None
344                         try:
345                                 d_node = plccache.GetNodeByName(nodename)
346                                 #d_node = plc.getNodes({'hostname': nodename}, ['pcu_ids', 'site_id', 
347                                 #                                               'date_created', 'last_updated', 
348                                 #                                               'last_contact', 'boot_state', 'nodegroup_ids'])[0]
349                         except:
350                                 traceback.print_exc()
351                         plc_lock.release()
352                         values['plc_node_stats'] = d_node
353
354                         ##### NMAP  ###################
355                         (n, v) = self.collectNMAP(nodename, None)
356                         values.update(v)
357
358                         ### GET PLC PCU ######################
359                         site_id = -1
360                         d_pcu = None
361                         if d_node:
362                                 pcu = d_node['pcu_ids']
363                                 if len(pcu) > 0:
364                                         d_pcu = pcu[0]
365
366                                 site_id = d_node['site_id']
367
368                         values['plc_pcuid'] = d_pcu
369
370                         ### GET PLC SITE ######################
371                         plc_lock.acquire()
372                         d_site = None
373                         values['loginbase'] = ""
374                         try:
375                                 d_site = plccache.GetSitesById([ site_id ])[0]
376                                 #d_site = plc.getSites({'site_id': site_id}, 
377                                 #                                       ['max_slices', 'slice_ids', 'node_ids', 'login_base'])[0]
378                                 values['loginbase'] = d_site['login_base']
379                         except:
380                                 traceback.print_exc()
381                         plc_lock.release()
382
383                         values['plc_site_stats'] = d_site 
384                         values['date_checked'] = datetime.now()
385                 except:
386                         print traceback.print_exc()
387
388                 return (nodename, values)
389
390 def internalprobe(hostname):
391         #fbsync = FindbadNodeRecordSync.findby_or_create(hostname="global", 
392         #                                                                                               if_new_set={'round' : 1})
393         scannode = ScanNodeInternal() # fbsync.round)
394         try:
395                 (nodename, values) = scannode.collectInternal(hostname, {})
396                 scannode.record(None, (nodename, values))
397                 session.flush()
398                 return True
399         except:
400                 print traceback.print_exc()
401                 return False
402
403 def externalprobe(hostname):
404         #fbsync = FindbadNodeRecordSync.findby_or_create(hostname="global", 
405         #                                                                                               if_new_set={'round' : 1})
406         scannode = ScanNodeInternal() # fbsync.round)
407         try:
408                 (nodename, values) = scannode.collectNMAP(hostname, {})
409                 scannode.record(None, (nodename, values))
410                 session.flush()
411                 return True
412         except:
413                 print traceback.print_exc()
414                 return False
415
416 class ScanPCU(ScanInterface):
417         recordclass = FindbadPCURecord
418         syncclass = None
419         primarykey = 'plc_pcuid'
420
421         def collectInternal(self, pcuname, cohash):
422
423                 continue_probe = True
424                 errors = None
425                 values = {'reboot_trial_status' : 'novalue'}
426                 ### GET PCU ######################
427                 try:
428                         b_except = False
429                         try:
430                                 v = get_plc_pcu_values(pcuname)
431                                 if v['hostname'] is not None: v['hostname'] = v['hostname'].strip()
432                                 if v['ip'] is not None: v['ip'] = v['ip'].strip()
433
434                                 if v is not None:
435                                         values['plc_pcu_stats'] = v
436                                 else:
437                                         continue_probe = False
438                         except:
439                                 b_except = True
440                                 traceback.print_exc()
441                                 continue_probe = False
442
443                         if b_except or not continue_probe: return (None, None, None)
444
445                         #### RUN NMAP ###############################
446                         if continue_probe:
447                                 nmap = command.CMD()
448                                 print "nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % reboot.pcu_name(values['plc_pcu_stats'])
449                                 (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']))
450                                 # NOTE: an empty / error value for oval, will still work.
451                                 (values['port_status'], continue_probe) = nmap_port_status(oval)
452                         else:
453                                 values['port_status'] = None
454                                 
455                         #### COMPLETE ENTRY   #######################
456
457                         values['entry_complete'] = []
458                         #if values['protocol'] is None or values['protocol'] is "":
459                         #       values['entry_complete'] += ["protocol"]
460                         if values['plc_pcu_stats']['model'] is None or values['plc_pcu_stats']['model'] is "":
461                                 values['entry_complete'] += ["model"]
462                                 # Cannot continue due to this condition
463                                 continue_probe = False
464
465                         if values['plc_pcu_stats']['password'] is None or values['plc_pcu_stats']['password'] is "":
466                                 values['entry_complete'] += ["password"]
467                                 # Cannot continue due to this condition
468                                 continue_probe = False
469
470                         if len(values['entry_complete']) > 0:
471                                 continue_probe = False
472
473                         if values['plc_pcu_stats']['hostname'] is None or values['plc_pcu_stats']['hostname'] is "":
474                                 values['entry_complete'] += ["hostname"]
475                         if values['plc_pcu_stats']['ip'] is None or values['plc_pcu_stats']['ip'] is "":
476                                 values['entry_complete'] += ["ip"]
477
478                         # If there are no nodes associated with this PCU, then we cannot continue.
479                         if len(values['plc_pcu_stats']['node_ids']) == 0:
480                                 continue_probe = False
481                                 values['entry_complete'] += ['nodeids']
482
483
484                         #### DNS and IP MATCH #######################
485                         if values['plc_pcu_stats']['hostname'] is not None and values['plc_pcu_stats']['hostname'] is not "" and \
486                            values['plc_pcu_stats']['ip'] is not None and values['plc_pcu_stats']['ip'] is not "":
487                                 try:
488                                         ipaddr = socket.gethostbyname(values['plc_pcu_stats']['hostname'])
489                                         if ipaddr == values['plc_pcu_stats']['ip']:
490                                                 values['dns_status'] = "DNS-OK"
491                                         else:
492                                                 values['dns_status'] = "DNS-MISMATCH"
493                                                 continue_probe = False
494
495                                 except Exception, err:
496                                         values['dns_status'] = "DNS-NOENTRY"
497                                         values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
498                         else:
499                                 if values['plc_pcu_stats']['ip'] is not None and values['plc_pcu_stats']['ip'] is not "":
500                                         values['dns_status'] = "NOHOSTNAME"
501                                         values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
502                                 else:
503                                         values['dns_status'] = "NO-DNS-OR-IP"
504                                         values['plc_pcu_stats']['hostname'] = "No_entry_in_DB"
505                                         continue_probe = False
506
507
508                         ######  DRY RUN  ############################
509                         if continue_probe and 'node_ids' in values['plc_pcu_stats'] and \
510                                 len(values['plc_pcu_stats']['node_ids']) > 0:
511                                 rb_ret = reboot.reboot_test_new(values['plc_pcu_stats']['nodenames'][0], 
512                                                                                                 values, 1, True)
513                         else:
514                                 rb_ret = "Not_Run" # No nodes to test"
515
516                         values['reboot_trial_status'] = rb_ret
517
518                 except:
519                         print "____________________________________"
520                         print values
521                         errors = values
522                         print "____________________________________"
523                         errors['traceback'] = traceback.format_exc()
524                         print errors['traceback']
525                         values['reboot_trial_status'] = str(errors['traceback'])
526                         print values
527
528                 values['entry_complete']=" ".join(values['entry_complete'])
529
530                 values['date_checked'] = datetime.now()
531                 return (pcuname, values)
532