16 #old_handler = signal.getsignal(signal.SIGCHLD)
18 #def sig_handler(signum, stack):
19 # """ Handle SIGCHLD signal """
21 # if signum == signal.SIGCHLD:
26 # if old_handler != signal.SIG_DFL:
27 # old_handler(signum, stack)
29 #orig_sig_handler = signal.signal(signal.SIGCHLD, sig_handler)
33 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
34 "table=table_nodeview&" + \
35 "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
38 #"select='lastcotop!=0'"
41 plc_lock = threading.Lock()
43 externalState = {'round': round, 'nodes': {'a': None}}
48 from reboot import pcu_name
57 def nmap_portstatus(status):
59 l_nmap = status.split()
62 continue_probe = False
64 results = port.split('/')
65 ps[results[0]] = results[1]
66 if results[1] == "open":
68 return (ps, continue_probe)
73 print "GetPCU from PLC %s" % pcuname
74 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
80 print "GetPCU from file %s" % pcuname
81 l_pcus = database.dbLoad("pculist")
83 if i['pcu_id'] == pcuname:
92 def get_nodes(node_ids):
96 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
99 plc_nodes = database.dbLoad("l_plcnodes")
101 if n['node_id'] in node_ids:
104 traceback.print_exc()
113 def get_plc_pcu_values(pcuname):
115 Try to contact PLC to get the PCU info.
116 If that fails, try a backup copy from the last run.
117 If that fails, return None
121 l_pcu = get_pcu(pcuname)
123 if l_pcu is not None:
124 site_id = l_pcu['site_id']
125 node_ids = l_pcu['node_ids']
126 l_node = get_nodes(node_ids)
128 if l_node is not None:
130 values[node['hostname']] = node['ports'][0]
132 values['nodenames'] = [node['hostname'] for node in l_node]
134 # NOTE: this is for a dry run later. It doesn't matter which node.
135 values['node_id'] = l_node[0]['node_id']
143 def get_plc_site_values(site_id):
144 ### GET PLC SITE ######################
150 d_site = plc.getSites({'site_id': site_id}, ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
155 plc_sites = database.dbLoad("l_plcsites")
156 for site in plc_sites:
157 if site['site_id'] == site_id:
161 traceback.print_exc()
166 if d_site is not None:
167 max_slices = d_site['max_slices']
168 num_slices = len(d_site['slice_ids'])
169 num_nodes = len(d_site['node_ids'])
170 loginbase = d_site['login_base']
171 values['plcsite'] = {'num_nodes' : num_nodes,
172 'max_slices' : max_slices,
173 'num_slices' : num_slices,
174 'login_base' : loginbase,
175 'status' : 'SUCCESS'}
183 def collectPingAndSSH(pcuname, cohash):
185 continue_probe = True
188 ### GET PCU ######################
192 v = get_plc_pcu_values(pcuname)
196 continue_probe = False
199 traceback.print_exc()
200 continue_probe = False
202 if b_except or not continue_probe: return (None, None, None)
204 if values['hostname'] is not None:
205 values['hostname'] = values['hostname'].strip()
207 if values['ip'] is not None:
208 values['ip'] = values['ip'].strip()
210 #### COMPLETE ENTRY #######################
212 values['complete_entry'] = []
213 #if values['protocol'] is None or values['protocol'] is "":
214 # values['complete_entry'] += ["protocol"]
215 if values['model'] is None or values['model'] is "":
216 values['complete_entry'] += ["model"]
217 # Cannot continue due to this condition
218 continue_probe = False
220 if values['password'] is None or values['password'] is "":
221 values['complete_entry'] += ["password"]
222 # Cannot continue due to this condition
223 continue_probe = False
225 if len(values['complete_entry']) > 0:
226 continue_probe = False
228 if values['hostname'] is None or values['hostname'] is "":
229 values['complete_entry'] += ["hostname"]
230 if values['ip'] is None or values['ip'] is "":
231 values['complete_entry'] += ["ip"]
233 # If there are no nodes associated with this PCU, then we cannot continue.
234 if len(values['node_ids']) == 0:
235 continue_probe = False
236 values['complete_entry'] += ['NoNodeIds']
238 #### DNS and IP MATCH #######################
239 if values['hostname'] is not None and values['hostname'] is not "" and \
240 values['ip'] is not None and values['ip'] is not "":
241 #print "Calling socket.gethostbyname(%s)" % values['hostname']
243 ipaddr = socket.gethostbyname(values['hostname'])
244 if ipaddr == values['ip']:
245 values['dnsmatch'] = "DNS-OK"
247 values['dnsmatch'] = "DNS-MISMATCH"
248 continue_probe = False
250 except Exception, err:
251 values['dnsmatch'] = "DNS-NOENTRY"
252 values['hostname'] = values['ip']
255 if values['ip'] is not None and values['ip'] is not "":
256 values['dnsmatch'] = "NOHOSTNAME"
257 values['hostname'] = values['ip']
259 values['dnsmatch'] = "NO-DNS-OR-IP"
260 values['hostname'] = "No_entry_in_DB"
261 continue_probe = False
263 #### RUN NMAP ###############################
265 nmap = moncommands.CMD()
266 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % pcu_name(values))
267 # NOTE: an empty / error value for oval, will still work.
268 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
270 values['portstatus'] = None
273 ###### DRY RUN ############################
274 if 'node_ids' in values and len(values['node_ids']) > 0:
275 rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
277 rb_ret = "Not_Run" # No nodes to test"
279 values['reboot'] = rb_ret
281 ### GET PLC SITE ######################
282 v = get_plc_site_values(values['site_id'])
286 values['plcsite'] = {'status' : "GS_FAILED"}
289 print "____________________________________"
292 print "____________________________________"
293 errors['traceback'] = traceback.format_exc()
294 print errors['traceback']
296 values['checked'] = time.time()
297 return (pcuname, values, errors)
299 def recordPingAndSSH(request, result):
303 (nodename, values, errors) = result
305 if values is not None:
306 global_round = externalState['round']
307 pcu_id = "id_%s" % nodename
308 externalState['nodes'][pcu_id]['values'] = values
309 externalState['nodes'][pcu_id]['round'] = global_round
312 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
313 database.dbDump(config.dbname, externalState)
315 if errors is not None:
316 pcu_id = "id_%s" % nodename
317 errorState[pcu_id] = errors
318 database.dbDump("findbadpcu_errors", errorState)
320 # this will be called when an exception occurs within a thread
321 def handle_exception(request, result):
322 print "Exception occured in request %s" % request.requestID
324 print "Result: %s" % i
327 def checkAndRecordState(l_pcus, cohash):
330 global_round = externalState['round']
332 tp = threadpool.ThreadPool(20)
334 # CREATE all the work requests
335 for pcuname in l_pcus:
336 pcu_id = "id_%s" % pcuname
337 if pcuname not in externalState['nodes']:
338 #print type(externalState['nodes'])
340 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
342 node_round = externalState['nodes'][pcu_id]['round']
343 if node_round < global_round:
344 # recreate node stats when refreshed
345 #print "%s" % nodename
346 req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {},
347 None, recordPingAndSSH, handle_exception)
350 # We just skip it, since it's "up to date"
352 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
355 # WAIT while all the work requests are processed.
361 # if more than two hours
362 if time.time() - begin > (60*60*1):
363 print "findbadpcus.py has run out of time!!!!!!"
364 database.dbDump(config.dbname, externalState)
366 except KeyboardInterrupt:
369 except threadpool.NoResultsPending:
370 print "All results collected."
378 l_pcus = database.if_cached_else_refresh(1, config.refresh, "pculist", lambda : plc.GetPCUs())
379 externalState = database.if_cached_else(1, config.dbname, lambda : externalState)
383 # update global round number to force refreshes across all nodes
384 externalState['round'] += 1
386 if config.site is not None:
387 api = plc.getAuthAPI()
388 site = api.GetSites(config.site)
389 l_nodes = api.GetNodes(site[0]['node_ids'], ['pcu_ids'])
392 pcus += node['pcu_ids']
393 l_pcus = [pcu for pcu in sets.Set(pcus)]
395 elif config.nodelist == None and config.pcuid == None:
396 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
397 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
398 elif config.nodelist is not None:
399 l_pcus = util.file.getListFromFile(config.nodelist)
400 l_pcus = [int(pcu) for pcu in l_pcus]
401 elif config.pcuid is not None:
402 l_pcus = [ config.pcuid ]
403 l_pcus = [int(pcu) for pcu in l_pcus]
405 checkAndRecordState(l_pcus, cohash)
410 if __name__ == '__main__':
412 logger = logging.getLogger("monitor")
413 logger.setLevel(logging.DEBUG)
414 fh = logging.FileHandler("monitor.log", mode = 'a')
415 fh.setLevel(logging.DEBUG)
416 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
417 fh.setFormatter(formatter)
418 logger.addHandler(fh)
419 import parser as parsermodule
420 parser = parsermodule.getParser()
421 parser.set_defaults(nodelist=None,
425 dbname="findbadpcus",
429 parser.add_option("-f", "--nodelist", dest="nodelist", metavar="FILE",
430 help="Provide the input file for the node list")
431 parser.add_option("", "--site", dest="site", metavar="FILE",
432 help="Get all pcus associated with the given site's nodes")
433 parser.add_option("", "--pcuid", dest="pcuid", metavar="id",
434 help="Provide the id for a single pcu")
436 parser.add_option("", "--cachenodes", action="store_true",
437 help="Cache node lookup from PLC")
438 parser.add_option("", "--dbname", dest="dbname", metavar="FILE",
439 help="Specify the name of the database to which the information is saved")
440 parser.add_option("", "--refresh", action="store_true", dest="refresh",
441 help="Refresh the cached values")
442 parser.add_option("-i", "--increment", action="store_true", dest="increment",
443 help="Increment round number to force refresh or retry")
444 parser = parsermodule.getParser(['defaults'], parser)
445 config = parsermodule.parse_args(parser)
447 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
448 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
449 if 'LANG' in os.environ:
450 del os.environ['LANG']
453 except Exception, err:
454 traceback.print_exc()
455 print "Exception: %s" % err
456 print "Saving data... exitting."
457 database.dbDump(config.dbname, externalState)