Example #1
0
def sensor_details(request, identifier):
    """Controller for getting sensor info"""
    sensor = get_object_or_404(Sensor, pk=identifier)

    if request.method == 'POST':
        if sensor.unit_of_measurement == sensor.UNIT_TRUTHVALUE:
            form = BooleanSensorForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                sensor.on_message_user = data['on_message']
                sensor.off_message_user = data['off_message']
                sensor.on_state_user = data['on_state']
                sensor.alert_type = data['alert_type']
                sensor.save()
                return redirect(request.path)
        else:
            form = SensorRangesForm(request.POST)
            if form.is_valid():
                sensor.display_minimum_user = form.cleaned_data['minimum']
                sensor.display_maximum_user = form.cleaned_data['maximum']
                sensor.save()
                return redirect(request.path)

    netbox_sysname = sensor.netbox.sysname

    navpath = NAVPATH + [
        (netbox_sysname,
         reverse('ipdevinfo-details-by-name',
                 kwargs={'name': netbox_sysname})), ('Sensor Details',)]
    heading = title = 'Sensor details: ' + six.text_type(sensor)

    metric = dict(id=sensor.get_metric_name())
    find_rules([metric])

    if sensor.unit_of_measurement == sensor.UNIT_TRUTHVALUE:
        form = BooleanSensorForm(initial={
            'on_message': sensor.on_message,
            'off_message': sensor.off_message,
            'on_state': sensor.on_state,
            'alert_type': sensor.alert_type,
        })
    else:
        form = SensorRangesForm(initial={
            'minimum': sensor.get_display_range()[0],
            'maximum': sensor.get_display_range()[1],
        })
    return render(request, 'ipdevinfo/sensor-details.html', {
        'data_url': get_simple_graph_url(
            sensor.get_metric_name(), time_frame='10minutes', format='json'),
        'sensor': sensor,
        'navpath': navpath,
        'heading': heading,
        'title': title,
        'metric': metric,
        'form': form,
        'graphite_data_url': Graph(magic_targets=[sensor.get_metric_name()],
                                   format='json')
    })
Example #2
0
def get_graph_url(request):
    """Get graph url based on metric"""
    graph_args = {
        'title': 'Latest values for this metric',
        'width': 600, 'height': 400
    }
    if 'metric' in request.GET:
        metric = request.GET['metric']
        if 'raw' in request.GET:
            graph = Graph(targets=[metric], **graph_args)
            return redirect(unicode(graph))
        else:
            return redirect(get_simple_graph_url([metric], **graph_args))

    return HttpResponse()
Example #3
0
def sensor_details(request, identifier):
    """Controller for getting sensor info"""
    sensor = get_object_or_404(Sensor, pk=identifier)

    if request.method == 'POST':
        form = SensorRangesForm(request.POST)
        if form.is_valid():
            sensor.display_minimum_user = form.cleaned_data['minimum']
            sensor.display_maximum_user = form.cleaned_data['maximum']
            sensor.save()
            return redirect(request.path)

    netbox_sysname = sensor.netbox.sysname

    navpath = NAVPATH + [(netbox_sysname,
                          reverse('ipdevinfo-details-by-name',
                                  kwargs={'name': netbox_sysname})),
                         ('Sensor Details', )]
    heading = title = 'Sensor details: ' + unicode(sensor)

    metric = dict(id=sensor.get_metric_name())
    find_rules([metric])

    form = SensorRangesForm(
        initial={
            'minimum': sensor.get_display_range()[0],
            'maximum': sensor.get_display_range()[1],
        })
    return render(
        request, 'ipdevinfo/sensor-details.html', {
            'sensor':
            sensor,
            'navpath':
            navpath,
            'heading':
            heading,
            'title':
            title,
            'metric':
            metric,
            'form':
            form,
            'graphite_data_url':
            Graph(magic_targets=[sensor.get_metric_name()], format='json')
        })
Example #4
0
def port_details(request,
                 netbox_sysname,
                 port_type=None,
                 port_id=None,
                 port_name=None):
    """Show detailed view of one IP device port"""

    if not (port_id or port_name):
        return Http404

    ports = Interface.objects.select_related()

    if port_id is not None:
        port = get_object_or_404(ports, id=port_id)
    elif port_name is not None:
        try:
            port = ports.get(netbox__sysname=netbox_sysname, ifname=port_name)
        except Interface.DoesNotExist:
            port = get_object_or_404(ports,
                                     netbox__sysname=netbox_sysname,
                                     ifdescr=port_name)

    navpath = NAVPATH + [(netbox_sysname,
                          reverse('ipdevinfo-details-by-name',
                                  kwargs={'name': netbox_sysname})),
                         ('Port Details', )]
    heading = title = 'Port details: ' + unicode(port)

    try:
        port_metrics = port.get_port_metrics()
        graphite_error = False
    except GraphiteUnreachableError:
        port_metrics = []
        graphite_error = True

    sensor_metrics = []
    for sensor in port.sensor_set.all():
        metric_id = sensor.get_metric_name()
        metric = {
            'id': metric_id,
            'sensor': sensor,
            'graphite_data_url': Graph(magic_targets=[metric_id],
                                       format='json'),
        }
        sensor_metrics.append(metric)
    find_rules(sensor_metrics)
    # If interface is detained in Arnold, this should be visible on the
    # port details view
    try:
        detention = port.identity_set.get(
            status__in=['quarantined', 'disabled'])
    except Identity.DoesNotExist:
        detention = None

    # Add urls to Graphite to the relevant objects
    port.combined_data_urls = create_combined_urls(port, COUNTER_TYPES)
    for metric in port_metrics:
        metric['graphite_data_url'] = Graph(magic_targets=[metric['id']],
                                            format='json')

    return render_to_response('ipdevinfo/port-details.html', {
        'port_type': port_type,
        'port': port,
        'navpath': navpath,
        'heading': heading,
        'title': title,
        'port_metrics': port_metrics,
        'graphite_error': graphite_error,
        'detention': detention,
        'sensor_metrics': sensor_metrics,
    },
                              context_instance=RequestContext(
                                  request, processors=[search_form_processor]))
Example #5
0
def ipdev_details(request, name=None, addr=None, netbox_id=None):
    """Show detailed view of one IP device"""

    if netbox_id:
        netbox = get_object_or_404(Netbox, id=netbox_id)
        return HttpResponseRedirect(netbox.get_absolute_url())

    def get_netbox(name=None, addr=None):
        """Lookup IP device in NAV by either hostname or IP address.

        :rtype: nav.models.manage.Netbox

        """
        # Prefetch related objects as to reduce number of database queries
        netboxes = Netbox.objects.select_related()
        netbox = None

        if name:
            try:
                netbox = netboxes.get(Q(sysname=name) | Q(ip=name))
            except Netbox.DoesNotExist:
                pass
        elif addr:
            try:
                netbox = netboxes.get(ip=addr)
            except Netbox.DoesNotExist:
                pass
        if not netbox:
            host_information = get_host_info(name or addr)
            for address in host_information['addresses']:
                if 'name' in address:
                    try:
                        netbox = netboxes.get(sysname=address['name'])
                        break  # Exit loop at first match
                    except Netbox.DoesNotExist:
                        pass

        return netbox

    def get_recent_alerts(netbox, days_back=7, max_num_alerts=15):
        """Returns the most recents alerts related to a netbox"""

        # Limit to alerts which where closed in the last days or which are
        # still open
        lowest_end_time = dt.datetime.now() - dt.timedelta(days=days_back)

        filter_stateful = Q(end_time__gt=lowest_end_time)
        filter_stateless = (Q(end_time__isnull=True)
                            & Q(start_time__gt=lowest_end_time))
        queryset = netbox.alerthistory_set.filter(
            filter_stateful | filter_stateless).order_by('-start_time')
        count = queryset.count()
        raw_alerts = queryset[:max_num_alerts]

        alerts = []
        has_unresolved_alerts = False
        for alert in raw_alerts:
            if alert.source.name == 'serviceping':
                try:
                    alert_type = Service.objects.get(id=alert.subid).handler
                except Service.DoesNotExist:
                    alert_type = '%s (%s)' % (alert.event_type, alert.subid)
            else:
                alert_type = '%s' % alert.event_type

            try:
                message = alert.messages.filter(type='sms')[0].message
            except IndexError:
                message = None

            if not has_unresolved_alerts and alert.is_open():
                has_unresolved_alerts = True

            alerts.append({
                'alert': alert,
                'type': alert_type,
                'message': message,
            })

        return {
            'days_back': days_back,
            'alerts': alerts,
            'count': count,
            'is_more_alerts': count > max_num_alerts,
            'has_unresolved_alerts': has_unresolved_alerts
        }

    def get_prefix_info(addr):
        """Return prefix based on address"""
        ipaddr = is_valid_ip(addr)
        if ipaddr:
            prefixes = Prefix.objects.select_related().extra(
                select={"mask_size": "masklen(netaddr)"},
                where=["%s << netaddr AND nettype <> 'scope'"],
                order_by=["-mask_size"],
                params=[ipaddr])[0:1]
            if prefixes:
                return prefixes[0]
        return None

    def get_arp_info(addr):
        """Return arp based on address"""
        ipaddr = is_valid_ip(addr)
        if ipaddr:
            arp_info = Arp.objects.extra(where=["ip = %s"],
                                         params=[ipaddr]).order_by(
                                             '-end_time', '-start_time')[0:1]
            if arp_info:
                return arp_info[0]
        return None

    def get_cam_info(mac):
        """Return cam objects based on mac address"""
        cam_info = Cam.objects.filter(mac=mac).order_by(
            '-end_time', '-start_time')[0:1]
        return cam_info[0] if cam_info else None

    # Get data needed by the template
    addr = is_valid_ip(addr)
    host_info = None
    netbox = get_netbox(name=name, addr=addr)

    # Assign default values to variables
    no_netbox = {
        'prefix': None,
        'arp': None,
        'cam': None,
        'dt_max': dt.datetime.max,
        'days_since_active': 7,
    }
    alert_info = None
    job_descriptions = None
    system_metrics = netbox_availability = []
    sensor_metrics = []

    graphite_error = False
    # If addr or host not a netbox it is not monitored by NAV
    if netbox is None:
        host_info = get_host_info(name or addr)
        if not addr and len(host_info['addresses']) > 0:
            # Picks the first address in array if addr not specified
            addr = host_info['addresses'][0]['addr']

        no_netbox['prefix'] = get_prefix_info(addr)
        netboxgroups = None
        navpath = NAVPATH + [(host_info['host'], '')]

        if no_netbox['prefix']:
            no_netbox['arp'] = get_arp_info(addr)
            if no_netbox['arp']:
                no_netbox['cam'] = get_cam_info(no_netbox['arp'].mac)
                if no_netbox['arp'].end_time < dt.datetime.max:
                    no_netbox['days_since_active'] = \
                        (dt.datetime.now() - no_netbox['arp'].end_time).days

    else:
        alert_info = get_recent_alerts(netbox)
        netboxgroups = netbox.netboxcategory_set.all()
        navpath = NAVPATH + [(netbox.sysname, '')]
        job_descriptions = get_job_descriptions()

        try:
            system_metrics = netbox.get_system_metrics()
            for metric in system_metrics:
                metric['graphite_data_url'] = Graph(
                    magic_targets=[metric['id']], format='json')
        except GraphiteUnreachableError:
            graphite_error = True

        try:
            netbox_availability = netbox.get_availability()
        except GraphiteUnreachableError:
            graphite_error = True

        for sensor in netbox.sensor_set.all():
            metric_id = sensor.get_metric_name()
            metric = {
                'id':
                metric_id,
                'sensor':
                sensor,
                'graphite_data_url':
                Graph(magic_targets=[metric_id], format='json'),
            }
            sensor_metrics.append(metric)
        find_rules(sensor_metrics)
    # Display info about current and scheduled maintenance tasks
    # related to this device
    current_tasks = MaintenanceTask.objects.current()
    future_tasks = MaintenanceTask.objects.future()
    relevant_current_tasks = []
    relevant_future_tasks = []
    for task in current_tasks:
        if netbox in task.get_event_subjects():
            relevant_current_tasks.append(task)

    for task in future_tasks:
        if netbox in task.get_event_subjects():
            relevant_future_tasks.append(task)

    interfaces = netbox.interface_set.order_by('ifindex') if netbox else []
    for interface in interfaces:
        interface.combined_data_urls = create_combined_urls(
            interface, COUNTER_TYPES)

    return render_to_response('ipdevinfo/ipdev-details.html', {
        'host_info': host_info,
        'netbox': netbox,
        'interfaces': interfaces,
        'counter_types': COUNTER_TYPES,
        'heading': navpath[-1][0],
        'alert_info': alert_info,
        'no_netbox': no_netbox,
        'netboxgroups': netboxgroups,
        'job_descriptions': job_descriptions,
        'navpath': navpath,
        'title': create_title(navpath),
        'system_metrics': system_metrics,
        'netbox_availability': netbox_availability,
        'graphite_error': graphite_error,
        'current_maintenance_tasks': relevant_current_tasks,
        'future_maintenance_tasks': relevant_future_tasks,
        'sensor_metrics': sensor_metrics,
    },
                              context_instance=RequestContext(
                                  request, processors=[search_form_processor]))