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."""
206 refurl = request.headers.get("Referer",link("pcu"))
209 # TODO: do this more intelligently...
210 uri_fields = urllib.splitquery(refurl)
211 if uri_fields[1] is not None:
212 val = query_to_dict(uri_fields[1])
215 elif 'hostname' in val:
216 pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).first().plc_pcuid
220 cherry_trail = cherrypy._cputil.get_object_trail()
221 for i in cherry_trail:
225 return self.pcuview(pcuid, **dict(exceptions=tg_exceptions))
227 def nodeaction(self, **data):
228 for item in data.keys():
229 print "%s %s" % ( item, data[item] )
231 if 'hostname' in data:
232 hostname = data['hostname']
234 flash("No hostname given in submitted data")
237 if 'submit' in data or 'type' in data:
239 action = data['submit']
241 action = data['type']
243 flash("No submit action given in submitted data")
246 if action == "Reboot":
247 print "REBOOT: %s" % hostname
248 ret = reboot.reboot_str(str(hostname))
250 if ret: raise RuntimeError("Error using PCU: " + ret)
251 flash("Reboot appeared to work. All at most 5 minutes. Run ExternalScan to check current status.")
253 elif action == "ExternalScan":
254 scanapi.externalprobe(str(hostname))
255 flash("External Scan Successful!")
256 elif action == "InternalScan":
257 scanapi.internalprobe(str(hostname))
258 flash("Internal Scan Successful!")
261 raise RuntimeError("Unknown action given")
264 # TODO: add form validation
265 @expose(template="monitorweb.templates.pcuview")
266 @exception_handler(nodeaction_handler,"isinstance(tg_exceptions,RuntimeError)")
267 def pcuview(self, loginbase=None, pcuid=None, hostname=None, **data):
276 if 'submit' in data.keys() or 'type' in data.keys():
277 if hostname: data['hostname'] = hostname
278 self.nodeaction(**data)
279 if 'exceptions' in data:
280 exceptions = data['exceptions']
283 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
285 for plcnode in site_lb2hn[loginbase]:
286 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
287 # NOTE: reformat some fields.
288 prep_node_for_display(node)
290 if node.plc_pcuid: # not None
291 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
292 prep_pcu_for_display(pcu)
293 pcus[node.plc_pcuid] = pcu
295 for pcuid_key in pcus:
296 pcuquery += [pcus[pcuid_key]]
298 if pcuid and hostname is None:
299 print "pcuid: %s" % pcuid
300 for pcu in FindbadPCURecord.get_latest_by(plc_pcuid=pcuid):
302 prep_pcu_for_display(pcu)
304 if 'site_id' in pcu.plc_pcu_stats:
305 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
307 if 'nodenames' in pcu.plc_pcu_stats:
308 for nodename in pcu.plc_pcu_stats['nodenames']:
309 print "query for %s" % nodename
310 q = FindbadNodeRecord.get_latest_by(hostname=nodename)
312 print "%s" % node.port_status
313 print "%s" % node.to_dict()
314 print "%s" % len(q.all())
316 prep_node_for_display(node)
319 if hostname and pcuid is None:
320 for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
321 # NOTE: reformat some fields.
322 prep_node_for_display(node)
323 sitequery = [node.site]
325 if node.plc_pcuid: # not None
326 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid).first()
327 prep_pcu_for_display(pcu)
330 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, exceptions=exceptions)
332 @expose(template="monitorweb.templates.pculist")
333 def pcu(self, filter='all'):
335 fbquery = FindbadPCURecord.get_all_latest()
337 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
341 if node.reboot_trial_status == str(0):
342 filtercount['ok'] += 1
343 elif node.reboot_trial_status == 'NetDown' or node.reboot_trial_status == 'Not_Run':
344 filtercount[node.reboot_trial_status] += 1
346 filtercount['pending'] += 1
348 prep_pcu_for_display(node)
353 elif filter == "ok" and node.reboot_trial_status == str(0):
355 elif filter == node.reboot_trial_status:
357 elif filter == "pending":
358 # TODO: look in message logs...
359 if node.reboot_trial_status != str(0) and \
360 node.reboot_trial_status != 'NetDown' and \
361 node.reboot_trial_status != 'Not_Run':
365 return dict(query=query, fc=filtercount)
367 @expose(template="monitorweb.templates.siteview")
368 def siteview(self, loginbase='pl'):
370 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
372 for plcnode in site_lb2hn[loginbase]:
373 for node in FindbadNodeRecord.get_latest_by(hostname=plcnode['hostname']):
374 # NOTE: reformat some fields.
375 prep_node_for_display(node)
377 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
379 @expose(template="monitorweb.templates.sitelist")
380 def site(self, filter='all'):
381 filtercount = {'good' : 0, 'down': 0, 'new' : 0, 'pending' : 0, 'all' : 0}
382 fbquery = HistorySiteRecord.query.all()
386 filtercount['all'] += 1
387 if site.new and site.slices_used == 0 and not site.enabled:
388 filtercount['new'] += 1
389 elif not site.enabled:
390 filtercount['pending'] += 1
392 filtercount[site.status] += 1
397 elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
399 elif filter == "pending" and not site.enabled:
401 elif filter == site.status:
404 return dict(query=query, fc=filtercount)
406 @expose(template="monitorweb.templates.actionlist")
407 def action(self, filter='all'):
408 session.bind = metadata.bind
409 filtercount = {'active' : 0, 'acknowledged': 0, 'all' : 0}
410 # With Acknowledgement
411 sql_ack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,a.message,e.eventid '+ \
412 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
413 ' WHERE f.itemid=i.itemid ' + \
414 ' AND h.hostid=i.hostid ' + \
415 ' AND hg.hostid=h.hostid ' + \
416 ' AND t.triggerid=f.triggerid ' + \
417 ' AND t.triggerid=e.triggerid ' + \
418 ' AND a.eventid=e.eventid ' + \
419 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
420 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
421 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
422 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
423 ' ORDER BY t.lastchange DESC';
425 # WithOUT Acknowledgement
426 sql_noack = 'SELECT DISTINCT h.host,t.description,t.priority,t.lastchange,e.eventid ' + \
427 ' FROM triggers t,hosts h,items i,functions f, hosts_groups hg,escalations e,acknowledges a ' + \
428 ' WHERE f.itemid=i.itemid ' + \
429 ' AND h.hostid=i.hostid ' + \
430 ' AND hg.hostid=h.hostid ' + \
431 ' AND t.triggerid=f.triggerid ' + \
432 ' AND t.triggerid=e.triggerid ' + \
433 ' AND e.eventid not in (select eventid from acknowledges) ' + \
434 ' AND t.status=' + str(defines.TRIGGER_STATUS_ENABLED) + \
435 ' AND i.status=' + str(defines.ITEM_STATUS_ACTIVE) + \
436 ' AND h.status=' + str(defines.HOST_STATUS_MONITORED) + \
437 ' AND t.value=' + str(defines.TRIGGER_VALUE_TRUE) + \
438 ' ORDER BY t.lastchange DESC';
439 # for i in session.execute(sql): print i
442 replace = re.compile(' {.*}')
443 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
444 result = session.execute(sql)
447 newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
449 print site_hn2lb.keys()
450 newrow = [ "unknown" ] + [ r for r in row ]
452 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
455 filtercount['all'] += 1
456 if not ack: # for unacknowledged
457 filtercount['active'] += 1
458 if filter == 'active':
461 filtercount['acknowledged'] += 1
462 if filter == 'acknowledged':
465 if filter != "acknowledged" and filter != "active":
468 return dict(query=query, fc=filtercount)