963822d3bebfcefd1a4953df135b25ff5435d7e9
[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
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                         print traceback.print_exc()
161                         pass
162
163 class ScanNodeInternal(ScanInterface):
164         recordclass = FindbadNodeRecord
165         #syncclass = FindbadNodeRecordSync
166         syncclass = None
167         primarykey = 'hostname'
168
169         def collectNMAP(self, nodename, cohash):
170                 #### RUN NMAP ###############################
171                 values = {}
172                 nmap = command.CMD()
173                 print "nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename
174                 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,80,806 %s | grep Host:" % nodename)
175                 # NOTE: an empty / error value for oval, will still work.
176                 (values['port_status'], continue_probe) = nmap_port_status(oval)
177
178                 values['date_checked'] = datetime.now()
179                                 
180                 return (nodename, values)
181
182         def collectInternal(self, nodename, cohash):
183                 ### RUN PING ######################
184                 ping = command.CMD()
185                 (oval,errval) = ping.run_noexcept("ping -c 1 -q %s | grep rtt" % nodename)
186
187                 try:
188                         values = {}
189
190                         if oval == "":
191                                 # An error occurred
192                                 values['ping_status'] = False
193                         else:
194                                 values['ping_status'] = True
195
196                         try:
197                                 for port in [22, 806]: 
198                                         ssh = command.SSH('root', nodename, port)
199
200                                         (oval, errval) = ssh.run_noexcept2(""" <<\EOF
201                                                 echo "{"
202                                                 echo '  "kernel_version":"'`uname -a`'",'
203                                                 echo '  "bmlog":"'`ls /tmp/bm.log`'",'
204                                                 echo '  "bootcd_version":"'`cat /mnt/cdrom/bootme/ID`'",'
205                                                 echo '  "nm_status":"'`ps ax | grep nm.py | grep -v grep`'",'
206                                                 echo '  "fs_status":"'`touch /var/log/monitor 2>&1`'",'
207                                                 echo '  "dns_status":"'`host boot.planet-lab.org 2>&1`'",'
208                                                 echo '  "princeton_comon_dir":"'`ls -d /vservers/princeton_comon`'",'
209
210                                                 ID=`grep princeton_comon /etc/passwd | awk -F : '{if ( $3 > 500 ) { print $3}}'` 
211                                                 echo '  "princeton_comon_running":"'`ls -d /proc/virtual/$ID`'",'
212                                                 echo '  "princeton_comon_procs":"'`vps ax | grep $ID | grep -v grep | wc -l`'",'
213                                                 echo "}"
214 EOF                             """)
215                                         
216                                         values['ssh_error'] = errval
217                                         if len(oval) > 0:
218                                                 #print "OVAL: %s" % oval
219                                                 values.update(eval(oval))
220                                                 values['ssh_portused'] = port
221                                                 break
222                                         else:
223                                                 values.update({'kernel_version': "", 'bmlog' : "", 'bootcd_version' : '', 
224                                                                                 'nm_status' : '', 
225                                                                                 'fs_status' : '',
226                                                                                 'dns_status' : '',
227                                                                                 'princeton_comon_dir' : "", 
228                                                                                 'princeton_comon_running' : "", 
229                                                                                 'princeton_comon_procs' : "", 'ssh_portused' : None})
230                         except:
231                                 print traceback.print_exc()
232                                 sys.exit(1)
233
234                         ### RUN SSH ######################
235                         b_getbootcd_id = True
236
237                         oval = values['kernel_version']
238                         if "2.6.17" in oval or "2.6.2" in oval:
239                                 values['ssh_status'] = True
240                                 values['observed_category'] = 'PROD'
241                                 if "bm.log" in values['bmlog']:
242                                         values['observed_status'] = 'DEBUG'
243                                 else:
244                                         values['observed_status'] = 'BOOT'
245                         elif "2.6.12" in oval or "2.6.10" in oval:
246                                 values['ssh_status'] = True
247                                 values['observed_category'] = 'OLDPROD'
248                                 if "bm.log" in values['bmlog']:
249                                         values['observed_status'] = 'DEBUG'
250                                 else:
251                                         values['observed_status'] = 'BOOT'
252                         
253                         # NOTE: on 2.6.8 kernels, with 4.2 bootstrapfs, the chroot 
254                         #       command fails.  I have no idea why.
255                         elif "2.4" in oval or "2.6.8" in oval:
256                                 b_getbootcd_id = False
257                                 values['ssh_status'] = True
258                                 values['observed_category'] = 'OLDBOOTCD'
259                                 values['observed_status'] = 'DEBUG'
260                         elif oval != "":
261                                 values['ssh_status'] = True
262                                 values['observed_category'] = 'UNKNOWN'
263                                 if "bm.log" in values['bmlog']:
264                                         values['observed_status'] = 'DEBUG'
265                                 else:
266                                         values['observed_status'] = 'BOOT'
267                         else:
268                                 # An error occurred.
269                                 b_getbootcd_id = False
270                                 values['ssh_status'] = False
271                                 values['observed_category'] = 'ERROR'
272                                 values['observed_status'] = 'DOWN'
273                                 val = errval.strip()
274                                 values['ssh_error'] = val
275                                 values['kernel_version'] = ""
276
277                         if b_getbootcd_id:
278                                 # try to get BootCD for all nodes that are not 2.4 nor inaccessible
279                                 oval = values['bootcd_version']
280                                 if "BootCD" in oval:
281                                         values['bootcd_version'] = oval
282                                         if "v2" in oval and \
283                                                 ( nodename is not "planetlab1.cs.unc.edu" and \
284                                                   nodename is not "planetlab2.cs.unc.edu" ):
285                                                 values['observed_category'] = 'OLDBOOTCD'
286                                 else:
287                                         values['bootcd_version'] = ""
288                         else:
289                                 values['bootcd_version'] = ""
290
291                         oval = values['nm_status']
292                         if "nm.py" in oval:
293                                 values['nm_status'] = "Y"
294                         else:
295                                 values['nm_status'] = "N"
296
297                         continue_slice_check = True
298                         oval = values['princeton_comon_dir']
299                         if "princeton_comon_dir" in oval:
300                                 values['princeton_comon_dir'] = True
301                         else:
302                                 values['princeton_comon_dir'] = False
303                                 continue_slice_check = False
304
305                         if continue_slice_check:
306                                 oval = values['princeton_comon_running']
307                                 if len(oval) > len('/proc/virtual/'):
308                                         values['princeton_comon_running'] = True
309                                 else:
310                                         values['princeton_comon_running'] = False
311                                         continue_slice_check = False
312                         else:
313                                 values['princeton_comon_running'] = False
314                                 
315                         if continue_slice_check:
316                                 oval = values['princeton_comon_procs']
317                                 values['princeton_comon_procs'] = int(oval)
318                         else:
319                                 values['princeton_comon_procs'] = None
320
321                                 
322                         if nodename in cohash: 
323                                 values['comon_stats'] = cohash[nodename]
324                         else:
325                                 values['comon_stats'] = {'resptime':  '-1', 
326                                                                                 'uptime':    '-1',
327                                                                                 'sshstatus': '-1', 
328                                                                                 'lastcotop': '-1',
329                                                                                 'cpuspeed' : "null",
330                                                                                 'disksize' : 'null',
331                                                                                 'memsize'  : 'null'}
332                         # include output value
333                         ### GET PLC NODE ######################
334                         plc_lock.acquire()
335                         d_node = None
336                         try:
337                                 d_node = plc.getNodes({'hostname': nodename}, ['pcu_ids', 'site_id', 
338                                                                                 'date_created', 'last_updated', 
339                                                                                 'last_contact', 'boot_state', 'nodegroup_ids'])[0]
340                         except:
341                                 traceback.print_exc()
342                         plc_lock.release()
343                         values['plc_node_stats'] = d_node
344
345                         ##### NMAP  ###################
346                         (n, v) = self.collectNMAP(nodename, None)
347                         values.update(v)
348
349                         ### GET PLC PCU ######################
350                         site_id = -1
351                         d_pcu = None
352                         if d_node:
353                                 pcu = d_node['pcu_ids']
354                                 if len(pcu) > 0:
355                                         d_pcu = pcu[0]
356
357                                 site_id = d_node['site_id']
358
359                         values['plc_pcuid'] = d_pcu
360
361                         ### GET PLC SITE ######################
362                         plc_lock.acquire()
363                         d_site = None
364                         values['loginbase'] = ""
365                         try:
366                                 d_site = plc.getSites({'site_id': site_id}, 
367                                                                         ['max_slices', 'slice_ids', 'node_ids', 'login_base'])[0]
368                                 values['loginbase'] = d_site['login_base']
369                         except:
370                                 traceback.print_exc()
371                         plc_lock.release()
372
373                         values['plc_site_stats'] = d_site 
374                         values['date_checked'] = datetime.now()
375                 except:
376                         print traceback.print_exc()
377
378                 return (nodename, values)
379
380 def internalprobe(hostname):
381         #fbsync = FindbadNodeRecordSync.findby_or_create(hostname="global", 
382         #                                                                                               if_new_set={'round' : 1})
383         scannode = ScanNodeInternal() # fbsync.round)
384         try:
385                 (nodename, values) = scannode.collectInternal(hostname, {})
386                 scannode.record(None, (nodename, values))
387                 session.flush()
388                 return True
389         except:
390                 print traceback.print_exc()
391                 return False
392
393 def externalprobe(hostname):
394         #fbsync = FindbadNodeRecordSync.findby_or_create(hostname="global", 
395         #                                                                                               if_new_set={'round' : 1})
396         scannode = ScanNodeInternal() # fbsync.round)
397         try:
398                 (nodename, values) = scannode.collectNMAP(hostname, {})
399                 scannode.record(None, (nodename, values))
400                 session.flush()
401                 return True
402         except:
403                 print traceback.print_exc()
404                 return False
405
406 class ScanPCU(ScanInterface):
407         recordclass = FindbadPCURecord
408         syncclass = None
409         primarykey = 'plc_pcuid'
410
411         def collectInternal(self, pcuname, cohash):
412
413                 continue_probe = True
414                 errors = None
415                 values = {'reboot_trial_status' : 'novalue'}
416                 ### GET PCU ######################
417                 try:
418                         b_except = False
419                         try:
420                                 v = get_plc_pcu_values(pcuname)
421                                 if v['hostname'] is not None: v['hostname'] = v['hostname'].strip()
422                                 if v['ip'] is not None: v['ip'] = v['ip'].strip()
423
424                                 if v is not None:
425                                         values['plc_pcu_stats'] = v
426                                 else:
427                                         continue_probe = False
428                         except:
429                                 b_except = True
430                                 traceback.print_exc()
431                                 continue_probe = False
432
433                         if b_except or not continue_probe: return (None, None, None)
434
435                         #### RUN NMAP ###############################
436                         if continue_probe:
437                                 nmap = command.CMD()
438                                 print "nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % reboot.pcu_name(values['plc_pcu_stats'])
439                                 (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']))
440                                 # NOTE: an empty / error value for oval, will still work.
441                                 (values['port_status'], continue_probe) = nmap_port_status(oval)
442                         else:
443                                 values['port_status'] = None
444                                 
445                         #### COMPLETE ENTRY   #######################
446
447                         values['entry_complete'] = []
448                         #if values['protocol'] is None or values['protocol'] is "":
449                         #       values['entry_complete'] += ["protocol"]
450                         if values['plc_pcu_stats']['model'] is None or values['plc_pcu_stats']['model'] is "":
451                                 values['entry_complete'] += ["model"]
452                                 # Cannot continue due to this condition
453                                 continue_probe = False
454
455                         if values['plc_pcu_stats']['password'] is None or values['plc_pcu_stats']['password'] is "":
456                                 values['entry_complete'] += ["password"]
457                                 # Cannot continue due to this condition
458                                 continue_probe = False
459
460                         if len(values['entry_complete']) > 0:
461                                 continue_probe = False
462
463                         if values['plc_pcu_stats']['hostname'] is None or values['plc_pcu_stats']['hostname'] is "":
464                                 values['entry_complete'] += ["hostname"]
465                         if values['plc_pcu_stats']['ip'] is None or values['plc_pcu_stats']['ip'] is "":
466                                 values['entry_complete'] += ["ip"]
467
468                         # If there are no nodes associated with this PCU, then we cannot continue.
469                         if len(values['plc_pcu_stats']['node_ids']) == 0:
470                                 continue_probe = False
471                                 values['entry_complete'] += ['nodeids']
472
473
474                         #### DNS and IP MATCH #######################
475                         if values['plc_pcu_stats']['hostname'] is not None and values['plc_pcu_stats']['hostname'] is not "" and \
476                            values['plc_pcu_stats']['ip'] is not None and values['plc_pcu_stats']['ip'] is not "":
477                                 try:
478                                         ipaddr = socket.gethostbyname(values['plc_pcu_stats']['hostname'])
479                                         if ipaddr == values['plc_pcu_stats']['ip']:
480                                                 values['dns_status'] = "DNS-OK"
481                                         else:
482                                                 values['dns_status'] = "DNS-MISMATCH"
483                                                 continue_probe = False
484
485                                 except Exception, err:
486                                         values['dns_status'] = "DNS-NOENTRY"
487                                         values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
488                         else:
489                                 if values['plc_pcu_stats']['ip'] is not None and values['plc_pcu_stats']['ip'] is not "":
490                                         values['dns_status'] = "NOHOSTNAME"
491                                         values['plc_pcu_stats']['hostname'] = values['plc_pcu_stats']['ip']
492                                 else:
493                                         values['dns_status'] = "NO-DNS-OR-IP"
494                                         values['plc_pcu_stats']['hostname'] = "No_entry_in_DB"
495                                         continue_probe = False
496
497
498                         ######  DRY RUN  ############################
499                         if continue_probe and 'node_ids' in values['plc_pcu_stats'] and \
500                                 len(values['plc_pcu_stats']['node_ids']) > 0:
501                                 rb_ret = reboot.reboot_test_new(values['plc_pcu_stats']['nodenames'][0], 
502                                                                                                 values, 1, True)
503                         else:
504                                 rb_ret = "Not_Run" # No nodes to test"
505
506                         values['reboot_trial_status'] = rb_ret
507
508                 except:
509                         print "____________________________________"
510                         print values
511                         errors = values
512                         print "____________________________________"
513                         errors['traceback'] = traceback.format_exc()
514                         print errors['traceback']
515                         values['reboot_trial_status'] = str(errors['traceback'])
516                         print values
517
518                 values['entry_complete']=" ".join(values['entry_complete'])
519
520                 values['date_checked'] = datetime.now()
521                 return (pcuname, values)
522