12 #old_handler = signal.getsignal(signal.SIGCHLD)
14 #def sig_handler(signum, stack):
15 # """ Handle SIGCHLD signal """
17 # if signum == signal.SIGCHLD:
22 # if old_handler != signal.SIG_DFL:
23 # old_handler(signum, stack)
25 #orig_sig_handler = signal.signal(signal.SIGCHLD, sig_handler)
29 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
30 "table=table_nodeview&" + \
31 "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
34 #"select='lastcotop!=0'"
37 plc_lock = threading.Lock()
39 externalState = {'round': round, 'nodes': {'a': None}}
44 from reboot import pcu_name
52 def nmap_portstatus(status):
54 l_nmap = status.split()
57 continue_probe = False
59 results = port.split('/')
60 ps[results[0]] = results[1]
61 if results[1] == "open":
63 return (ps, continue_probe)
68 print "GetPCU from PLC %s" % pcuname
69 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
75 print "GetPCU from file %s" % pcuname
76 l_pcus = soltesz.dbLoad("pculist")
78 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:
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 = soltesz.dbLoad("l_plcsites")
153 for site in plc_sites:
154 if site['site_id'] == site_id:
159 traceback.print_exc()
164 if d_site is not None:
165 max_slices = d_site['max_slices']
166 num_slices = len(d_site['slice_ids'])
167 num_nodes = len(d_site['node_ids'])
168 loginbase = d_site['login_base']
169 values['plcsite'] = {'num_nodes' : num_nodes,
170 'max_slices' : max_slices,
171 'num_slices' : num_slices,
172 'login_base' : loginbase,
173 'status' : 'SUCCESS'}
181 def collectPingAndSSH(pcuname, cohash):
183 continue_probe = True
186 ### GET PCU ######################
190 v = get_plc_pcu_values(pcuname)
194 continue_probe = False
198 traceback.print_exc()
199 continue_probe = False
201 if b_except or not continue_probe: return (None, None, None)
203 if values['hostname'] is not None:
204 values['hostname'] = values['hostname'].strip()
206 if values['ip'] is not None:
207 values['ip'] = values['ip'].strip()
209 #### COMPLETE ENTRY #######################
211 values['complete_entry'] = []
212 #if values['protocol'] is None or values['protocol'] is "":
213 # values['complete_entry'] += ["protocol"]
214 if values['model'] is None or values['model'] is "":
215 values['complete_entry'] += ["model"]
216 # Cannot continue due to this condition
217 continue_probe = False
219 if values['password'] is None or values['password'] is "":
220 values['complete_entry'] += ["password"]
221 # Cannot continue due to this condition
222 continue_probe = False
224 if len(values['complete_entry']) > 0:
225 continue_probe = False
227 if values['hostname'] is None or values['hostname'] is "":
228 values['complete_entry'] += ["hostname"]
229 if values['ip'] is None or values['ip'] is "":
230 values['complete_entry'] += ["ip"]
232 # If there are no nodes associated with this PCU, then we cannot continue.
233 if len(values['node_ids']) == 0:
234 continue_probe = False
235 values['complete_entry'] += ['NoNodeIds']
237 #### DNS and IP MATCH #######################
238 if values['hostname'] is not None and values['hostname'] is not "" and \
239 values['ip'] is not None and values['ip'] is not "":
240 #print "Calling socket.gethostbyname(%s)" % values['hostname']
242 ipaddr = socket.gethostbyname(values['hostname'])
243 if ipaddr == values['ip']:
244 values['dnsmatch'] = "DNS-OK"
246 values['dnsmatch'] = "DNS-MISMATCH"
247 continue_probe = False
249 except Exception, err:
250 values['dnsmatch'] = "DNS-NOENTRY"
251 values['hostname'] = values['ip']
254 if values['ip'] is not None and values['ip'] is not "":
255 values['dnsmatch'] = "NOHOSTNAME"
256 values['hostname'] = values['ip']
258 values['dnsmatch'] = "NO-DNS-OR-IP"
259 values['hostname'] = "No_entry_in_DB"
260 continue_probe = False
262 #### RUN NMAP ###############################
265 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,9100,16992 %s | grep Host:" % pcu_name(values))
266 # NOTE: an empty / error value for oval, will still work.
267 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
269 values['portstatus'] = None
272 ###### DRY RUN ############################
273 if 'node_ids' in values and len(values['node_ids']) > 0:
274 rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
276 rb_ret = "Not_Run" # No nodes to test"
278 values['reboot'] = rb_ret
280 ### GET PLC SITE ######################
281 v = get_plc_site_values(values['site_id'])
285 values['plcsite'] = {'status' : "GS_FAILED"}
288 print "____________________________________"
291 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 soltesz.dbDump(config.dbname, externalState)
315 if errors is not None:
316 pcu_id = "id_%s" % nodename
317 errorState[pcu_id] = errors
318 soltesz.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.
360 except KeyboardInterrupt:
363 except threadpool.NoResultsPending:
364 print "All results collected."
372 l_pcus = soltesz.if_cached_else_refresh(1, config.refresh, "pculist", lambda : plc.GetPCUs())
373 externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState)
377 # update global round number to force refreshes across all nodes
378 externalState['round'] += 1
380 if config.filename == None and config.pcuid == None:
381 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
382 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
383 elif config.filename is not None:
384 l_pcus = config.getListFromFile(config.filename)
385 l_pcus = [int(pcu) for pcu in l_pcus]
386 elif config.pcuid is not None:
387 l_pcus = [ config.pcuid ]
388 l_pcus = [int(pcu) for pcu in l_pcus]
390 checkAndRecordState(l_pcus, cohash)
395 if __name__ == '__main__':
397 logger = logging.getLogger("monitor")
398 logger.setLevel(logging.DEBUG)
399 fh = logging.FileHandler("monitor.log", mode = 'a')
400 fh.setLevel(logging.DEBUG)
401 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
402 fh.setFormatter(formatter)
403 logger.addHandler(fh)
404 from config import config
405 from optparse import OptionParser
406 parser = OptionParser()
407 parser.set_defaults(filename=None,
410 dbname="findbadpcus",
414 parser.add_option("-f", "--nodelist", dest="filename", metavar="FILE",
415 help="Provide the input file for the node list")
416 parser.add_option("", "--pcuid", dest="pcuid", metavar="id",
417 help="Provide the id for a single pcu")
418 parser.add_option("", "--cachenodes", action="store_true",
419 help="Cache node lookup from PLC")
420 parser.add_option("", "--dbname", dest="dbname", metavar="FILE",
421 help="Specify the name of the database to which the information is saved")
422 parser.add_option("", "--refresh", action="store_true", dest="refresh",
423 help="Refresh the cached values")
424 parser.add_option("-i", "--increment", action="store_true", dest="increment",
425 help="Increment round number to force refresh or retry")
426 config = config(parser)
429 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
430 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
431 if 'LANG' in os.environ:
432 del os.environ['LANG']
435 except Exception, err:
437 traceback.print_exc()
438 print "Exception: %s" % err
439 print "Saving data... exitting."
440 soltesz.dbDump(config.dbname, externalState)