moved found_within to common.py
[monitor.git] / web / MonitorWeb / monitorweb / controllers.py
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
5 import cherrypy
6 # from monitorweb import model
7 # import logging
8 # log = logging.getLogger("monitorweb.controllers")
9 import re
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
14
15 from monitor import reboot
16 from monitor import scanapi
17
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
21
22 from monitorweb.templates.links import *
23
24
25
26 def query_to_dict(query):
27         """ take a url query string and chop it up """
28         val = {}
29         query_fields = query.split('&')
30         for f in query_fields:
31                 (k,v) = urllib.splitvalue(f)
32                 val[k] = v
33
34         return val
35
36 def format_ports(data, pcumodel=None):
37         retval = []
38         filtered_length=0
39
40         if pcumodel:
41                 supported_ports=reboot.model_to_object(pcumodel).supported_ports
42         else:
43                 # ports of a production node
44                 supported_ports=[22,80,806]
45
46         if data and len(data.keys()) > 0 :
47                 for port in supported_ports:
48                         try:
49                                 state = data[str(port)]
50                         except:
51                                 state = "unknown"
52
53                         if state == "filtered":
54                                 filtered_length += 1
55                                 
56                         retval.append( (port, state) )
57
58         if retval == []: 
59                 retval = [( "Closed/Filtered", "state" )]
60
61         if filtered_length == len(supported_ports):
62                 retval = [( "All Filtered", "state" )]
63
64         return retval
65
66 def format_pcu_shortstatus(pcu):
67         status = "error"
68         if pcu:
69                 if pcu.reboot_trial_status == str(0):
70                         status = "Ok"
71                 elif pcu.reboot_trial_status == "NetDown" or pcu.reboot_trial_status == "Not_Run":
72                         status = pcu.reboot_trial_status
73                 else:
74                         status = "error"
75
76         return status
77
78 def prep_pcu_for_display(pcu):
79                 
80         try:
81                 pcu.loginbase = site_id2lb[pcu.plc_pcu_stats['site_id']]
82         except:
83                 pcu.loginbase = "unknown"
84
85         pcu.ports = format_ports(pcu.port_status, pcu.plc_pcu_stats['model'])
86         pcu.status = format_pcu_shortstatus(pcu)
87
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'
101
102 class NodeWidget(widgets.Widget):
103         pass
104
105 def prep_node_for_display(node):
106         if node.plc_pcuid:
107                 pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
108                 if pcu:
109                         node.pcu_status = pcu.reboot_trial_status
110                         node.pcu_short_status = format_pcu_shortstatus(pcu)
111                         node.pcu = pcu
112                         prep_pcu_for_display(node.pcu)
113                 else:
114                         node.pcu_short_status = "none"
115                         node.pcu_status = "nodata"
116                         node.pcu = None
117
118         else:
119                 node.pcu_status = "nopcu"
120                 node.pcu_short_status = "none"
121                 node.pcu = None
122
123
124         if node.kernel_version:
125                 node.kernel = node.kernel_version.split()[2]
126         else:
127                 node.kernel = ""
128
129         try:
130                 node.loginbase = site_id2lb[node.plc_node_stats['site_id']]
131         except:
132                 node.loginbase = "unknown"
133
134         if node.loginbase:
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")
139                         
140
141         node.history = HistoryNodeRecord.by_hostname(node.hostname)
142
143         node.ports = format_ports(node.port_status)
144
145         try:
146                 exists = node.plc_node_stats['last_contact']
147         except:
148                 node.plc_node_stats = {'last_contact' : None}
149
150
151
152 class Root(controllers.RootController):
153         @expose(template="monitorweb.templates.welcome")
154         def index(self):
155                 import time
156                 # log.debug("Happy TurboGears Controller Responding For Duty")
157                 flash("Your application is now running")
158                 return dict(now=time.ctime())
159
160         @expose(template="monitorweb.templates.pcuview")
161         def nodeview(self, hostname=None):
162                 nodequery=[]
163                 if hostname:
164                         for node in FindbadNodeRecord.get_latest_by(hostname=hostname):
165                                 # NOTE: reformat some fields.
166                                 prep_node_for_display(node)
167                                 nodequery += [node]
168
169                 return self.pcuview(None, hostname) # dict(nodequery=nodequery)
170
171         @expose(template="monitorweb.templates.nodelist")
172         def node(self, filter='boot'):
173                 import time
174                 fbquery = FindbadNodeRecord.get_all_latest()
175                 query = []
176                 filtercount = {'down' : 0, 'boot': 0, 'debug' : 0, 'diagnose' : 0, 'disabled': 0, 
177                                                 'neverboot' : 0, 'pending' : 0, 'all' : 0, None : 0}
178                 for node in fbquery:
179                         # NOTE: reformat some fields.
180                         prep_node_for_display(node)
181
182                         node.history.status
183
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
187                                 else:
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
193                         else:
194                                 filtercount[node.history.status] += 1
195                                 
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
202                         #               else:
203                         #                       filtercount['debug'] += 1
204                         #                       
205                         #       else:
206                         #               filtercount[node.observed_status] += 1
207                         #else:
208                         #       if node.plc_node_stats and node.plc_node_stats['last_contact'] != None:
209                         #               filtercount[node.observed_status] += 1
210                         #       else:
211                         #               filtercount['neverboot'] += 1
212
213                         # NOTE: apply filter
214                         if filter == "neverboot":
215                                 if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
216                                         query.append(node)
217                         elif filter == "all":
218                                 query.append(node)
219                         elif filter == node.history.status:
220                                 query.append(node)
221
222                         #if filter == node.observed_status:
223                         #       if filter == "DOWN":
224                         #               if node.plc_node_stats['last_contact'] != None:
225                         #                       query.append(node)
226                         #       else:
227                         #               query.append(node)
228                         #elif filter == "neverboot":
229                         #       if not node.plc_node_stats or node.plc_node_stats['last_contact'] == None:
230                         #               query.append(node)
231                         #elif filter == "pending":
232                         #       # TODO: look in message logs...
233                         #       pass
234                         #elif filter == node.plc_node_stats['boot_state']:
235                         #       query.append(node)
236                         #elif filter == "all":
237                         #       query.append(node)
238                                 
239                 widget = NodeWidget(template='monitorweb.templates.node_template')
240                 return dict(now=time.ctime(), query=query, fc=filtercount, nodewidget=widget)
241         
242         def nodeaction_handler(self, tg_exceptions=None):
243                 """Handle any kind of error."""
244
245                 if 'pcuid' in request.params:
246                         pcuid = request.params['pcuid']
247                 else:
248                         refurl = request.headers.get("Referer",link("pcu"))
249                         print refurl
250
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])
255                                 if 'pcuid' in val:
256                                         pcuid = val['pcuid']
257                                 elif 'hostname' in val:
258                                         pcuid = FindbadNodeRecord.get_latest_by(hostname=val['hostname']).plc_pcuid
259                                 else:
260                                         pcuid=None
261                         else:
262                                 pcuid=None
263
264                 cherry_trail = cherrypy._cputil.get_object_trail()
265                 for i in cherry_trail:
266                         print "trail: ", i
267
268                 print pcuid
269                 return self.pcuview(None, pcuid, **dict(exceptions=tg_exceptions))
270
271         def nodeaction(self, **data):
272                 for item in data.keys():
273                         print "%s %s" % ( item, data[item] )
274
275                 if 'hostname' in data:
276                         hostname = data['hostname']
277                 else:
278                         flash("No hostname given in submitted data")
279                         return
280
281                 if 'submit' in data or 'type' in data:
282                         try:
283                                 action = data['submit']
284                         except:
285                                 action = data['type']
286                 else:
287                         flash("No submit action given in submitted data")
288                         return
289
290                 if action == "Reboot":
291                         print "REBOOT: %s" % hostname
292                         ret = reboot.reboot_str(str(hostname))
293                         print ret
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.")
296
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!")
303                 else:
304                         # unknown action
305                         raise RuntimeError("Unknown action given")
306                 return
307
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):
312                 sitequery=[]
313                 pcuquery=[]
314                 nodequery=[]
315                 actions=[]
316                 exceptions = None
317
318                 for key in data:
319                         print key, data[key]
320
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']
326
327                 if loginbase:
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)]
333                         pcus = {}
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)
338                                         nodequery += [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
343
344                         for pcuid_key in pcus:
345                                 pcuquery += [pcus[pcuid_key]]
346
347                 if pcuid and hostname is None:
348                         print "pcuid: %s" % pcuid
349                         pcu = FindbadPCURecord.get_latest_by(plc_pcuid=pcuid)
350                         # NOTE: count filter
351                         prep_pcu_for_display(pcu)
352                         pcuquery += [pcu]
353                         if 'site_id' in pcu.plc_pcu_stats:
354                                 sitequery = [HistorySiteRecord.by_loginbase(pcu.loginbase)]
355                                 
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()
362                                         if node:
363                                                 prep_node_for_display(node)
364                                                 nodequery += [node]
365
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]
371                                 nodequery += [node]
372                                 if node.plc_pcuid:      # not None
373                                         pcu = FindbadPCURecord.get_latest_by(plc_pcuid=node.plc_pcuid)
374                                         prep_pcu_for_display(pcu)
375                                         pcuquery += [pcu]
376                         
377                 return dict(sitequery=sitequery, pcuquery=pcuquery, nodequery=nodequery, actions=actions, exceptions=exceptions)
378
379         @expose(template="monitorweb.templates.pculist")
380         def pcu(self, filter='all'):
381                 import time
382                 fbquery = FindbadPCURecord.get_all_latest()
383                 query = []
384                 filtercount = {'ok' : 0, 'NetDown': 0, 'Not_Run' : 0, 'pending' : 0, 'all' : 0}
385                 for node in fbquery:
386
387                         # NOTE: count filter
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
392                         else:
393                                 filtercount['pending'] += 1
394
395                         prep_pcu_for_display(node)
396
397                         # NOTE: apply filter
398                         if filter == "all":
399                                 query.append(node)
400                         elif filter == "ok" and node.reboot_trial_status == str(0):
401                                 query.append(node)
402                         elif filter == node.reboot_trial_status:
403                                 query.append(node)
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':
409
410                                         query.append(node)
411                                 
412                 return dict(query=query, fc=filtercount)
413
414         @expose(template="monitorweb.templates.siteview")
415         def siteview(self, loginbase='pl'):
416                 # get site query
417                 sitequery = [HistorySiteRecord.by_loginbase(loginbase)]
418                 nodequery = []
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)
423                                 nodequery += [node]
424                 return dict(sitequery=sitequery, nodequery=nodequery, fc={})
425
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()
430                 query = []
431                 for site in fbquery:
432                         # count filter
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
438                         else:
439                                 filtercount[site.status] += 1
440
441                         # apply filter
442                         if filter == "all":
443                                 query.append(site)
444                         elif filter == 'new' and site.new and site.slices_used == 0 and not site.enabled:
445                                 query.append(site)
446                         elif filter == "pending" and not site.enabled:
447                                 query.append(site)
448                         elif filter == site.status:
449                                 query.append(site)
450                                 
451                 return dict(query=query, fc=filtercount)
452
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';
471
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
487
488                 query=[]
489                 replace = re.compile(' {.*}')
490                 for sql,ack in [(sql_ack,True), (sql_noack,False)]:
491                         result = session.execute(sql)
492                         for row in result:
493                                 try:
494                                         newrow = [ site_hn2lb[row[0].lower()] ] + [ r for r in row ]
495                                 except:
496                                         print site_hn2lb.keys()
497                                         newrow = [ "unknown" ] + [ r for r in row ]
498
499                                 newrow[2] = replace.sub("", newrow[2]) # strip {.*} expressions
500
501                                 # NOTE: filter count
502                                 filtercount['all'] += 1
503                                 if not ack: # for unacknowledged
504                                         filtercount['active'] += 1
505                                         if filter == 'active':
506                                                 query.append(newrow)
507                                 else:
508                                         filtercount['acknowledged'] += 1
509                                         if filter == 'acknowledged':
510                                                 query.append(newrow)
511                                         
512                                 if filter != "acknowledged" and filter != "active":
513                                         query.append(newrow)
514
515                 return dict(query=query, fc=filtercount)