from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType import os, re, sys, socket from adhesions.models import Adhesion from services.models import Service, ServiceType, IPResource, Route from accounts.models import Profile check_reverse = True regex = re.compile('^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) ([a-z.0-9]+)$') class Command(BaseCommand): help = 'Comparaison des allocations IP dans Djadhere avec ip_ttnn.txt' def add_arguments(self, parser): parser.add_argument('file', help='Fichier ip_ttnn.txt') parser.add_argument('--no-reverse', action='store_false') def handle(self, *args, **options): try: f = open(options['file']) except FileNotFoundError: raise CommandError('Le fichier "%s" n’a pas été trouvé.' % options['file']) else: with f: self.check_ip(f) def check_ip(self, f): i = 0 j = 0 for line in f: i += 1 g = regex.match(line) if not g: self.stdout.write(self.style.ERROR("Impossible de parser la ligne n°%d: '%s'" % (i, line[:-1]))) continue resource = IPResource.objects.get(ip=g.group(1)) route = g.group(2) if route == 'reserved': if resource.in_use: alloc = resource.allocations.get(active=True) self.stdout.write(self.style.WARNING("L’IP %s est marqué réservée dans ip_ttnn.txt mais allouée au service #%d sur Djadhere" % (resource, alloc.service.pk))) if not resource.reserved: self.stdout.write(self.style.WARNING("L’IP %s est marqué réservée dans ip_ttnn.txt mais pas dans Djadhere" % resource)) continue if route == "unused": if resource.in_use: alloc = resource.allocations.get(active=True) self.stdout.write(self.style.WARNING("L’IP %s est marqué disponible dans ip_ttnn.txt mais allouée au service #%d sur Djadhere" % (resource, alloc.service.pk))) continue route = Route.objects.get(name=route) if resource.in_use: alloc = resource.allocations.get(active=True) if alloc.route != route: self.stdout.write(self.style.WARNING("L’IP %s est routée sur %s dans ip_ttnn.txt mais routée sur %s pour le service #%d sur Djadhere" % (resource, route, alloc.route, alloc.service.pk))) continue if route.name in ['cluster', 'tls']: if resource.reserved: self.stdout.write(self.style.WARNING("L’IP %s est marqué réservée dans Djadhere alors que routée via %s dans ip_ttnn.txt" % (resource, route))) if check_reverse: try: reverse, _, _ = socket.gethostbyaddr(str(resource)) except: reverse = '?' else: reverse = '?' self.stdout.write(self.style.WARNING("L’IP %s est disponible dans Djadhere alors que routée via %s dans ip_ttnn.txt (reverse : %s)" % (resource, route, reverse))) else: if not resource.reserved: self.stdout.write(self.style.WARNING("L’IP %s est routée via %s dans ip_ttnn.txt mais disponible dans Djadhere" % (resource, route)))