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:
222 #if filter == node.observed_status:
223 # if filter == "DOWN":
224 # if node.plc_node_stats['last_contact'] != None:
228 #elif filter == "neverboot":
229 # if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
231 #elif filter == "pending":
232 # # TODO: look in message logs...
234 #elif filter == node.plc_node_stats['boot_state']:
236 #elif filter == "all":
239 widget = NodeWidget(template='monitorweb.templates.node_template')
240 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
242 def nodeaction_handler(self, tg_exceptions=None):
243 """Handle any kind of error."""
245 if 'pcuid' in request.params:
246 pcuid = request.params['pcuid']
248 refurl = request.headers.get("Referer",link("pcu"))
251 # TODO: do this more intelligently...
252 uri_fields = urllib.splitquery(refurl)
253 if uri_fields[1] is not None:
254 val = query_to_dict(uri_fields[1])
257 elif 'hostname' in val:
258 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
264 cherry_trail = cherrypy._cputil.get_object_trail()
265 for i in cherry_trail:
269 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
271 def nodeaction(self, **data):
272 for item in data.keys():
273 print "%s %s" % ( item, data[item] )
275 if 'hostname' in data:
276 hostname = data['hostname']
278 flash("No hostname given in submitted data")
281 if 'submit' in data or 'type' in data:
283 action = data['submit']
285 action = data['type']
287 flash("No submit action given in submitted data")
290 if action == "Reboot":
291 print "REBOOT: %s" % hostname
292 ret = reboot.reboot_str(str(hostname))
294 if ret: raise RuntimeError("Error using PCU: " + str(ret))
295 flash("Reboot appeared to work. All at most 5 minutes. Run ExternalScan to check current status.")
297 elif action == "ExternalScan":
298 scanapi.externalprobe(str(hostname))
299 flash("External Scan Successful!")
300 elif action == "InternalScan":
301 scanapi.internalprobe(str(hostname))
302 flash("Internal Scan Successful!")
305 raise RuntimeError("Unknown action given")
308 # TODO: add form validation
309 @expose(template="monitorweb.templates.pcuview")
310 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
311 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
321 if 'submit' in data.keys() or 'type' in data.keys():
322 if hostname: data['hostname'] = hostname
323 self.nodeaction(**data)
324 if 'exceptions' in data:
325 exceptions = data['exceptions']
328 actions = ActionRecord.query.filter_by(loginbase=loginbase
329 ).filter(ActionRecord.date_created >= datetime.now() - timedelta(7)
330 ).order_by(ActionRecord.date_created.desc())
331 actions = [ a for a in actions ]
332 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
334 for plcnode in site_lb2hn[loginbase]:
335 node = FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname'])
336 # NOTE: reformat some fields.
337 prep_node_for_display(node)
339 if node.plc_pcuid: # not None
340 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
341 prep_pcu_for_display(pcu)
342 pcus[node.plc_pcuid] = pcu
344 for pcuid_key in pcus:
345 pcuquery += [pcus[pcuid_key]]
347 if pcuid and hostname is None:
348 print "pcuid: %s" % pcuid
349 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
351 prep_pcu_for_display(pcu)
353 if 'site_id' in pcu.plc_pcu_stats:
354 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
356 if 'nodenames' in pcu.plc_pcu_stats:
357 for nodename in pcu.plc_pcu_stats['nodenames']:
358 print "query for %s" % nodename
359 node = FindbadNodeRecord.get_latest_by(hostname=nodename)
360 print "%s" % node.port_status
361 print "%s" % node.to_dict()
363 prep_node_for_display(node)
366 if hostname and pcuid is None:
367 node = FindbadNodeRecord.get_latest_by(hostname=hostname)
368 # NOTE: reformat some fields.
369 prep_node_for_display(node)
370 sitequery = [node.site]
372 if node.plc_pcuid: # not None
373 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
374 prep_pcu_for_display(pcu)
377 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
379 @expose(template="monitorweb.templates.pculist")
380 def pcu(self, filter='all'):
382 fbquery = FindbadPCURecord.get_all_latest()
384 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
388 if node.reboot_trial_status == str(0):
389 filtercount['ok'] += 1
390 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
391 filtercount[node.reboot_trial_status] += 1
393 filtercount['pending'] += 1
395 prep_pcu_for_display(node)
400 elif filter == "ok" and node.reboot_trial_status == str(0):
402 elif filter == node.reboot_trial_status:
404 elif filter == "pending":
405 # TODO: look in message logs...
406 if node.reboot_trial_status != str(0) and \
407 node.reboot_trial_status != 'NetDown' and \
408 node.reboot_trial_status != 'Not_Run':
412 return dict(query=query, fc=filtercount)
414 @expose(template="monitorweb.templates.siteview")
415 def siteview(self, loginbase='pl'):
417 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
419 for plcnode in site_lb2hn[loginbase]:
420 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
421 # NOTE: reformat some fields.
422 prep_node_for_display(node)
424 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
426 @expose(template="monitorweb.templates.sitelist")
427 def site(self, filter='all'):
428 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
429 fbquery = HistorySiteRecord.query.all()
433 filtercount['all'] += 1
434 if site.new and site.slices_used == 0 and not site.enabled:
435 filtercount['new'] += 1
436 elif not site.enabled:
437 filtercount['pending'] += 1
439 filtercount[site.status] += 1
444 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
446 elif filter == "pending" and not site.enabled:
448 elif filter == site.status:
451 return dict(query=query, fc=filtercount)
453 @expose(template="monitorweb.templates.actionlist")
454 def action(self, filter='all'):
455 session.bind = metadata.bind
456 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
457 # With Acknowledgement
458 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
459 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
460 ' WHERE f.itemid=i.itemid ' + \
461 ' AND h.hostid=i.hostid ' + \
462 ' AND hg.hostid=h.hostid ' + \
463 ' AND t.triggerid=f.triggerid ' + \
464 ' AND t.triggerid=e.triggerid ' + \
465 ' AND a.eventid=e.eventid ' + \
466 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
467 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
468 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
469 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
470 ' ORDER BY t.lastchange DESC';
472 # WithOUT Acknowledgement
473 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
474 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
475 ' WHERE f.itemid=i.itemid ' + \
476 ' AND h.hostid=i.hostid ' + \
477 ' AND hg.hostid=h.hostid ' + \
478 ' AND t.triggerid=f.triggerid ' + \
479 ' AND t.triggerid=e.triggerid ' + \
480 ' AND e.eventid not in (select eventid from acknowledges) ' + \
481 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
482 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
483 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
484 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
485 ' ORDER BY t.lastchange DESC';
486 # for i in session.execute(sql): print i
489 replace = re.compile(' {.*}')
490 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
491 result = session.execute(sql)
494 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
496 print site_hn2lb.keys()
497 newrow = [ "unknown" ] + [ r for r in row ]
499 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
502 filtercount['all'] += 1
503 if not ack: # for unacknowledged
504 filtercount['active'] += 1
505 if filter == 'active':
508 filtercount['acknowledged'] += 1
509 if filter == 'acknowledged':
512 if filter != "acknowledged" and filter != "active":
515 return dict(query=query, fc=filtercount)