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