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
15 from monitor import reboot
16 from monitor import scanapi
18 from monitor.wrapper.plccache import plcdb_id2lb as site_id2lb
19 from monitor.wrapper.plccache import plcdb_hn2lb as site_hn2lb
20 from monitor.wrapper.plccache import plcdb_lb2hn as site_lb2hn
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 = site_id2lb[pcu.plc_pcu_stats['site_id']]
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 = site_id2lb[node.plc_node_stats['site_id']]
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")
141 node.history = HistoryNodeRecord.by_hostname(node.hostname)
143 node.ports = format_ports(node.port_status)
146 exists = node.plc_node_stats['last_contact']
148 node.plc_node_stats = {'last_contact' : None}
152 class Root(controllers.RootController):
153 @expose(template="monitorweb.templates.welcome")
156 # log.debug("Happy TurboGears Controller Responding For Duty")
157 flash("Your application is now running")
158 return dict(now=time.ctime())
160 @expose(template="monitorweb.templates.pcuview")
161 def nodeview(self, hostname=None):
164 for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
165 # NOTE: reformat some fields.
166 prep_node_for_display(node)
169 return self.pcuview(None, hostname) # dict(nodequery=nodequery)
171 @expose(template="monitorweb.templates.nodelist")
172 def node(self, filter='boot'):
174 fbquery = FindbadNodeRecord.get_all_latest()
176 filtercount = {'down' : 0, 'boot': 0, 'debug' : 0, 'diagnose' : 0, 'disabled': 0,
177 'neverboot' : 0, 'pending' : 0, 'all' : 0, None : 0}
179 # NOTE: reformat some fields.
180 prep_node_for_display(node)
184 if node.history.status in ['down', 'offline']:
185 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
186 filtercount['down'] += 1
188 filtercount['neverboot'] += 1
189 elif node.history.status in ['good', 'online']:
190 filtercount['boot'] += 1
191 elif node.history.status in ['debug', 'monitordebug']:
192 filtercount['debug'] += 1
194 filtercount[node.history.status] += 1
196 ## NOTE: count filters
197 #if node.observed_status != 'DOWN':
198 # print node.hostname, node.observed_status
199 # if node.observed_status == 'DEBUG':
200 # if node.plc_node_stats['boot_state'] in ['debug', 'diagnose', 'disabled']:
201 # filtercount[node.plc_node_stats['boot_state']] += 1
203 # filtercount['debug'] += 1
206 # filtercount[node.observed_status] += 1
208 # if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
209 # filtercount[node.observed_status] += 1
211 # filtercount['neverboot'] += 1
214 if filter == "neverboot":
215 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
217 elif filter == "all":
219 elif filter == node.history.status:
221 elif filter == 'boot':
224 #if filter == node.observed_status:
225 # if filter == "DOWN":
226 # if node.plc_node_stats['last_contact'] != None:
230 #elif filter == "neverboot":
231 # if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
233 #elif filter == "pending":
234 # # TODO: look in message logs...
236 #elif filter == node.plc_node_stats['boot_state']:
238 #elif filter == "all":
241 widget = NodeWidget(template='monitorweb.templates.node_template')
242 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
244 def nodeaction_handler(self, tg_exceptions=None):
245 """Handle any kind of error."""
247 if 'pcuid' in request.params:
248 pcuid = request.params['pcuid']
250 refurl = request.headers.get("Referer",link("pcu"))
253 # TODO: do this more intelligently...
254 uri_fields = urllib.splitquery(refurl)
255 if uri_fields[1] is not None:
256 val = query_to_dict(uri_fields[1])
259 elif 'hostname' in val:
260 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
266 cherry_trail = cherrypy._cputil.get_object_trail()
267 for i in cherry_trail:
271 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
273 def nodeaction(self, **data):
274 for item in data.keys():
275 print "%s %s" % ( item, data[item] )
277 if 'hostname' in data:
278 hostname = data['hostname']
280 flash("No hostname given in submitted data")
283 if 'submit' in data or 'type' in data:
285 action = data['submit']
287 action = data['type']
289 flash("No submit action given in submitted data")
292 if action == "Reboot":
293 print "REBOOT: %s" % hostname
294 ret = reboot.reboot_str(str(hostname))
296 if ret: raise RuntimeError("Error using PCU: " + str(ret))
297 flash("Reboot appeared to work. All at most 5 minutes. Run ExternalScan to check current status.")
299 elif action == "ExternalScan":
300 scanapi.externalprobe(str(hostname))
301 flash("External Scan Successful!")
302 elif action == "InternalScan":
303 scanapi.internalprobe(str(hostname))
304 flash("Internal Scan Successful!")
307 raise RuntimeError("Unknown action given")
310 # TODO: add form validation
311 @expose(template="monitorweb.templates.pcuview")
312 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
313 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
323 if 'submit' in data.keys() or 'type' in data.keys():
324 if hostname: data['hostname'] = hostname
325 self.nodeaction(**data)
326 if 'exceptions' in data:
327 exceptions = data['exceptions']
330 actions = ActionRecord.query.filter_by(loginbase=loginbase
331 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(7)
332 ).order_by(ActionRecord.date_created.desc())
333 actions = [ a for a in actions ]
334 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
336 for plcnode in site_lb2hn[loginbase]:
337 node = FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname'])
338 # NOTE: reformat some fields.
339 prep_node_for_display(node)
341 if node.plc_pcuid: # not None
342 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
343 prep_pcu_for_display(pcu)
344 pcus[node.plc_pcuid] = pcu
346 for pcuid_key in pcus:
347 pcuquery += [pcus[pcuid_key]]
349 if pcuid and hostname is None:
350 print "pcuid: %s" % pcuid
351 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
353 prep_pcu_for_display(pcu)
355 if 'site_id' in pcu.plc_pcu_stats:
356 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
358 if 'nodenames' in pcu.plc_pcu_stats:
359 for nodename in pcu.plc_pcu_stats['nodenames']:
360 print "query for %s" % nodename
361 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
362 print "%s" % node.port_status
363 print "%s" % node.to_dict()
365 prep_node_for_display(node)
368 if hostname and pcuid is None:
369 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
370 # NOTE: reformat some fields.
371 prep_node_for_display(node)
372 sitequery = [node.site]
374 if node.plc_pcuid: # not None
375 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
376 prep_pcu_for_display(pcu)
379 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
381 @expose(template="monitorweb.templates.pculist")
382 def pcu(self, filter='all'):
384 fbquery = FindbadPCURecord.get_all_latest()
386 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
390 if node.reboot_trial_status == str(0):
391 filtercount['ok'] += 1
392 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
393 filtercount[node.reboot_trial_status] += 1
395 filtercount['pending'] += 1
397 prep_pcu_for_display(node)
402 elif filter == "ok" and node.reboot_trial_status == str(0):
404 elif filter == node.reboot_trial_status:
406 elif filter == "pending":
407 # TODO: look in message logs...
408 if node.reboot_trial_status != str(0) and \
409 node.reboot_trial_status != 'NetDown' and \
410 node.reboot_trial_status != 'Not_Run':
414 return dict(query=query, fc=filtercount)
416 @expose(template="monitorweb.templates.siteview")
417 def siteview(self, loginbase='pl'):
419 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
421 for plcnode in site_lb2hn[loginbase]:
422 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
423 # NOTE: reformat some fields.
424 prep_node_for_display(node)
426 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
428 @expose(template="monitorweb.templates.sitelist")
429 def site(self, filter='all'):
430 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
431 fbquery = HistorySiteRecord.query.all()
435 filtercount['all'] += 1
436 if site.new and site.slices_used == 0 and not site.enabled:
437 filtercount['new'] += 1
438 elif not site.enabled:
439 filtercount['pending'] += 1
441 filtercount[site.status] += 1
446 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
448 elif filter == "pending" and not site.enabled:
450 elif filter == site.status:
453 return dict(query=query, fc=filtercount)
455 @expose(template="monitorweb.templates.actionlist")
456 def action(self, filter='all'):
457 session.bind = metadata.bind
458 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
459 # With Acknowledgement
460 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
461 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
462 ' WHERE f.itemid=i.itemid ' + \
463 ' AND h.hostid=i.hostid ' + \
464 ' AND hg.hostid=h.hostid ' + \
465 ' AND t.triggerid=f.triggerid ' + \
466 ' AND t.triggerid=e.triggerid ' + \
467 ' AND a.eventid=e.eventid ' + \
468 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
469 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
470 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
471 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
472 ' ORDER BY t.lastchange DESC';
474 # WithOUT Acknowledgement
475 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
476 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
477 ' WHERE f.itemid=i.itemid ' + \
478 ' AND h.hostid=i.hostid ' + \
479 ' AND hg.hostid=h.hostid ' + \
480 ' AND t.triggerid=f.triggerid ' + \
481 ' AND t.triggerid=e.triggerid ' + \
482 ' AND e.eventid not in (select eventid from acknowledges) ' + \
483 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
484 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
485 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
486 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
487 ' ORDER BY t.lastchange DESC';
488 # for i in session.execute(sql): print i
491 replace = re.compile(' {.*}')
492 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
493 result = session.execute(sql)
496 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
498 print site_hn2lb.keys()
499 newrow = [ "unknown" ] + [ r for r in row ]
501 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
504 filtercount['all'] += 1
505 if not ack: # for unacknowledged
506 filtercount['active'] += 1
507 if filter == 'active':
510 filtercount['acknowledged'] += 1
511 if filter == 'acknowledged':
514 if filter != "acknowledged" and filter != "active":
517 return dict(query=query, fc=filtercount)