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}}
65 from reboot import pcu_name
73 def nmap_portstatus(status):
75 l_nmap = status.split()
78 continue_probe = False
80 results = port.split('/')
81 ps[results[0]] = results[1]
82 if results[1] == "open":
84 return (ps, continue_probe)
86 def collectPingAndSSH(pcuname, cohash):
91 ### GET PCU ######################
97 l_pcu = plc.GetPCUs({'pcu_id' : pcuname})
100 site_id = l_pcu[0]['site_id']
102 node_ids = l_pcu[0]['node_ids']
103 l_node = plc.getNodes(node_ids, ['hostname', 'last_contact',
107 values[node['hostname']] = node['ports'][0]
109 values['nodenames'] = [node['hostname'] for node in l_node]
110 # NOTE: this is for a dry run later. It doesn't matter which node.
111 values['node_id'] = l_node[0]['node_id']
114 values.update(l_pcu[0])
116 continue_probe = False
121 traceback.print_exc()
123 continue_probe = False
126 if b_except: return (None, None)
128 if values['hostname'] is not None:
129 values['hostname'] = values['hostname'].strip()
131 if values['ip'] is not None:
132 values['ip'] = values['ip'].strip()
134 #### COMPLETE ENTRY #######################
136 values['complete_entry'] = []
137 #if values['protocol'] is None or values['protocol'] is "":
138 # values['complete_entry'] += ["protocol"]
139 if values['model'] is None or values['model'] is "":
140 values['complete_entry'] += ["model"]
141 # Cannot continue due to this condition
142 continue_probe = False
144 if values['password'] is None or values['password'] is "":
145 values['complete_entry'] += ["password"]
146 # Cannot continue due to this condition
147 continue_probe = False
149 if len(values['complete_entry']) > 0:
150 continue_probe = False
152 if values['hostname'] is None or values['hostname'] is "":
153 values['complete_entry'] += ["hostname"]
154 if values['ip'] is None or values['ip'] is "":
155 values['complete_entry'] += ["ip"]
157 # If there are no nodes associated with this PCU, then we cannot continue.
158 if len(values['node_ids']) == 0:
159 continue_probe = False
160 values['complete_entry'] += ['NoNodeIds']
162 #### DNS and IP MATCH #######################
163 if values['hostname'] is not None and values['hostname'] is not "" and \
164 values['ip'] is not None and values['ip'] is not "":
165 #print "Calling socket.gethostbyname(%s)" % values['hostname']
167 ipaddr = socket.gethostbyname(values['hostname'])
168 if ipaddr == values['ip']:
169 values['dnsmatch'] = "DNS-OK"
171 values['dnsmatch'] = "DNS-MISMATCH"
172 continue_probe = False
174 except Exception, err:
175 values['dnsmatch'] = "DNS-NOENTRY"
176 values['hostname'] = values['ip']
179 if values['ip'] is not None and values['ip'] is not "":
180 values['dnsmatch'] = "NOHOSTNAME"
181 values['hostname'] = values['ip']
183 values['dnsmatch'] = "NO-DNS-OR-IP"
184 values['hostname'] = "No_entry_in_DB"
185 continue_probe = False
187 #### RUN NMAP ###############################
190 (oval,eval) = nmap.run_noexcept("nmap -oG - -P0 -p22,23,80,443,5869,16992 %s | grep Host:" % pcu_name(values))
191 # NOTE: an empty / error value for oval, will still work.
192 (values['portstatus'], continue_probe) = nmap_portstatus(oval)
194 ###### DRY RUN ############################
195 if 'node_ids' in values and len(values['node_ids']) > 0:
196 rb_ret = reboot.reboot_test(values['nodenames'][0], values, continue_probe, 1, True)
198 rb_ret = "Not_Run" # No nodes to test"
200 values['reboot'] = rb_ret
202 ### GET PLC SITE ######################
207 d_site = plc.getSites({'site_id': site_id},
208 ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
212 traceback.print_exc()
215 if b_except: return (None, None)
217 if d_site and len(d_site) > 0:
218 max_slices = d_site[0]['max_slices']
219 num_slices = len(d_site[0]['slice_ids'])
220 num_nodes = len(d_site[0]['node_ids'])
221 loginbase = d_site[0]['login_base']
222 values['plcsite'] = {'num_nodes' : num_nodes,
223 'max_slices' : max_slices,
224 'num_slices' : num_slices,
225 'login_base' : loginbase,
226 'status' : 'SUCCESS'}
228 values['plcsite'] = {'status' : "GS_FAILED"}
230 print "____________________________________"
233 print "____________________________________"
235 errors['traceback'] = traceback.format_exc()
236 print errors['traceback']
238 values['checked'] = time.time()
239 return (pcuname, values, errors)
241 def recordPingAndSSH(request, result):
245 (nodename, values, errors) = result
247 if values is not None:
248 global_round = externalState['round']
249 pcu_id = "id_%s" % nodename
250 externalState['nodes'][pcu_id]['values'] = values
251 externalState['nodes'][pcu_id]['round'] = global_round
254 print "%d %s %s" % (count, nodename, externalState['nodes'][pcu_id]['values'])
255 soltesz.dbDump(config.dbname, externalState)
257 if errors is not None:
258 pcu_id = "id_%s" % nodename
259 errorState[pcu_id] = errors
260 soltesz.dbDump("findbadpcu_errors", errorState)
262 # this will be called when an exception occurs within a thread
263 def handle_exception(request, result):
264 print "Exception occured in request %s" % request.requestID
266 print "Result: %s" % i
269 def checkAndRecordState(l_pcus, cohash):
272 global_round = externalState['round']
274 tp = threadpool.ThreadPool(20)
276 # CREATE all the work requests
277 for pcuname in l_pcus:
278 pcu_id = "id_%s" % pcuname
279 if pcuname not in externalState['nodes']:
280 #print type(externalState['nodes'])
282 externalState['nodes'][pcu_id] = {'round': 0, 'values': []}
284 node_round = externalState['nodes'][pcu_id]['round']
285 if node_round < global_round:
286 # recreate node stats when refreshed
287 #print "%s" % nodename
288 req = threadpool.WorkRequest(collectPingAndSSH, [pcuname, cohash], {},
289 None, recordPingAndSSH, handle_exception)
292 # We just skip it, since it's "up to date"
294 print "%d %s %s" % (count, pcu_id, externalState['nodes'][pcu_id]['values'])
297 # WAIT while all the work requests are processed.
302 except KeyboardInterrupt:
305 except threadpool.NoResultsPending:
306 print "All results collected."
314 externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState)
318 # update global round number to force refreshes across all nodes
319 externalState['round'] += 1
321 if config.filename == "":
322 print "Calling API GetPCUs() : refresh(%s)" % config.refresh
323 l_pcus = soltesz.if_cached_else_refresh(1,
324 config.refresh, "pculist", lambda : plc.GetPCUs())
325 l_pcus = [pcu['pcu_id'] for pcu in l_pcus]
327 l_pcus = config.getListFromFile(config.filename)
328 l_pcus = [int(pcu) for pcu in l_pcus]
330 checkAndRecordState(l_pcus, cohash)
335 logger = logging.getLogger("monitor")
336 logger.setLevel(logging.DEBUG)
337 fh = logging.FileHandler("monitor.log", mode = 'a')
338 fh.setLevel(logging.DEBUG)
339 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
340 fh.setFormatter(formatter)
341 logger.addHandler(fh)
344 if __name__ == '__main__':
346 # NOTE: evidently, there is a bizarre interaction between iLO and ssh
347 # when LANG is set... Do not know why. Unsetting LANG, fixes the problem.
348 if 'LANG' in os.environ:
349 del os.environ['LANG']
352 except Exception, err:
353 print "Exception: %s" % err
354 print "Saving data... exitting."
355 soltesz.dbDump(config.dbname, externalState)