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: if is_valid_ip(name, strict=True): netbox = netboxes.get(Q(sysname=name) | Q(ip=name)) else: netbox = netboxes.get(sysname=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 host_info['addresses']: # 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': sensor.get_graph(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) # Only display services tab for certain instances display_services_tab = netbox and (netbox.category.is_srv() or netbox.service_set.count()) return render( request, '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, 'display_services_tab': display_services_tab, }, )
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""" # Prefetch related objects as to reduce number of database queries netboxes = Netbox.objects.select_related(depth=2) 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 = [] 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() except GraphiteUnreachableError: graphite_error = True try: netbox_availability = netbox.get_availability() except GraphiteUnreachableError: graphite_error = True return render_to_response('ipdevinfo/ipdev-details.html', { 'host_info': host_info, 'netbox': netbox, 'interfaces': (netbox.interface_set.order_by('ifindex') if netbox else None), 'counter_types': ('Octets', 'UcastPkts', 'Errors', 'Discards'), '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, }, context_instance=RequestContext( request, processors=[search_form_processor]))
def test_job_two_descr(self): self.assertEqual(get_job_descriptions(self.config)['two'],'')
def test_job_three_descr(self): self.assertEqual(get_job_descriptions(self.config)['three'], 'blepp')
def test_job_prefix_must_be_filtered(self): descriptions = get_job_descriptions(self.config) for desc in descriptions: self.assertFalse(desc.startswith('job_'))
def test_description_should_not_contain_newline(self): descr = get_job_descriptions(self.config) self.assertEqual(descr['one'], 'blapp blupp')
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""" # Prefetch related objects as to reduce number of database queries netboxes = Netbox.objects.select_related(depth=2) 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 = [] 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() except GraphiteUnreachableError: graphite_error = True try: netbox_availability = netbox.get_availability() except GraphiteUnreachableError: graphite_error = True return render_to_response( 'ipdevinfo/ipdev-details.html', { 'host_info': host_info, 'netbox': netbox, 'interfaces': (netbox.interface_set.order_by('ifindex') if netbox else None), 'counter_types': ('Octets', 'UcastPkts', 'Errors', 'Discards'), '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, }, context_instance=RequestContext(request, processors=[search_form_processor]))
def test_job_three_descr(self, config): assert get_job_descriptions(config)['three'] == 'blepp'
def test_job_two_descr(self, config): assert get_job_descriptions(config)['two'] == ''
def test_description_should_not_contain_newline(self, config): descr = get_job_descriptions(config) assert descr['one'] == 'blapp blupp'
def test_job_prefix_must_be_filtered(self, config): descriptions = get_job_descriptions(config) for desc in descriptions: assert not desc.startswith('job_')