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