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}}
64 from reboot import pcu_name
72 def nmap_portstatus(status):
74 l_nmap = status.split()
77 continue_probe = False
79 results = port.split('/')
80 ps[results[0]] = results[1]
81 if results[1] == "open":
83 return (ps, continue_probe)
85 def collectPingAndSSH(pcuname, cohash):
89 ### GET PCU ######################
95 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
98 node_ids = l_pcu[0]['node_ids']
99 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact', 'node_id'])
100 site_id = l_pcu[0]['site_id']
102 values['pcu_id'] = l_pcu[0]['pcu_id']
105 values['nodenames'] = [node['hostname'] for node in l_node]
106 # NOTE: this is for a dry run later. It doesn't matter which node.
107 values['node_id'] = l_node[0]['node_id']
110 values.update(l_pcu[0])
112 continue_probe = False
117 traceback.print_exc()
119 continue_probe = False
122 if b_except: return (None, None)
124 if values['hostname'] is not None:
125 values['hostname'] = values['hostname'].strip()
127 if values['ip'] is not None:
128 values['ip'] = values['ip'].strip()
130 #### COMPLETE ENTRY #######################
132 values['complete_entry'] = []
133 if values['protocol'] is None or values['protocol'] is "":
134 values['complete_entry'] += ["protocol"]
135 if values['model'] is None or values['model'] is "":
136 values['complete_entry'] += ["model"]
137 # Cannot continue due to this condition
138 continue_probe = False
140 if values['password'] is None or values['password'] is "":
141 values['complete_entry'] += ["password"]
142 # Cannot continue due to this condition
143 continue_probe = False
145 if len(values['complete_entry']) > 0:
146 continue_probe = False
148 if values['hostname'] is None or values['hostname'] is "":
149 values['complete_entry'] += ["hostname"]
150 if values['ip'] is None or values['ip'] is "":
151 values['complete_entry'] += ["ip"]
153 # If there are no nodes associated with this PCU, then we cannot continue.
154 if len(values['node_ids']) == 0:
155 continue_probe = False
156 values['complete_entry'] += ['NoNodeIds']
158 #### DNS and IP MATCH #######################
159 if values['hostname'] is not None and values['hostname'] is not "" and \
160 values['ip'] is not None and values['ip'] is not "":
161 #print "Calling socket.gethostbyname(%s)" % values['hostname']
163 ipaddr = socket.gethostbyname(values['hostname'])
164 if ipaddr == values['ip']:
165 values['dnsmatch'] = "DNS-OK"
167 values['dnsmatch'] = "DNS-MISMATCH"
168 continue_probe = False
170 except Exception, err:
171 values['dnsmatch'] = "DNS-NOENTRY"
172 values['hostname'] = values['ip']
175 if values['ip'] is not None and values['ip'] is not "":
176 values['dnsmatch'] = "NOHOSTNAME"
177 values['hostname'] = values['ip']
179 values['dnsmatch'] = "NO-DNS-OR-IP"
180 values['hostname'] = "No_entry_in_DB"
181 continue_probe = False
183 #### RUN NMAP ###############################
186 (oval,eval) = nmap.run_noexcept("nmap -oG - -p22,23,80,443,16992 %s | grep Host:" % pcu_name(values))
187 # NOTE: an empty / error value for oval, will still work.
188 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
190 ###### DRY RUN ############################
191 node_ids = values['node_ids']
192 ports = values['ports']
197 nid2port[id] = ports[i]
201 # TODO: check port status above for whether or not to try...
203 # DataProbe iPal (many sites)
204 if continue_probe and values['model'].find("Dataprobe IP-41x/IP-81x") >= 0:
205 if values['portstatus']['23'] == "open":
206 rb_ret = reboot.ipal_reboot(pcu_name(values),
208 nid2port[values['node_id']],
211 rb_ret = "Unsupported_Port"
214 # APC Masterswitch (Berkeley)
215 elif continue_probe and values['model'].find("APC AP79xx/Masterswitch") >= 0:
216 if values['portstatus']['22'] == "open" or \
217 values['portstatus']['23'] == "open":
218 rb_ret = reboot.apc_reboot(pcu_name(values),
221 nid2port[values['node_id']],
222 values['portstatus'],
225 rb_ret = "Unsupported_Port"
227 elif continue_probe and values['model'].find("Baytech DS4-RPC") >= 0:
228 if values['portstatus']['22'] == "open":
229 rb_ret = reboot.baytech_reboot(pcu_name(values),
232 nid2port[values['node_id']],
235 rb_ret = "Unsupported_Port"
239 elif continue_probe and values['model'].find("HP iLO") >= 0:
240 if values['portstatus']['22'] == "open":
241 rb_ret = reboot.ilo_reboot(pcu_name(values),
246 rb_ret = "Unsupported_Port"
249 elif continue_probe and values['model'].find("Dell RAC") >= 0:
250 if values['portstatus']['22'] == "open":
251 rb_ret = reboot.drac_reboot(pcu_name(values),
256 rb_ret = "Unsupported_Port"
259 # BlackBox PSExxx-xx (e.g. PSE505-FR)
260 elif continue_probe and \
261 (values['model'].find("BlackBox PS5xx") >= 0 or
262 values['model'].find("ePowerSwitch 1/4/8x") >=0 ):
263 if values['portstatus']['80'] == "open":
264 rb_ret = reboot.bbpse_reboot(pcu_name(values),
267 nid2port[values['node_id']],
271 rb_ret = "Unsupported_PCU"
274 elif continue_probe and values['protocol'] == "ssh" and \
275 values['model'] == "x10toggle":
276 rb_ret = reboot.x10toggle_reboot(pcu_name(values),
279 nid2port[values['node_id']],
282 elif continue_probe and values['protocol'] == "racadm" and \
283 values['model'] == "RAC":
284 rb_ret = reboot.racadm_reboot(pcu_name(values),
287 nid2port[values['node_id']],
290 rb_ret = "Unsupported_PCU"
292 elif continue_probe == False:
293 if 'portstatus' in values:
300 values['reboot'] = rb_ret
302 ### GET PLC SITE ######################
307 d_site = plc.getSites({'site_id': site_id},
308 ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
312 traceback.print_exc()
315 if b_except: return (None, None)
317 if d_site and len(d_site) > 0:
318 max_slices = d_site[0]['max_slices']
319 num_slices = len(d_site[0]['slice_ids'])
320 num_nodes = len(d_site[0]['node_ids'])
321 loginbase = d_site[0]['login_base']
322 values['plcsite'] = {'num_nodes' : num_nodes,
323 'max_slices' : max_slices,
324 'num_slices' : num_slices,
325 'login_base' : loginbase,
326 'status' : 'SUCCESS'}
328 values['plcsite'] = {'status' : "GS_FAILED"}
330 print "____________________________________"
332 print "____________________________________"
334 traceback.print_exc()
336 return (pcuname, values)
338 def recordPingAndSSH(request, result):
341 (nodename, values) = result
343 if values is not None:
344 global_round = externalState['round']
345 pcu_id = "id_%s" % nodename
346 externalState['nodes'][pcu_id]['values'] = values
347 externalState['nodes'][pcu_id]['round'] = global_round
350 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
351 soltesz.dbDump(config.dbname, externalState)
353 # this will be called when an exception occurs within a thread
354 def handle_exception(request, result):
355 print "Exception occured in request %s" % request.requestID
357 print "Result: %s" % i
360 def checkAndRecordState(l_pcus, cohash):
363 global_round = externalState['round']
365 tp = threadpool.ThreadPool(20)
367 # CREATE all the work requests
368 for pcuname in l_pcus:
369 pcu_id = "id_%s" % pcuname
370 if pcuname not in externalState['nodes']:
371 #print type(externalState['nodes'])
373 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
375 node_round = externalState['nodes'][pcu_id]['round']
376 if node_round < global_round:
377 # recreate node stats when refreshed
378 #print "%s" % nodename
379 req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {},
380 None, recordPingAndSSH, handle_exception)
383 # We just skip it, since it's "up to date"
385 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
388 # WAIT while all the work requests are processed.
393 except KeyboardInterrupt:
396 except threadpool.NoResultsPending:
397 print "All results collected."
405 externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState)
409 # update global round number to force refreshes across all nodes
410 externalState['round'] += 1
412 if config.filename == "":
413 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
414 l_pcus = soltesz.if_cached_else_refresh(1,
415 config.refresh, "pculist", lambda : plc.GetPCUs())
416 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
418 l_pcus = config.getListFromFile(config.filename)
419 l_pcus = [int(pcu) for pcu in l_pcus]
421 checkAndRecordState(l_pcus, cohash)
426 logger = logging.getLogger("monitor")
427 logger.setLevel(logging.DEBUG)
428 fh = logging.FileHandler("monitor.log", mode = 'a')
429 fh.setLevel(logging.DEBUG)
430 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
431 fh.setFormatter(formatter)
432 logger.addHandler(fh)
435 if __name__ == '__main__':
437 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
438 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
439 if 'LANG' in os.environ:
440 del os.environ['LANG']
443 except Exception, err:
444 print "Exception: %s" % err
445 print "Saving data... exitting."
446 soltesz.dbDump(config.dbname, externalState)