models.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 IPNetwork, IPSet
  9. def validate_subnet(cidr):
  10. """Checks that a CIDR object is indeed a subnet, i.e. the host bits are
  11. all set to zero."""
  12. if not isinstance(cidr, IPNetwork):
  13. raise ValidationError("Erreur, objet IPNetwork attendu.")
  14. if cidr.ip != cidr.network:
  15. raise ValidationError("{} n'est pas un sous-réseau valide, voulez-vous dire {} ?".format(cidr, cidr.cidr))
  16. class IPPool(models.Model):
  17. """Pool of IP addresses (either v4 or v6)."""
  18. name = models.CharField(max_length=255, blank=False, null=False,
  19. verbose_name='nom',
  20. help_text="Nom du pool d'IP")
  21. default_subnetsize = models.PositiveSmallIntegerField(blank=False,
  22. verbose_name='taille de sous-réseau par défaut',
  23. help_text='Taille par défaut du sous-réseau à allouer aux abonnés dans ce pool',
  24. validators=[MaxValueValidator(64)])
  25. inet = CidrAddressField(validators=[validate_subnet],
  26. verbose_name='réseau',
  27. help_text="Bloc d'adresses IP du pool")
  28. objects = NetManager()
  29. def clean(self):
  30. if self.inet:
  31. max_subnetsize = 64 if self.inet.version == 6 else 32
  32. if not self.inet.prefixlen <= self.default_subnetsize <= max_subnetsize:
  33. raise ValidationError('Taille de sous-réseau invalide')
  34. # Check that related subnet are in the pool (useful when
  35. # modifying an existing pool that already has subnets
  36. # allocated in it)
  37. incorrect = [str(subnet) for subnet in self.ipsubnet_set.all()
  38. if not subnet.inet in self.inet]
  39. if incorrect:
  40. err = "Des sous-réseaux se retrouveraient en-dehors du bloc d'IP: {}".format(incorrect)
  41. raise ValidationError(err)
  42. def __unicode__(self):
  43. return self.name
  44. class Meta:
  45. verbose_name = "pool d'IP"
  46. verbose_name_plural = "pools d'IP"
  47. class IPSubnet(models.Model):
  48. # TODO: find some way to signal to Subscriptions objects when a subnet
  49. # gets modified (so that the subscription can update the LDAP backend
  50. # accordingly)
  51. # Actually, a better idea would be to build a custom relation and update
  52. # LDAP in the relation itself.
  53. inet = CidrAddressField(blank=True, validators=[validate_subnet],
  54. verbose_name="sous-réseau",
  55. help_text="Laisser vide pour allouer automatiquement")
  56. objects = NetManager()
  57. ip_pool = models.ForeignKey(IPPool, verbose_name="pool d'IP")
  58. configuration = models.ForeignKey('configuration.Configuration',
  59. related_name='ip_subnet',
  60. verbose_name='configuration')
  61. delegate_reverse_dns = models.BooleanField(default=False,
  62. verbose_name='déléguer le reverse DNS',
  63. help_text='Déléguer la résolution DNS inverse de ce sous-réseau à un ou plusieurs serveurs de noms')
  64. name_server = models.ManyToManyField('reverse_dns.NameServer',
  65. blank=True,
  66. verbose_name='serveur de noms',
  67. help_text="Serveur de noms à qui déléguer la résolution DNS inverse")
  68. def allocate(self):
  69. """Automatically allocate a free subnet"""
  70. pool = IPSet([self.ip_pool.inet])
  71. used = IPSet((s.inet for s in self.ip_pool.ipsubnet_set.all()))
  72. free = pool.difference(used)
  73. # Generator for efficiency (we don't build the whole list)
  74. available = (p for p in free.iter_cidrs() if p.prefixlen <= self.ip_pool.default_subnetsize)
  75. # TODO: for IPv4, get rid of the network and broadcast
  76. # addresses? Not really needed nowadays, and we usually don't
  77. # have a real subnet in practice (i.e. Ethernet segment), but
  78. # many /32.
  79. try:
  80. first_free = available.next()
  81. except StopIteration:
  82. raise ValidationError("Impossible d'allouer un sous-réseau : bloc d'IP rempli.")
  83. self.inet = first_free.subnet(self.ip_pool.default_subnetsize, 1).next()
  84. def validate_inclusion(self):
  85. """Check that we are included in the IP pool"""
  86. if not self.inet in self.ip_pool.inet:
  87. raise ValidationError("Le sous-réseau doit être inclus dans le bloc d'IP.")
  88. # Check that we don't conflict with existing subnets.
  89. conflicting = self.ip_pool.ipsubnet_set.filter(Q(inet__net_contained_or_equal=self.inet) |
  90. Q(inet__net_contains_or_equals=self.inet)).exclude(id=self.id)
  91. if conflicting:
  92. raise ValidationError("Le sous-réseau est en conflit avec des sous-réseaux existants: {}.".format(conflicting))
  93. def validate_reverse_dns(self):
  94. """Check that reverse DNS entries, if any, are included in the subnet"""
  95. incorrect = [str(rev.ip) for rev in self.reversednsentry_set.all() if not rev.ip in self.inet]
  96. if incorrect:
  97. raise ValidationError("Des entrées DNS inverse ne sont pas dans le sous-réseau: {}.".format(incorrect))
  98. def clean(self):
  99. if not self.inet:
  100. self.allocate()
  101. else:
  102. self.validate_inclusion()
  103. self.validate_reverse_dns()
  104. def __unicode__(self):
  105. return str(self.inet)
  106. class Meta:
  107. verbose_name = "sous-réseau IP"
  108. verbose_name_plural = "sous-réseaux IP"