www/database.php
[monitor.git] / findbadpcu.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import string
6 import time
7 import socket
8 import util.file
9 import plc
10 import sets
11
12     
13 import signal
14 import traceback
15
16 #old_handler = signal.getsignal(signal.SIGCHLD)
17
18 #def sig_handler(signum, stack):
19 #       """ Handle SIGCHLD signal """
20 #       global old_handler
21 #       if signum == signal.SIGCHLD:
22 #               try:
23 #                       os.wait()
24 #               except:
25 #                       pass
26 #       if old_handler != signal.SIG_DFL:
27 #               old_handler(signum, stack)
28 #
29 #orig_sig_handler = signal.signal(signal.SIGCHLD, sig_handler)
30
31
32 # QUERY all nodes.
33 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
34                                         "table=table_nodeview&" + \
35                                     "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
36                                     "formatcsv"
37                                     #"formatcsv&" + \
38                                         #"select='lastcotop!=0'"
39
40 import threading
41 plc_lock = threading.Lock()
42 round = 1
43 externalState = {'round': round, 'nodes': {'a': None}}
44 errorState = {}
45 count = 0
46
47 import reboot
48 from reboot import pcu_name
49
50 import database
51 import moncommands
52 import plc
53 import comon
54 import threadpool
55 import syncplcdb
56
57 def nmap_portstatus(status):
58         ps = {}
59         l_nmap = status.split()
60         ports = l_nmap[4:]
61
62         continue_probe = False
63         for port in ports:
64                 results = port.split('/')
65                 ps[results[0]] = results[1]
66                 if results[1] == "open":
67                         continue_probe = True
68         return (ps, continue_probe)
69
70 def get_pcu(pcuname):
71         plc_lock.acquire()
72         try:
73                 print "GetPCU from PLC %s" % pcuname
74                 l_pcu  = plc.GetPCUs({'pcu_id' : pcuname})
75                 print l_pcu
76                 if len(l_pcu) > 0:
77                         l_pcu = l_pcu[0]
78         except:
79                 try:
80                         print "GetPCU from file %s" % pcuname
81                         l_pcus = database.dbLoad("pculist")
82                         for i in l_pcus:
83                                 if i['pcu_id'] == pcuname:
84                                         l_pcu = i
85                 except:
86                         traceback.print_exc()
87                         l_pcu = None
88
89         plc_lock.release()
90         return l_pcu
91
92 def get_nodes(node_ids):
93         plc_lock.acquire()
94         l_node = []
95         try:
96                 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
97         except:
98                 try:
99                         plc_nodes = database.dbLoad("l_plcnodes")
100                         for n in plc_nodes:
101                                 if n['node_id'] in node_ids:
102                                         l_node.append(n)
103                 except:
104                         traceback.print_exc()
105                         l_node = None
106
107         plc_lock.release()
108         if l_node == []:
109                 l_node = None
110         return l_node
111         
112
113 def get_plc_pcu_values(pcuname):
114         """
115                 Try to contact PLC to get the PCU info.
116                 If that fails, try a backup copy from the last run.
117                 If that fails, return None
118         """
119         values = {}
120
121         l_pcu = get_pcu(pcuname)
122         
123         if l_pcu is not None:
124                 site_id = l_pcu['site_id']
125                 node_ids = l_pcu['node_ids']
126                 l_node = get_nodes(node_ids) 
127                                 
128                 if l_node is not None:
129                         for node in l_node:
130                                 values[node['hostname']] = node['ports'][0]
131
132                         values['nodenames'] = [node['hostname'] for node in l_node]
133
134                         # NOTE: this is for a dry run later. It doesn't matter which node.
135                         values['node_id'] = l_node[0]['node_id']
136
137                 values.update(l_pcu)
138         else:
139                 values = None
140         
141         return values
142
143 def get_plc_site_values(site_id):
144         ### GET PLC SITE ######################
145         plc_lock.acquire()
146         values = {}
147         d_site = None
148
149         try:
150                 d_site = plc.getSites({'site_id': site_id}, ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
151                 if len(d_site) > 0:
152                         d_site = d_site[0]
153         except:
154                 try:
155                         plc_sites = database.dbLoad("l_plcsites")
156                         for site in plc_sites:
157                                 if site['site_id'] == site_id:
158                                         d_site = site
159                                         break
160                 except:
161                         traceback.print_exc()
162                         values = None
163
164         plc_lock.release()
165
166         if d_site is not None:
167                 max_slices = d_site['max_slices']
168                 num_slices = len(d_site['slice_ids'])
169                 num_nodes = len(d_site['node_ids'])
170                 loginbase = d_site['login_base']
171                 values['plcsite'] = {'num_nodes' : num_nodes, 
172                                                         'max_slices' : max_slices, 
173                                                         'num_slices' : num_slices,
174                                                         'login_base' : loginbase,
175                                                         'status'     : 'SUCCESS'}
176         else:
177                 values = None
178
179
180         return values
181
182
183 def collectPingAndSSH(pcuname, cohash):
184
185         continue_probe = True
186         errors = None
187         values = {}
188         ### GET PCU ######################
189         try:
190                 b_except = False
191                 try:
192                         v = get_plc_pcu_values(pcuname)
193                         if v is not None:
194                                 values.update(v)
195                         else:
196                                 continue_probe = False
197                 except:
198                         b_except = True
199                         traceback.print_exc()
200                         continue_probe = False
201
202                 if b_except or not continue_probe: return (None, None, None)
203
204                 if values['hostname'] is not None:
205                         values['hostname'] = values['hostname'].strip()
206
207                 if values['ip'] is not None:
208                         values['ip'] = values['ip'].strip()
209
210                 #### COMPLETE ENTRY   #######################
211
212                 values['complete_entry'] = []
213                 #if values['protocol'] is None or values['protocol'] is "":
214                 #       values['complete_entry'] += ["protocol"]
215                 if values['model'] is None or values['model'] is "":
216                         values['complete_entry'] += ["model"]
217                         # Cannot continue due to this condition
218                         continue_probe = False
219
220                 if values['password'] is None or values['password'] is "":
221                         values['complete_entry'] += ["password"]
222                         # Cannot continue due to this condition
223                         continue_probe = False
224
225                 if len(values['complete_entry']) > 0:
226                         continue_probe = False
227
228                 if values['hostname'] is None or values['hostname'] is "":
229                         values['complete_entry'] += ["hostname"]
230                 if values['ip'] is None or values['ip'] is "":
231                         values['complete_entry'] += ["ip"]
232
233                 # If there are no nodes associated with this PCU, then we cannot continue.
234                 if len(values['node_ids']) == 0:
235                         continue_probe = False
236                         values['complete_entry'] += ['NoNodeIds']
237
238                 #### DNS and IP MATCH #######################
239                 if values['hostname'] is not None and values['hostname'] is not "" and \
240                    values['ip'] is not None and values['ip'] is not "":
241                         #print "Calling socket.gethostbyname(%s)" % values['hostname']
242                         try:
243                                 ipaddr = socket.gethostbyname(values['hostname'])
244                                 if ipaddr == values['ip']:
245                                         values['dnsmatch'] = "DNS-OK"
246                                 else:
247                                         values['dnsmatch'] = "DNS-MISMATCH"
248                                         continue_probe = False
249
250                         except Exception, err:
251                                 values['dnsmatch'] = "DNS-NOENTRY"
252                                 values['hostname'] = values['ip']
253                                 #print err
254                 else:
255                         if values['ip'] is not None and values['ip'] is not "":
256                                 values['dnsmatch'] = "NOHOSTNAME"
257                                 values['hostname'] = values['ip']
258                         else:
259                                 values['dnsmatch'] = "NO-DNS-OR-IP"
260                                 values['hostname'] = "No_entry_in_DB"
261                                 continue_probe = False
262
263                 #### RUN NMAP ###############################
264                 if continue_probe:
265                         nmap = moncommands.CMD()
266                         (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % pcu_name(values))
267                         # NOTE: an empty / error value for oval, will still work.
268                         (values['portstatus'], continue_probe) = nmap_portstatus(oval)
269                 else:
270                         values['portstatus'] = None
271                         
272
273                 ######  DRY RUN  ############################
274                 if 'node_ids' in values and len(values['node_ids']) > 0:
275                         rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
276                 else:
277                         rb_ret = "Not_Run" # No nodes to test"
278
279                 values['reboot'] = rb_ret
280
281                 ### GET PLC SITE ######################
282                 v = get_plc_site_values(values['site_id'])
283                 if v is not None:
284                         values.update(v)
285                 else:
286                         values['plcsite'] = {'status' : "GS_FAILED"}
287                         
288         except:
289                 print "____________________________________"
290                 print values
291                 errors = values
292                 print "____________________________________"
293                 errors['traceback'] = traceback.format_exc()
294                 print errors['traceback']
295
296         values['checked'] = time.time()
297         return (pcuname, values, errors)
298
299 def recordPingAndSSH(request, result):
300         global errorState
301         global externalState
302         global count
303         (nodename, values, errors) = result
304
305         if values is not None:
306                 global_round = externalState['round']
307                 pcu_id = "id_%s" % nodename
308                 externalState['nodes'][pcu_id]['values'] = values
309                 externalState['nodes'][pcu_id]['round'] = global_round
310
311                 count += 1
312                 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
313                 database.dbDump(config.dbname, externalState)
314
315         if errors is not None:
316                 pcu_id = "id_%s" % nodename
317                 errorState[pcu_id] = errors
318                 database.dbDump("findbadpcu_errors", errorState)
319
320 # this will be called when an exception occurs within a thread
321 def handle_exception(request, result):
322         print "Exception occured in request %s" % request.requestID
323         for i in result:
324                 print "Result: %s" % i
325
326
327 def checkAndRecordState(l_pcus, cohash):
328         global externalState
329         global count
330         global_round = externalState['round']
331
332         tp = threadpool.ThreadPool(20)
333
334         # CREATE all the work requests
335         for pcuname in l_pcus:
336                 pcu_id = "id_%s" % pcuname
337                 if pcuname not in externalState['nodes']:
338                         #print type(externalState['nodes'])
339
340                         externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
341
342                 node_round   = externalState['nodes'][pcu_id]['round']
343                 if node_round < global_round:
344                         # recreate node stats when refreshed
345                         #print "%s" % nodename
346                         req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {}, 
347                                                                                  None, recordPingAndSSH, handle_exception)
348                         tp.putRequest(req)
349                 else:
350                         # We just skip it, since it's "up to date"
351                         count += 1
352                         print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
353                         pass
354
355         # WAIT while all the work requests are processed.
356         begin = time.time()
357         while 1:
358                 try:
359                         time.sleep(1)
360                         tp.poll()
361                         # if more than two hours
362                         if time.time() - begin > (60*60*1):
363                                 print "findbadpcus.py has run out of time!!!!!!"
364                                 database.dbDump(config.dbname, externalState)
365                                 os._exit(1)
366                 except KeyboardInterrupt:
367                         print "Interrupted!"
368                         break
369                 except threadpool.NoResultsPending:
370                         print "All results collected."
371                         break
372
373
374
375 def main():
376         global externalState
377
378         l_pcus = database.if_cached_else_refresh(1, config.refresh, "pculist", lambda : plc.GetPCUs())
379         externalState = database.if_cached_else(1, config.dbname, lambda : externalState) 
380         cohash = {}
381
382         if config.increment:
383                 # update global round number to force refreshes across all nodes
384                 externalState['round'] += 1
385
386         if config.site is not None:
387                 api = plc.getAuthAPI()
388                 site = api.GetSites(config.site)
389                 l_nodes = api.GetNodes(site[0]['node_ids'], ['pcu_ids'])
390                 pcus = []
391                 for node in l_nodes:
392                         pcus += node['pcu_ids']
393                 l_pcus = [pcu for pcu in sets.Set(pcus)]
394
395         elif config.nodelist == None and config.pcuid == None:
396                 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
397                 l_pcus  = [pcu['pcu_id'] for pcu in l_pcus]
398         elif config.nodelist is not None:
399                 l_pcus = util.file.getListFromFile(config.nodelist)
400                 l_pcus = [int(pcu) for pcu in l_pcus]
401         elif config.pcuid is not None:
402                 l_pcus = [ config.pcuid ] 
403                 l_pcus = [int(pcu) for pcu in l_pcus]
404
405         checkAndRecordState(l_pcus, cohash)
406
407         return 0
408
409
410 if __name__ == '__main__':
411         import logging
412         logger = logging.getLogger("monitor")
413         logger.setLevel(logging.DEBUG)
414         fh = logging.FileHandler("monitor.log", mode = 'a')
415         fh.setLevel(logging.DEBUG)
416         formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
417         fh.setFormatter(formatter)
418         logger.addHandler(fh)
419         import parser as parsermodule
420         parser = parsermodule.getParser()
421         parser.set_defaults(nodelist=None, 
422                                                 increment=False, 
423                                                 pcuid=None,
424                                                 site=None,
425                                                 dbname="findbadpcus", 
426                                                 cachenodes=False,
427                                                 refresh=False,
428                                                 )
429         parser.add_option("-f", "--nodelist", dest="nodelist", metavar="FILE", 
430                                                 help="Provide the input file for the node list")
431         parser.add_option("", "--site", dest="site", metavar="FILE", 
432                                                 help="Get all pcus associated with the given site's nodes")
433         parser.add_option("", "--pcuid", dest="pcuid", metavar="id", 
434                                                 help="Provide the id for a single pcu")
435
436         parser.add_option("", "--cachenodes", action="store_true",
437                                                 help="Cache node lookup from PLC")
438         parser.add_option("", "--dbname", dest="dbname", metavar="FILE", 
439                                                 help="Specify the name of the database to which the information is saved")
440         parser.add_option("", "--refresh", action="store_true", dest="refresh",
441                                                 help="Refresh the cached values")
442         parser.add_option("-i", "--increment", action="store_true", dest="increment", 
443                                                 help="Increment round number to force refresh or retry")
444         parser = parsermodule.getParser(['defaults'], parser)
445         config = parsermodule.parse_args(parser)
446         try:
447                 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
448                 # when LANG is set... Do not know why.  Unsetting LANG, fixes the problem.
449                 if 'LANG' in os.environ:
450                         del os.environ['LANG']
451                 main()
452                 time.sleep(1)
453         except Exception, err:
454                 traceback.print_exc()
455                 print "Exception: %s" % err
456                 print "Saving data... exitting."
457                 database.dbDump(config.dbname, externalState)
458                 sys.exit(0)