models.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. delegate_reverse_dns = models.BooleanField(default=False)
  47. name_server = models.ManyToManyField('reverse_dns.NameServer',
  48. blank=True,
  49. verbose_name="nameserver to use for the delegation of reverse DNS")
  50. def allocate(self):
  51. """Automatically allocate a free subnet"""
  52. pool = IPSet([self.ip_pool.inet])
  53. used = IPSet((s.inet for s in self.ip_pool.ipsubnet_set.all()))
  54. free = pool.difference(used)
  55. # Generator for efficiency (we don't build the whole list)
  56. available = (p for p in free.iter_cidrs() if p.prefixlen <= self.ip_pool.default_subnetsize)
  57. # TODO: for IPv4, get rid of the network and broadcast
  58. # addresses? Not really needed nowadays, and we usually don't
  59. # have a real subnet in practice (i.e. Ethernet segment), but
  60. # many /32.
  61. try:
  62. first_free = available.next()
  63. except StopIteration:
  64. raise ValidationError('Unable to allocate an IP subnet in the specified pool: not enough space left.')
  65. self.inet = first_free.subnet(self.ip_pool.default_subnetsize, 1).next()
  66. def validate_inclusion(self):
  67. """Check that we are included in the IP pool"""
  68. if not self.inet in self.ip_pool.inet:
  69. raise ValidationError('Subnet must be included in the IP pool.')
  70. # Check that we don't conflict with existing subnets.
  71. conflicting = self.ip_pool.ipsubnet_set.filter(Q(inet__net_contained_or_equal=self.inet) |
  72. Q(inet__net_contains_or_equals=self.inet)).exclude(id=self.id)
  73. if conflicting:
  74. raise ValidationError('Subnet must not intersect with existing subnets.\nIntersected subnets: {}.'.format(conflicting))
  75. def validate_reverse_dns(self):
  76. """Check that reverse DNS entries, if any, are included in the subnet"""
  77. incorrect = [str(rev.ip) for rev in self.reversednsentry_set.all() if not rev.ip in self.inet]
  78. if incorrect:
  79. raise ValidationError('Some reverse DNS entries are not in the subnet: {}.'.format(incorrect))
  80. def clean(self):
  81. if not self.inet:
  82. self.allocate()
  83. else:
  84. self.validate_inclusion()
  85. self.validate_reverse_dns()
  86. def __unicode__(self):
  87. return str(self.inet)