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