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
53 def nmap_portstatus(status):
55 l_nmap = status.split()
58 continue_probe = False
60 results = port.split('/')
61 ps[results[0]] = results[1]
62 if results[1] == "open":
64 return (ps, continue_probe)
69 print "GetPCU from PLC %s" % pcuname
70 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
76 print "GetPCU from file %s" % pcuname
77 l_pcus = soltesz.dbLoad("pculist")
79 if i['pcu_id'] == pcuname:
88 def get_nodes(node_ids):
92 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id', 'ports'])
95 plc_nodes = soltesz.dbLoad("l_plcnodes")
97 if n['node_id'] in node_ids:
100 traceback.print_exc()
109 def get_plc_pcu_values(pcuname):
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
117 l_pcu = get_pcu(pcuname)
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)
124 if l_node is not None:
126 values[node['hostname']] = node['ports'][0]
128 values['nodenames'] = [node['hostname'] for node in l_node]
130 # NOTE: this is for a dry run later. It doesn't matter which node.
131 values['node_id'] = l_node[0]['node_id']
139 def get_plc_site_values(site_id):
140 ### GET PLC SITE ######################
146 d_site = plc.getSites({'site_id': site_id}, ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
151 plc_sites = soltesz.dbLoad("l_plcsites")
152 for site in plc_sites:
153 if site['site_id'] == site_id:
157 traceback.print_exc()
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'}
179 def collectPingAndSSH(pcuname, cohash):
181 continue_probe = True
184 ### GET PCU ######################
188 v = get_plc_pcu_values(pcuname)
192 continue_probe = False
195 traceback.print_exc()
196 continue_probe = False
198 if b_except or not continue_probe: return (None, None, None)
200 if values['hostname'] is not None:
201 values['hostname'] = values['hostname'].strip()
203 if values['ip'] is not None:
204 values['ip'] = values['ip'].strip()
206 #### COMPLETE ENTRY #######################
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
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
221 if len(values['complete_entry']) > 0:
222 continue_probe = False
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"]
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']
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']
239 ipaddr = socket.gethostbyname(values['hostname'])
240 if ipaddr == values['ip']:
241 values['dnsmatch'] = "DNS-OK"
243 values['dnsmatch'] = "DNS-MISMATCH"
244 continue_probe = False
246 except Exception, err:
247 values['dnsmatch'] = "DNS-NOENTRY"
248 values['hostname'] = values['ip']
251 if values['ip'] is not None and values['ip'] is not "":
252 values['dnsmatch'] = "NOHOSTNAME"
253 values['hostname'] = values['ip']
255 values['dnsmatch'] = "NO-DNS-OR-IP"
256 values['hostname'] = "No_entry_in_DB"
257 continue_probe = False
259 #### RUN NMAP ###############################
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)
266 values['portstatus'] = None
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)
273 rb_ret = "Not_Run" # No nodes to test"
275 values['reboot'] = rb_ret
277 ### GET PLC SITE ######################
278 v = get_plc_site_values(values['site_id'])
282 values['plcsite'] = {'status' : "GS_FAILED"}
285 print "____________________________________"
288 print "____________________________________"
289 errors['traceback'] = traceback.format_exc()
290 print errors['traceback']
292 values['checked'] = time.time()
293 return (pcuname, values, errors)
295 def recordPingAndSSH(request, result):
299 (nodename, values, errors) = result
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
308 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
309 soltesz.dbDump(config.dbname, externalState)
311 if errors is not None:
312 pcu_id = "id_%s" % nodename
313 errorState[pcu_id] = errors
314 soltesz.dbDump("findbadpcu_errors", errorState)
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
320 print "Result: %s" % i
323 def checkAndRecordState(l_pcus, cohash):
326 global_round = externalState['round']
328 tp = threadpool.ThreadPool(20)
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'])
336 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
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)
346 # We just skip it, since it's "up to date"
348 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
351 # WAIT while all the work requests are processed.
356 except KeyboardInterrupt:
359 except threadpool.NoResultsPending:
360 print "All results collected."
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)
373 # update global round number to force refreshes across all nodes
374 externalState['round'] += 1
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]
386 checkAndRecordState(l_pcus, cohash)
391 if __name__ == '__main__':
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,
406 dbname="findbadpcus",
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)
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']
431 except Exception, err:
432 traceback.print_exc()
433 print "Exception: %s" % err
434 print "Saving data... exitting."
435 soltesz.dbDump(config.dbname, externalState)