5 from monitor import database
6 from nodecommon import *
7 from unified_model import Record
16 from monitor.pcu import reboot
17 from monitor.wrapper import plc
18 api = plc.getAuthAPI()
20 from monitor.database import FindbadNodeRecord, FindbadNodeRecordSync
21 from monitor import util
22 from monitor import config
27 class NoKeyException(Exception): pass
29 def daysdown_print_nodeinfo(fbnode, hostname):
30 fbnode['hostname'] = hostname
31 fbnode['daysdown'] = Record.getStrDaysDown(fbnode)
32 fbnode['intdaysdown'] = Record.getDaysDown(fbnode)
34 print "%(intdaysdown)5s %(hostname)-44s | %(state)10.10s | %(daysdown)s" % fbnode
36 def fb_print_nodeinfo(fbnode, hostname, fields=None):
37 #fbnode['hostname'] = hostname
38 #fbnode['checked'] = diff_time(fbnode['checked'])
39 if fbnode['bootcd_version']:
40 fbnode['bootcd_version'] = fbnode['bootcd_version'].split()[-1]
42 fbnode['bootcd_version'] = "unknown"
43 fbnode['pcu'] = color_pcu_state(fbnode)
46 if ( fbnode['observed_status'] is not None and \
47 'DOWN' in fbnode['observed_status'] ) or \
48 fbnode['kernel_version'] is None:
49 fbnode['kernel_version'] = ""
51 fbnode['kernel_version'] = fbnode['kernel_version'].split()[2]
53 if fbnode['plc_node_stats'] is not None:
54 fbnode['boot_state'] = fbnode['plc_node_stats']['boot_state']
56 fbnode['boot_state'] = "unknown"
59 if len(fbnode['nodegroups']) > 0:
60 fbnode['category'] = fbnode['nodegroups'][0]
62 #print "ERROR!!!!!!!!!!!!!!!!!!!!!"
65 print "%(hostname)-45s | %(date_checked)11.11s | %(boot_state)5.5s| %(observed_status)8.8s | %(ssh_status)5.5s | %(pcu)6.6s | %(bootcd_version)6.6s | %(kernel_version)s" % fbnode
69 format += "%%(%s)s " % f
73 indexes = path.split("/")
77 values = values[index]
79 raise NoKeyException(index)
82 def verifyType(constraints, data):
84 constraints is a list of key, value pairs.
85 # [ {... : ...}==AND , ... , ... , ] == OR
88 for con in constraints:
89 #print "con: %s" % con
90 if len(con.keys()) == 0:
95 for key in con.keys():
96 #print "looking at key: %s" % key
104 if o.name() == "Match":
105 if get(data,key) is not None:
106 value_re = re.compile(o.value)
107 con_and_true = con_and_true & (value_re.search(get(data,key)) is not None)
110 elif o.name() == "ListMatch":
111 if get(data,key) is not None:
113 for listitem in get(data,key):
114 value_re = re.compile(o.value)
115 if value_re.search(listitem) is not None:
118 con_and_true = con_and_true & match
121 elif o.name() == "Is":
122 con_and_true = con_and_true & (get(data,key) == o.value)
123 elif o.name() == "FilledIn":
124 con_and_true = con_and_true & (len(get(data,key)) > 0)
125 elif o.name() == "PortOpen":
126 if get(data,key) is not None:
128 con_and_true = con_and_true & (v[str(o.value)] == "open")
132 value_re = re.compile(o.value)
133 con_and_true = con_and_true & (value_re.search(get(data,key)) is not None)
135 except NoKeyException, key:
136 print "missing key %s" % key,
138 #print "missing key %s" % key
139 #con_and_true = False
141 con_or_true = con_or_true | con_and_true
145 def verifyDBrecord(constraints, record):
147 constraints is a list of key, value pairs.
148 # [ {... : ...}==AND , ... , ... , ] == OR
150 def has_key(obj, key):
152 x = obj.__getattribute__(key)
157 def get_val(obj, key):
159 return obj.__getattribute__(key)
164 indexes = path.split("/")
165 value = get_val(obj,indexes[0])
166 if value is not None and len(indexes) > 1:
167 for key in indexes[1:]:
171 raise NoKeyException(key)
174 #print constraints, record
177 for con in constraints:
178 #print "con: %s" % con
179 if len(con.keys()) == 0:
184 for key in con.keys():
185 #print "looking at key: %s" % key
186 if has_key(record, key):
187 value_re = re.compile(con[key])
188 if type([]) == type(get(record,key)):
189 local_or_true = False
190 for val in get(record,key):
191 local_or_true = local_or_true | (value_re.search(val) is not None)
192 con_and_true = con_and_true & local_or_true
194 if get(record,key) is not None:
195 con_and_true = con_and_true & (value_re.search(get(record,key)) is not None)
197 print "missing key %s" % key,
200 con_or_true = con_or_true | con_and_true
204 def verify(constraints, data):
206 constraints is a list of key, value pairs.
207 # [ {... : ...}==AND , ... , ... , ] == OR
210 for con in constraints:
211 #print "con: %s" % con
212 if len(con.keys()) == 0:
217 for key in con.keys():
218 #print "looking at key: %s" % key
220 value_re = re.compile(con[key])
221 if type([]) == type(data[key]):
222 local_or_true = False
223 for val in data[key]:
224 local_or_true = local_or_true | (value_re.search(val) is not None)
225 con_and_true = con_and_true & local_or_true
227 if data[key] is not None:
228 con_and_true = con_and_true & (value_re.search(data[key]) is not None)
229 elif key not in data:
230 print "missing key %s" % key,
233 con_or_true = con_or_true | con_and_true
237 def query_to_dict(query):
241 or_queries = query.split('||')
242 for or_query in or_queries:
243 and_queries = or_query.split('&&')
247 for and_query in and_queries:
248 (key, value) = and_query.split('=')
256 if 'plcnode' in fbdata:
257 if 'pcu_ids' in fbdata['plcnode']:
258 if len(fbdata['plcnode']['pcu_ids']) > 0:
262 def pcu_select(str_query, nodelist=None):
267 if str_query is None: return (nodenames, pcunames)
270 fb = database.dbLoad("findbad")
272 fbpcu = database.dbLoad("findbadpcus")
275 dict_query = query_to_dict(str_query)
278 for node in fb['nodes'].keys():
279 if nodelist is not None:
280 if node not in nodelist: continue
282 fb_nodeinfo = fb['nodes'][node]['values']
283 if pcu_in(fb_nodeinfo):
284 pcuinfo = fbpcu['nodes']['id_%s' % fb_nodeinfo['plcnode']['pcu_ids'][0]]['values']
285 if verify(dict_query, pcuinfo):
286 nodenames.append(node)
287 str = "cmdhttps/locfg.pl -s %s -f iloxml/License.xml -u %s -p '%s' | grep MESSAGE" % \
288 (reboot.pcu_name(pcuinfo), pcuinfo['username'], pcuinfo['password'])
289 #pcunames.append(str)
290 pcunames.append(pcuinfo['pcu_id'])
291 return (nodenames, pcunames)
293 def node_select(str_query, nodelist=None, fbdb=None):
297 if str_query is None: return hostnames
300 dict_query = query_to_dict(str_query)
306 for node in nodelist:
307 #if nodelist is not None:
308 # if node not in nodelist: continue
312 fb_noderec = FindbadNodeRecord.query.filter(FindbadNodeRecord.hostname==node).order_by(FindbadNodeRecord.date_checked.desc()).first()
314 print traceback.print_exc()
318 fb_nodeinfo = fb_noderec.to_dict()
320 #fb_nodeinfo['pcu'] = color_pcu_state(fb_nodeinfo)
321 #if 'plcnode' in fb_nodeinfo:
322 # fb_nodeinfo.update(fb_nodeinfo['plcnode'])
324 #if verifyDBrecord(dict_query, fb_nodeinfo):
325 if verify(dict_query, fb_nodeinfo):
326 #print node #fb_nodeinfo
327 hostnames.append(node)
329 #print "NO MATCH", node
339 from monitor import parser as parsermodule
340 parser = parsermodule.getParser()
342 parser.set_defaults(node=None, fromtime=None, select=None, list=None,
343 pcuselect=None, nodelist=None, daysdown=None, fields=None)
344 parser.add_option("", "--daysdown", dest="daysdown", action="store_true",
345 help="List the node state and days down...")
346 parser.add_option("", "--select", dest="select", metavar="key=value",
347 help="List all nodes with the given key=value pattern")
348 parser.add_option("", "--fields", dest="fields", metavar="key,list,...",
349 help="a list of keys to display for each entry.")
350 parser.add_option("", "--list", dest="list", action="store_true",
351 help="Write only the hostnames as output.")
352 parser.add_option("", "--pcuselect", dest="pcuselect", metavar="key=value",
353 help="List all nodes with the given key=value pattern")
354 parser.add_option("", "--nodelist", dest="nodelist", metavar="nodelist.txt",
355 help="A list of nodes to bring out of debug mode.")
356 parser.add_option("", "--fromtime", dest="fromtime", metavar="YYYY-MM-DD",
357 help="Specify a starting date from which to begin the query.")
359 parser = parsermodule.getParser(['defaults'], parser)
360 config = parsermodule.parse_args(parser)
364 archive = database.SPickle(path)
365 d = datetime_fromstr(config.fromtime)
366 glob_str = "%s*.production.findbad.pkl" % d.strftime("%Y-%m-%d")
369 file = glob.glob(glob_str)[0]
370 #print "loading %s" % file
372 fb = archive.load(file[:-4])
374 #fbnodes = FindbadNodeRecord.select(FindbadNodeRecord.q.hostname, orderBy='date_checked',distinct=True).reversed()
375 #fb = database.dbLoad("findbad")
378 fbpcu = database.dbLoad("findbadpcus")
382 nodelist = util.file.getListFromFile(config.nodelist)
384 # NOTE: list of nodes should come from findbad db. Otherwise, we
385 # don't know for sure that there's a record in the db..
386 plcnodes = database.dbLoad("l_plcnodes")
387 nodelist = [ node['hostname'] for node in plcnodes ]
388 #nodelist = ['planetlab-1.cs.princeton.edu']
391 if config.select is not None and config.pcuselect is not None:
392 nodelist = node_select(config.select, nodelist, fb)
393 nodelist, pculist = pcu_select(config.pcuselect, nodelist)
394 elif config.select is not None:
395 nodelist = node_select(config.select, nodelist, fb)
396 elif config.pcuselect is not None:
397 nodelist, pculist = pcu_select(config.pcuselect, nodelist)
403 for node in nodelist:
406 if node not in nodelist:
410 # Find the most recent record
411 fb_noderec = FindbadNodeRecord.query.filter(FindbadNodeRecord.hostname==node).order_by(FindbadNodeRecord.date_checked.desc()).first()
413 print traceback.print_exc()
414 pass #fb_nodeinfo = fb['nodes'][node]['values']
420 daysdown_print_nodeinfo(fb_nodeinfo, node)
422 fb_nodeinfo = fb_noderec.to_dict()
425 fields = config.fields.split(",")
429 fb_print_nodeinfo(fb_nodeinfo, node, fields)
430 elif not config.select and 'state' in fb_nodeinfo:
431 fb_print_nodeinfo(fb_nodeinfo, node)
435 if __name__ == "__main__":