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
19 from monitor.wrapper.plccache import plcdb_id2lb as site_id2lb
20 from monitor.wrapper.plccache import plcdb_hn2lb as site_hn2lb
21 from monitor.wrapper.plccache import plcdb_lb2hn as site_lb2hn
23 from monitorweb.templates.links import *
27 def query_to_dict(query):
28 """ take a url query string and chop it up """
30 query_fields = query.split('&')
31 for f in query_fields:
32 (k,v) = urllib.splitvalue(f)
37 def format_ports(data, pcumodel=None):
42 supported_ports=reboot.model_to_object(pcumodel).supported_ports
44 # ports of a production node
45 supported_ports=[22,80,806]
47 if data and len(data.keys()) > 0 :
48 for port in supported_ports:
50 state = data[str(port)]
54 if state == "filtered":
57 retval.append( (port, state) )
60 retval = [( "Closed/Filtered", "state" )]
62 if filtered_length == len(supported_ports):
63 retval = [( "All Filtered", "state" )]
67 def format_pcu_shortstatus(pcu):
70 if pcu.reboot_trial_status == str(0):
72 elif pcu.reboot_trial_status == "NetDown" or pcu.reboot_trial_status == "Not_Run":
73 status = pcu.reboot_trial_status
79 def prep_pcu_for_display(pcu):
82 pcu.loginbase = site_id2lb[pcu.plc_pcu_stats['site_id']]
84 pcu.loginbase = "unknown"
86 pcu.ports = format_ports(pcu.port_status, pcu.plc_pcu_stats['model'])
87 pcu.status = format_pcu_shortstatus(pcu)
89 #print pcu.entry_complete
90 pcu.entry_complete_str = pcu.entry_complete
91 #pcu.entry_complete_str += "".join([ f[0] for f in pcu.entry_complete.split() ])
92 if pcu.dns_status == "NOHOSTNAME":
93 pcu.dns_short_status = 'NoHost'
94 elif pcu.dns_status == "DNS-OK":
95 pcu.dns_short_status = 'Ok'
96 elif pcu.dns_status == "DNS-NOENTRY":
97 pcu.dns_short_status = 'NoEntry'
98 elif pcu.dns_status == "NO-DNS-OR-IP":
99 pcu.dns_short_status = 'NoHostOrIP'
100 elif pcu.dns_status == "DNS-MISMATCH":
101 pcu.dns_short_status = 'Mismatch'
103 class NodeWidget(widgets.Widget):
106 def prep_node_for_display(node):
108 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
110 node.pcu_status = pcu.reboot_trial_status
111 node.pcu_short_status = format_pcu_shortstatus(pcu)
113 prep_pcu_for_display(node.pcu)
115 node.pcu_short_status = "none"
116 node.pcu_status = "nodata"
120 node.pcu_status = "nopcu"
121 node.pcu_short_status = "none"
125 if node.kernel_version:
126 node.kernel = node.kernel_version.split()[2]
131 node.loginbase = site_id2lb[node.plc_node_stats['site_id']]
133 node.loginbase = "unknown"
136 node.site = HistorySiteRecord.by_loginbase(node.loginbase)
137 if node.site is None:
138 # TODO: need a cleaner fix for this...
139 node.site = HistorySiteRecord.by_loginbase("pl")
142 node.history = HistoryNodeRecord.by_hostname(node.hostname)
144 node.ports = format_ports(node.port_status)
147 exists = node.plc_node_stats['last_contact']
149 node.plc_node_stats = {'last_contact' : None}
153 class Root(controllers.RootController, MonitorXmlrpcServer):
154 @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 for node in 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'):
175 fbquery = FindbadNodeRecord.get_all_latest()
177 filtercount = {'down' : 0, 'boot': 0, 'debug' : 0, 'diagnose' : 0, 'disabled': 0,
178 'neverboot' : 0, 'pending' : 0, 'all' : 0, None : 0}
180 # NOTE: reformat some fields.
181 prep_node_for_display(node)
185 if node.history.status in ['down', 'offline']:
186 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
187 filtercount['down'] += 1
189 filtercount['neverboot'] += 1
190 elif node.history.status in ['good', 'online']:
191 filtercount['boot'] += 1
192 elif node.history.status in ['debug', 'monitordebug']:
193 filtercount['debug'] += 1
195 filtercount[node.history.status] += 1
197 ## NOTE: count filters
198 #if node.observed_status != 'DOWN':
199 # print node.hostname, node.observed_status
200 # if node.observed_status == 'DEBUG':
201 # if node.plc_node_stats['boot_state'] in ['debug', 'diagnose', 'disabled']:
202 # filtercount[node.plc_node_stats['boot_state']] += 1
204 # filtercount['debug'] += 1
207 # filtercount[node.observed_status] += 1
209 # if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
210 # filtercount[node.observed_status] += 1
212 # filtercount['neverboot'] += 1
215 if filter == "neverboot":
216 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
218 elif filter == "all":
220 elif filter == node.history.status:
222 elif filter == 'boot':
225 #if filter == node.observed_status:
226 # if filter == "DOWN":
227 # if node.plc_node_stats['last_contact'] != None:
231 #elif filter == "neverboot":
232 # if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
234 #elif filter == "pending":
235 # # TODO: look in message logs...
237 #elif filter == node.plc_node_stats['boot_state']:
239 #elif filter == "all":
242 widget = NodeWidget(template='monitorweb.templates.node_template')
243 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
245 def nodeaction_handler(self, tg_exceptions=None):
246 """Handle any kind of error."""
247 print "NODEACTION_HANDLER------------------"
249 if 'pcuid' in request.params:
250 pcuid = request.params['pcuid']
252 refurl = request.headers.get("Referer",link("pcu"))
255 # TODO: do this more intelligently...
256 uri_fields = urllib.splitquery(refurl)
257 if uri_fields[1] is not None:
258 val = query_to_dict(uri_fields[1])
261 elif 'hostname' in val:
262 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
268 cherry_trail = cherrypy._cputil.get_object_trail()
269 for i in cherry_trail:
273 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
275 def nodeaction(self, **data):
276 print "NODEACTION------------------"
277 for item in data.keys():
278 print "%s %s" % ( item, data[item] )
280 if 'hostname' in data:
281 hostname = data['hostname']
283 flash("No hostname given in submitted data")
286 if 'submit' in data or 'type' in data:
288 action = data['submit']
290 action = data['type']
292 flash("No submit action given in submitted data")
295 if action == "Reboot":
296 print "REBOOT: %s" % hostname
297 ret = reboot.reboot_str(str(hostname))
299 if ret: raise RuntimeError("Error using PCU: " + str(ret))
300 flash("Reboot appeared to work. Allow at most 5 minutes. Then run ExternalScan to check current status.")
302 elif action == "ExternalScan":
303 scanapi.externalprobe(str(hostname))
304 flash("External Scan Successful!")
305 elif action == "InternalScan":
306 scanapi.internalprobe(str(hostname))
307 flash("Internal Scan Successful!")
310 raise RuntimeError("Unknown action given")
313 # TODO: add form validation
314 @expose(template="monitorweb.templates.pcuview")
315 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
316 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
317 print "PCUVIEW------------------"
318 print "befor-len: ", len( [ i for i in session] )
319 session.flush(); session.clear()
320 print "after-len: ", len( [ i for i in session] )
330 if 'submit' in data.keys() or 'type' in data.keys():
331 if hostname: data['hostname'] = hostname
332 self.nodeaction(**data)
333 if 'exceptions' in data:
334 exceptions = data['exceptions']
337 actions = ActionRecord.query.filter_by(loginbase=loginbase
338 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(14)
339 ).order_by(ActionRecord.date_created.desc())
340 actions = [ a for a in actions ]
341 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
343 for plcnode in site_lb2hn[loginbase]:
344 node = FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname'])
345 # NOTE: reformat some fields.
346 prep_node_for_display(node)
348 if node.plc_pcuid: # not None
349 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
350 prep_pcu_for_display(pcu)
351 pcus[node.plc_pcuid] = pcu
353 for pcuid_key in pcus:
354 pcuquery += [pcus[pcuid_key]]
356 if pcuid and hostname is None:
357 print "pcuid: %s" % pcuid
358 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
360 prep_pcu_for_display(pcu)
362 if 'site_id' in pcu.plc_pcu_stats:
363 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
365 if 'nodenames' in pcu.plc_pcu_stats:
366 for nodename in pcu.plc_pcu_stats['nodenames']:
367 print "query for %s" % nodename
368 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
369 print "%s" % node.port_status
370 print "%s" % node.to_dict()
372 prep_node_for_display(node)
375 if hostname and pcuid is None:
376 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
377 # NOTE: reformat some fields.
378 prep_node_for_display(node)
379 sitequery = [node.site]
381 if node.plc_pcuid: # not None
382 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
383 prep_pcu_for_display(pcu)
386 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
388 @expose(template="monitorweb.templates.nodehistory")
389 def nodehistory(self, hostname=None):
392 #fbnode = FindbadNodeRecord.get_by(hostname=hostname)
393 ## TODO: add links for earlier history if desired.
394 #l = fbnode.versions[-100:]
397 # prep_node_for_display(node)
400 fbnode = HistoryNodeRecord.get_by(hostname=hostname)
401 l = fbnode.versions[-100:]
404 #prep_node_for_display(node)
407 return dict(query=query, hostname=hostname)
409 @expose(template="monitorweb.templates.sitehistory")
410 def sitehistory(self, loginbase=None):
413 fbsite = HistorySiteRecord.get_by(loginbase=loginbase)
414 # TODO: add links for earlier history if desired.
415 l = fbsite.versions[-100:]
419 return dict(query=query, loginbase=loginbase)
422 @expose(template="monitorweb.templates.pculist")
423 def pcu(self, filter='all'):
425 fbquery = FindbadPCURecord.get_all_latest()
427 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
431 if node.reboot_trial_status == str(0):
432 filtercount['ok'] += 1
433 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
434 filtercount[node.reboot_trial_status] += 1
436 filtercount['pending'] += 1
438 prep_pcu_for_display(node)
443 elif filter == "ok" and node.reboot_trial_status == str(0):
445 elif filter == node.reboot_trial_status:
447 elif filter == "pending":
448 # TODO: look in message logs...
449 if node.reboot_trial_status != str(0) and \
450 node.reboot_trial_status != 'NetDown' and \
451 node.reboot_trial_status != 'Not_Run':
455 return dict(query=query, fc=filtercount)
457 @expose(template="monitorweb.templates.siteview")
458 def siteview(self, loginbase='pl'):
460 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
462 for plcnode in site_lb2hn[loginbase]:
463 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
464 # NOTE: reformat some fields.
465 prep_node_for_display(node)
467 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
469 @expose(template="monitorweb.templates.sitelist")
470 def site(self, filter='all'):
471 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
472 fbquery = HistorySiteRecord.query.all()
476 filtercount['all'] += 1
477 if site.new and site.slices_used == 0 and not site.enabled:
478 filtercount['new'] += 1
479 elif not site.enabled:
480 filtercount['pending'] += 1
481 elif site.status in ['good', 'online']:
482 filtercount['good'] += 1
483 elif site.status in ['down', 'offline']:
484 filtercount['down'] += 1
489 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
491 elif filter == "pending" and not site.enabled:
493 elif filter == 'good' and site.status in ['good', 'online']:
495 elif filter == 'down' and site.status in ['down', 'offline']:
498 return dict(query=query, fc=filtercount)
500 @expose(template="monitorweb.templates.actionlist")
501 def action(self, filter='all'):
502 session.bind = metadata.bind
503 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
504 # With Acknowledgement
505 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
506 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
507 ' WHERE f.itemid=i.itemid ' + \
508 ' AND h.hostid=i.hostid ' + \
509 ' AND hg.hostid=h.hostid ' + \
510 ' AND t.triggerid=f.triggerid ' + \
511 ' AND t.triggerid=e.triggerid ' + \
512 ' AND a.eventid=e.eventid ' + \
513 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
514 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
515 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
516 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
517 ' ORDER BY t.lastchange DESC';
519 # WithOUT Acknowledgement
520 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
521 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
522 ' WHERE f.itemid=i.itemid ' + \
523 ' AND h.hostid=i.hostid ' + \
524 ' AND hg.hostid=h.hostid ' + \
525 ' AND t.triggerid=f.triggerid ' + \
526 ' AND t.triggerid=e.triggerid ' + \
527 ' AND e.eventid not in (select eventid from acknowledges) ' + \
528 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
529 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
530 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
531 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
532 ' ORDER BY t.lastchange DESC';
533 # for i in session.execute(sql): print i
536 replace = re.compile(' {.*}')
537 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
538 result = session.execute(sql)
541 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
543 print site_hn2lb.keys()
544 newrow = [ "unknown" ] + [ r for r in row ]
546 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
549 filtercount['all'] += 1
550 if not ack: # for unacknowledged
551 filtercount['active'] += 1
552 if filter == 'active':
555 filtercount['acknowledged'] += 1
556 if filter == 'acknowledged':
559 if filter != "acknowledged" and filter != "active":
562 return dict(query=query, fc=filtercount)