Beispiel #1
0
def _validate_mac(mac, parsed_macs, row_number):
    if not is_mac_valid(Eth("", mac, "")):
        raise forms.ValidationError("Row %s: Invalid MAC address." %
                                    row_number)
    if mac in parsed_macs:
        raise forms.ValidationError("Row %s: Duplicated MAC address. "
                                    "Please check previous rows..." %
                                    row_number)
Beispiel #2
0
def _validate_mac(mac, parsed_macs, row_number):
    if not is_mac_valid(Eth("", mac, "")):
        raise forms.ValidationError(
            "Row %s: Invalid MAC address." % row_number
        )
    if mac in parsed_macs:
        raise forms.ValidationError(
            "Row %s: Duplicated MAC address. "
            "Please check previous rows..." % row_number
        )
Beispiel #3
0
def _get_mac_addresses(ssh):
    """Get the MAC addresses"""

    stdin, stdout, stderr = ssh.exec_command(
        "/sbin/ip addr show | /bin/grep 'link/ether'", )
    mac_addresses = set()
    for line in stdout:
        mac_address = line.split(None, 3)[1]
        if is_mac_valid(Eth(label='', mac=mac_address, speed=0)):
            mac_addresses.add(mac_address)
    return list(mac_addresses)
Beispiel #4
0
def _get_mac_addresses(ssh):
    """Get the MAC addresses"""

    stdin, stdout, stderr = ssh.exec_command(
        "/sbin/ip addr show | /bin/grep 'link/ether'",
    )
    mac_addresses = set()
    for line in stdout:
        mac_address = line.split(None, 3)[1]
        if is_mac_valid(Eth(label='', mac=mac_address, speed=0)):
            mac_addresses.add(mac_address)
    return list(mac_addresses)
Beispiel #5
0
 def clean_macs(self):
     sn = self.cleaned_data['sn']
     macs_text = self.cleaned_data['macs']
     macs = []
     for mac in macs_text.split(' \r\n\t,;'):
         try:
             eth = Eth('', MACAddressField.normalize(mac), 0)
             if is_mac_valid(eth):
                 macs.append(eth.mac)
         except ValueError as e:
             raise forms.ValidationError(e)
     if not (macs or sn):
         raise forms.ValidationError("Either MACs or serial number required.")
     return ' '.join(macs)
Beispiel #6
0
 def clean_macs(self):
     sn = self.cleaned_data["sn"]
     macs_text = self.cleaned_data["macs"]
     macs = []
     for mac in macs_text.split(" \r\n\t,;"):
         if not mac:
             continue
         try:
             eth = Eth("", MACAddressField.normalize(mac), 0)
             if is_mac_valid(eth):
                 macs.append(eth.mac)
         except ValueError as e:
             raise forms.ValidationError(e)
     if not (macs or sn):
         raise forms.ValidationError("Either MACs or serial number required.")
     return " ".join(macs)
Beispiel #7
0
 def clean_macs(self):
     sn = self.cleaned_data['sn']
     macs_text = self.cleaned_data['macs']
     macs = []
     for mac in macs_text.split(' \r\n\t,;'):
         if not mac:
             continue
         try:
             eth = Eth('', MACAddressField.normalize(mac), 0)
             if is_mac_valid(eth):
                 macs.append(eth.mac)
         except ValueError as e:
             raise forms.ValidationError(e)
     if not (macs or sn):
         raise forms.ValidationError(
             "Either MACs or serial number required.")
     return ' '.join(macs)
Beispiel #8
0
 def create(cls,
            ethernets=None,
            sn=None,
            model=None,
            model_name=None,
            model_type=None,
            device=None,
            allow_stub=False,
            priority=0,
            **kwargs):
     if 'parent' in kwargs and kwargs['parent'] is None:
         del kwargs['parent']
     if not model and (not model_name or not model_type):
         raise ValueError(
             'Either provide model or model_type and model_name.')
     dev = device
     ethernets = [
         Eth(*e) for e in (ethernets or []) if is_mac_valid(Eth(*e))
     ]
     if ethernets:
         macs = set(
             [MACAddressField.normalize(eth.mac) for eth in ethernets])
         devs = Device.admin_objects.filter(
             ethernet__mac__in=macs).distinct()
         if len(devs) > 1:
             raise ValueError('Multiple devices match MACs: %r' % macs)
         elif len(devs) == 1:
             if dev and devs[0].id != dev.id:
                 raise ValueError('Conflict of devices %r and %r!' %
                                  (dev, devs[0]))
             else:
                 dev = devs[0]
     if sn:
         sn = sn.strip()
     if sn in SERIAL_BLACKLIST:
         sn = None
     if not any((sn, ethernets, allow_stub)):
         raise ValueError(
             "Neither `sn` nor `ethernets` given.  Use `allow_stub` "
             "to override.")
     if sn:
         try:
             sndev = Device.admin_objects.get(sn=sn)
         except Device.DoesNotExist:
             pass
         else:
             if dev is None:
                 dev = sndev
             elif sndev.id != dev.id:
                 # both devices are properly placed in the tree
                 if any((
                         sndev.parent and dev.parent,
                         # the device found using ethernets (or explicitly
                         # given as `device`) has different sn than `sn`
                         dev.sn and dev.sn != sn,
                         # the device found using `sn` already has other
                         # ethernets
                         sndev.ethernet_set.exists())):
                     raise ValueError('Conflict of devices %r and %r!' %
                                      (dev, sndev))
                 sndev.delete()
     if model is None:
         model, model_created = DeviceModel.concurrent_get_or_create(
             name=model_name,
             defaults={
                 'type': model_type.id,
             },
         )
     if dev is None:
         dev, created = Device.concurrent_get_or_create(
             sn=sn,
             defaults={
                 'model': model,
             },
         )
     elif dev.deleted:
         # Ignore the priority and undelete even if it was manually deleted
         priorities = dev.get_save_priorities()
         priorities['deleted'] = 0
         dev.update_save_priorities(priorities)
         dev.deleted = False
     if model and model.type != DeviceType.unknown.id:
         dev.model = model
     if not dev.sn and sn:
         dev.sn = sn
     for k, v in kwargs.iteritems():
         if k in ('name', 'last_seen'):
             continue
         setattr(dev, k, v)
     try:
         user = kwargs.get('user')
     except KeyError:
         user = None
     dev.save(user=user, update_last_seen=True, priority=priority)
     for eth in ethernets:
         ethernet, eth_created = Ethernet.concurrent_get_or_create(
             mac=eth.mac,
             defaults={
                 'device': dev,
             },
         )
         ethernet.device = dev
         ethernet.label = eth.label or 'Autocreated'
         if eth.speed:
             ethernet.speed = eth.speed
         ethernet.save(priority=priority)
     return dev
Beispiel #9
0
    def create(cls, ethernets=None, sn=None, model=None,  model_name=None,
            model_type=None, device=None, allow_stub=False, priority=0, **kwargs):
        if 'parent' in kwargs and kwargs['parent'] is None:
            del kwargs['parent']
        if not model and (not model_name or not model_type):
            raise ValueError('Either provide model or model_type and model_name.')
        dev = device
        ethernets = [Eth(*e) for e in (ethernets or []) if is_mac_valid(Eth(*e))]
        if ethernets:
            macs = set([MACAddressField.normalize(eth.mac) for eth in ethernets])
            devs = Device.objects.filter(ethernet__mac__in=macs).distinct()
            if len(devs) > 1:
                raise ValueError('Multiple devices match MACs: %r' % macs)
            elif len(devs) == 1:
                if dev and devs[0].id != dev.id:
                    raise ValueError('Conflict of devices %r and %r!' % (
                        dev, devs[0]))
                else:
                    dev = devs[0]
        if sn:
            sn = sn.strip()
        if sn in SERIAL_BLACKLIST:
            sn = None
        if not any((sn, ethernets, allow_stub)):
            raise ValueError("Neither `sn` nor `ethernets` given. "
                "Use `allow_stub` to override.")
        if sn:
            try:
                sndev = Device.objects.get(sn=sn)
            except Device.DoesNotExist:
                pass
            else:
                if dev is None:
                    dev = sndev
                elif sndev.id != dev.id:
                    if any((# both devices are properly placed in the tree
                            sndev.parent and dev.parent,
                            # the device found using ethernets (or explicitly
                            # given as `device`) has different sn than `sn` 
                            dev.sn and dev.sn != sn,
                            # the device found using `sn` already has other
                            # ethernets
                            sndev.ethernet_set.exists())):
                        raise ValueError('Conflict of devices %r and %r!' %
                                (dev, sndev))
                    sndev.delete()
        if model is None:
            model, model_created = DeviceModel.concurrent_get_or_create(
                name=model_name, type=model_type.id)
        if dev is None:
            dev, created = Device.concurrent_get_or_create(sn=sn, model=model)
        if model and model.type != DeviceType.unknown.id:
            dev.model = model

        if not dev.sn and sn:
            dev.sn = sn
        for k, v in kwargs.iteritems():
            if k in ('name', 'last_seen'):
                continue
            setattr(dev, k, v)
        dev.save(update_last_seen=True, priority=priority)

        for eth in ethernets:
            ethernet, eth_created = Ethernet.concurrent_get_or_create(
                    device=dev, mac=eth.mac)
            if eth_created:
                ethernet.label = eth.label or 'Autocreated'
                if eth.speed:
                    ethernet.speed = eth.speed
            ethernet.save(priority=priority)
        return dev
Beispiel #10
0
 def create(cls, ethernets=None, sn=None, model=None, model_name=None,
            model_type=None, device=None, allow_stub=False, priority=0,
            **kwargs):
     if 'parent' in kwargs and kwargs['parent'] is None:
         del kwargs['parent']
     if not model and (not model_name or not model_type):
         raise ValueError(
             'Either provide model or model_type and model_name.'
         )
     dev = device
     ethernets = [Eth(*e) for e in (ethernets or []) if
                  is_mac_valid(Eth(*e))]
     if ethernets:
         macs = set([MACAddressField.normalize(eth.mac) for
                     eth in ethernets])
         devs = Device.admin_objects.filter(
             ethernet__mac__in=macs
         ).distinct()
         if len(devs) > 1:
             raise ValueError('Multiple devices match MACs: %r' % macs)
         elif len(devs) == 1:
             if dev and devs[0].id != dev.id:
                 raise ValueError('Conflict of devices %r and %r!' % (
                     dev, devs[0]))
             else:
                 dev = devs[0]
     if sn:
         sn = sn.strip()
     if sn in SERIAL_BLACKLIST:
         # we don't raise an exception here because blacklisted/missing sn
         # is not enough to fail device's creation
         sn = None
     if not any((sn, ethernets, allow_stub)):
         if sn in SERIAL_BLACKLIST:
             msg = ("You have provided `sn` which is blacklisted. "
                    "Please use a different one.")
         else:
             msg = ("Neither `sn` nor `ethernets` given.  Use `allow_stub` "
                    "to override.")
         raise ValueError(msg)
     if sn:
         try:
             sndev = Device.admin_objects.get(sn=sn)
         except Device.DoesNotExist:
             pass
         else:
             if dev is None:
                 dev = sndev
             elif sndev.id != dev.id:
                 # both devices are properly placed in the tree
                 if any((
                         sndev.parent and dev.parent,
                         # the device found using ethernets (or explicitly
                         # given as `device`) has different sn than `sn`
                         dev.sn and dev.sn != sn,
                         # the device found using `sn` already has other
                         # ethernets
                         sndev.ethernet_set.exists())):
                     raise ValueError(
                         'Conflict of devices %r and %r!' % (dev, sndev)
                     )
                 sndev.delete()
     if model is None:
         model, model_created = DeviceModel.concurrent_get_or_create(
             name=model_name,
             defaults={
                 'type': model_type.id,
             },
         )
     if dev is None:
         dev, created = Device.concurrent_get_or_create(
             sn=sn,
             defaults={
                 'model': model,
             },
         )
     elif dev.deleted:
         # Ignore the priority and undelete even if it was manually deleted
         priorities = dev.get_save_priorities()
         priorities['deleted'] = 0
         dev.update_save_priorities(priorities)
         dev.deleted = False
     if model and model.type != DeviceType.unknown.id:
         dev.model = model
     if not dev.sn and sn:
         dev.sn = sn
     for k, v in kwargs.iteritems():
         if k in ('name', 'last_seen'):
             continue
         setattr(dev, k, v)
     try:
         user = kwargs.get('user')
     except KeyError:
         user = None
     dev.save(user=user, update_last_seen=True, priority=priority)
     for eth in ethernets:
         ethernet, eth_created = Ethernet.concurrent_get_or_create(
             mac=eth.mac,
             defaults={
                 'device': dev,
             },
         )
         ethernet.device = dev
         ethernet.label = eth.label or 'Autocreated'
         if eth.speed:
             ethernet.speed = eth.speed
         ethernet.save(priority=priority)
     return dev
Beispiel #11
0
 def create(
     cls,
     ethernets=None,
     sn=None,
     model=None,
     model_name=None,
     model_type=None,
     device=None,
     allow_stub=False,
     priority=0,
     **kwargs
 ):
     if "parent" in kwargs and kwargs["parent"] is None:
         del kwargs["parent"]
     if not model and (not model_name or not model_type):
         raise ValueError("Either provide model or model_type and model_name.")
     dev = device
     ethernets = [Eth(*e) for e in (ethernets or []) if is_mac_valid(Eth(*e))]
     if ethernets:
         macs = set([MACAddressField.normalize(eth.mac) for eth in ethernets])
         devs = Device.admin_objects.filter(ethernet__mac__in=macs).distinct()
         if len(devs) > 1:
             raise ValueError("Multiple devices match MACs: %r" % macs)
         elif len(devs) == 1:
             if dev and devs[0].id != dev.id:
                 raise ValueError("Conflict of devices %r and %r!" % (dev, devs[0]))
             else:
                 dev = devs[0]
     if sn:
         sn = sn.strip()
     if sn in SERIAL_BLACKLIST:
         sn = None
     if not any((sn, ethernets, allow_stub)):
         raise ValueError("Neither `sn` nor `ethernets` given.  Use `allow_stub` " "to override.")
     if sn:
         try:
             sndev = Device.admin_objects.get(sn=sn)
         except Device.DoesNotExist:
             pass
         else:
             if dev is None:
                 dev = sndev
             elif sndev.id != dev.id:
                 # both devices are properly placed in the tree
                 if any(
                     (
                         sndev.parent and dev.parent,
                         # the device found using ethernets (or explicitly
                         # given as `device`) has different sn than `sn`
                         dev.sn and dev.sn != sn,
                         # the device found using `sn` already has other
                         # ethernets
                         sndev.ethernet_set.exists(),
                     )
                 ):
                     raise ValueError("Conflict of devices %r and %r!" % (dev, sndev))
                 sndev.delete()
     if model is None:
         model, model_created = DeviceModel.concurrent_get_or_create(
             name=model_name, defaults={"type": model_type.id}
         )
     if dev is None:
         dev, created = Device.concurrent_get_or_create(sn=sn, defaults={"model": model})
     elif dev.deleted:
         # Ignore the priority and undelete even if it was manually deleted
         priorities = dev.get_save_priorities()
         priorities["deleted"] = 0
         dev.update_save_priorities(priorities)
         dev.deleted = False
     if model and model.type != DeviceType.unknown.id:
         dev.model = model
     if not dev.sn and sn:
         dev.sn = sn
     for k, v in kwargs.iteritems():
         if k in ("name", "last_seen"):
             continue
         setattr(dev, k, v)
     try:
         user = kwargs.get("user")
     except KeyError:
         user = None
     dev.save(user=user, update_last_seen=True, priority=priority)
     for eth in ethernets:
         ethernet, eth_created = Ethernet.concurrent_get_or_create(mac=eth.mac, defaults={"device": dev})
         ethernet.device = dev
         ethernet.label = eth.label or "Autocreated"
         if eth.speed:
             ethernet.speed = eth.speed
         ethernet.save(priority=priority)
     return dev