13 #old_handler = signal.getsignal(signal.SIGCHLD)
15 #def sig_handler(signum, stack):
16 # """ Handle SIGCHLD signal """
18 # if signum == signal.SIGCHLD:
23 # if old_handler != signal.SIG_DFL:
24 # old_handler(signum, stack)
26 #orig_sig_handler = signal.signal(signal.SIGCHLD, sig_handler)
30 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
31 "table=table_nodeview&" + \
32 "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
35 #"select='lastcotop!=0'"
38 plc_lock = threading.Lock()
40 externalState = {'round': round, 'nodes': {'a': None}}
45 from reboot import pcu_name
54 def nmap_portstatus(status):
56 l_nmap = status.split()
59 continue_probe = False
61 results = port.split('/')
62 ps[results[0]] = results[1]
63 if results[1] == "open":
65 return (ps, continue_probe)
70 print "GetPCU from PLC %s" % pcuname
71 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
77 print "GetPCU from file %s" % pcuname
78 l_pcus = database.dbLoad("pculist")
80 if i['pcu_id'] == pcuname:
89 def get_nodes(node_ids):
93 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
96 plc_nodes = database.dbLoad("l_plcnodes")
98 if n['node_id'] in node_ids:
101 traceback.print_exc()
110 def get_plc_pcu_values(pcuname):
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
118 l_pcu = get_pcu(pcuname)
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)
125 if l_node is not None:
127 values[node['hostname']] = node['ports'][0]
129 values['nodenames'] = [node['hostname'] for node in l_node]
131 # NOTE: this is for a dry run later. It doesn't matter which node.
132 values['node_id'] = l_node[0]['node_id']
140 def get_plc_site_values(site_id):
141 ### GET PLC SITE ######################
147 d_site = plc.getSites({'site_id': site_id}, ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
152 plc_sites = database.dbLoad("l_plcsites")
153 for site in plc_sites:
154 if site['site_id'] == site_id:
158 traceback.print_exc()
163 if d_site is not None:
164 max_slices = d_site['max_slices']
165 num_slices = len(d_site['slice_ids'])
166 num_nodes = len(d_site['node_ids'])
167 loginbase = d_site['login_base']
168 values['plcsite'] = {'num_nodes' : num_nodes,
169 'max_slices' : max_slices,
170 'num_slices' : num_slices,
171 'login_base' : loginbase,
172 'status' : 'SUCCESS'}
180 def collectPingAndSSH(pcuname, cohash):
182 continue_probe = True
185 ### GET PCU ######################
189 v = get_plc_pcu_values(pcuname)
193 continue_probe = False
196 traceback.print_exc()
197 continue_probe = False
199 if b_except or not continue_probe: return (None, None, None)
201 if values['hostname'] is not None:
202 values['hostname'] = values['hostname'].strip()
204 if values['ip'] is not None:
205 values['ip'] = values['ip'].strip()
207 #### COMPLETE ENTRY #######################
209 values['complete_entry'] = []
210 #if values['protocol'] is None or values['protocol'] is "":
211 # values['complete_entry'] += ["protocol"]
212 if values['model'] is None or values['model'] is "":
213 values['complete_entry'] += ["model"]
214 # Cannot continue due to this condition
215 continue_probe = False
217 if values['password'] is None or values['password'] is "":
218 values['complete_entry'] += ["password"]
219 # Cannot continue due to this condition
220 continue_probe = False
222 if len(values['complete_entry']) > 0:
223 continue_probe = False
225 if values['hostname'] is None or values['hostname'] is "":
226 values['complete_entry'] += ["hostname"]
227 if values['ip'] is None or values['ip'] is "":
228 values['complete_entry'] += ["ip"]
230 # If there are no nodes associated with this PCU, then we cannot continue.
231 if len(values['node_ids']) == 0:
232 continue_probe = False
233 values['complete_entry'] += ['NoNodeIds']
235 #### DNS and IP MATCH #######################
236 if values['hostname'] is not None and values['hostname'] is not "" and \
237 values['ip'] is not None and values['ip'] is not "":
238 #print "Calling socket.gethostbyname(%s)" % values['hostname']
240 ipaddr = socket.gethostbyname(values['hostname'])
241 if ipaddr == values['ip']:
242 values['dnsmatch'] = "DNS-OK"
244 values['dnsmatch'] = "DNS-MISMATCH"
245 continue_probe = False
247 except Exception, err:
248 values['dnsmatch'] = "DNS-NOENTRY"
249 values['hostname'] = values['ip']
252 if values['ip'] is not None and values['ip'] is not "":
253 values['dnsmatch'] = "NOHOSTNAME"
254 values['hostname'] = values['ip']
256 values['dnsmatch'] = "NO-DNS-OR-IP"
257 values['hostname'] = "No_entry_in_DB"
258 continue_probe = False
260 #### RUN NMAP ###############################
262 nmap = moncommands.CMD()
263 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % pcu_name(values))
264 # NOTE: an empty / error value for oval, will still work.
265 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
267 values['portstatus'] = None
270 ###### DRY RUN ############################
271 if 'node_ids' in values and len(values['node_ids']) > 0:
272 rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
274 rb_ret = "Not_Run" # No nodes to test"
276 values['reboot'] = rb_ret
278 ### GET PLC SITE ######################
279 v = get_plc_site_values(values['site_id'])
283 values['plcsite'] = {'status' : "GS_FAILED"}
286 print "____________________________________"
289 print "____________________________________"
290 errors['traceback'] = traceback.format_exc()
291 print errors['traceback']
293 values['checked'] = time.time()
294 return (pcuname, values, errors)
296 def recordPingAndSSH(request, result):
300 (nodename, values, errors) = result
302 if values is not None:
303 global_round = externalState['round']
304 pcu_id = "id_%s" % nodename
305 externalState['nodes'][pcu_id]['values'] = values
306 externalState['nodes'][pcu_id]['round'] = global_round
309 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
310 database.dbDump(config.dbname, externalState)
312 if errors is not None:
313 pcu_id = "id_%s" % nodename
314 errorState[pcu_id] = errors
315 database.dbDump("findbadpcu_errors", errorState)
317 # this will be called when an exception occurs within a thread
318 def handle_exception(request, result):
319 print "Exception occured in request %s" % request.requestID
321 print "Result: %s" % i
324 def checkAndRecordState(l_pcus, cohash):
327 global_round = externalState['round']
329 tp = threadpool.ThreadPool(20)
331 # CREATE all the work requests
332 for pcuname in l_pcus:
333 pcu_id = "id_%s" % pcuname
334 if pcuname not in externalState['nodes']:
335 #print type(externalState['nodes'])
337 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
339 node_round = externalState['nodes'][pcu_id]['round']
340 if node_round < global_round:
341 # recreate node stats when refreshed
342 #print "%s" % nodename
343 req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {},
344 None, recordPingAndSSH, handle_exception)
347 # We just skip it, since it's "up to date"
349 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
352 # WAIT while all the work requests are processed.
358 # if more than two hours
359 if time.time() - begin > (60*60*1):
360 print "findbadpcus.py has run out of time!!!!!!"
361 database.dbDump(config.dbname, externalState)
363 except KeyboardInterrupt:
366 except threadpool.NoResultsPending:
367 print "All results collected."
375 l_pcus = database.if_cached_else_refresh(1, config.refresh, "pculist", lambda : plc.GetPCUs())
376 externalState = database.if_cached_else(1, config.dbname, lambda : externalState)
380 # update global round number to force refreshes across all nodes
381 externalState['round'] += 1
383 if config.nodelist == None and config.pcuid == None:
384 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
385 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
386 elif config.nodelist is not None:
387 l_pcus = config.getListFromFile(config.nodelist)
388 l_pcus = [int(pcu) for pcu in l_pcus]
389 elif config.pcuid is not None:
390 l_pcus = [ config.pcuid ]
391 l_pcus = [int(pcu) for pcu in l_pcus]
393 checkAndRecordState(l_pcus, cohash)
398 if __name__ == '__main__':
400 logger = logging.getLogger("monitor")
401 logger.setLevel(logging.DEBUG)
402 fh = logging.FileHandler("monitor.log", mode = 'a')
403 fh.setLevel(logging.DEBUG)
404 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
405 fh.setFormatter(formatter)
406 logger.addHandler(fh)
407 from config import config
408 from optparse import OptionParser
409 parser = OptionParser()
410 parser.set_defaults(nodelist=None,
413 dbname="findbadpcus",
417 parser.add_option("-f", "--nodelist", dest="nodelist", metavar="FILE",
418 help="Provide the input file for the node list")
419 parser.add_option("", "--pcuid", dest="pcuid", metavar="id",
420 help="Provide the id for a single pcu")
421 parser.add_option("", "--cachenodes", action="store_true",
422 help="Cache node lookup from PLC")
423 parser.add_option("", "--dbname", dest="dbname", metavar="FILE",
424 help="Specify the name of the database to which the information is saved")
425 parser.add_option("", "--refresh", action="store_true", dest="refresh",
426 help="Refresh the cached values")
427 parser.add_option("-i", "--increment", action="store_true", dest="increment",
428 help="Increment round number to force refresh or retry")
429 config = config(parser)
432 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
433 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
434 if 'LANG' in os.environ:
435 del os.environ['LANG']
438 except Exception, err:
439 traceback.print_exc()
440 print "Exception: %s" % err
441 print "Saving data... exitting."
442 database.dbDump(config.dbname, externalState)