Updated findbadpcu.py with changes made in reboot.py. Simpler interface and
[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 errorState = {}
62 count = 0
63
64 import reboot
65 from reboot import pcu_name
66
67 import soltesz
68 import plc
69 import comon
70 import threadpool
71 import syncplcdb
72
73 def nmap_portstatus(status):
74         ps = {}
75         l_nmap = status.split()
76         ports = l_nmap[4:]
77
78         continue_probe = False
79         for port in ports:
80                 results = port.split('/')
81                 ps[results[0]] = results[1]
82                 if results[1] == "open":
83                         continue_probe = True
84         return (ps, continue_probe)
85
86 def collectPingAndSSH(pcuname, cohash):
87
88         continue_probe = True
89         errors = None
90         values = {}
91         ### GET PCU ######################
92         try:
93                 b_except = False
94                 plc_lock.acquire()
95
96                 try:
97                         l_pcu  = plc.GetPCUs({'pcu_id' : pcuname})
98                         
99                         if len(l_pcu) > 0:
100                                 site_id = l_pcu[0]['site_id']
101
102                                 node_ids = l_pcu[0]['node_ids']
103                                 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 
104                                                                                                  'node_id', 'ports'])
105                         if len(l_node) > 0:
106                                 for node in l_node:
107                                         values[node['hostname']] = node['ports'][0]
108
109                                 values['nodenames'] = [node['hostname'] for node in l_node]
110                                 # NOTE: this is for a dry run later. It doesn't matter which node.
111                                 values['node_id'] = l_node[0]['node_id']
112
113                         if len(l_pcu) > 0:
114                                 values.update(l_pcu[0])
115                         else:
116                                 continue_probe = False
117
118                 except:
119                         b_except = True
120                         import traceback
121                         traceback.print_exc()
122
123                         continue_probe = False
124
125                 plc_lock.release()
126                 if b_except: return (None, None)
127
128                 if values['hostname'] is not None:
129                         values['hostname'] = values['hostname'].strip()
130
131                 if values['ip'] is not None:
132                         values['ip'] = values['ip'].strip()
133
134                 #### COMPLETE ENTRY   #######################
135
136                 values['complete_entry'] = []
137                 #if values['protocol'] is None or values['protocol'] is "":
138                 #       values['complete_entry'] += ["protocol"]
139                 if values['model'] is None or values['model'] is "":
140                         values['complete_entry'] += ["model"]
141                         # Cannot continue due to this condition
142                         continue_probe = False
143
144                 if values['password'] is None or values['password'] is "":
145                         values['complete_entry'] += ["password"]
146                         # Cannot continue due to this condition
147                         continue_probe = False
148
149                 if len(values['complete_entry']) > 0:
150                         continue_probe = False
151
152                 if values['hostname'] is None or values['hostname'] is "":
153                         values['complete_entry'] += ["hostname"]
154                 if values['ip'] is None or values['ip'] is "":
155                         values['complete_entry'] += ["ip"]
156
157                 # If there are no nodes associated with this PCU, then we cannot continue.
158                 if len(values['node_ids']) == 0:
159                         continue_probe = False
160                         values['complete_entry'] += ['NoNodeIds']
161
162                 #### DNS and IP MATCH #######################
163                 if values['hostname'] is not None and values['hostname'] is not "" and \
164                    values['ip'] is not None and values['ip'] is not "":
165                         #print "Calling socket.gethostbyname(%s)" % values['hostname']
166                         try:
167                                 ipaddr = socket.gethostbyname(values['hostname'])
168                                 if ipaddr == values['ip']:
169                                         values['dnsmatch'] = "DNS-OK"
170                                 else:
171                                         values['dnsmatch'] = "DNS-MISMATCH"
172                                         continue_probe = False
173
174                         except Exception, err:
175                                 values['dnsmatch'] = "DNS-NOENTRY"
176                                 values['hostname'] = values['ip']
177                                 #print err
178                 else:
179                         if values['ip'] is not None and values['ip'] is not "":
180                                 values['dnsmatch'] = "NOHOSTNAME"
181                                 values['hostname'] = values['ip']
182                         else:
183                                 values['dnsmatch'] = "NO-DNS-OR-IP"
184                                 values['hostname'] = "No_entry_in_DB"
185                                 continue_probe = False
186
187                 #### RUN NMAP ###############################
188                 if continue_probe:
189                         nmap = soltesz.CMD()
190                         (oval,eval) = nmap.run_noexcept("nmap -oG - -p22,23,80,443,5869,16992 %s | grep Host:" % pcu_name(values))
191                         # NOTE: an empty / error value for oval, will still work.
192                         (values['portstatus'], continue_probe) = nmap_portstatus(oval)
193
194                 ######  DRY RUN  ############################
195                 if 'node_ids' in values and len(values['node_ids']) > 0:
196                         rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
197                 else:
198                         rb_ret = "Not_Run" # No nodes to test"
199
200                 values['reboot'] = rb_ret
201
202                 ### GET PLC SITE ######################
203                 b_except = False
204                 plc_lock.acquire()
205
206                 try:
207                         d_site = plc.getSites({'site_id': site_id}, 
208                                                                 ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
209                 except:
210                         b_except = True
211                         import traceback
212                         traceback.print_exc()
213
214                 plc_lock.release()
215                 if b_except: return (None, None)
216
217                 if d_site and len(d_site) > 0:
218                         max_slices = d_site[0]['max_slices']
219                         num_slices = len(d_site[0]['slice_ids'])
220                         num_nodes = len(d_site[0]['node_ids'])
221                         loginbase = d_site[0]['login_base']
222                         values['plcsite'] = {'num_nodes' : num_nodes, 
223                                                                 'max_slices' : max_slices, 
224                                                                 'num_slices' : num_slices,
225                                                                 'login_base' : loginbase,
226                                                                 'status'     : 'SUCCESS'}
227                 else:
228                         values['plcsite'] = {'status' : "GS_FAILED"}
229         except:
230                 print "____________________________________"
231                 print values
232                 errors = values
233                 print "____________________________________"
234                 import traceback
235                 errors['traceback'] = traceback.format_exc()
236                 print errors['traceback']
237
238         return (pcuname, values, errors)
239
240 def recordPingAndSSH(request, result):
241         global errorState
242         global externalState
243         global count
244         (nodename, values, errors) = result
245
246         if values is not None:
247                 global_round = externalState['round']
248                 pcu_id = "id_%s" % nodename
249                 externalState['nodes'][pcu_id]['values'] = values
250                 externalState['nodes'][pcu_id]['round'] = global_round
251
252                 count += 1
253                 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
254                 soltesz.dbDump(config.dbname, externalState)
255
256         if errors is not None:
257                 pcu_id = "id_%s" % nodename
258                 errorState[pcu_id] = errors
259                 soltesz.dbDump("findbadpcu_errors", errorState)
260
261 # this will be called when an exception occurs within a thread
262 def handle_exception(request, result):
263         print "Exception occured in request %s" % request.requestID
264         for i in result:
265                 print "Result: %s" % i
266
267
268 def checkAndRecordState(l_pcus, cohash):
269         global externalState
270         global count
271         global_round = externalState['round']
272
273         tp = threadpool.ThreadPool(20)
274
275         # CREATE all the work requests
276         for pcuname in l_pcus:
277                 pcu_id = "id_%s" % pcuname
278                 if pcuname not in externalState['nodes']:
279                         #print type(externalState['nodes'])
280
281                         externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
282
283                 node_round   = externalState['nodes'][pcu_id]['round']
284                 if node_round < global_round:
285                         # recreate node stats when refreshed
286                         #print "%s" % nodename
287                         req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {}, 
288                                                                                  None, recordPingAndSSH, handle_exception)
289                         tp.putRequest(req)
290                 else:
291                         # We just skip it, since it's "up to date"
292                         count += 1
293                         print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
294                         pass
295
296         # WAIT while all the work requests are processed.
297         while 1:
298                 try:
299                         time.sleep(1)
300                         tp.poll()
301                 except KeyboardInterrupt:
302                         print "Interrupted!"
303                         break
304                 except threadpool.NoResultsPending:
305                         print "All results collected."
306                         break
307
308
309
310 def main():
311         global externalState
312
313         externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState) 
314         cohash = {}
315
316         if config.increment:
317                 # update global round number to force refreshes across all nodes
318                 externalState['round'] += 1
319
320         if config.filename == "":
321                 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
322                 l_pcus = soltesz.if_cached_else_refresh(1, 
323                                                                 config.refresh, "pculist", lambda : plc.GetPCUs())
324                 l_pcus  = [pcu['pcu_id'] for pcu in l_pcus]
325         else:
326                 l_pcus = config.getListFromFile(config.filename)
327                 l_pcus = [int(pcu) for pcu in l_pcus]
328
329         checkAndRecordState(l_pcus, cohash)
330
331         return 0
332
333 import logging
334 logger = logging.getLogger("monitor")
335 logger.setLevel(logging.DEBUG)
336 fh = logging.FileHandler("monitor.log", mode = 'a')
337 fh.setLevel(logging.DEBUG)
338 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
339 fh.setFormatter(formatter)
340 logger.addHandler(fh)
341
342
343 if __name__ == '__main__':
344         try:
345                 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
346                 # when LANG is set... Do not know why.  Unsetting LANG, fixes the problem.
347                 if 'LANG' in os.environ:
348                         del os.environ['LANG']
349                 main()
350                 time.sleep(1)
351         except Exception, err:
352                 print "Exception: %s" % err
353                 print "Saving data... exitting."
354                 soltesz.dbDump(config.dbname, externalState)
355                 sys.exit(0)