models.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: utf-8 -*-
  2. from django.db import models
  3. from django.core.exceptions import ValidationError
  4. from django.core.validators import MaxValueValidator
  5. from netfields import CidrAddressField, NetManager
  6. from netaddr import IPNetwork, IPSet
  7. def validate_subnet(cidr):
  8. """Checks that a CIDR object is indeed a subnet, i.e. the host bits are
  9. all set to zero."""
  10. if not isinstance(cidr, IPNetwork):
  11. raise ValidationError("Internal error, expected IPNetwork object")
  12. if cidr.ip != cidr.network:
  13. raise ValidationError("{} is not a proper subnet, you probably mean {}".format(cidr, cidr.cidr))
  14. class IPPool(models.Model):
  15. """Pool of IP addresses (either v4 or v6)."""
  16. name = models.CharField(max_length=255, blank=False, null=False,
  17. verbose_name='Name of the IP pool')
  18. default_subnetsize = models.PositiveSmallIntegerField(blank=False,
  19. verbose_name='Default subnet size to allocate to subscribers in this pool',
  20. validators=[MaxValueValidator(64)])
  21. inet = CidrAddressField(validators=[validate_subnet])
  22. objects = NetManager()
  23. def clean(self):
  24. if self.inet:
  25. max_subnetsize = 64 if self.inet.version == 6 else 32
  26. if not self.inet.prefixlen <= self.default_subnetsize <= max_subnetsize:
  27. raise ValidationError('Invalid default subnet size')
  28. # Check that related subnet are in the pool (useful when
  29. # modifying an existing pool that already has subnets
  30. # allocated in it)
  31. incorrect = [str(subnet) for subnet in self.ipsubnet_set.all()
  32. if not subnet.inet in self.inet]
  33. if incorrect:
  34. err = 'Some subnets allocated in this pool are outside the pool: {}'.format(incorrect)
  35. raise ValidationError(err)
  36. def __unicode__(self):
  37. return self.name
  38. class IPSubnet(models.Model):
  39. inet = CidrAddressField(blank=True, validators=[validate_subnet],
  40. verbose_name="Leave empty for automatic allocation")
  41. objects = NetManager()
  42. ip_pool = models.ForeignKey(IPPool)
  43. offer_subscription = models.ForeignKey('offers.OfferSubscription',
  44. related_name='ip_subnet')
  45. def clean(self):
  46. if not self.inet:
  47. # Automatically allocate a free subnet
  48. pool = IPSet([self.ip_pool.inet])
  49. used = IPSet((s.inet for s in self.ip_pool.ipsubnet_set.all()))
  50. free = pool.difference(used)
  51. # Generator for efficiency (we don't build the whole list)
  52. available = (p for p in free.iter_cidrs() if p.prefixlen <= self.ip_pool.default_subnetsize)
  53. # TODO: for IPv4, get rid of the network and broadcast
  54. # addresses? Not really needed nowadays, and we usually don't
  55. # have a real subnet in practice (i.e. Ethernet segment), but
  56. # many /32.
  57. try:
  58. first_free = available.next()
  59. except StopIteration:
  60. raise ValidationError('Unable to allocate an IP subnet in the specified pool: not enough space left.')
  61. self.inet = first_free.subnet(self.ip_pool.default_subnetsize, 1).next()
  62. else:
  63. # Check that we are included in the IP pool.
  64. if not self.inet in self.ip_pool.inet:
  65. raise ValidationError('Subnet must be included in the IP pool.')
  66. # Check that we don't conflict with existing subnets.
  67. # TODO: use precise database query instead of querying all
  68. # subnets and filtering in Python.
  69. existing = IPSet((s.inet for s in self.ip_pool.ipsubnet_set.all()))
  70. intersection = IPSet([self.inet]).intersection(existing)
  71. if intersection.size:
  72. raise ValidationError('Subnet must not intersect with existing subnets.\nIntersected subnets: {}.'.format([str(p) for p in intersection.iter_cidrs()]))
  73. def __unicode__(self):
  74. return str(self.inet)