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