models.py 4.0 KB

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