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