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)
136 node.history = HistoryNodeRecord.by_hostname(node.hostname)
138 node.ports = format_ports(node.port_status)
141 exists = node.plc_node_stats['last_contact']
143 node.plc_node_stats = {'last_contact' : None}
147 class Root(controllers.RootController):
148 @expose(template="monitorweb.templates.welcome")
151 # log.debug("Happy TurboGears Controller Responding For Duty")
152 flash("Your application is now running")
153 return dict(now=time.ctime())
155 @expose(template="monitorweb.templates.pcuview")
156 def nodeview(self, hostname=None):
159 for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
160 # NOTE: reformat some fields.
161 prep_node_for_display(node)
164 return self.pcuview(None, hostname) # dict(nodequery=nodequery)
166 @expose(template="monitorweb.templates.nodelist")
167 def node(self, filter='BOOT'):
169 fbquery = FindbadNodeRecord.get_all_latest()
171 filtercount = {'DOWN' : 0, 'BOOT': 0, 'DEBUG' : 0, 'neverboot' : 0, 'pending' : 0, 'all' : 0}
173 # NOTE: reformat some fields.
174 prep_node_for_display(node)
176 # NOTE: count filters
177 if node.observed_status != 'DOWN':
178 filtercount[node.observed_status] += 1
180 if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
181 filtercount[node.observed_status] += 1
183 filtercount['neverboot'] += 1
186 if filter == node.observed_status:
188 if node.plc_node_stats['last_contact'] != None:
192 elif filter == "neverboot":
193 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
195 elif filter == "pending":
196 # TODO: look in message logs...
198 elif filter == "all":
201 widget = NodeWidget(template='monitorweb.templates.node_template')
202 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
204 def nodeaction_handler(self, tg_exceptions=None):
205 """Handle any kind of error."""
207 if 'pcuid' in request.params:
208 pcuid = request.params['pcuid']
210 refurl = request.headers.get("Referer",link("pcu"))
213 # TODO: do this more intelligently...
214 uri_fields = urllib.splitquery(refurl)
215 if uri_fields[1] is not None:
216 val = query_to_dict(uri_fields[1])
219 elif 'hostname' in val:
220 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).first().plc_pcuid
226 cherry_trail = cherrypy._cputil.get_object_trail()
227 for i in cherry_trail:
231 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
233 def nodeaction(self, **data):
234 for item in data.keys():
235 print "%s %s" % ( item, data[item] )
237 if 'hostname' in data:
238 hostname = data['hostname']
240 flash("No hostname given in submitted data")
243 if 'submit' in data or 'type' in data:
245 action = data['submit']
247 action = data['type']
249 flash("No submit action given in submitted data")
252 if action == "Reboot":
253 print "REBOOT: %s" % hostname
254 ret = reboot.reboot_str(str(hostname))
256 if ret: raise RuntimeError("Error using PCU: " + str(ret))
257 flash("Reboot appeared to work. All at most 5 minutes. Run ExternalScan to check current status.")
259 elif action == "ExternalScan":
260 scanapi.externalprobe(str(hostname))
261 flash("External Scan Successful!")
262 elif action == "InternalScan":
263 scanapi.internalprobe(str(hostname))
264 flash("Internal Scan Successful!")
267 raise RuntimeError("Unknown action given")
270 # TODO: add form validation
271 @expose(template="monitorweb.templates.pcuview")
272 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
273 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
282 if 'submit' in data.keys() or 'type' in data.keys():
283 if hostname: data['hostname'] = hostname
284 self.nodeaction(**data)
285 if 'exceptions' in data:
286 exceptions = data['exceptions']
289 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
291 for plcnode in site_lb2hn[loginbase]:
292 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
293 # NOTE: reformat some fields.
294 prep_node_for_display(node)
296 if node.plc_pcuid: # not None
297 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
298 prep_pcu_for_display(pcu)
299 pcus[node.plc_pcuid] = pcu
301 for pcuid_key in pcus:
302 pcuquery += [pcus[pcuid_key]]
304 if pcuid and hostname is None:
305 print "pcuid: %s" % pcuid
306 for pcu in FindbadPCURecord.get_latest_by(plc_pcuid=pcuid):
308 prep_pcu_for_display(pcu)
310 if 'site_id' in pcu.plc_pcu_stats:
311 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
313 if 'nodenames' in pcu.plc_pcu_stats:
314 for nodename in pcu.plc_pcu_stats['nodenames']:
315 print "query for %s" % nodename
316 q = FindbadNodeRecord.get_latest_by(hostname=nodename)
318 print "%s" % node.port_status
319 print "%s" % node.to_dict()
320 print "%s" % len(q.all())
322 prep_node_for_display(node)
325 if hostname and pcuid is None:
326 for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
327 # NOTE: reformat some fields.
328 prep_node_for_display(node)
329 sitequery = [node.site]
331 if node.plc_pcuid: # not None
332 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
333 prep_pcu_for_display(pcu)
336 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, exceptions=exceptions)
338 @expose(template="monitorweb.templates.pculist")
339 def pcu(self, filter='all'):
341 fbquery = FindbadPCURecord.get_all_latest()
343 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
347 if node.reboot_trial_status == str(0):
348 filtercount['ok'] += 1
349 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
350 filtercount[node.reboot_trial_status] += 1
352 filtercount['pending'] += 1
354 prep_pcu_for_display(node)
359 elif filter == "ok" and node.reboot_trial_status == str(0):
361 elif filter == node.reboot_trial_status:
363 elif filter == "pending":
364 # TODO: look in message logs...
365 if node.reboot_trial_status != str(0) and \
366 node.reboot_trial_status != 'NetDown' and \
367 node.reboot_trial_status != 'Not_Run':
371 return dict(query=query, fc=filtercount)
373 @expose(template="monitorweb.templates.siteview")
374 def siteview(self, loginbase='pl'):
376 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
378 for plcnode in site_lb2hn[loginbase]:
379 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
380 # NOTE: reformat some fields.
381 prep_node_for_display(node)
383 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
385 @expose(template="monitorweb.templates.sitelist")
386 def site(self, filter='all'):
387 filtercount = {'good' : 0, 'down': 0, 'new' : 0, 'pending' : 0, 'all' : 0}
388 fbquery = HistorySiteRecord.query.all()
392 filtercount['all'] += 1
393 if site.new and site.slices_used == 0 and not site.enabled:
394 filtercount['new'] += 1
395 elif not site.enabled:
396 filtercount['pending'] += 1
398 filtercount[site.status] += 1
403 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
405 elif filter == "pending" and not site.enabled:
407 elif filter == site.status:
410 return dict(query=query, fc=filtercount)
412 @expose(template="monitorweb.templates.actionlist")
413 def action(self, filter='all'):
414 session.bind = metadata.bind
415 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
416 # With Acknowledgement
417 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
418 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
419 ' WHERE f.itemid=i.itemid ' + \
420 ' AND h.hostid=i.hostid ' + \
421 ' AND hg.hostid=h.hostid ' + \
422 ' AND t.triggerid=f.triggerid ' + \
423 ' AND t.triggerid=e.triggerid ' + \
424 ' AND a.eventid=e.eventid ' + \
425 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
426 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
427 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
428 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
429 ' ORDER BY t.lastchange DESC';
431 # WithOUT Acknowledgement
432 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
433 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
434 ' WHERE f.itemid=i.itemid ' + \
435 ' AND h.hostid=i.hostid ' + \
436 ' AND hg.hostid=h.hostid ' + \
437 ' AND t.triggerid=f.triggerid ' + \
438 ' AND t.triggerid=e.triggerid ' + \
439 ' AND e.eventid not in (select eventid from acknowledges) ' + \
440 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
441 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
442 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
443 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
444 ' ORDER BY t.lastchange DESC';
445 # for i in session.execute(sql): print i
448 replace = re.compile(' {.*}')
449 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
450 result = session.execute(sql)
453 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
455 print site_hn2lb.keys()
456 newrow = [ "unknown" ] + [ r for r in row ]
458 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
461 filtercount['all'] += 1
462 if not ack: # for unacknowledged
463 filtercount['active'] += 1
464 if filter == 'active':
467 filtercount['acknowledged'] += 1
468 if filter == 'acknowledged':
471 if filter != "acknowledged" and filter != "active":
474 return dict(query=query, fc=filtercount)