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, 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."""
246 print "NODEACTION_HANDLER------------------"
248 if 'pcuid' in request.params:
249 pcuid = request.params['pcuid']
251 refurl = request.headers.get("Referer",link("pcu"))
254 # TODO: do this more intelligently...
255 uri_fields = urllib.splitquery(refurl)
256 if uri_fields[1] is not None:
257 val = query_to_dict(uri_fields[1])
260 elif 'hostname' in val:
261 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
267 cherry_trail = cherrypy._cputil.get_object_trail()
268 for i in cherry_trail:
272 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
274 def nodeaction(self, **data):
275 print "NODEACTION------------------"
276 for item in data.keys():
277 print "%s %s" % ( item, data[item] )
279 if 'hostname' in data:
280 hostname = data['hostname']
282 flash("No hostname given in submitted data")
285 if 'submit' in data or 'type' in data:
287 action = data['submit']
289 action = data['type']
291 flash("No submit action given in submitted data")
294 if action == "Reboot":
295 print "REBOOT: %s" % hostname
296 ret = reboot.reboot_str(str(hostname))
298 if ret: raise RuntimeError("Error using PCU: " + str(ret))
299 flash("Reboot appeared to work. Allow at most 5 minutes. Then run ExternalScan to check current status.")
301 elif action == "ExternalScan":
302 scanapi.externalprobe(str(hostname))
303 flash("External Scan Successful!")
304 elif action == "InternalScan":
305 scanapi.internalprobe(str(hostname))
306 flash("Internal Scan Successful!")
309 raise RuntimeError("Unknown action given")
312 # TODO: add form validation
313 @expose(template="monitorweb.templates.pcuview")
314 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
315 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
316 print "PCUVIEW------------------"
327 if 'submit' in data.keys() or 'type' in data.keys():
328 if hostname: data['hostname'] = hostname
329 self.nodeaction(**data)
330 if 'exceptions' in data:
331 exceptions = data['exceptions']
334 actions = ActionRecord.query.filter_by(loginbase=loginbase
335 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(7)
336 ).order_by(ActionRecord.date_created.desc())
337 actions = [ a for a in actions ]
338 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
340 for plcnode in site_lb2hn[loginbase]:
341 node = FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname'])
342 # NOTE: reformat some fields.
343 prep_node_for_display(node)
345 if node.plc_pcuid: # not None
346 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
347 prep_pcu_for_display(pcu)
348 pcus[node.plc_pcuid] = pcu
350 for pcuid_key in pcus:
351 pcuquery += [pcus[pcuid_key]]
353 if pcuid and hostname is None:
354 print "pcuid: %s" % pcuid
355 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
357 prep_pcu_for_display(pcu)
359 if 'site_id' in pcu.plc_pcu_stats:
360 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
362 if 'nodenames' in pcu.plc_pcu_stats:
363 for nodename in pcu.plc_pcu_stats['nodenames']:
364 print "query for %s" % nodename
365 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
366 print "%s" % node.port_status
367 print "%s" % node.to_dict()
369 prep_node_for_display(node)
372 if hostname and pcuid is None:
373 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
374 # NOTE: reformat some fields.
375 prep_node_for_display(node)
376 sitequery = [node.site]
378 if node.plc_pcuid: # not None
379 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
380 prep_pcu_for_display(pcu)
383 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
385 @expose(template="monitorweb.templates.pculist")
386 def pcu(self, filter='all'):
388 fbquery = FindbadPCURecord.get_all_latest()
390 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
394 if node.reboot_trial_status == str(0):
395 filtercount['ok'] += 1
396 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
397 filtercount[node.reboot_trial_status] += 1
399 filtercount['pending'] += 1
401 prep_pcu_for_display(node)
406 elif filter == "ok" and node.reboot_trial_status == str(0):
408 elif filter == node.reboot_trial_status:
410 elif filter == "pending":
411 # TODO: look in message logs...
412 if node.reboot_trial_status != str(0) and \
413 node.reboot_trial_status != 'NetDown' and \
414 node.reboot_trial_status != 'Not_Run':
418 return dict(query=query, fc=filtercount)
420 @expose(template="monitorweb.templates.siteview")
421 def siteview(self, loginbase='pl'):
423 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
425 for plcnode in site_lb2hn[loginbase]:
426 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
427 # NOTE: reformat some fields.
428 prep_node_for_display(node)
430 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
432 @expose(template="monitorweb.templates.sitelist")
433 def site(self, filter='all'):
434 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
435 fbquery = HistorySiteRecord.query.all()
439 filtercount['all'] += 1
440 if site.new and site.slices_used == 0 and not site.enabled:
441 filtercount['new'] += 1
442 elif not site.enabled:
443 filtercount['pending'] += 1
445 filtercount[site.status] += 1
450 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
452 elif filter == "pending" and not site.enabled:
454 elif filter == site.status:
457 return dict(query=query, fc=filtercount)
459 @expose(template="monitorweb.templates.actionlist")
460 def action(self, filter='all'):
461 session.bind = metadata.bind
462 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
463 # With Acknowledgement
464 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
465 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
466 ' WHERE f.itemid=i.itemid ' + \
467 ' AND h.hostid=i.hostid ' + \
468 ' AND hg.hostid=h.hostid ' + \
469 ' AND t.triggerid=f.triggerid ' + \
470 ' AND t.triggerid=e.triggerid ' + \
471 ' AND a.eventid=e.eventid ' + \
472 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
473 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
474 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
475 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
476 ' ORDER BY t.lastchange DESC';
478 # WithOUT Acknowledgement
479 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
480 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
481 ' WHERE f.itemid=i.itemid ' + \
482 ' AND h.hostid=i.hostid ' + \
483 ' AND hg.hostid=h.hostid ' + \
484 ' AND t.triggerid=f.triggerid ' + \
485 ' AND t.triggerid=e.triggerid ' + \
486 ' AND e.eventid not in (select eventid from acknowledges) ' + \
487 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
488 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
489 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
490 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
491 ' ORDER BY t.lastchange DESC';
492 # for i in session.execute(sql): print i
495 replace = re.compile(' {.*}')
496 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
497 result = session.execute(sql)
500 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
502 print site_hn2lb.keys()
503 newrow = [ "unknown" ] + [ r for r in row ]
505 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
508 filtercount['all'] += 1
509 if not ack: # for unacknowledged
510 filtercount['active'] += 1
511 if filter == 'active':
514 filtercount['acknowledged'] += 1
515 if filter == 'acknowledged':
518 if filter != "acknowledged" and filter != "active":
521 return dict(query=query, fc=filtercount)