15 from nodequery import pcu_select
17 #old_handler = signal.getsignal(signal.SIGCHLD)
19 #def sig_handler(signum, stack):
20 # """ Handle SIGCHLD signal """
22 # if signum == signal.SIGCHLD:
27 # if old_handler != signal.SIG_DFL:
28 # old_handler(signum, stack)
30 #orig_sig_handler = signal.signal(signal.SIGCHLD, sig_handler)
34 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
35 "table=table_nodeview&" + \
36 "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
39 #"select='lastcotop!=0'"
42 plc_lock = threading.Lock()
44 externalState = {'round': round, 'nodes': {'a': None}}
49 from reboot import pcu_name
58 def nmap_portstatus(status):
60 l_nmap = status.split()
63 continue_probe = False
65 results = port.split('/')
66 ps[results[0]] = results[1]
67 if results[1] == "open":
69 return (ps, continue_probe)
74 print "GetPCU from PLC %s" % pcuname
75 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
81 print "GetPCU from file %s" % pcuname
82 l_pcus = database.dbLoad("pculist")
84 if i['pcu_id'] == pcuname:
93 def get_nodes(node_ids):
97 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
100 plc_nodes = database.dbLoad("l_plcnodes")
102 if n['node_id'] in node_ids:
105 traceback.print_exc()
114 def get_plc_pcu_values(pcuname):
116 Try to contact PLC to get the PCU info.
117 If that fails, try a backup copy from the last run.
118 If that fails, return None
122 l_pcu = get_pcu(pcuname)
124 if l_pcu is not None:
125 site_id = l_pcu['site_id']
126 node_ids = l_pcu['node_ids']
127 l_node = get_nodes(node_ids)
129 if l_node is not None:
131 values[node['hostname']] = node['ports'][0]
133 values['nodenames'] = [node['hostname'] for node in l_node]
135 # NOTE: this is for a dry run later. It doesn't matter which node.
136 values['node_id'] = l_node[0]['node_id']
144 def get_plc_site_values(site_id):
145 ### GET PLC SITE ######################
151 d_site = plc.getSites({'site_id': site_id}, ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
156 plc_sites = database.dbLoad("l_plcsites")
157 for site in plc_sites:
158 if site['site_id'] == site_id:
162 traceback.print_exc()
167 if d_site is not None:
168 max_slices = d_site['max_slices']
169 num_slices = len(d_site['slice_ids'])
170 num_nodes = len(d_site['node_ids'])
171 loginbase = d_site['login_base']
172 values['plcsite'] = {'num_nodes' : num_nodes,
173 'max_slices' : max_slices,
174 'num_slices' : num_slices,
175 'login_base' : loginbase,
176 'status' : 'SUCCESS'}
184 def collectPingAndSSH(pcuname, cohash):
186 continue_probe = True
189 ### GET PCU ######################
193 v = get_plc_pcu_values(pcuname)
197 continue_probe = False
200 traceback.print_exc()
201 continue_probe = False
203 if b_except or not continue_probe: return (None, None, None)
205 if values['hostname'] is not None:
206 values['hostname'] = values['hostname'].strip()
208 if values['ip'] is not None:
209 values['ip'] = values['ip'].strip()
211 #### COMPLETE ENTRY #######################
213 values['complete_entry'] = []
214 #if values['protocol'] is None or values['protocol'] is "":
215 # values['complete_entry'] += ["protocol"]
216 if values['model'] is None or values['model'] is "":
217 values['complete_entry'] += ["model"]
218 # Cannot continue due to this condition
219 continue_probe = False
221 if values['password'] is None or values['password'] is "":
222 values['complete_entry'] += ["password"]
223 # Cannot continue due to this condition
224 continue_probe = False
226 if len(values['complete_entry']) > 0:
227 continue_probe = False
229 if values['hostname'] is None or values['hostname'] is "":
230 values['complete_entry'] += ["hostname"]
231 if values['ip'] is None or values['ip'] is "":
232 values['complete_entry'] += ["ip"]
234 # If there are no nodes associated with this PCU, then we cannot continue.
235 if len(values['node_ids']) == 0:
236 continue_probe = False
237 values['complete_entry'] += ['NoNodeIds']
239 #### DNS and IP MATCH #######################
240 if values['hostname'] is not None and values['hostname'] is not "" and \
241 values['ip'] is not None and values['ip'] is not "":
242 #print "Calling socket.gethostbyname(%s)" % values['hostname']
244 ipaddr = socket.gethostbyname(values['hostname'])
245 if ipaddr == values['ip']:
246 values['dnsmatch'] = "DNS-OK"
248 values['dnsmatch'] = "DNS-MISMATCH"
249 continue_probe = False
251 except Exception, err:
252 values['dnsmatch'] = "DNS-NOENTRY"
253 values['hostname'] = values['ip']
256 if values['ip'] is not None and values['ip'] is not "":
257 values['dnsmatch'] = "NOHOSTNAME"
258 values['hostname'] = values['ip']
260 values['dnsmatch'] = "NO-DNS-OR-IP"
261 values['hostname'] = "No_entry_in_DB"
262 continue_probe = False
264 #### RUN NMAP ###############################
266 nmap = moncommands.CMD()
267 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % pcu_name(values))
268 # NOTE: an empty / error value for oval, will still work.
269 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
271 values['portstatus'] = None
274 ###### DRY RUN ############################
275 if 'node_ids' in values and len(values['node_ids']) > 0:
276 rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
278 rb_ret = "Not_Run" # No nodes to test"
280 values['reboot'] = rb_ret
282 ### GET PLC SITE ######################
283 v = get_plc_site_values(values['site_id'])
287 values['plcsite'] = {'status' : "GS_FAILED"}
290 print "____________________________________"
293 print "____________________________________"
294 errors['traceback'] = traceback.format_exc()
295 print errors['traceback']
297 values['checked'] = time.time()
298 return (pcuname, values, errors)
300 def recordPingAndSSH(request, result):
304 (nodename, values, errors) = result
306 if values is not None:
307 global_round = externalState['round']
308 pcu_id = "id_%s" % nodename
309 externalState['nodes'][pcu_id]['values'] = values
310 externalState['nodes'][pcu_id]['round'] = global_round
313 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
314 database.dbDump(config.dbname, externalState)
316 if errors is not None:
317 pcu_id = "id_%s" % nodename
318 errorState[pcu_id] = errors
319 database.dbDump("findbadpcu_errors", errorState)
321 # this will be called when an exception occurs within a thread
322 def handle_exception(request, result):
323 print "Exception occured in request %s" % request.requestID
325 print "Result: %s" % i
328 def checkAndRecordState(l_pcus, cohash):
331 global_round = externalState['round']
333 tp = threadpool.ThreadPool(10)
335 # CREATE all the work requests
336 for pcuname in l_pcus:
337 pcu_id = "id_%s" % pcuname
338 if pcuname not in externalState['nodes']:
339 #print type(externalState['nodes'])
341 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
343 node_round = externalState['nodes'][pcu_id]['round']
344 if node_round < global_round:
345 # recreate node stats when refreshed
346 #print "%s" % nodename
347 req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {},
348 None, recordPingAndSSH, handle_exception)
351 # We just skip it, since it's "up to date"
353 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
356 # WAIT while all the work requests are processed.
362 # if more than two hours
363 if time.time() - begin > (60*60*1):
364 print "findbadpcus.py has run out of time!!!!!!"
365 database.dbDump(config.dbname, externalState)
367 except KeyboardInterrupt:
370 except threadpool.NoResultsPending:
371 print "All results collected."
379 l_pcus = database.if_cached_else_refresh(1, config.refresh, "pculist", lambda : plc.GetPCUs())
380 externalState = database.if_cached_else(1, config.dbname, lambda : externalState)
384 # update global round number to force refreshes across all nodes
385 externalState['round'] += 1
387 if config.site is not None:
388 api = plc.getAuthAPI()
389 site = api.GetSites(config.site)
390 l_nodes = api.GetNodes(site[0]['node_ids'], ['pcu_ids'])
393 pcus += node['pcu_ids']
395 l_pcus = [pcu for pcu in sets.Set(pcus)]
396 elif config.pcuselect is not None:
397 n, pcus = pcu_select(config.pcuselect)
399 l_pcus = [pcu for pcu in sets.Set(pcus)]
401 elif config.nodelist == None and config.pcuid == None:
402 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
403 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
404 elif config.nodelist is not None:
405 l_pcus = util.file.getListFromFile(config.nodelist)
406 l_pcus = [int(pcu) for pcu in l_pcus]
407 elif config.pcuid is not None:
408 l_pcus = [ config.pcuid ]
409 l_pcus = [int(pcu) for pcu in l_pcus]
411 checkAndRecordState(l_pcus, cohash)
416 if __name__ == '__main__':
418 logger = logging.getLogger("monitor")
419 logger.setLevel(logging.DEBUG)
420 fh = logging.FileHandler("monitor.log", mode = 'a')
421 fh.setLevel(logging.DEBUG)
422 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
423 fh.setFormatter(formatter)
424 logger.addHandler(fh)
425 import parser as parsermodule
426 parser = parsermodule.getParser()
427 parser.set_defaults(nodelist=None,
432 dbname="findbadpcus",
436 parser.add_option("-f", "--nodelist", dest="nodelist", metavar="FILE",
437 help="Provide the input file for the node list")
438 parser.add_option("", "--site", dest="site", metavar="FILE",
439 help="Get all pcus associated with the given site's nodes")
440 parser.add_option("", "--pcuselect", dest="pcuselect", metavar="FILE",
441 help="Query string to apply to the findbad pcus")
442 parser.add_option("", "--pcuid", dest="pcuid", metavar="id",
443 help="Provide the id for a single pcu")
445 parser.add_option("", "--cachenodes", action="store_true",
446 help="Cache node lookup from PLC")
447 parser.add_option("", "--dbname", dest="dbname", metavar="FILE",
448 help="Specify the name of the database to which the information is saved")
449 parser.add_option("", "--refresh", action="store_true", dest="refresh",
450 help="Refresh the cached values")
451 parser.add_option("-i", "--increment", action="store_true", dest="increment",
452 help="Increment round number to force refresh or retry")
453 parser = parsermodule.getParser(['defaults'], parser)
454 config = parsermodule.parse_args(parser)
456 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
457 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
458 if 'LANG' in os.environ:
459 del os.environ['LANG']
462 except Exception, err:
463 traceback.print_exc()
464 print "Exception: %s" % err
465 print "Saving data... exitting."
466 database.dbDump(config.dbname, externalState)