The most current version of everything.
[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
28 # QUERY all nodes.
29 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
30                                         "table=table_nodeview&" + \
31                                     "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
32                                     "formatcsv"
33                                     #"formatcsv&" + \
34                                         #"select='lastcotop!=0'"
35
36 import threading
37 plc_lock = threading.Lock()
38 round = 1
39 externalState = {'round': round, 'nodes': {'a': None}}
40 errorState = {}
41 count = 0
42
43 import reboot
44 from reboot import pcu_name
45
46 import soltesz
47 import plc
48 import comon
49 import threadpool
50 import syncplcdb
51
52 def nmap_portstatus(status):
53         ps = {}
54         l_nmap = status.split()
55         ports = l_nmap[4:]
56
57         continue_probe = False
58         for port in ports:
59                 results = port.split('/')
60                 ps[results[0]] = results[1]
61                 if results[1] == "open":
62                         continue_probe = True
63         return (ps, continue_probe)
64
65 def get_pcu(pcuname):
66         plc_lock.acquire()
67         try:
68                 print "GetPCU from PLC %s" % pcuname
69                 l_pcu  = plc.GetPCUs({'pcu_id' : pcuname})
70                 print l_pcu
71                 if len(l_pcu) > 0:
72                         l_pcu = l_pcu[0]
73         except:
74                 try:
75                         print "GetPCU from file %s" % pcuname
76                         l_pcus = soltesz.dbLoad("pculist")
77                         for i in l_pcus:
78                                 if i['pcu_id'] == pcuname:
79                                         l_pcu = i
80                 except:
81                         import traceback
82                         traceback.print_exc()
83                         l_pcu = None
84
85         plc_lock.release()
86         return l_pcu
87
88 def get_nodes(node_ids):
89         plc_lock.acquire()
90         l_node = []
91         try:
92                 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
93         except:
94                 try:
95                         plc_nodes = soltesz.dbLoad("l_plcnodes")
96                         for n in plc_nodes:
97                                 if n['node_id'] in node_ids:
98                                         l_node.append(n)
99                 except:
100                         import traceback
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 = soltesz.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                         import traceback
159                         traceback.print_exc()
160                         values = None
161
162         plc_lock.release()
163
164         if d_site is not None:
165                 max_slices = d_site['max_slices']
166                 num_slices = len(d_site['slice_ids'])
167                 num_nodes = len(d_site['node_ids'])
168                 loginbase = d_site['login_base']
169                 values['plcsite'] = {'num_nodes' : num_nodes, 
170                                                         'max_slices' : max_slices, 
171                                                         'num_slices' : num_slices,
172                                                         'login_base' : loginbase,
173                                                         'status'     : 'SUCCESS'}
174         else:
175                 values = None
176
177
178         return values
179
180
181 def collectPingAndSSH(pcuname, cohash):
182
183         continue_probe = True
184         errors = None
185         values = {}
186         ### GET PCU ######################
187         try:
188                 b_except = False
189                 try:
190                         v = get_plc_pcu_values(pcuname)
191                         if v is not None:
192                                 values.update(v)
193                         else:
194                                 continue_probe = False
195                 except:
196                         b_except = True
197                         import traceback
198                         traceback.print_exc()
199                         continue_probe = False
200
201                 if b_except or not continue_probe: return (None, None, None)
202
203                 if values['hostname'] is not None:
204                         values['hostname'] = values['hostname'].strip()
205
206                 if values['ip'] is not None:
207                         values['ip'] = values['ip'].strip()
208
209                 #### COMPLETE ENTRY   #######################
210
211                 values['complete_entry'] = []
212                 #if values['protocol'] is None or values['protocol'] is "":
213                 #       values['complete_entry'] += ["protocol"]
214                 if values['model'] is None or values['model'] is "":
215                         values['complete_entry'] += ["model"]
216                         # Cannot continue due to this condition
217                         continue_probe = False
218
219                 if values['password'] is None or values['password'] is "":
220                         values['complete_entry'] += ["password"]
221                         # Cannot continue due to this condition
222                         continue_probe = False
223
224                 if len(values['complete_entry']) > 0:
225                         continue_probe = False
226
227                 if values['hostname'] is None or values['hostname'] is "":
228                         values['complete_entry'] += ["hostname"]
229                 if values['ip'] is None or values['ip'] is "":
230                         values['complete_entry'] += ["ip"]
231
232                 # If there are no nodes associated with this PCU, then we cannot continue.
233                 if len(values['node_ids']) == 0:
234                         continue_probe = False
235                         values['complete_entry'] += ['NoNodeIds']
236
237                 #### DNS and IP MATCH #######################
238                 if values['hostname'] is not None and values['hostname'] is not "" and \
239                    values['ip'] is not None and values['ip'] is not "":
240                         #print "Calling socket.gethostbyname(%s)" % values['hostname']
241                         try:
242                                 ipaddr = socket.gethostbyname(values['hostname'])
243                                 if ipaddr == values['ip']:
244                                         values['dnsmatch'] = "DNS-OK"
245                                 else:
246                                         values['dnsmatch'] = "DNS-MISMATCH"
247                                         continue_probe = False
248
249                         except Exception, err:
250                                 values['dnsmatch'] = "DNS-NOENTRY"
251                                 values['hostname'] = values['ip']
252                                 #print err
253                 else:
254                         if values['ip'] is not None and values['ip'] is not "":
255                                 values['dnsmatch'] = "NOHOSTNAME"
256                                 values['hostname'] = values['ip']
257                         else:
258                                 values['dnsmatch'] = "NO-DNS-OR-IP"
259                                 values['hostname'] = "No_entry_in_DB"
260                                 continue_probe = False
261
262                 #### RUN NMAP ###############################
263                 if continue_probe:
264                         nmap = soltesz.CMD()
265                         (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % pcu_name(values))
266                         # NOTE: an empty / error value for oval, will still work.
267                         (values['portstatus'], continue_probe) = nmap_portstatus(oval)
268                 else:
269                         values['portstatus'] = None
270                         
271
272                 ######  DRY RUN  ############################
273                 if 'node_ids' in values and len(values['node_ids']) > 0:
274                         rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
275                 else:
276                         rb_ret = "Not_Run" # No nodes to test"
277
278                 values['reboot'] = rb_ret
279
280                 ### GET PLC SITE ######################
281                 v = get_plc_site_values(values['site_id'])
282                 if v is not None:
283                         values.update(v)
284                 else:
285                         values['plcsite'] = {'status' : "GS_FAILED"}
286                         
287         except:
288                 print "____________________________________"
289                 print values
290                 errors = values
291                 print "____________________________________"
292                 import traceback
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                 soltesz.dbDump(config.dbname, externalState)
314
315         if errors is not None:
316                 pcu_id = "id_%s" % nodename
317                 errorState[pcu_id] = errors
318                 soltesz.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         while 1:
357                 try:
358                         time.sleep(1)
359                         tp.poll()
360                 except KeyboardInterrupt:
361                         print "Interrupted!"
362                         break
363                 except threadpool.NoResultsPending:
364                         print "All results collected."
365                         break
366
367
368
369 def main():
370         global externalState
371
372         l_pcus = soltesz.if_cached_else_refresh(1, config.refresh, "pculist", lambda : plc.GetPCUs())
373         externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState) 
374         cohash = {}
375
376         if config.increment:
377                 # update global round number to force refreshes across all nodes
378                 externalState['round'] += 1
379
380         if config.filename == None and config.pcuid == None:
381                 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
382                 l_pcus  = [pcu['pcu_id'] for pcu in l_pcus]
383         elif config.filename is not None:
384                 l_pcus = config.getListFromFile(config.filename)
385                 l_pcus = [int(pcu) for pcu in l_pcus]
386         elif config.pcuid is not None:
387                 l_pcus = [ config.pcuid ] 
388                 l_pcus = [int(pcu) for pcu in l_pcus]
389
390         checkAndRecordState(l_pcus, cohash)
391
392         return 0
393
394
395 if __name__ == '__main__':
396         import logging
397         logger = logging.getLogger("monitor")
398         logger.setLevel(logging.DEBUG)
399         fh = logging.FileHandler("monitor.log", mode = 'a')
400         fh.setLevel(logging.DEBUG)
401         formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
402         fh.setFormatter(formatter)
403         logger.addHandler(fh)
404         from config import config
405         from optparse import OptionParser
406         parser = OptionParser()
407         parser.set_defaults(filename=None, 
408                                                 increment=False, 
409                                                 pcuid=None,
410                                                 dbname="findbadpcus", 
411                                                 cachenodes=False,
412                                                 refresh=False,
413                                                 )
414         parser.add_option("-f", "--nodelist", dest="filename", metavar="FILE", 
415                                                 help="Provide the input file for the node list")
416         parser.add_option("", "--pcuid", dest="pcuid", metavar="id", 
417                                                 help="Provide the id for a single pcu")
418         parser.add_option("", "--cachenodes", action="store_true",
419                                                 help="Cache node lookup from PLC")
420         parser.add_option("", "--dbname", dest="dbname", metavar="FILE", 
421                                                 help="Specify the name of the database to which the information is saved")
422         parser.add_option("", "--refresh", action="store_true", dest="refresh",
423                                                 help="Refresh the cached values")
424         parser.add_option("-i", "--increment", action="store_true", dest="increment", 
425                                                 help="Increment round number to force refresh or retry")
426         config = config(parser)
427         config.parse_args()
428         try:
429                 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
430                 # when LANG is set... Do not know why.  Unsetting LANG, fixes the problem.
431                 if 'LANG' in os.environ:
432                         del os.environ['LANG']
433                 main()
434                 time.sleep(1)
435         except Exception, err:
436                 import traceback
437                 traceback.print_exc()
438                 print "Exception: %s" % err
439                 print "Saving data... exitting."
440                 soltesz.dbDump(config.dbname, externalState)
441                 sys.exit(0)