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 pcucontrol import reboot
16 from monitor.wrapper.plccache import plcdb_id2lb as site_id2lb
17 from monitor.wrapper.plccache import plcdb_hn2lb as site_hn2lb
18 from monitor.wrapper.plccache import plcdb_lb2hn as site_lb2hn
20 from monitorweb.templates.links import *
22 from monitor import scanapi
25 def query_to_dict(query):
26 """ take a url query string and chop it up """
28 query_fields = query.split('&')
29 for f in query_fields:
30 (k,v) = urllib.splitvalue(f)
35 def format_ports(data, pcumodel=None):
40 supported_ports=reboot.model_to_object(pcumodel).supported_ports
42 # ports of a production node
43 supported_ports=[22,80,806]
45 if data and len(data.keys()) > 0 :
46 for port in supported_ports:
48 state = data[str(port)]
52 if state == "filtered":
55 retval.append( (port, state) )
58 retval = [( "Closed/Filtered", "state" )]
60 if filtered_length == len(supported_ports):
61 retval = [( "All Filtered", "state" )]
65 def format_pcu_shortstatus(pcu):
68 if pcu.reboot_trial_status == str(0):
70 elif pcu.reboot_trial_status == "NetDown" or pcu.reboot_trial_status == "Not_Run":
71 status = pcu.reboot_trial_status
77 def prep_pcu_for_display(pcu):
80 pcu.loginbase = site_id2lb[pcu.plc_pcu_stats['site_id']]
82 pcu.loginbase = "unknown"
84 pcu.ports = format_ports(pcu.port_status, pcu.plc_pcu_stats['model'])
85 pcu.status = format_pcu_shortstatus(pcu)
87 #print pcu.entry_complete
88 pcu.entry_complete_str = pcu.entry_complete
89 #pcu.entry_complete_str += "".join([ f[0] for f in pcu.entry_complete.split() ])
90 if pcu.dns_status == "NOHOSTNAME":
91 pcu.dns_short_status = 'NoHost'
92 elif pcu.dns_status == "DNS-OK":
93 pcu.dns_short_status = 'Ok'
94 elif pcu.dns_status == "DNS-NOENTRY":
95 pcu.dns_short_status = 'NoEntry'
96 elif pcu.dns_status == "NO-DNS-OR-IP":
97 pcu.dns_short_status = 'NoHostOrIP'
98 elif pcu.dns_status == "DNS-MISMATCH":
99 pcu.dns_short_status = 'Mismatch'
101 class NodeWidget(widgets.Widget):
104 def prep_node_for_display(node):
106 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
108 node.pcu_status = pcu.reboot_trial_status
109 node.pcu_short_status = format_pcu_shortstatus(pcu)
111 prep_pcu_for_display(node.pcu)
113 node.pcu_short_status = "none"
114 node.pcu_status = "nodata"
118 node.pcu_status = "nopcu"
119 node.pcu_short_status = "none"
123 if node.kernel_version:
124 node.kernel = node.kernel_version.split()[2]
129 node.loginbase = site_id2lb[node.plc_node_stats['site_id']]
131 node.loginbase = "unknown"
134 node.site = HistorySiteRecord.by_loginbase(node.loginbase)
135 if node.site is None:
136 # TODO: need a cleaner fix for this...
137 node.site = HistorySiteRecord.by_loginbase("pl")
140 node.history = HistoryNodeRecord.by_hostname(node.hostname)
142 node.ports = format_ports(node.port_status)
145 exists = node.plc_node_stats['last_contact']
147 node.plc_node_stats = {'last_contact' : None}
151 class Root(controllers.RootController):
152 @expose(template="monitorweb.templates.welcome")
155 # log.debug("Happy TurboGears Controller Responding For Duty")
156 flash("Your application is now running")
157 return dict(now=time.ctime())
159 @expose(template="monitorweb.templates.pcuview")
160 def nodeview(self, hostname=None):
163 for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
164 # NOTE: reformat some fields.
165 prep_node_for_display(node)
168 return self.pcuview(None, hostname) # dict(nodequery=nodequery)
170 @expose(template="monitorweb.templates.nodelist")
171 def node(self, filter='BOOT'):
173 fbquery = FindbadNodeRecord.get_all_latest()
175 filtercount = {'DOWN' : 0, 'BOOT': 0, 'DEBUG' : 0, 'neverboot' : 0, 'pending' : 0, 'all' : 0, None : 0}
177 # NOTE: reformat some fields.
178 prep_node_for_display(node)
180 # NOTE: count filters
181 if node.observed_status != 'DOWN':
182 print node.hostname, node.observed_status
183 filtercount[node.observed_status] += 1
185 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
186 filtercount[node.observed_status] += 1
188 filtercount['neverboot'] += 1
191 if filter == node.observed_status:
193 if node.plc_node_stats['last_contact'] != None:
197 elif filter == "neverboot":
198 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
200 elif filter == "pending":
201 # TODO: look in message logs...
203 elif filter == "all":
206 widget = NodeWidget(template='monitorweb.templates.node_template')
207 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
209 def nodeaction_handler(self, tg_exceptions=None):
210 """Handle any kind of error."""
212 if 'pcuid' in request.params:
213 pcuid = request.params['pcuid']
215 refurl = request.headers.get("Referer",link("pcu"))
218 # TODO: do this more intelligently...
219 uri_fields = urllib.splitquery(refurl)
220 if uri_fields[1] is not None:
221 val = query_to_dict(uri_fields[1])
224 elif 'hostname' in val:
225 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).first().plc_pcuid
231 cherry_trail = cherrypy._cputil.get_object_trail()
232 for i in cherry_trail:
236 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
238 def nodeaction(self, **data):
239 for item in data.keys():
240 print "%s %s" % ( item, data[item] )
242 if 'hostname' in data:
243 hostname = data['hostname']
245 flash("No hostname given in submitted data")
248 if 'submit' in data or 'type' in data:
250 action = data['submit']
252 action = data['type']
254 flash("No submit action given in submitted data")
257 if action == "Reboot":
258 print "REBOOT: %s" % hostname
259 ret = reboot.reboot_str(str(hostname))
261 if ret: raise RuntimeError("Error using PCU: " + str(ret))
262 flash("Reboot appeared to work. All at most 5 minutes. Run ExternalScan to check current status.")
264 elif action == "ExternalScan":
265 scanapi.externalprobe(str(hostname))
266 flash("External Scan Successful!")
267 elif action == "InternalScan":
268 scanapi.internalprobe(str(hostname))
269 flash("Internal Scan Successful!")
272 raise RuntimeError("Unknown action given")
275 # TODO: add form validation
276 @expose(template="monitorweb.templates.pcuview")
277 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
278 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
288 if 'submit' in data.keys() or 'type' in data.keys():
289 if hostname: data['hostname'] = hostname
290 self.nodeaction(**data)
291 if 'exceptions' in data:
292 exceptions = data['exceptions']
295 actions = ActionRecord.query.filter_by(loginbase=loginbase).order_by(ActionRecord.date_created.desc())
296 actions = [ a for a in actions ]
297 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
299 for plcnode in site_lb2hn[loginbase]:
300 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
301 # NOTE: reformat some fields.
302 prep_node_for_display(node)
304 if node.plc_pcuid: # not None
305 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
306 prep_pcu_for_display(pcu)
307 pcus[node.plc_pcuid] = pcu
309 for pcuid_key in pcus:
310 pcuquery += [pcus[pcuid_key]]
312 if pcuid and hostname is None:
313 print "pcuid: %s" % pcuid
314 for pcu in FindbadPCURecord.get_latest_by(plc_pcuid=pcuid):
316 prep_pcu_for_display(pcu)
318 if 'site_id' in pcu.plc_pcu_stats:
319 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
321 if 'nodenames' in pcu.plc_pcu_stats:
322 for nodename in pcu.plc_pcu_stats['nodenames']:
323 print "query for %s" % nodename
324 q = FindbadNodeRecord.get_latest_by(hostname=nodename)
326 print "%s" % node.port_status
327 print "%s" % node.to_dict()
328 print "%s" % len(q.all())
330 prep_node_for_display(node)
333 if hostname and pcuid is None:
334 for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
335 # NOTE: reformat some fields.
336 prep_node_for_display(node)
337 sitequery = [node.site]
339 if node.plc_pcuid: # not None
340 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
341 prep_pcu_for_display(pcu)
344 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
346 @expose(template="monitorweb.templates.pculist")
347 def pcu(self, filter='all'):
349 fbquery = FindbadPCURecord.get_all_latest()
351 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
355 if node.reboot_trial_status == str(0):
356 filtercount['ok'] += 1
357 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
358 filtercount[node.reboot_trial_status] += 1
360 filtercount['pending'] += 1
362 prep_pcu_for_display(node)
367 elif filter == "ok" and node.reboot_trial_status == str(0):
369 elif filter == node.reboot_trial_status:
371 elif filter == "pending":
372 # TODO: look in message logs...
373 if node.reboot_trial_status != str(0) and \
374 node.reboot_trial_status != 'NetDown' and \
375 node.reboot_trial_status != 'Not_Run':
379 return dict(query=query, fc=filtercount)
381 @expose(template="monitorweb.templates.siteview")
382 def siteview(self, loginbase='pl'):
384 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
386 for plcnode in site_lb2hn[loginbase]:
387 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
388 # NOTE: reformat some fields.
389 prep_node_for_display(node)
391 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
393 @expose(template="monitorweb.templates.sitelist")
394 def site(self, filter='all'):
395 filtercount = {'good' : 0, 'down': 0, 'online':0, 'offline' : 0, 'new' : 0, 'pending' : 0, 'all' : 0}
396 fbquery = HistorySiteRecord.query.all()
400 filtercount['all'] += 1
401 if site.new and site.slices_used == 0 and not site.enabled:
402 filtercount['new'] += 1
403 elif not site.enabled:
404 filtercount['pending'] += 1
406 filtercount[site.status] += 1
411 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
413 elif filter == "pending" and not site.enabled:
415 elif filter == site.status:
418 return dict(query=query, fc=filtercount)
420 @expose(template="monitorweb.templates.actionlist")
421 def action(self, filter='all'):
422 session.bind = metadata.bind
423 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
424 # With Acknowledgement
425 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
426 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
427 ' WHERE f.itemid=i.itemid ' + \
428 ' AND h.hostid=i.hostid ' + \
429 ' AND hg.hostid=h.hostid ' + \
430 ' AND t.triggerid=f.triggerid ' + \
431 ' AND t.triggerid=e.triggerid ' + \
432 ' AND a.eventid=e.eventid ' + \
433 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
434 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
435 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
436 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
437 ' ORDER BY t.lastchange DESC';
439 # WithOUT Acknowledgement
440 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
441 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
442 ' WHERE f.itemid=i.itemid ' + \
443 ' AND h.hostid=i.hostid ' + \
444 ' AND hg.hostid=h.hostid ' + \
445 ' AND t.triggerid=f.triggerid ' + \
446 ' AND t.triggerid=e.triggerid ' + \
447 ' AND e.eventid not in (select eventid from acknowledges) ' + \
448 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
449 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
450 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
451 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
452 ' ORDER BY t.lastchange DESC';
453 # for i in session.execute(sql): print i
456 replace = re.compile(' {.*}')
457 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
458 result = session.execute(sql)
461 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
463 print site_hn2lb.keys()
464 newrow = [ "unknown" ] + [ r for r in row ]
466 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
469 filtercount['all'] += 1
470 if not ack: # for unacknowledged
471 filtercount['active'] += 1
472 if filter == 'active':
475 filtercount['acknowledged'] += 1
476 if filter == 'acknowledged':
479 if filter != "acknowledged" and filter != "active":
482 return dict(query=query, fc=filtercount)