models.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.db import models
  4. from django.core.exceptions import ValidationError
  5. from django.core.validators import MaxValueValidator
  6. from django.db.models import Q
  7. from netfields import CidrAddressField, NetManager
  8. from netaddr import IPSet
  9. class IPPool(models.Model):
  10. """Pool of IP addresses (either v4 or v6)."""
  11. name = models.CharField(max_length=255, blank=False, null=False,
  12. verbose_name='nom',
  13. help_text="Nom du pool d'IP")
  14. default_subnetsize = models.PositiveSmallIntegerField(blank=False,
  15. verbose_name='taille de sous-réseau par défaut',
  16. help_text='Taille par défaut du sous-réseau à allouer aux abonnés dans ce pool',
  17. validators=[MaxValueValidator(64)])
  18. inet = CidrAddressField(verbose_name='réseau',
  19. help_text="Bloc d'adresses IP du pool")
  20. objects = NetManager()
  21. def clean(self):
  22. if self.inet:
  23. max_subnetsize = 64 if self.inet.version == 6 else 32
  24. if not self.inet.prefixlen <= self.default_subnetsize <= max_subnetsize:
  25. raise ValidationError('Taille de sous-réseau invalide')
  26. # Check that related subnet are in the pool (useful when
  27. # modifying an existing pool that already has subnets
  28. # allocated in it)
  29. incorrect = [str(subnet) for subnet in self.ipsubnet_set.all()
  30. if not subnet.inet in self.inet]
  31. if incorrect:
  32. err = "Des sous-réseaux se retrouveraient en-dehors du bloc d'IP: {}".format(incorrect)
  33. raise ValidationError(err)
  34. def __unicode__(self):
  35. return self.name
  36. class Meta:
  37. verbose_name = "pool d'IP"
  38. verbose_name_plural = "pools d'IP"
  39. class IPSubnet(models.Model):
  40. inet = CidrAddressField(blank=True,
  41. unique=True, verbose_name="sous-réseau",
  42. help_text="Laisser vide pour allouer automatiquement")
  43. objects = NetManager()
  44. ip_pool = models.ForeignKey(IPPool, verbose_name="pool d'IP")
  45. configuration = models.ForeignKey('configuration.Configuration',
  46. related_name='ip_subnet',
  47. verbose_name='configuration')
  48. delegate_reverse_dns = models.BooleanField(default=False,
  49. verbose_name='déléguer le reverse DNS',
  50. help_text='Déléguer la résolution DNS inverse de ce sous-réseau à un ou plusieurs serveurs de noms')
  51. name_server = models.ManyToManyField('reverse_dns.NameServer',
  52. blank=True,
  53. verbose_name='serveur de noms',
  54. help_text="Serveur de noms à qui déléguer la résolution DNS inverse")
  55. def allocate(self):
  56. """Automatically allocate a free subnet"""
  57. pool = IPSet([self.ip_pool.inet])
  58. used = IPSet((s.inet for s in self.ip_pool.ipsubnet_set.all()))
  59. free = pool.difference(used)
  60. # Generator for efficiency (we don't build the whole list)
  61. available = (p for p in free.iter_cidrs() if p.prefixlen <= self.ip_pool.default_subnetsize)
  62. # TODO: for IPv4, get rid of the network and broadcast
  63. # addresses? Not really needed nowadays, and we usually don't
  64. # have a real subnet in practice (i.e. Ethernet segment), but
  65. # many /32.
  66. try:
  67. first_free = available.next()
  68. except StopIteration:
  69. raise ValidationError("Impossible d'allouer un sous-réseau : bloc d'IP rempli.")
  70. # first_free is a subnet, but it might be too large for our needs.
  71. # This selects the first sub-subnet of the right size.
  72. self.inet = first_free.subnet(self.ip_pool.default_subnetsize, 1).next()
  73. def validate_inclusion(self):
  74. """Check that we are included in the IP pool"""
  75. if not self.inet in self.ip_pool.inet:
  76. raise ValidationError("Le sous-réseau doit être inclus dans le bloc d'IP.")
  77. # Check that we don't conflict with existing subnets.
  78. conflicting = self.ip_pool.ipsubnet_set.filter(Q(inet__net_contained_or_equal=self.inet) |
  79. Q(inet__net_contains_or_equals=self.inet)).exclude(id=self.id)
  80. if conflicting:
  81. raise ValidationError("Le sous-réseau est en conflit avec des sous-réseaux existants: {}.".format(conflicting))
  82. def validate_reverse_dns(self):
  83. """Check that reverse DNS entries, if any, are included in the subnet"""
  84. incorrect = [str(rev.ip) for rev in self.reversednsentry_set.all() if not rev.ip in self.inet]
  85. if incorrect:
  86. raise ValidationError("Des entrées DNS inverse ne sont pas dans le sous-réseau: {}.".format(incorrect))
  87. def clean(self):
  88. if not self.inet:
  89. self.allocate()
  90. else:
  91. self.validate_inclusion()
  92. self.validate_reverse_dns()
  93. def __unicode__(self):
  94. return str(self.inet)
  95. class Meta:
  96. verbose_name = "sous-réseau IP"
  97. verbose_name_plural = "sous-réseaux IP"