eyes / eyeswebapp / core /

Full commit
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseBadRequest, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext

from django import forms
from django.forms import ModelForm

import os
import time
from core.models import Monitor
from core.models import Host
from core.models import Datastore
from util.monitor import ArgSet
from util.nagios import NagiosPoller

Core Views

* models supporting the core monitoring infrastructure


class HostForm(ModelForm):
    class Meta:
        model = Host

class MonitorForm(ModelForm):
    class Meta:
        model = Monitor

class NewMonitorForm(forms.Form):
    plugin_list = NagiosPoller().plugin_list()
    plugin_choices = []
    for plugin_name in plugin_list:
        plugin_choices.append((plugin_name, plugin_name,))
    host_queryset = Host.objects.all()
    name = forms.CharField(max_length=250)  # user specified name
    plugin_name = forms.ChoiceField(choices=plugin_choices)  # names of nagios plugins - like check_snmp
    # normally set , initial="check_ping" for the plugin_name
    # but avoiding it due to rendering bug in jQueryMobile 1.0a2
    argument = forms.CharField()  # string argument...
    alerting = forms.BooleanField(initial=True, required=False)
    passive = forms.BooleanField(initial=False, required=False)  # identifies a passive monitor
    host = forms.ModelChoiceField(queryset=host_queryset, empty_label="(No Host)")

    # if request.method == 'POST': # If the form has been submitted...
    #     form = ContactForm(request.POST) # A form bound to the POST data
    #     if form.is_valid():
    #         subject = form.cleaned_data['subject']
    #         message = form.cleaned_data['message']
    #         sender = form.cleaned_data['sender']
    #         cc_myself = form.cleaned_data['cc_myself']
    #         return HttpResponseRedirect('/thanks/') # Redirect after POST
    # else:
    #     form = ContactForm() # An unbound form
    # return render_to_response('contact.html', {
    #     'form': form,
    # })

def render_response(req, *args, **kwargs):
    """ a variation on render_to_response that inserts the RequestContext
    into each template context from these views."""
    kwargs['context_instance'] = RequestContext(req)
    return render_to_response(*args, **kwargs)

#user profile view - supporting authentication/users
def userprofile(request):
    return render_response(request, 'registration/user_profile.html', {})

# Create your views here.
def index(request):
    """ default web view for the 'front page' of the web application. """
    # user = User.get_by_key_name('admin')
    # if not user or user.username != 'admin' or not (user.is_active and
    #         user.is_staff and user.is_superuser and
    #         user.check_password('admin')):
    #     user = User(key_name='admin', username='admin',
    #         email='admin@localhost', first_name='Boss', last_name='Admin',
    #         is_active=True, is_staff=True, is_superuser=True)
    #     user.set_password('admin')
    #     user.put()
    monitors_in_unknown = Monitor.objects.filter(latest_state=3)
    monitors_in_error = Monitor.objects.filter(latest_state=2)
    monitors_in_warning = Monitor.objects.filter(latest_state=1)
    return render_response(request, 'core/monitor_list.html',
        'monitors_in_unknown': monitors_in_unknown,
        'monitors_in_error': monitors_in_error,
        'monitors_in_warning': monitors_in_warning,

def visual_test(request):
    """ test view """
    context_dict = {}
    context_dict['error'] = "this is an error message"
    context_dict['info'] = "information message"
    message_list = ["message1", "a much longer message 2 is inserted in this location to work the sizing of the format."]
    context_dict['messages'] = message_list
    return render_response(request, 'visualtest.html', context_dict)

def host_detail(request, host_id):
    """ detail view of the individual monitor"""
    host = get_object_or_404(Host, pk=host_id)
    return render_response(request, 'core/host_detail.html', {'host': host})

def monitor_detail(request, monitor_id):
    """ detail view of the individual monitor"""
    mon = get_object_or_404(Monitor, pk=monitor_id)
    form = MonitorForm(instance=mon)
    if request.method == 'POST':
        form = MonitorForm(request.POST, instance=mon)
        if form.is_valid():
    return render_response(request, 'core/monitor_detail.html', {'monitor': mon, 'form': form,})

def datastore_detail(request, datastore_id):
    """ detail view of the individual monitor"""
    this_ds = get_object_or_404(Datastore, pk=datastore_id)
    return render_response(request, 'core/datastore_detail.html', {'datastore': this_ds})

def datastore_image(request, datastore_id):
    png result of graphing an individual datastore element
    code thoughts on dynamic generation:
    this_ds = get_object_or_404(Datastore, pk=datastore_id)
    name = "%s.png" % (, )
    png_file = os.path.join(this_ds.png_path, name)
    # check to see if file exists, if not - create:
    if not(os.path.exists(png_file)):
    # check to see if file is older than 5 minutes, if so, regen.
    modified_sec = os.path.getmtime(png_file)
    five_min_ago = time.time() - (60 * 5)
    if modified_sec < five_min_ago:
    from django.core.servers.basehttp import FileWrapper
    wrapper = FileWrapper(file(png_file))
    response = HttpResponse(wrapper, content_type='image/png')
    response['Content-Length'] = os.path.getsize(png_file)
    return response

def host_list(request):
    host_list = Host.objects.all()
    form = HostForm()
    if request.method == 'POST':
        form = HostForm(request.POST)
        if form.is_valid():
    return render_response(request, 'core/host_list.html', {'host_list': host_list, 'form': form})

def monitor_list(request):
    """ default web view for the 'front page' of the web application. """
    monitor_list = Monitor.objects.all()
    form = NewMonitorForm()
    if request.method == 'POST': # If the form has been submitted...
        form = NewMonitorForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            print "Starting..."
            new_monitor = Monitor()
   = form.cleaned_data['host']
   = form.cleaned_data['name']
            new_monitor.alerting = form.cleaned_data['alerting']
            new_monitor.passive = form.cleaned_data['passive']
            new_monitor.plugin_name = form.cleaned_data['plugin_name']
            print "created the newmonitor..."
            argset = ArgSet()
            a_string = form.cleaned_data['argument']
            import simplejson
            print a_string
            print a_string.__class__
            foo = simplejson.loads(a_string)
            # for string_arg in request.POST.getlist('argument'):
            #     argset.add_argument(string_arg)
            new_monitor.arg_set = argset
            print "saving..."
            print new_monitor
    return render_response(request, 'core/monitor_list.html', {'monitor_list': monitor_list, 'form': form})

def plugin_list(request):
    """ returns an HTML list of the plugins from the built in Poller (NagiosPoller)"""
    nagios_based_poller = NagiosPoller()
    list_of_plugins = nagios_based_poller.plugin_list()
    return render_response(request, 'core/plugin_list.html', {'plugin_list': list_of_plugins})

def test_monitor(request, plugin_name):
    """ runs and returns the result of running help on a specific monitor plugin """
    nagios_based_poller = NagiosPoller()
    help_monitor_result = nagios_based_poller.plugin_help(plugin_name)
    return render_response(request, 'core/test_monitor.html',
                        {'plugin_name': plugin_name,
                         'monitor_result': help_monitor_result})

def ajax_monitor(request, plugin_name):
    """ AJAX method that invokes a monitor and returns the MonitorResult object"""
    nagios_based_poller = NagiosPoller()
    # .plugin_help(plugin_name)
    # .run_plugin(plugin_name, argset)
    if request.is_ajax():
        mimetype = 'application/javascript'
        if request.method == 'GET':
            help_monitor_result = nagios_based_poller.plugin_help(plugin_name)
            json_data = help_monitor_result.json()
        elif request.method == 'POST':
            # expected to get a set of key labeled "argument" - with 1..4 (or higher) elements
            argset = ArgSet()
            for string_arg in request.POST.getlist('argument'):
            mon_result = nagios_based_poller.run_plugin(plugin_name, argset)
            json_data = mon_result.json()
        return HttpResponse(json_data, mimetype)
        return HttpResponseBadRequest