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)
189 if node.history.status in ['down', 'offline']:
190 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
191 filtercount['down'] += 1
193 filtercount['neverboot'] += 1
194 elif node.history.status in ['good', 'online']:
195 filtercount['boot'] += 1
196 elif node.history.status in ['debug', 'monitordebug']:
197 filtercount['debug'] += 1
199 # TODO: need a better fix. filtercount
200 # doesn't maps to GetBootStates() on
201 # 4.3 so this one fails quite often.
202 if filtercount.has_key(node.history.status):
203 filtercount[node.history.status] += 1
207 if filter == "neverboot":
208 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
210 elif filter == "all":
212 elif filter == node.history.status:
214 elif filter == 'boot':
218 widget = NodeWidget(template='monitorweb.templates.node_template')
219 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
221 def nodeaction_handler(self, tg_exceptions=None):
222 """Handle any kind of error."""
223 print "NODEACTION_HANDLER------------------"
225 if 'pcuid' in request.params:
226 pcuid = request.params['pcuid']
228 refurl = request.headers.get("Referer",link("pcu"))
231 # TODO: do this more intelligently...
232 uri_fields = urllib.splitquery(refurl)
233 if uri_fields[1] is not None:
234 val = query_to_dict(uri_fields[1])
237 elif 'hostname' in val:
238 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
244 cherry_trail = cherrypy._cputil.get_object_trail()
245 for i in cherry_trail:
249 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
251 def nodeaction(self, **data):
252 print "NODEACTION------------------"
253 for item in data.keys():
254 print "%s %s" % ( item, data[item] )
256 if 'hostname' in data:
257 hostname = data['hostname']
259 flash("No hostname given in submitted data")
262 if 'submit' in data or 'type' in data:
264 action = data['submit']
266 action = data['type']
268 flash("No submit action given in submitted data")
271 if action == "Reboot":
272 print "REBOOT: %s" % hostname
273 ret = reboot.reboot_str(str(hostname))
275 if ret: raise RuntimeError("Error using PCU: " + str(ret))
276 flash("Reboot appeared to work. Allow at most 5 minutes. Then run ExternalScan to check current status.")
278 elif action == "ExternalScan":
279 scanapi.externalprobe(str(hostname))
280 flash("External Scan Successful!")
281 elif action == "InternalScan":
282 scanapi.internalprobe(str(hostname))
283 flash("Internal Scan Successful!")
286 raise RuntimeError("Unknown action given")
289 # TODO: add form validation
290 @expose(template="monitorweb.templates.pcuview")
291 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
292 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
293 print "PCUVIEW------------------"
294 print "befor-len: ", len( [ i for i in session] )
295 session.flush(); session.clear()
296 print "after-len: ", len( [ i for i in session] )
306 if 'submit' in data.keys() or 'type' in data.keys():
307 if hostname: data['hostname'] = hostname
308 self.nodeaction(**data)
309 if 'exceptions' in data:
310 exceptions = data['exceptions']
313 actions = ActionRecord.query.filter_by(loginbase=loginbase
314 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(14)
315 ).order_by(ActionRecord.date_created.desc())
316 actions = [ a for a in actions ]
317 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
319 for node in FindbadNodeRecord.query.filter_by(loginbase=loginbase):
320 # NOTE: reformat some fields.
321 prep_node_for_display(node)
323 if node.plc_pcuid: # not None
324 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
325 prep_pcu_for_display(pcu)
326 pcus[node.plc_pcuid] = pcu
328 for pcuid_key in pcus:
329 pcuquery += [pcus[pcuid_key]]
331 if pcuid and hostname is None:
332 print "pcuid: %s" % pcuid
333 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
335 prep_pcu_for_display(pcu)
337 if 'site_id' in pcu.plc_pcu_stats:
338 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
340 if 'nodenames' in pcu.plc_pcu_stats:
341 for nodename in pcu.plc_pcu_stats['nodenames']:
342 print "query for %s" % nodename
343 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
344 print "%s" % node.port_status
345 print "%s" % node.to_dict()
347 prep_node_for_display(node)
350 if hostname and pcuid is None:
351 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
352 # NOTE: reformat some fields.
353 prep_node_for_display(node)
354 sitequery = [node.site]
356 if node.plc_pcuid: # not None
357 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
358 prep_pcu_for_display(pcu)
361 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
363 @expose(template="monitorweb.templates.nodehistory")
364 def nodehistory(self, hostname=None):
367 #fbnode = FindbadNodeRecord.get_by(hostname=hostname)
368 ## TODO: add links for earlier history if desired.
369 #l = fbnode.versions[-100:]
372 # prep_node_for_display(node)
375 fbnode = HistoryNodeRecord.get_by(hostname=hostname)
376 l = fbnode.versions[-100:]
379 #prep_node_for_display(node)
382 return dict(query=query, hostname=hostname)
384 @expose(template="monitorweb.templates.sitehistory")
385 def sitehistory(self, loginbase=None):
388 fbsite = HistorySiteRecord.get_by(loginbase=loginbase)
389 # TODO: add links for earlier history if desired.
390 l = fbsite.versions[-100:]
394 return dict(query=query, loginbase=loginbase)
397 @expose(template="monitorweb.templates.pculist")
398 def pcu(self, filter='all'):
399 print "PCUVIEW------------------"
400 print "befor-len: ", len( [ i for i in session] )
401 session.flush(); session.clear()
402 print "after-len: ", len( [ i for i in session] )
403 fbquery = FindbadPCURecord.get_all_latest()
405 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
409 if node.reboot_trial_status == str(0):
410 filtercount['ok'] += 1
411 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
412 filtercount[node.reboot_trial_status] += 1
414 filtercount['pending'] += 1
416 prep_pcu_for_display(node)
421 elif filter == "ok" and node.reboot_trial_status == str(0):
423 elif filter == node.reboot_trial_status:
425 elif filter == "pending":
426 # TODO: look in message logs...
427 if node.reboot_trial_status != str(0) and \
428 node.reboot_trial_status != 'NetDown' and \
429 node.reboot_trial_status != 'Not_Run':
433 return dict(query=query, fc=filtercount)
435 @expose(template="monitorweb.templates.siteview")
436 def siteview(self, loginbase='pl'):
438 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
440 for node in FindbadNodeRecord.query.filter_by(loginbase=loginbase):
441 # NOTE: reformat some fields.
442 prep_node_for_display(node)
444 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
446 @expose(template="monitorweb.templates.sitelist")
447 def site(self, filter='all'):
448 print "SITE------------------"
449 print "befor-len: ", len( [ i for i in session] )
450 session.flush(); session.clear()
451 print "after-len: ", len( [ i for i in session] )
452 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
453 fbquery = HistorySiteRecord.query.all()
457 filtercount['all'] += 1
458 if site.new and site.slices_used == 0 and not site.enabled:
459 filtercount['new'] += 1
460 elif not site.enabled:
461 filtercount['pending'] += 1
462 elif site.status in ['good', 'online']:
463 filtercount['good'] += 1
464 elif site.status in ['down', 'offline']:
465 filtercount['down'] += 1
470 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
472 elif filter == "pending" and not site.enabled:
474 elif filter == 'good' and site.status in ['good', 'online']:
476 elif filter == 'down' and site.status in ['down', 'offline']:
479 return dict(query=query, fc=filtercount)
481 @expose(template="monitorweb.templates.actionlist")
482 def action(self, filter='all'):
483 session.bind = metadata.bind
484 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
485 # With Acknowledgement
486 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
487 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
488 ' WHERE f.itemid=i.itemid ' + \
489 ' AND h.hostid=i.hostid ' + \
490 ' AND hg.hostid=h.hostid ' + \
491 ' AND t.triggerid=f.triggerid ' + \
492 ' AND t.triggerid=e.triggerid ' + \
493 ' AND a.eventid=e.eventid ' + \
494 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
495 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
496 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
497 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
498 ' ORDER BY t.lastchange DESC';
500 # WithOUT Acknowledgement
501 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
502 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
503 ' WHERE f.itemid=i.itemid ' + \
504 ' AND h.hostid=i.hostid ' + \
505 ' AND hg.hostid=h.hostid ' + \
506 ' AND t.triggerid=f.triggerid ' + \
507 ' AND t.triggerid=e.triggerid ' + \
508 ' AND e.eventid not in (select eventid from acknowledges) ' + \
509 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
510 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
511 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
512 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
513 ' ORDER BY t.lastchange DESC';
514 # for i in session.execute(sql): print i
517 replace = re.compile(' {.*}')
518 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
519 result = session.execute(sql)
522 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
524 print site_hn2lb.keys()
525 newrow = [ "unknown" ] + [ r for r in row ]
527 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
530 filtercount['all'] += 1
531 if not ack: # for unacknowledged
532 filtercount['active'] += 1
533 if filter == 'active':
536 filtercount['acknowledged'] += 1
537 if filter == 'acknowledged':
540 if filter != "acknowledged" and filter != "active":
543 return dict(query=query, fc=filtercount)