models.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. class IPPool(models.Model):
  8. """Pool of IP addresses (either v4 or v6)."""
  9. name = models.CharField(max_length=255, blank=False, null=False,
  10. verbose_name='Name of the IP pool')
  11. default_subnetsize = models.PositiveSmallIntegerField(blank=False,
  12. verbose_name='Default subnet size to allocate to subscribers in this pool',
  13. validators=[MaxValueValidator(64)])
  14. inet = CidrAddressField()
  15. objects = NetManager()
  16. def __unicode__(self):
  17. return self.name
  18. class IPSubnet(models.Model):
  19. inet = CidrAddressField(blank=True, verbose_name="Leave empty for automatic allocation")
  20. objects = NetManager()
  21. ip_pool = models.ForeignKey(IPPool)
  22. offer_subscription = models.ForeignKey('offers.OfferSubscription',
  23. related_name='ip_subnet')
  24. def clean(self):
  25. if not self.inet:
  26. # Automatically allocate a free subnet
  27. pool = IPSet([self.ip_pool.inet])
  28. used = IPSet((s.inet for s in self.ip_pool.ipsubnet_set.all()))
  29. free = pool.difference(used)
  30. # Generator for efficiency (we don't build the whole list)
  31. available = (p for p in free.iter_cidrs() if p.prefixlen <= self.ip_pool.default_subnetsize)
  32. # TODO: for IPv4, get rid of the network and broadcast
  33. # addresses? Not really needed nowadays, and we usually don't
  34. # have a real subnet in practice (i.e. Ethernet segment), but
  35. # many /32.
  36. try:
  37. first_free = available.next()
  38. except StopIteration:
  39. raise ValidationError('Unable to allocate an IP subnet in the specified pool: not enough space left.')
  40. self.inet = first_free.subnet(SUBNET_SIZE, 1).next()
  41. else:
  42. # TODO:
  43. # Check that we are included in the IP pool.
  44. # Check that we don't conflict with existing subnets
  45. pass
  46. def __unicode__(self):
  47. return str(self.inet)