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):
324 if 'submit' in data.keys() or 'type' in data.keys():
325 if hostname: data['hostname'] = hostname
326 self.nodeaction(**data)
327 if 'exceptions' in data:
328 exceptions = data['exceptions']
331 actions = ActionRecord.query.filter_by(loginbase=loginbase
332 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(7)
333 ).order_by(ActionRecord.date_created.desc())
334 actions = [ a for a in actions ]
335 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
337 for plcnode in site_lb2hn[loginbase]:
338 node = FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname'])
339 # NOTE: reformat some fields.
340 prep_node_for_display(node)
342 if node.plc_pcuid: # not None
343 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
344 prep_pcu_for_display(pcu)
345 pcus[node.plc_pcuid] = pcu
347 for pcuid_key in pcus:
348 pcuquery += [pcus[pcuid_key]]
350 if pcuid and hostname is None:
351 print "pcuid: %s" % pcuid
352 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
354 prep_pcu_for_display(pcu)
356 if 'site_id' in pcu.plc_pcu_stats:
357 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
359 if 'nodenames' in pcu.plc_pcu_stats:
360 for nodename in pcu.plc_pcu_stats['nodenames']:
361 print "query for %s" % nodename
362 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
363 print "%s" % node.port_status
364 print "%s" % node.to_dict()
366 prep_node_for_display(node)
369 if hostname and pcuid is None:
370 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
371 # NOTE: reformat some fields.
372 prep_node_for_display(node)
373 sitequery = [node.site]
375 if node.plc_pcuid: # not None
376 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
377 prep_pcu_for_display(pcu)
380 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
382 @expose(template="monitorweb.templates.pculist")
383 def pcu(self, filter='all'):
385 fbquery = FindbadPCURecord.get_all_latest()
387 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
391 if node.reboot_trial_status == str(0):
392 filtercount['ok'] += 1
393 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
394 filtercount[node.reboot_trial_status] += 1
396 filtercount['pending'] += 1
398 prep_pcu_for_display(node)
403 elif filter == "ok" and node.reboot_trial_status == str(0):
405 elif filter == node.reboot_trial_status:
407 elif filter == "pending":
408 # TODO: look in message logs...
409 if node.reboot_trial_status != str(0) and \
410 node.reboot_trial_status != 'NetDown' and \
411 node.reboot_trial_status != 'Not_Run':
415 return dict(query=query, fc=filtercount)
417 @expose(template="monitorweb.templates.siteview")
418 def siteview(self, loginbase='pl'):
420 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
422 for plcnode in site_lb2hn[loginbase]:
423 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
424 # NOTE: reformat some fields.
425 prep_node_for_display(node)
427 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
429 @expose(template="monitorweb.templates.sitelist")
430 def site(self, filter='all'):
431 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
432 fbquery = HistorySiteRecord.query.all()
436 filtercount['all'] += 1
437 if site.new and site.slices_used == 0 and not site.enabled:
438 filtercount['new'] += 1
439 elif not site.enabled:
440 filtercount['pending'] += 1
442 filtercount[site.status] += 1
447 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
449 elif filter == "pending" and not site.enabled:
451 elif filter == site.status:
454 return dict(query=query, fc=filtercount)
456 @expose(template="monitorweb.templates.actionlist")
457 def action(self, filter='all'):
458 session.bind = metadata.bind
459 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
460 # With Acknowledgement
461 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
462 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
463 ' WHERE f.itemid=i.itemid ' + \
464 ' AND h.hostid=i.hostid ' + \
465 ' AND hg.hostid=h.hostid ' + \
466 ' AND t.triggerid=f.triggerid ' + \
467 ' AND t.triggerid=e.triggerid ' + \
468 ' AND a.eventid=e.eventid ' + \
469 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
470 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
471 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
472 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
473 ' ORDER BY t.lastchange DESC';
475 # WithOUT Acknowledgement
476 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
477 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
478 ' WHERE f.itemid=i.itemid ' + \
479 ' AND h.hostid=i.hostid ' + \
480 ' AND hg.hostid=h.hostid ' + \
481 ' AND t.triggerid=f.triggerid ' + \
482 ' AND t.triggerid=e.triggerid ' + \
483 ' AND e.eventid not in (select eventid from acknowledges) ' + \
484 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
485 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
486 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
487 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
488 ' ORDER BY t.lastchange DESC';
489 # for i in session.execute(sql): print i
492 replace = re.compile(' {.*}')
493 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
494 result = session.execute(sql)
497 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
499 print site_hn2lb.keys()
500 newrow = [ "unknown" ] + [ r for r in row ]
502 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
505 filtercount['all'] += 1
506 if not ack: # for unacknowledged
507 filtercount['active'] += 1
508 if filter == 'active':
511 filtercount['acknowledged'] += 1
512 if filter == 'acknowledged':
515 if filter != "acknowledged" and filter != "active":
518 return dict(query=query, fc=filtercount)