Ejemplo n.º 1
0
def test_is_valid_ip():
    valid_ips = ['129.241.75.1', '10.0.25.62', '2001:700:1::abcd', 'fe80::baad']
    invalid_ips = ['www.uninett.no', '92835235', '5:4', '-5325']

    for ip in valid_ips:
        assert util.is_valid_ip(ip), "%s should be valid" % ip

    for ip in invalid_ips:
        assert not util.is_valid_ip(ip), "%s should be invalid" % ip
Ejemplo n.º 2
0
    def test_is_valid_ip(self):
        valid_ips = ['129.241.75.1', '10.0.25.62', '2001:700:1::abcd',
                     'fe80::baad']
        invalid_ips = ['www.uninett.no', '92835235', '5:4', '-5325']

        for ip in valid_ips:
            self.assert_(util.is_valid_ip(ip),
                         msg="%s should be valid" % ip)

        for ip in invalid_ips:
            self.assertFalse(util.is_valid_ip(ip),
                             msg="%s should be invalid" % ip)
Ejemplo n.º 3
0
    def test_is_valid_ip(self):
        valid_ips = [
            '129.241.75.1', '10.0.25.62', '2001:700:1::abcd', 'fe80::baad'
        ]
        invalid_ips = ['www.uninett.no', '92835235', '5:4', '-5325']

        for ip in valid_ips:
            self.assert_(util.is_valid_ip(ip), msg="%s should be valid" % ip)

        for ip in invalid_ips:
            self.assertFalse(util.is_valid_ip(ip),
                             msg="%s should be invalid" % ip)
Ejemplo n.º 4
0
def find_netboxes(errors, query):
    """Find netboxes based on query parameter

    :param errors: list of errors
    :param query: form input
    :return: querylist
    """
    ip = is_valid_ip(query)
    netboxes = None
    if ip:
        netboxes = Netbox.objects.filter(ip=ip)
    elif is_valid_hostname(query):
        # Check perfect match first
        sysname_filter = Q(sysname=query)
        if settings.DOMAIN_SUFFIX is not None:
            sysname_filter |= Q(sysname='%s%s' %
                                        (query, settings.DOMAIN_SUFFIX))
        netboxes = Netbox.objects.filter(sysname_filter)
        if len(netboxes) != 1:
            # No exact match, search for matches in substrings
            netboxes = Netbox.objects.filter(sysname__icontains=query)
    else:
        errors.append('The query does not seem to be a valid IP address'
                      ' (v4 or v6) or a hostname.')

    return netboxes
Ejemplo n.º 5
0
def get_address_info(request):
    """Displays a template for the user for manual verification of the
    address"""

    address = request.GET.get('address')
    if address:
        if is_valid_ip(address):
            return JsonResponse({'is_ip': True})

        try:
            address_tuples = socket.getaddrinfo(
                address, None, 0, socket.SOCK_STREAM)
            sorted_tuples = sorted(address_tuples,
                                   key=lambda item:
                                   socket.inet_pton(item[0], item[4][0]))
            addresses = [x[4][0] for x in sorted_tuples]
        except socket.error as error:
            context = {'error': str(error)}
        except UnicodeError as error:
            context = {'error': str(error)}
        else:
            context = {
                'addresses': addresses,
            }

        return JsonResponse(context)
    else:
        return HttpResponse('No address given', status=400)
Ejemplo n.º 6
0
 def to_python(self, value):
     """Verifies that the value is a string with a valid CIDR IP address"""
     if value and not is_valid_cidr(value) and not is_valid_ip(value):
         raise exceptions.ValidationError(
             "Value must be a valid CIDR address")
     else:
         return value
Ejemplo n.º 7
0
    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):
                    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
Ejemplo n.º 8
0
    def clean_target(self):
        """Validate target"""
        target = self.cleaned_data['target'].strip()
        if not (is_valid_ip(target) or is_valid_mac(target)):
            raise forms.ValidationError('Not a valid ip or mac-address')

        return target
Ejemplo n.º 9
0
def find_netboxes(errors, query):
    """Find netboxes based on query parameter

    :param errors: list of errors
    :param query: form input
    :return: querylist
    """
    ip = is_valid_ip(query)
    netboxes = None
    if ip:
        netboxes = Netbox.objects.filter(ip=ip)
    elif is_valid_hostname(query):
        # Check perfect match first
        sysname_filter = Q(sysname=query)
        if settings.DOMAIN_SUFFIX is not None:
            sysname_filter |= Q(sysname='%s%s' %
                                (query, settings.DOMAIN_SUFFIX))
        netboxes = Netbox.objects.filter(sysname_filter)
        if len(netboxes) != 1:
            # No exact match, search for matches in substrings
            netboxes = Netbox.objects.filter(sysname__icontains=query)
    else:
        errors.append('The query does not seem to be a valid IP address'
                      ' (v4 or v6) or a hostname.')

    return netboxes
Ejemplo n.º 10
0
    def clean_target(self):
        """Validate target"""
        target = self.cleaned_data['target'].strip()
        if not (is_valid_ip(target) or is_valid_mac(target)):
            raise forms.ValidationError('Not a valid ip or mac-address')

        return target
Ejemplo n.º 11
0
 def to_python(self, value):
     """Verifies that the value is a string with a valid CIDR IP address"""
     if value:
         if isinstance(value, six.binary_type):
             value = six.text_type(value, encoding='utf-8')
         if not is_valid_cidr(value) and not is_valid_ip(value):
             raise exceptions.ValidationError("Value must be a valid CIDR address")
     return value
Ejemplo n.º 12
0
def _get_host_info(host):
    """Returns a dictionary containing DNS information about the host"""
    if is_valid_ip(host):
        addresses = list(reverse_lookup([host]))
    else:
        addresses = forward_lookup(host) or []
        if addresses:
            addresses = list(reverse_lookup(addresses))

    return {'host': host, 'addresses': addresses}
Ejemplo n.º 13
0
 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
Ejemplo n.º 14
0
def find_input_type(ip_or_mac):
    """Try to determine whether input is a valid ip-address,
    mac-address or an swportid. Return type and reformatted input as a
    tuple"""
    # Support mac-adresses on xx:xx... format
    ip_or_mac = str(ip_or_mac)
    mac = ip_or_mac.replace(':', '')

    # idValidIP returns 10.0.0.0 if you type 10.0.0. Check that this is not the
    # case.
    input_type = "UNKNOWN"
    if is_valid_ip(ip_or_mac) and not is_valid_ip(ip_or_mac).endswith('.0'):
        input_type = "IP"
    elif re.match("^[A-Fa-f0-9]{12}$", mac):
        input_type = "MAC"
    elif re.match("^\d+$", ip_or_mac):
        input_type = "SWPORTID"

    return input_type
Ejemplo n.º 15
0
 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
Ejemplo n.º 16
0
def find_input_type(ip_or_mac):
    """Try to determine whether input is a valid ip-address,
    mac-address or an swportid. Return type and reformatted input as a
    tuple"""
    # Support mac-adresses on xx:xx... format
    ip_or_mac = str(ip_or_mac)
    mac = ip_or_mac.replace(':', '')

    # idValidIP returns 10.0.0.0 if you type 10.0.0. Check that this is not the
    # case.
    input_type = "UNKNOWN"
    if is_valid_ip(ip_or_mac) and not is_valid_ip(ip_or_mac).endswith('.0'):
        input_type = "IP"
    elif re.match("^[A-Fa-f0-9]{12}$", mac):
        input_type = "MAC"
    elif re.match("^\d+$", ip_or_mac):
        input_type = "SWPORTID"

    return input_type
Ejemplo n.º 17
0
def _get_host_info(host):
    """Returns a dictionary containing DNS information about the host"""
    if is_valid_ip(host):
        addresses = list(reverse_lookup([host]))
    else:
        addresses = forward_lookup(host) or []
        if addresses:
            addresses = list(reverse_lookup(addresses))

    return {'host': host, 'addresses': addresses}
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
def parse_address(address):
    match = (pattern.match(address) for pattern in ADDRESS_PATTERNS)
    match = reduce(lambda x, y: x or y, match)
    if match:
        match = match.groupdict()
        addr = match['addr']
        port = int(match.get('port', None) or DEFAULT_PORT)
        if is_valid_ip(addr):
            return addr, port

    raise ValueError("%s is not a valid address" % address)
Ejemplo n.º 20
0
 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
Ejemplo n.º 21
0
 def fetch_results(self):
     if is_valid_ip(self.query):
         self.results.append(
             SearchResult(
                 reverse('ipdevinfo-details-by-addr',
                         kwargs={'addr': self.query}), None))
     elif is_valid_hostname(self.query):
         self.results.append(
             SearchResult(
                 reverse('ipdevinfo-details-by-name',
                         kwargs={'name': self.query}), None))
Ejemplo n.º 22
0
def parse_address(address):
    match = (pattern.match(address) for pattern in ADDRESS_PATTERNS)
    match = reduce(lambda x, y: x or y, match)
    if match:
        match = match.groupdict()
        addr = match['addr']
        port = int(match.get('port', None) or DEFAULT_PORT)
        if is_valid_ip(addr):
            return addr, port

    raise ValueError("%s is not a valid address" % address)
Ejemplo n.º 23
0
    def fetch_results(self):
        if is_valid_ip(self.query):
            results = Netbox.objects.filter(ip=self.query)
        else:
            results = Netbox.objects.filter(sysname__icontains=self.query)

        results.order_by("sysname")
        for result in results:
            self.results.append(
                SearchResult(
                    reverse('ipdevinfo-details-by-name',
                            kwargs={'name': result.sysname}), result))
Ejemplo n.º 24
0
Archivo: views.py Proyecto: LiuJux/nav
def search(query):
    """Search for something in portadmin"""
    netbox_filters = [
        Q(sysname__icontains=query),
    ]
    if is_valid_ip(query):
        netbox_filters.append(Q(ip=query))
    netboxes = Netbox.objects.filter(reduce(
        OR, netbox_filters)).order_by('sysname')
    interfaces = Interface.objects.filter(ifalias__icontains=query).order_by(
        'netbox__sysname', 'ifname')
    return netboxes, interfaces
Ejemplo n.º 25
0
def is_inside_vlans(ip, vlans):
    """Check if ip is inside the vlans

    vlans: a string with comma-separated vlans.

    """
    vlans = [x.strip() for x in vlans.split(',')]

    # For each vlan, check if it is inside the prefix of the vlan.
    for vlan in vlans:
        if vlan.isdigit() and is_valid_ip(ip):
            if Prefix.objects.filter(vlan__vlan=vlan).extra(
                    where=['%s << netaddr'], params=[ip]):
                return True
    return False
Ejemplo n.º 26
0
Archivo: arnold.py Proyecto: yytsui/nav
def is_inside_vlans(ip, vlans):
    """Check if ip is inside the vlans

    vlans: a string with comma-separated vlans.

    """
    vlans = [x.strip() for x in vlans.split(',')]

    # For each vlan, check if it is inside the prefix of the vlan.
    for vlan in vlans:
        if vlan.isdigit() and is_valid_ip(ip):
            if Prefix.objects.filter(vlan__vlan=vlan).extra(
                    where=['%s << netaddr'], params=[ip]):
                return True
    return False
Ejemplo n.º 27
0
def _get_host_info(host):
    """Returns a dictionary containing DNS information about the host"""
    if is_valid_ip(host, use_socket_lib=True):
        addresses = list(reverse_lookup([host]))
    else:
        try:
            addresses = forward_lookup(host) or []
        except UnicodeError:
            # Probably just some invalid string that cannot be represented using IDNA
            # encoding. Let's just pretend it never happened (i.e. we can't look it up)
            addresses = []
        if addresses:
            addresses = list(reverse_lookup(addresses))

    return {'host': host, 'addresses': addresses}
Ejemplo n.º 28
0
    def _get_netbox_from_row(row):
        netbox = Netbox(ip=row['ip'])
        netbox.room = get_object_or_fail(Room, id=row['roomid'])
        netbox.organization = get_object_or_fail(Organization, id=row['orgid'])
        netbox.category = get_object_or_fail(Category, id=row['catid'])
        netbox.sysname = netbox.ip

        master = row.get('master')
        if master:
            if is_valid_ip(master, use_socket_lib=True):
                netbox.master = get_object_or_fail(Netbox, ip=master)
            else:
                netbox.master = get_object_or_fail(Netbox,
                                                   sysname__startswith=master)

        return netbox
Ejemplo n.º 29
0
Archivo: arnold.py Proyecto: yytsui/nav
def find_input_type(ip_or_mac):
    """Try to determine whether input is a valid ip-address,
    mac-address or an swportid. Return type and reformatted input as a
    tuple"""
    # Support mac-adresses on xx:xx... format
    ip_or_mac = str(ip_or_mac)
    mac = ip_or_mac.replace(':', '')

    input_type = "UNKNOWN"
    if is_valid_ip(ip_or_mac, use_socket_lib=True):
        input_type = "IP"
    elif re.match("^[A-Fa-f0-9]{12}$", mac):
        input_type = "MAC"
    elif re.match(r"^\d+$", ip_or_mac):
        input_type = "SWPORTID"

    return input_type
Ejemplo n.º 30
0
    def __call__(self, parser, namespace, values, option_string=None):
        if not values:
            parser.error("%s argument must be non-empty" % option_string)

        search_base = manage.Netbox.objects.select_related(
            'type', 'type__vendor').order_by('sysname')
        if is_valid_ip(values, strict=True):
            matches = search_base.filter(ip=values)
        else:
            matches = search_base.filter(sysname__startswith=values)

        if len(matches) == 1:
            namespace.netbox = matches[0]
            namespace.foreground = True
            namespace.logstderr = True
            return
        elif len(matches) > 1:
            print("matched more than one netbox:")
            print('\n'.join("%s (%s)" % (n.sysname, n.ip) for n in matches))
        else:
            print("no netboxes match %r" % values)

        sys.exit(1)
Ejemplo n.º 31
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"""

        # 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]))
Ejemplo n.º 32
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"""

        # 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]))
Ejemplo n.º 33
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:
                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,
        },
    )
Ejemplo n.º 34
0
 def is_ip(self):
     return is_valid_ip(self.host, strict=True)
Ejemplo n.º 35
0
 def is_ip(self):
     return is_valid_ip(self.host, use_socket_lib=True)