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)
186 if node.history.status in ['down', 'offline']:
187 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
188 filtercount['down'] += 1
190 filtercount['neverboot'] += 1
191 elif node.history.status in ['good', 'online']:
192 filtercount['boot'] += 1
193 elif node.history.status in ['debug', 'monitordebug']:
194 filtercount['debug'] += 1
196 filtercount[node.history.status] += 1
198 ## NOTE: count filters
199 #if node.observed_status != 'DOWN':
200 # print node.hostname, node.observed_status
201 # if node.observed_status == 'DEBUG':
202 # if node.plc_node_stats['boot_state'] in ['debug', 'diagnose', 'disabled']:
203 # filtercount[node.plc_node_stats['boot_state']] += 1
205 # filtercount['debug'] += 1
208 # filtercount[node.observed_status] += 1
210 # if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
211 # filtercount[node.observed_status] += 1
213 # filtercount['neverboot'] += 1
216 if filter == "neverboot":
217 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
219 elif filter == "all":
221 elif filter == node.history.status:
223 elif filter == 'boot':
226 #if filter == node.observed_status:
227 # if filter == "DOWN":
228 # if node.plc_node_stats['last_contact'] != None:
232 #elif filter == "neverboot":
233 # if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
235 #elif filter == "pending":
236 # # TODO: look in message logs...
238 #elif filter == node.plc_node_stats['boot_state']:
240 #elif filter == "all":
243 widget = NodeWidget(template='monitorweb.templates.node_template')
244 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
246 def nodeaction_handler(self, tg_exceptions=None):
247 """Handle any kind of error."""
248 print "NODEACTION_HANDLER------------------"
250 if 'pcuid' in request.params:
251 pcuid = request.params['pcuid']
253 refurl = request.headers.get("Referer",link("pcu"))
256 # TODO: do this more intelligently...
257 uri_fields = urllib.splitquery(refurl)
258 if uri_fields[1] is not None:
259 val = query_to_dict(uri_fields[1])
262 elif 'hostname' in val:
263 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
269 cherry_trail = cherrypy._cputil.get_object_trail()
270 for i in cherry_trail:
274 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
276 def nodeaction(self, **data):
277 print "NODEACTION------------------"
278 for item in data.keys():
279 print "%s %s" % ( item, data[item] )
281 if 'hostname' in data:
282 hostname = data['hostname']
284 flash("No hostname given in submitted data")
287 if 'submit' in data or 'type' in data:
289 action = data['submit']
291 action = data['type']
293 flash("No submit action given in submitted data")
296 if action == "Reboot":
297 print "REBOOT: %s" % hostname
298 ret = reboot.reboot_str(str(hostname))
300 if ret: raise RuntimeError("Error using PCU: " + str(ret))
301 flash("Reboot appeared to work. Allow at most 5 minutes. Then run ExternalScan to check current status.")
303 elif action == "ExternalScan":
304 scanapi.externalprobe(str(hostname))
305 flash("External Scan Successful!")
306 elif action == "InternalScan":
307 scanapi.internalprobe(str(hostname))
308 flash("Internal Scan Successful!")
311 raise RuntimeError("Unknown action given")
314 # TODO: add form validation
315 @expose(template="monitorweb.templates.pcuview")
316 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
317 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
318 print "PCUVIEW------------------"
319 print "befor-len: ", len( [ i for i in session] )
320 session.flush(); session.clear()
321 print "after-len: ", len( [ i for i in session] )
331 if 'submit' in data.keys() or 'type' in data.keys():
332 if hostname: data['hostname'] = hostname
333 self.nodeaction(**data)
334 if 'exceptions' in data:
335 exceptions = data['exceptions']
338 actions = ActionRecord.query.filter_by(loginbase=loginbase
339 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(14)
340 ).order_by(ActionRecord.date_created.desc())
341 actions = [ a for a in actions ]
342 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
344 for plcnode in site_lb2hn[loginbase]:
345 node = FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname'])
346 # NOTE: reformat some fields.
347 prep_node_for_display(node)
349 if node.plc_pcuid: # not None
350 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
351 prep_pcu_for_display(pcu)
352 pcus[node.plc_pcuid] = pcu
354 for pcuid_key in pcus:
355 pcuquery += [pcus[pcuid_key]]
357 if pcuid and hostname is None:
358 print "pcuid: %s" % pcuid
359 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
361 prep_pcu_for_display(pcu)
363 if 'site_id' in pcu.plc_pcu_stats:
364 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
366 if 'nodenames' in pcu.plc_pcu_stats:
367 for nodename in pcu.plc_pcu_stats['nodenames']:
368 print "query for %s" % nodename
369 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
370 print "%s" % node.port_status
371 print "%s" % node.to_dict()
373 prep_node_for_display(node)
376 if hostname and pcuid is None:
377 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
378 # NOTE: reformat some fields.
379 prep_node_for_display(node)
380 sitequery = [node.site]
382 if node.plc_pcuid: # not None
383 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
384 prep_pcu_for_display(pcu)
387 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
389 @expose(template="monitorweb.templates.nodehistory")
390 def nodehistory(self, hostname=None):
393 #fbnode = FindbadNodeRecord.get_by(hostname=hostname)
394 ## TODO: add links for earlier history if desired.
395 #l = fbnode.versions[-100:]
398 # prep_node_for_display(node)
401 fbnode = HistoryNodeRecord.get_by(hostname=hostname)
402 l = fbnode.versions[-100:]
405 #prep_node_for_display(node)
408 return dict(query=query, hostname=hostname)
410 @expose(template="monitorweb.templates.sitehistory")
411 def sitehistory(self, loginbase=None):
414 fbsite = HistorySiteRecord.get_by(loginbase=loginbase)
415 # TODO: add links for earlier history if desired.
416 l = fbsite.versions[-100:]
420 return dict(query=query, loginbase=loginbase)
423 @expose(template="monitorweb.templates.pculist")
424 def pcu(self, filter='all'):
426 fbquery = FindbadPCURecord.get_all_latest()
428 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
432 if node.reboot_trial_status == str(0):
433 filtercount['ok'] += 1
434 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
435 filtercount[node.reboot_trial_status] += 1
437 filtercount['pending'] += 1
439 prep_pcu_for_display(node)
444 elif filter == "ok" and node.reboot_trial_status == str(0):
446 elif filter == node.reboot_trial_status:
448 elif filter == "pending":
449 # TODO: look in message logs...
450 if node.reboot_trial_status != str(0) and \
451 node.reboot_trial_status != 'NetDown' and \
452 node.reboot_trial_status != 'Not_Run':
456 return dict(query=query, fc=filtercount)
458 @expose(template="monitorweb.templates.siteview")
459 def siteview(self, loginbase='pl'):
461 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
463 for plcnode in site_lb2hn[loginbase]:
464 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
465 # NOTE: reformat some fields.
466 prep_node_for_display(node)
468 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
470 @expose(template="monitorweb.templates.sitelist")
471 def site(self, filter='all'):
472 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
473 fbquery = HistorySiteRecord.query.all()
477 filtercount['all'] += 1
478 if site.new and site.slices_used == 0 and not site.enabled:
479 filtercount['new'] += 1
480 elif not site.enabled:
481 filtercount['pending'] += 1
482 elif site.status in ['good', 'online']:
483 filtercount['good'] += 1
484 elif site.status in ['down', 'offline']:
485 filtercount['down'] += 1
490 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
492 elif filter == "pending" and not site.enabled:
494 elif filter == 'good' and site.status in ['good', 'online']:
496 elif filter == 'down' and site.status in ['down', 'offline']:
499 return dict(query=query, fc=filtercount)
501 @expose(template="monitorweb.templates.actionlist")
502 def action(self, filter='all'):
503 session.bind = metadata.bind
504 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
505 # With Acknowledgement
506 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
507 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
508 ' WHERE f.itemid=i.itemid ' + \
509 ' AND h.hostid=i.hostid ' + \
510 ' AND hg.hostid=h.hostid ' + \
511 ' AND t.triggerid=f.triggerid ' + \
512 ' AND t.triggerid=e.triggerid ' + \
513 ' AND a.eventid=e.eventid ' + \
514 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
515 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
516 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
517 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
518 ' ORDER BY t.lastchange DESC';
520 # WithOUT Acknowledgement
521 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
522 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
523 ' WHERE f.itemid=i.itemid ' + \
524 ' AND h.hostid=i.hostid ' + \
525 ' AND hg.hostid=h.hostid ' + \
526 ' AND t.triggerid=f.triggerid ' + \
527 ' AND t.triggerid=e.triggerid ' + \
528 ' AND e.eventid not in (select eventid from acknowledges) ' + \
529 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
530 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
531 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
532 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
533 ' ORDER BY t.lastchange DESC';
534 # for i in session.execute(sql): print i
537 replace = re.compile(' {.*}')
538 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
539 result = session.execute(sql)
542 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
544 print site_hn2lb.keys()
545 newrow = [ "unknown" ] + [ r for r in row ]
547 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
550 filtercount['all'] += 1
551 if not ack: # for unacknowledged
552 filtercount['active'] += 1
553 if filter == 'active':
556 filtercount['acknowledged'] += 1
557 if filter == 'acknowledged':
560 if filter != "acknowledged" and filter != "active":
563 return dict(query=query, fc=filtercount)