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