<commit_before># -*- coding: utf-8 -*-
#
# Copyright 2010, <NAME> <<EMAIL>>
#
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.shortcuts import render_to_response, redirect, HttpResponse, Http404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
import os
from os.path import dirname

from pynag.Model import ObjectDefinition, string_to_class
from pynag import Model
from pynag.Parsers import status
from collections import defaultdict, namedtuple
import pynag.Model

from adagios import settings
from adagios.objectbrowser.forms import *
from adagios.views import adagios_decorator


@adagios_decorator
def home(request):
    return redirect('adagios')


@adagios_decorator
def list_object_types(request):
    """ Collects statistics about pynag objects and returns to template """
    c = {}
    return render_to_response('list_object_types.html', c, context_instance=RequestContext(request))


@adagios_decorator
def geek_edit(request, object_id):
    """ Function handles POST requests for the geek edit form """
    c = {}
    c.update(csrf(request))
    c['messages'] = m = []
    c['errors'] = []

    # Get our object
    try:
        o = ObjectDefinition.objects.get_by_id(id=object_id)
    except Exception, e:
        # This is an ugly hack. If unknown object ID was specified and it so happens to
        # Be the same as a brand new empty object definition we will assume that we are
        # to create a new object definition instead of throwing error because ours was
        # not found.
        for i in Model.string_to_class.values():
            if i().get_id() == object_id:
                o = i()
                break
        else:
            c['error_summary'] = 'Unable to find object'
            c['error'] = e
            return render_to_response('error.html', c, context_instance=RequestContext(request))
    c['my_object'] = o
    if request.method == 'POST':
        # Manual edit of the form
        form = GeekEditObjectForm(pynag_object=o, data=request.POST)
        if form.is_valid():
            try:
                form.save()
                m.append("Object Saved manually to '%s'" % o['filename'])
            except Exception, e:
                c['errors'].append(e)
                return render_to_response('edit_object.html', c, context_instance=RequestContext(request))
        else:
            c['errors'].append("Problem with saving object")
            return render_to_response('edit_object.html', c, context_instance=RequestContext(request))
    else:
        form = GeekEditObjectForm(
            initial={'definition': o['meta']['raw_definition'], })

    c['geek_edit'] = form
    # Lets return the user to the general edit_object form
    return HttpResponseRedirect(reverse('edit_object', kwargs={'object_id': o.get_id()}))


@adagios_decorator
def advanced_edit(request, object_id):
    """ Handles POST only requests for the "advanced" object edit form. """
    c = {}
    c.update(csrf(request))
    c['messages'] = m = []
    c['errors'] = []
    # Get our object
    try:
        o = ObjectDefinition.objects.get_by_id(id=object_id)
        c['my_object'] = o
    except Exception, e:
        # This is an ugly hack. If unknown object ID was specified and it so happens to
        # Be the same as a brand new empty object definition we will assume that we are
        # to create a new object definition instead of throwing error because ours was
        # not found.
        for i in Model.string_to_class.values():
            if i().get_id() == object_id:
                o = i()
                break
        else:
            c['error_summary'] = 'Unable to get object'
            c['error'] = e
            return render_to_response('error.html', c, context_instance=RequestContext(request))

    if request.method == 'POST':
        # User is posting data into our form
        c['advanced_form'] = AdvancedEditForm(
            pynag_object=o, initial=o._original_attributes, data=request.POST)
        if c['advanced_form'].is_valid():
            try:
                c['advanced_form'].save()
                m.append("Object Saved to %s" % o['filename'])
            except Exception, e:
                c['errors'].append(e)
                return render_to_response('edit_object.html', c, context_instance=RequestContext(request))
    else:
            c['errors'].append("Problem reading form input")
            return render_to_response('edit_object.html', c, context_instance=RequestContext(request))

    return HttpResponseRedirect(reverse('edit_object', args=[o.get_id()]))


@adagios_decorator
def edit_object(request, object_id=None):
    """ Brings up an edit dialog for one specific object.

        If an object_id is specified, bring us to that exact object.

        Otherwise we expect some search arguments to have been provided via querystring
    """
    c = {}
    c.update(csrf(request))
    c['messages'] = []
    c['errors'] = []
    my_object = None  # This is where we store our item that we are editing

    # If object_id was not provided, lets see if anything was given to us in a querystring
    if not object_id:
        objects = pynag.Model.ObjectDefinition.objects.filter(**request.GET)
        if len(objects) == 1:
            my_object = objects[0]
        else:
            return search_objects(request)
    else:
        try:
            my_object = pynag.Model.ObjectDefinition.objects.get_by_id(object_id)
        except KeyError:
            c['error_summary'] = 'Could not find any object with id="%s" :/' % object_id
            c['error_type'] = "object not found"
            return render_to_response('error.html', c, context_instance=RequestContext(request))

    if request.method == 'POST':
        # User is posting data into our form
        c['form'] = PynagForm(
            pynag_object=my_object,
            initial=my_object._original_attributes,
            data=request.POST
        )
        if c['form'].is_valid():
            try:
                c['form'].save()
                c['messages'].append("Object Saved to %s" % my_object['filename'])
                return HttpResponseRedirect(reverse('edit_object', kwargs={'object_id': my_object.get_id()}))
            except Exception, e:
                c['errors'].append(e)
        else:
            c['errors'].append("Could not validate form input")
    if 'form' not in c:
        c['form'] = PynagForm(pynag_object=my_object, initial=my_object._original_attributes)
    c['my_object'] = my_object
    c['geek_edit'] = GeekEditObjectForm(
        initial={'definition': my_object['meta']['raw_definition'], })
    c['advanced_form'] = AdvancedEditForm(
        pynag_object=my_object, initial=my_object._original_attributes)

    try:
        c['effective_hosts'] = my_object.get_effective_hosts()
    except KeyError, e:
        c['errors'].append("Could not find host: %s" % str(e))
    except AttributeError:
        pass

    try:
        c['effective_parents'] = my_object.get_effective_parents()
    except KeyError, e:
        c['errors'].append("Could not find parent: %s" % str(e))

    # Every object type has some special treatment, so lets resort
    # to appropriate helper function
    if False:
        pass
    elif my_object['object_type'] == 'servicegroup':
        return _edit_servicegroup(request, c)
    elif my_object['object_type'] == 'hostdependency':
        return _edit_hostdependency(request, c)
    elif my_object['object_type'] == 'service':
        return _edit_service(request, c)
    elif my_object['object_type'] == 'contactgroup':
        return _edit_contactgroup(request, c)
    elif my_object['object_type'] == 'hostgroup':
        return _edit_hostgroup(request, c)
    elif my_object['object_type'] == 'host':
        return _edit_host(request, c)
    elif my_object['object_type'] == 'contact':
        return _edit_contact(request, c)
    elif my_object['object_type'] == 'command':
        return _edit_command(request, c)
    elif my_object['object_type'] == 'servicedependency':
        return _edit_servicedependency(request, c)
    elif my_object['object_type'] == 'timeperiod':
        return _edit_timeperiod(request, c)
    else:
        return render_to_response('edit_object.html', c, context_instance=RequestContext(request))


def _edit_contact(request, c):
    """ This is a helper function to edit_object """
    try:
        c['effective_contactgroups'] = c[
            'my_object'].get_effective_contactgroups()
    except KeyError, e:
        c['errors'].append("Could not find contact: %s" % str(e))

    return render_to_response('edit_contact.html', c, context_instance=RequestContext(request))


def _edit_service(request, c):
    """ This is a helper function to edit_object """
    service = c['my_object']
    try:
        c['command_line'] = service.get_effective_command_line()
    except KeyError:
        c['command_line'] = None
    try:
        c['object_macros'] = service.get_all_macros()
    except KeyError:
        c['object_macros'] = None
    # Get the current status from Nagios
    try:
        s = status()
        s.parse()
        c['status'] = s.get_servicestatus(
            service['host_name'], service['service_description'])
        current_state = c['status']['current_state']
        if current_state == "0":
            c['status']['text'] = 'OK'
            c['status']['css_label'] = 'label-success'
        elif current_state == "1":
            c['status']['text'] = 'Warning'
            c['status']['css_label'] = 'label-warning'
        elif current_state == "2":
            c['status']['text'] = 'Critical'
            c['status']['css_label'] = 'label-important'
        else:
            c['status']['text'] = 'Unknown'
            c['status']['css_label'] = 'label-inverse'
    except Exception:
        pass

    try:
        c['effective_servicegroups'] = service.get_effective_servicegroups()
    except KeyError, e:
        c['errors'].append("Could not find servicegroup: %s" % str(e))

    try:
        c['effective_contacts'] = service.get_effective_contacts()
    except KeyError, e:
        c['errors'].append("Could not find contact: %s" % str(e))

    try:
        c['effective_contactgroups'] = service.get_effective_contact_groups()
    except KeyError, e:
        c['errors'].append("Could not find contact_group: %s" % str(e))

    try:
        c['effective_hostgroups'] = service.get_effective_hostgroups()
    except KeyError, e:
        c['errors'].append("Could not find hostgroup: %s" % str(e))

    try:
        c['effective_command'] = service.get_effective_check_command()
    except KeyError, e:
        if service.check_command is not None:
            c['errors'].append("Could not find check_command: %s" % str(e))
        elif service.register != '0':
            c['errors'].append("You need to define a check command")

    # For the check_command editor, we inject current check_command and a list
    # of all check_commands
    c['check_command'] = (service.check_command or '').split("!")[0]
    c['command_names'] = map(
        lambda x: x.get("command_name", ''), Model.Command.objects.all)
    if c['check_command'] in (None, '', 'None'):
        c['check_command'] = ''

    return render_to_response('edit_service.html', c, context_instance=RequestContext(request))


def _edit_contactgroup(request, c):
    """ This is a helper function to edit_object """
    try:
        c['effective_contactgroups'] = c[
            'my_object'].get_effective_contactgroups()
    except KeyError, e:
        c['errors'].append("Could not find contact_group: %s" % str(e))

    try:
        c['effective_contacts'] = c['my_object'].get_effective_contacts()
    except KeyError, e:
        c['errors'].append("Could not find contact: %s" % str(e))

    try:
        c['effective_memberof'] = Model.Contactgroup.objects.filter(
            contactgroup_members__has_field=c['my_object'].contactgroup_name)
    except Exception, e:
        c['errors'].append(e)
    return render_to_response('edit_contactgroup.html', c, context_instance=RequestContext(request))


def _edit_hostgroup(request, c):
    """ This is a helper function to edit_object """
    hostgroup = c['my_object']
    try:
        c['effective_services'] = sorted(
            hostgroup.get_effective_services(), key=lambda x: x.get_description())
    except KeyError, e:
        c['errors'].append("Could not find service: %s" % str(e))
    try:
        c['effective_memberof'] = Model.Hostgroup.objects.filter(
            hostgroup_members__has_field=c['my_object'].hostgroup_name)
    except Exception, e:
        c['errors'].append(e)
    return render_to_response('edit_hostgroup.html', c, context_instance=RequestContext(request))


def _edit_servicegroup(request, c):
    """ This is a helper function to edit_object """
    try:
        c['effective_memberof'] = Model.Servicegroup.objects.filter(
            servicegroup_members__has_field=c['my_object'].servicegroup_name)
    except Exception, e:
        c['errors'].append(e)
    return render_to_response('edit_servicegroup.html', c, context_instance=RequestContext(request))


def _edit_command(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('edit_command.html', c, context_instance=RequestContext(request))


def _edit_hostdependency(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('edit_hostdepedency.html', c, context_instance=RequestContext(request))


def _edit_servicedependency(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('_edit_servicedependency.html', c, context_instance=RequestContext(request))


def _edit_timeperiod(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('edit_timeperiod.html', c, context_instance=RequestContext(request))


def _edit_host(request, c):
    """ This is a helper function to edit_object """
    host = c['my_object']
    try:
        c['command_line'] = host.get_effective_command_line()
    except KeyError:
        c['command_line'] = None
    try:
        c['object_macros'] = host.get_all_macros()
    except KeyError:
        c['object_macros'] = None

    if not 'errors' in c:
        c['errors'] = []

    try:
        c['effective_services'] = sorted(<commit_msg>objectbrowser/edit optimized<commit_after># -*- coding: utf-8 -*-
#
# Copyright 2010, <NAME> <<EMAIL>>
#
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.shortcuts import render_to_response, redirect, HttpResponse, Http404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
import os
from os.path import dirname

from pynag.Model import ObjectDefinition, string_to_class
from pynag import Model
from pynag.Parsers import status
import pynag.Utils
from collections import defaultdict, namedtuple
import pynag.Model

from adagios import settings
from adagios.objectbrowser.forms import *
from adagios.views import adagios_decorator


@adagios_decorator
def home(request):
    return redirect('adagios')


@adagios_decorator
def list_object_types(request):
    """ Collects statistics about pynag objects and returns to template """
    c = {}
    return render_to_response('list_object_types.html', c, context_instance=RequestContext(request))


@adagios_decorator
def geek_edit(request, object_id):
    """ Function handles POST requests for the geek edit form """
    c = {}
    c.update(csrf(request))
    c['messages'] = m = []
    c['errors'] = []

    # Get our object
    try:
        o = ObjectDefinition.objects.get_by_id(id=object_id)
    except Exception, e:
        # This is an ugly hack. If unknown object ID was specified and it so happens to
        # Be the same as a brand new empty object definition we will assume that we are
        # to create a new object definition instead of throwing error because ours was
        # not found.
        for i in Model.string_to_class.values():
            if i().get_id() == object_id:
                o = i()
                break
        else:
            c['error_summary'] = 'Unable to find object'
            c['error'] = e
            return render_to_response('error.html', c, context_instance=RequestContext(request))
    c['my_object'] = o
    if request.method == 'POST':
        # Manual edit of the form
        form = GeekEditObjectForm(pynag_object=o, data=request.POST)
        if form.is_valid():
            try:
                form.save()
                m.append("Object Saved manually to '%s'" % o['filename'])
            except Exception, e:
                c['errors'].append(e)
                return render_to_response('edit_object.html', c, context_instance=RequestContext(request))
        else:
            c['errors'].append("Problem with saving object")
            return render_to_response('edit_object.html', c, context_instance=RequestContext(request))
    else:
        form = GeekEditObjectForm(
            initial={'definition': o['meta']['raw_definition'], })

    c['geek_edit'] = form
    # Lets return the user to the general edit_object form
    return HttpResponseRedirect(reverse('edit_object', kwargs={'object_id': o.get_id()}))


@adagios_decorator
def advanced_edit(request, object_id):
    """ Handles POST only requests for the "advanced" object edit form. """
    c = {}
    c.update(csrf(request))
    c['messages'] = m = []
    c['errors'] = []
    # Get our object
    try:
        o = ObjectDefinition.objects.get_by_id(id=object_id)
        c['my_object'] = o
    except Exception, e:
        # This is an ugly hack. If unknown object ID was specified and it so happens to
        # Be the same as a brand new empty object definition we will assume that we are
        # to create a new object definition instead of throwing error because ours was
        # not found.
        for i in Model.string_to_class.values():
            if i().get_id() == object_id:
                o = i()
                break
        else:
            c['error_summary'] = 'Unable to get object'
            c['error'] = e
            return render_to_response('error.html', c, context_instance=RequestContext(request))

    if request.method == 'POST':
        # User is posting data into our form
        c['advanced_form'] = AdvancedEditForm(
            pynag_object=o, initial=o._original_attributes, data=request.POST)
        if c['advanced_form'].is_valid():
            try:
                c['advanced_form'].save()
                m.append("Object Saved to %s" % o['filename'])
            except Exception, e:
                c['errors'].append(e)
                return render_to_response('edit_object.html', c, context_instance=RequestContext(request))
    else:
            c['errors'].append("Problem reading form input")
            return render_to_response('edit_object.html', c, context_instance=RequestContext(request))

    return HttpResponseRedirect(reverse('edit_object', args=[o.get_id()]))


@adagios_decorator
def edit_object(request, object_id=None):
    """ Brings up an edit dialog for one specific object.

        If an object_id is specified, bring us to that exact object.

        Otherwise we expect some search arguments to have been provided via querystring
    """
    c = {}
    c.update(csrf(request))
    c['messages'] = []
    c['errors'] = []
    my_object = None  # This is where we store our item that we are editing

    # If object_id was not provided, lets see if anything was given to us in a querystring
    if not object_id:
        objects = pynag.Model.ObjectDefinition.objects.filter(**request.GET)
        if len(objects) == 1:
            my_object = objects[0]
        else:
            return search_objects(request)
    else:
        try:
            my_object = pynag.Model.ObjectDefinition.objects.get_by_id(object_id)
        except KeyError:
            c['error_summary'] = 'Could not find any object with id="%s" :/' % object_id
            c['error_type'] = "object not found"
            return render_to_response('error.html', c, context_instance=RequestContext(request))

    if request.method == 'POST':
        # User is posting data into our form
        c['form'] = PynagForm(
            pynag_object=my_object,
            initial=my_object._original_attributes,
            data=request.POST
        )
        if c['form'].is_valid():
            try:
                c['form'].save()
                c['messages'].append("Object Saved to %s" % my_object['filename'])
                return HttpResponseRedirect(reverse('edit_object', kwargs={'object_id': my_object.get_id()}))
            except Exception, e:
                c['errors'].append(e)
        else:
            c['errors'].append("Could not validate form input")
    if 'form' not in c:
        c['form'] = PynagForm(pynag_object=my_object, initial=my_object._original_attributes)
    c['my_object'] = my_object
    c['geek_edit'] = GeekEditObjectForm(
        initial={'definition': my_object['meta']['raw_definition'], })
    c['advanced_form'] = AdvancedEditForm(
        pynag_object=my_object, initial=my_object._original_attributes)

    try:
        c['effective_hosts'] = my_object.get_effective_hosts()
    except KeyError, e:
        c['errors'].append("Could not find host: %s" % str(e))
    except AttributeError:
        pass

    try:
        c['effective_parents'] = my_object.get_effective_parents(cache_only=True)
    except KeyError, e:
        c['errors'].append("Could not find parent: %s" % str(e))

    # Every object type has some special treatment, so lets resort
    # to appropriate helper function
    if False:
        pass
    elif my_object['object_type'] == 'servicegroup':
        return _edit_servicegroup(request, c)
    elif my_object['object_type'] == 'hostdependency':
        return _edit_hostdependency(request, c)
    elif my_object['object_type'] == 'service':
        return _edit_service(request, c)
    elif my_object['object_type'] == 'contactgroup':
        return _edit_contactgroup(request, c)
    elif my_object['object_type'] == 'hostgroup':
        return _edit_hostgroup(request, c)
    elif my_object['object_type'] == 'host':
        return _edit_host(request, c)
    elif my_object['object_type'] == 'contact':
        return _edit_contact(request, c)
    elif my_object['object_type'] == 'command':
        return _edit_command(request, c)
    elif my_object['object_type'] == 'servicedependency':
        return _edit_servicedependency(request, c)
    elif my_object['object_type'] == 'timeperiod':
        return _edit_timeperiod(request, c)
    else:
        return render_to_response('edit_object.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_contact(request, c):
    """ This is a helper function to edit_object """
    try:
        c['effective_contactgroups'] = c[
            'my_object'].get_effective_contactgroups()
    except KeyError, e:
        c['errors'].append("Could not find contact: %s" % str(e))

    return render_to_response('edit_contact.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_service(request, c):
    """ This is a helper function to edit_object """
    service = c['my_object']
    try:
        c['command_line'] = service.get_effective_command_line()
    except KeyError:
        c['command_line'] = None
    try:
        c['object_macros'] = service.get_all_macros()
    except KeyError:
        c['object_macros'] = None
    # Get the current status from Nagios
    try:
        s = status()
        s.parse()
        c['status'] = s.get_servicestatus(
            service['host_name'], service['service_description'])
        current_state = c['status']['current_state']
        if current_state == "0":
            c['status']['text'] = 'OK'
            c['status']['css_label'] = 'label-success'
        elif current_state == "1":
            c['status']['text'] = 'Warning'
            c['status']['css_label'] = 'label-warning'
        elif current_state == "2":
            c['status']['text'] = 'Critical'
            c['status']['css_label'] = 'label-important'
        else:
            c['status']['text'] = 'Unknown'
            c['status']['css_label'] = 'label-inverse'
    except Exception:
        pass

    try:
        c['effective_servicegroups'] = service.get_effective_servicegroups()
    except KeyError, e:
        c['errors'].append("Could not find servicegroup: %s" % str(e))

    try:
        c['effective_contacts'] = service.get_effective_contacts()
    except KeyError, e:
        c['errors'].append("Could not find contact: %s" % str(e))

    try:
        c['effective_contactgroups'] = service.get_effective_contact_groups()
    except KeyError, e:
        c['errors'].append("Could not find contact_group: %s" % str(e))

    try:
        c['effective_hostgroups'] = service.get_effective_hostgroups()
    except KeyError, e:
        c['errors'].append("Could not find hostgroup: %s" % str(e))

    try:
        c['effective_command'] = service.get_effective_check_command()
    except KeyError, e:
        if service.check_command is not None:
            c['errors'].append("Could not find check_command: %s" % str(e))
        elif service.register != '0':
            c['errors'].append("You need to define a check command")

    # For the check_command editor, we inject current check_command and a list
    # of all check_commands
    c['check_command'] = (service.check_command or '').split("!")[0]
    c['command_names'] = map(
        lambda x: x.get("command_name", ''), Model.Command.objects.all)
    if c['check_command'] in (None, '', 'None'):
        c['check_command'] = ''

    return render_to_response('edit_service.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_contactgroup(request, c):
    """ This is a helper function to edit_object """
    try:
        c['effective_contactgroups'] = c[
            'my_object'].get_effective_contactgroups()
    except KeyError, e:
        c['errors'].append("Could not find contact_group: %s" % str(e))

    try:
        c['effective_contacts'] = c['my_object'].get_effective_contacts()
    except KeyError, e:
        c['errors'].append("Could not find contact: %s" % str(e))

    try:
        c['effective_memberof'] = Model.Contactgroup.objects.filter(
            contactgroup_members__has_field=c['my_object'].contactgroup_name)
    except Exception, e:
        c['errors'].append(e)
    return render_to_response('edit_contactgroup.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_hostgroup(request, c):
    """ This is a helper function to edit_object """
    hostgroup = c['my_object']
    try:
        c['effective_services'] = sorted(
            hostgroup.get_effective_services(), key=lambda x: x.get_description())
    except KeyError, e:
        c['errors'].append("Could not find service: %s" % str(e))
    try:
        c['effective_memberof'] = Model.Hostgroup.objects.filter(
            hostgroup_members__has_field=c['my_object'].hostgroup_name)
    except Exception, e:
        c['errors'].append(e)
    return render_to_response('edit_hostgroup.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_servicegroup(request, c):
    """ This is a helper function to edit_object """
    try:
        c['effective_memberof'] = Model.Servicegroup.objects.filter(
            servicegroup_members__has_field=c['my_object'].servicegroup_name)
    except Exception, e:
        c['errors'].append(e)
    return render_to_response('edit_servicegroup.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_command(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('edit_command.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_hostdependency(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('edit_hostdepedency.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_servicedependency(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('_edit_servicedependency.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_timeperiod(request, c):
    """ This is a helper function to edit_object """
    return render_to_response('edit_timeperiod.html', c, context_instance=RequestContext(request))


@pynag.Utils.cache_only
def _edit_host(request, c):
    """ This is a helper function to edit_object """
    host = c['my_object']
    try:
        c['command_line'] = host.get_effective_command_line()
    except KeyError:
        c['command_line'] = None
    try:
        c['object_macros'] = host.get_all_macros()
    except KeyError:
        c['object_macros'] = None

    if not 'errors' in c:
        c['errors'] = []

    try:
        c['effective_services'] = sorted(
{'fraction_non_alphanumeric': 0.11710116412526644, 'fraction_numerical': 0.0010493523528447286, 'mean_word_length': 3.079186730872124, 'pattern_counts': {'":': 6, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5370556', 'n_tokens_mistral': 8889, 'n_tokens_neox': 8720, 'n_words': 2340}