1 import turbogears as tg
2 from turbogears import controllers, expose, flash, exception_handler
3 from turbogears import widgets
4 from cherrypy import request, response
6 # from monitorweb import model
8 # log = logging.getLogger("monitorweb.controllers")
10 from monitor.database.info.model import *
11 #from monitor.database.zabbixapi.model import *
12 #from monitor.database.dborm import zab_session as session
13 #from monitor.database.dborm import zab_metadata as metadata
14 from monitor_xmlrpc import MonitorXmlrpcServer
16 from monitor import reboot
17 from monitor import scanapi
20 from monitor.wrapper.plccache import plcdb_hn2lb as site_hn2lb
22 from monitorweb.templates.links import *
26 def query_to_dict(query):
27 """ take a url query string and chop it up """
29 query_fields = query.split('&')
30 for f in query_fields:
31 (k,v) = urllib.splitvalue(f)
36 def format_ports(data, pcumodel=None):
41 supported_ports=reboot.model_to_object(pcumodel).supported_ports
43 # ports of a production node
44 supported_ports=[22,80,806]
46 if data and len(data.keys()) > 0 :
47 for port in supported_ports:
49 state = data[str(port)]
53 if state == "filtered":
56 retval.append( (port, state) )
59 retval = [( "Closed/Filtered", "state" )]
61 if filtered_length == len(supported_ports):
62 retval = [( "All Filtered", "state" )]
66 def format_pcu_shortstatus(pcu):
69 if pcu.reboot_trial_status == str(0):
71 elif pcu.reboot_trial_status == "NetDown" or pcu.reboot_trial_status == "Not_Run":
72 status = pcu.reboot_trial_status
78 def prep_pcu_for_display(pcu):
81 pcu.loginbase = PlcSite.query.get(pcu.plc_pcu_stats['site_id']).plc_site_stats['login_base']
83 pcu.loginbase = "unknown"
85 pcu.ports = format_ports(pcu.port_status, pcu.plc_pcu_stats['model'])
86 pcu.status = format_pcu_shortstatus(pcu)
88 #print pcu.entry_complete
89 pcu.entry_complete_str = pcu.entry_complete
90 #pcu.entry_complete_str += "".join([ f[0] for f in pcu.entry_complete.split() ])
91 if pcu.dns_status == "NOHOSTNAME":
92 pcu.dns_short_status = 'NoHost'
93 elif pcu.dns_status == "DNS-OK":
94 pcu.dns_short_status = 'Ok'
95 elif pcu.dns_status == "DNS-NOENTRY":
96 pcu.dns_short_status = 'NoEntry'
97 elif pcu.dns_status == "NO-DNS-OR-IP":
98 pcu.dns_short_status = 'NoHostOrIP'
99 elif pcu.dns_status == "DNS-MISMATCH":
100 pcu.dns_short_status = 'Mismatch'
102 class NodeWidget(widgets.Widget):
105 def prep_node_for_display(node):
107 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
109 node.pcu_status = pcu.reboot_trial_status
110 node.pcu_short_status = format_pcu_shortstatus(pcu)
112 prep_pcu_for_display(node.pcu)
114 node.pcu_short_status = "none"
115 node.pcu_status = "nodata"
119 node.pcu_status = "nopcu"
120 node.pcu_short_status = "none"
124 if node.kernel_version:
125 node.kernel = node.kernel_version.split()[2]
130 node.loginbase = PlcSite.query.get(node.plc_node_stats['site_id']).plc_site_stats['login_base']
132 node.loginbase = "unknown"
135 node.site = HistorySiteRecord.by_loginbase(node.loginbase)
136 if node.site is None:
137 # TODO: need a cleaner fix for this...
138 node.site = HistorySiteRecord.by_loginbase("pl")
140 node.site = HistorySiteRecord.by_loginbase("ple")
143 node.history = HistoryNodeRecord.by_hostname(node.hostname)
145 node.ports = format_ports(node.port_status)
148 exists = node.plc_node_stats['last_contact']
150 node.plc_node_stats = {'last_contact' : None}
154 class Root(controllers.RootController, MonitorXmlrpcServer):
155 @expose(template="monitorweb.templates.welcome")
157 # log.debug("Happy TurboGears Controller Responding For Duty")
158 flash("Your application is now running")
159 return dict(now=time.ctime())
161 @expose(template="monitorweb.templates.pcuview")
162 def nodeview(self, hostname=None):
165 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
166 # NOTE: reformat some fields.
167 prep_node_for_display(node)
170 return self.pcuview(None, None, hostname) # dict(nodequery=nodequery)
172 @expose(template="monitorweb.templates.nodelist")
173 def node(self, filter='boot'):
174 print "NODE------------------"
175 print "befor-len: ", len( [ i for i in session] )
176 session.flush(); session.clear()
177 print "after-len: ", len( [ i for i in session] )
178 fbquery = FindbadNodeRecord.get_all_latest()
180 filtercount = {'down' : 0, 'boot': 0, 'debug' : 0, 'diagnose' : 0, 'disabled': 0,
181 'neverboot' : 0, 'pending' : 0, 'all' : 0, None : 0}
183 # NOTE: reformat some fields.
184 prep_node_for_display(node)
192 if node.history.status in ['down', 'offline']:
193 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
194 filtercount['down'] += 1
196 filtercount['neverboot'] += 1
197 elif node.history.status in ['good', 'online']:
198 filtercount['boot'] += 1
199 elif node.history.status in ['debug', 'monitordebug']:
200 filtercount['debug'] += 1
202 # TODO: need a better fix. filtercount
203 # doesn't maps to GetBootStates() on
204 # 4.3 so this one fails quite often.
205 if filtercount.has_key(node.history.status):
206 filtercount[node.history.status] += 1
210 if filter == "neverboot":
211 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
213 elif filter == "all":
215 elif filter == node.history.status:
217 elif filter == 'boot':
221 widget = NodeWidget(template='monitorweb.templates.node_template')
222 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
224 def nodeaction_handler(self, tg_exceptions=None):
225 """Handle any kind of error."""
226 print "NODEACTION_HANDLER------------------"
228 if 'pcuid' in request.params:
229 pcuid = request.params['pcuid']
231 refurl = request.headers.get("Referer",link("pcu"))
234 # TODO: do this more intelligently...
235 uri_fields = urllib.splitquery(refurl)
236 if uri_fields[1] is not None:
237 val = query_to_dict(uri_fields[1])
240 elif 'hostname' in val:
241 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
247 cherry_trail = cherrypy._cputil.get_object_trail()
248 for i in cherry_trail:
252 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
254 def nodeaction(self, **data):
255 print "NODEACTION------------------"
256 for item in data.keys():
257 print "%s %s" % ( item, data[item] )
259 if 'hostname' in data:
260 hostname = data['hostname']
262 flash("No hostname given in submitted data")
265 if 'submit' in data or 'type' in data:
267 action = data['submit']
269 action = data['type']
271 flash("No submit action given in submitted data")
274 if action == "Reboot":
275 print "REBOOT: %s" % hostname
276 ret = reboot.reboot_str(str(hostname))
278 if ret: raise RuntimeError("Error using PCU: " + str(ret))
279 flash("Reboot appeared to work. Allow at most 5 minutes. Then run ExternalScan to check current status.")
281 elif action == "ExternalScan":
282 scanapi.externalprobe(str(hostname))
283 flash("External Scan Successful!")
284 elif action == "InternalScan":
285 scanapi.internalprobe(str(hostname))
286 flash("Internal Scan Successful!")
289 raise RuntimeError("Unknown action given")
292 # TODO: add form validation
293 @expose(template="monitorweb.templates.pcuview")
294 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
295 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
296 print "PCUVIEW------------------"
297 print "befor-len: ", len( [ i for i in session] )
298 session.flush(); session.clear()
299 print "after-len: ", len( [ i for i in session] )
309 if 'submit' in data.keys() or 'type' in data.keys():
310 if hostname: data['hostname'] = hostname
311 self.nodeaction(**data)
312 if 'exceptions' in data:
313 exceptions = data['exceptions']
316 actions = ActionRecord.query.filter_by(loginbase=loginbase
317 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(14)
318 ).order_by(ActionRecord.date_created.desc())
319 actions = [ a for a in actions ]
320 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
322 for node in FindbadNodeRecord.query.filter_by(loginbase=loginbase):
323 # NOTE: reformat some fields.
324 prep_node_for_display(node)
326 if node.plc_pcuid: # not None
327 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
328 prep_pcu_for_display(pcu)
329 pcus[node.plc_pcuid] = pcu
331 for pcuid_key in pcus:
332 pcuquery += [pcus[pcuid_key]]
334 if pcuid and hostname is None:
335 print "pcuid: %s" % pcuid
336 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
338 prep_pcu_for_display(pcu)
340 if 'site_id' in pcu.plc_pcu_stats:
341 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
343 if 'nodenames' in pcu.plc_pcu_stats:
344 for nodename in pcu.plc_pcu_stats['nodenames']:
345 print "query for %s" % nodename
346 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
347 print "%s" % node.port_status
348 print "%s" % node.to_dict()
350 prep_node_for_display(node)
353 if hostname and pcuid is None:
354 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
355 # NOTE: reformat some fields.
356 prep_node_for_display(node)
357 sitequery = [node.site]
359 if node.plc_pcuid: # not None
360 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
361 prep_pcu_for_display(pcu)
364 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
366 @expose(template="monitorweb.templates.pcuhistory")
367 def pcuhistory(self, pcu_id=None):
370 fbnode = HistoryPCURecord.get_by(plc_pcuid=pcu_id)
371 l = fbnode.versions[-100:]
374 #prep_node_for_display(node)
377 return dict(query=query, pcu_id=pcu_id)
379 @expose(template="monitorweb.templates.nodehistory")
380 def nodehistory(self, hostname=None):
383 #fbnode = FindbadNodeRecord.get_by(hostname=hostname)
384 ## TODO: add links for earlier history if desired.
385 #l = fbnode.versions[-100:]
388 # prep_node_for_display(node)
391 fbnode = HistoryNodeRecord.get_by(hostname=hostname)
392 l = fbnode.versions[-100:]
395 #prep_node_for_display(node)
398 return dict(query=query, hostname=hostname)
400 @expose(template="monitorweb.templates.sitehistory")
401 def sitehistory(self, loginbase=None):
404 fbsite = HistorySiteRecord.get_by(loginbase=loginbase)
405 # TODO: add links for earlier history if desired.
406 l = fbsite.versions[-100:]
410 return dict(query=query, loginbase=loginbase)
413 @expose(template="monitorweb.templates.pculist")
414 def pcu(self, filter='all'):
415 print "PCUVIEW------------------"
416 print "befor-len: ", len( [ i for i in session] )
417 session.flush(); session.clear()
418 print "after-len: ", len( [ i for i in session] )
419 fbquery = FindbadPCURecord.get_all_latest()
421 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
425 if node.reboot_trial_status == str(0):
426 filtercount['ok'] += 1
427 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
428 filtercount[node.reboot_trial_status] += 1
430 filtercount['pending'] += 1
432 prep_pcu_for_display(node)
437 elif filter == "ok" and node.reboot_trial_status == str(0):
439 elif filter == node.reboot_trial_status:
441 elif filter == "pending":
442 # TODO: look in message logs...
443 if node.reboot_trial_status != str(0) and \
444 node.reboot_trial_status != 'NetDown' and \
445 node.reboot_trial_status != 'Not_Run':
449 return dict(query=query, fc=filtercount)
451 @expose(template="monitorweb.templates.siteview")
452 def siteview(self, loginbase='pl'):
454 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
456 for node in FindbadNodeRecord.query.filter_by(loginbase=loginbase):
457 # NOTE: reformat some fields.
458 prep_node_for_display(node)
460 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
462 @expose(template="monitorweb.templates.sitelist")
463 def site(self, filter='all'):
464 print "SITE------------------"
465 print "befor-len: ", len( [ i for i in session] )
466 session.flush(); session.clear()
467 print "after-len: ", len( [ i for i in session] )
468 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
469 fbquery = HistorySiteRecord.query.all()
473 filtercount['all'] += 1
474 if site.new and site.slices_used == 0 and not site.enabled:
475 filtercount['new'] += 1
476 elif not site.enabled:
477 filtercount['pending'] += 1
478 elif site.status in ['good', 'online']:
479 filtercount['good'] += 1
480 elif site.status in ['down', 'offline']:
481 filtercount['down'] += 1
486 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
488 elif filter == "pending" and not site.enabled:
490 elif filter == 'good' and site.status in ['good', 'online']:
492 elif filter == 'down' and site.status in ['down', 'offline']:
495 return dict(query=query, fc=filtercount)
497 @expose(template="monitorweb.templates.actionlist")
498 def action(self, filter='all'):
499 session.bind = metadata.bind
500 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
501 # With Acknowledgement
502 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
503 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
504 ' WHERE f.itemid=i.itemid ' + \
505 ' AND h.hostid=i.hostid ' + \
506 ' AND hg.hostid=h.hostid ' + \
507 ' AND t.triggerid=f.triggerid ' + \
508 ' AND t.triggerid=e.triggerid ' + \
509 ' AND a.eventid=e.eventid ' + \
510 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
511 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
512 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
513 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
514 ' ORDER BY t.lastchange DESC';
516 # WithOUT Acknowledgement
517 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
518 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
519 ' WHERE f.itemid=i.itemid ' + \
520 ' AND h.hostid=i.hostid ' + \
521 ' AND hg.hostid=h.hostid ' + \
522 ' AND t.triggerid=f.triggerid ' + \
523 ' AND t.triggerid=e.triggerid ' + \
524 ' AND e.eventid not in (select eventid from acknowledges) ' + \
525 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
526 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
527 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
528 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
529 ' ORDER BY t.lastchange DESC';
530 # for i in session.execute(sql): print i
533 replace = re.compile(' {.*}')
534 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
535 result = session.execute(sql)
538 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
540 print site_hn2lb.keys()
541 newrow = [ "unknown" ] + [ r for r in row ]
543 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
546 filtercount['all'] += 1
547 if not ack: # for unacknowledged
548 filtercount['active'] += 1
549 if filter == 'active':
552 filtercount['acknowledged'] += 1
553 if filter == 'acknowledged':
556 if filter != "acknowledged" and filter != "active":
559 return dict(query=query, fc=filtercount)