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)
27 from config import config
28 from optparse import OptionParser
29 parser = OptionParser()
30 parser.set_defaults(filename="",
36 parser.add_option("-f", "--nodelist", dest="filename", metavar="FILE",
37 help="Provide the input file for the node list")
38 parser.add_option("", "--cachenodes", action="store_true",
39 help="Cache node lookup from PLC")
40 parser.add_option("", "--dbname", dest="dbname", metavar="FILE",
41 help="Specify the name of the database to which the information is saved")
42 parser.add_option("", "--refresh", action="store_true", dest="refresh",
43 help="Refresh the cached values")
44 parser.add_option("-i", "--increment", action="store_true", dest="increment",
45 help="Increment round number to force refresh or retry")
46 config = config(parser)
50 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
51 "table=table_nodeview&" + \
52 "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
55 #"select='lastcotop!=0'"
58 plc_lock = threading.Lock()
60 externalState = {'round': round, 'nodes': {'a': None}}
72 if pcu['hostname'] is not None and pcu['hostname'] is not "":
73 return pcu['hostname']
74 elif pcu['ip'] is not None and pcu['ip'] is not "":
79 def nmap_portstatus(status):
81 l_nmap = status.split()
84 continue_probe = False
86 results = port.split('/')
87 ps[results[0]] = results[1]
88 if results[1] == "open":
90 return (ps, continue_probe)
92 def collectPingAndSSH(pcuname, cohash):
96 ### GET PCU ######################
102 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
105 node_ids = l_pcu[0]['node_ids']
106 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id'])
107 site_id = l_pcu[0]['site_id']
109 values['pcu_id'] = l_pcu[0]['pcu_id']
112 values['nodenames'] = [node['hostname'] for node in l_node]
113 # NOTE: this is for a dry run later. It doesn't matter which node.
114 values['node_id'] = l_node[0]['node_id']
117 values.update(l_pcu[0])
119 continue_probe = False
124 traceback.print_exc()
126 continue_probe = False
129 if b_except: return (None, None)
131 if values['hostname'] is not None:
132 values['hostname'] = values['hostname'].strip()
134 if values['ip'] is not None:
135 values['ip'] = values['ip'].strip()
137 #### COMPLETE ENTRY #######################
139 values['complete_entry'] = []
140 if values['protocol'] is None or values['protocol'] is "":
141 values['complete_entry'] += ["protocol"]
142 if values['model'] is None or values['model'] is "":
143 values['complete_entry'] += ["model"]
144 # Cannot continue due to this condition
145 continue_probe = False
147 if values['password'] is None or values['password'] is "":
148 values['complete_entry'] += ["password"]
149 # Cannot continue due to this condition
150 continue_probe = False
152 if len(values['complete_entry']) > 0:
153 continue_probe = False
155 if values['hostname'] is None or values['hostname'] is "":
156 values['complete_entry'] += ["hostname"]
157 if values['ip'] is None or values['ip'] is "":
158 values['complete_entry'] += ["ip"]
160 # If there are no nodes associated with this PCU, then we cannot continue.
161 if len(values['node_ids']) == 0:
162 continue_probe = False
163 values['complete_entry'] += ['NoNodeIds']
165 #### DNS and IP MATCH #######################
166 if values['hostname'] is not None and values['hostname'] is not "" and \
167 values['ip'] is not None and values['ip'] is not "":
168 #print "Calling socket.gethostbyname(%s)" % values['hostname']
170 ipaddr = socket.gethostbyname(values['hostname'])
171 if ipaddr == values['ip']:
172 values['dnsmatch'] = "DNS-OK"
174 values['dnsmatch'] = "DNS-MISMATCH"
175 continue_probe = False
177 except Exception, err:
178 values['dnsmatch'] = "DNS-NOENTRY"
179 values['hostname'] = values['ip']
182 if values['ip'] is not None and values['ip'] is not "":
183 values['dnsmatch'] = "NOHOSTNAME"
184 values['hostname'] = values['ip']
186 values['dnsmatch'] = "NO-DNS-OR-IP"
187 values['hostname'] = "No_entry_in_DB"
188 continue_probe = False
190 #### RUN NMAP ###############################
193 (oval,eval) = nmap.run_noexcept("nmap -oG - -p22,23,80,443,16992 %s | grep Host:" % pcu_name(values))
194 # NOTE: an empty / error value for oval, will still work.
195 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
197 ###### DRY RUN ############################
198 node_ids = values['node_ids']
199 ports = values['ports']
204 nid2port[id] = ports[i]
208 # TODO: check port status above for whether or not to try...
210 # DataProbe iPal (many sites)
211 if continue_probe and values['model'].find("Dataprobe IP-41x/IP-81x") >= 0:
212 if values['portstatus']['23'] == "open":
213 rb_ret = reboot.ipal_reboot(pcu_name(values),
215 nid2port[values['node_id']],
218 rb_ret = "Unsupported_Port"
221 # APC Masterswitch (Berkeley)
222 elif continue_probe and values['model'].find("APC AP79xx/Masterswitch") >= 0:
223 if values['portstatus']['22'] == "open" or \
224 values['portstatus']['23'] == "open":
225 rb_ret = reboot.apc_reboot(pcu_name(values),
228 nid2port[values['node_id']],
229 values['portstatus'],
232 rb_ret = "Unsupported_Port"
234 elif continue_probe and values['model'].find("Baytech DS4-RPC") >= 0:
235 if values['portstatus']['22'] == "open":
236 rb_ret = reboot.baytech_reboot(pcu_name(values),
239 nid2port[values['node_id']],
242 rb_ret = "Unsupported_Port"
246 elif continue_probe and values['model'].find("HP iLO") >= 0:
247 if values['portstatus']['22'] == "open":
248 rb_ret = reboot.ilo_reboot(pcu_name(values),
253 rb_ret = "Unsupported_Port"
256 elif continue_probe and values['model'].find("Dell RAC") >= 0:
257 if values['portstatus']['22'] == "open":
258 rb_ret = reboot.drac_reboot(pcu_name(values),
263 rb_ret = "Unsupported_Port"
266 # BlackBox PSExxx-xx (e.g. PSE505-FR)
267 elif continue_probe and \
268 (values['model'].find("BlackBox PS5xx") >= 0 or
269 values['model'].find("ePowerSwitch 1/4/8x") >=0 ):
270 if values['portstatus']['80'] == "open":
271 rb_ret = reboot.bbpse_reboot(pcu_name(values),
274 nid2port[values['node_id']],
278 rb_ret = "Unsupported_PCU"
281 elif continue_probe and values['protocol'] == "ssh" and \
282 values['model'] == "x10toggle":
283 rb_ret = reboot.x10toggle_reboot(pcu_name(values),
286 nid2port[values['node_id']],
289 elif continue_probe and values['protocol'] == "racadm" and \
290 values['model'] == "RAC":
291 rb_ret = reboot.racadm_reboot(pcu_name(values),
294 nid2port[values['node_id']],
297 rb_ret = "Unsupported_PCU"
299 elif continue_probe == False:
300 if 'portstatus' in values:
307 values['reboot'] = rb_ret
309 ### GET PLC SITE ######################
314 d_site = plc.getSites({'site_id': site_id},
315 ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
319 traceback.print_exc()
322 if b_except: return (None, None)
324 if d_site and len(d_site) > 0:
325 max_slices = d_site[0]['max_slices']
326 num_slices = len(d_site[0]['slice_ids'])
327 num_nodes = len(d_site[0]['node_ids'])
328 loginbase = d_site[0]['login_base']
329 values['plcsite'] = {'num_nodes' : num_nodes,
330 'max_slices' : max_slices,
331 'num_slices' : num_slices,
332 'login_base' : loginbase,
333 'status' : 'SUCCESS'}
335 values['plcsite'] = {'status' : "GS_FAILED"}
337 print "____________________________________"
339 print "____________________________________"
341 traceback.print_exc()
343 return (pcuname, values)
345 def recordPingAndSSH(request, result):
348 (nodename, values) = result
350 if values is not None:
351 global_round = externalState['round']
352 pcu_id = "id_%s" % nodename
353 externalState['nodes'][pcu_id]['values'] = values
354 externalState['nodes'][pcu_id]['round'] = global_round
357 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
358 soltesz.dbDump(config.dbname, externalState, 'php')
360 # this will be called when an exception occurs within a thread
361 def handle_exception(request, result):
362 print "Exception occured in request %s" % request.requestID
364 print "Result: %s" % i
367 def checkAndRecordState(l_pcus, cohash):
370 global_round = externalState['round']
372 tp = threadpool.ThreadPool(20)
374 # CREATE all the work requests
375 for pcuname in l_pcus:
376 pcu_id = "id_%s" % pcuname
377 if pcuname not in externalState['nodes']:
378 #print type(externalState['nodes'])
380 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
382 node_round = externalState['nodes'][pcu_id]['round']
383 if node_round < global_round:
384 # recreate node stats when refreshed
385 #print "%s" % nodename
386 req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {},
387 None, recordPingAndSSH, handle_exception)
390 # We just skip it, since it's "up to date"
392 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
395 # WAIT while all the work requests are processed.
400 except KeyboardInterrupt:
403 except threadpool.NoResultsPending:
404 print "All results collected."
412 externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState, 'php')
416 # update global round number to force refreshes across all nodes
417 externalState['round'] += 1
419 if config.filename == "":
420 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
421 l_pcus = soltesz.if_cached_else_refresh(1,
422 config.refresh, "pculist", lambda : plc.GetPCUs(), 'php')
423 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
425 l_pcus = config.getListFromFile(config.filename)
426 l_pcus = [int(pcu) for pcu in l_pcus]
428 checkAndRecordState(l_pcus, cohash)
433 logger = logging.getLogger("monitor")
434 logger.setLevel(logging.DEBUG)
435 fh = logging.FileHandler("monitor.log", mode = 'a')
436 fh.setLevel(logging.DEBUG)
437 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
438 fh.setFormatter(formatter)
439 logger.addHandler(fh)
442 if __name__ == '__main__':
444 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
445 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
446 if 'LANG' in os.environ:
447 del os.environ['LANG']
450 except Exception, err:
451 print "Exception: %s" % err
452 print "Saving data... exitting."
453 soltesz.dbDump(config.dbname, externalState, 'php')