from django.core.management.base import BaseCommand from django.utils import timezone from datetime import timedelta from itertools import groupby from services.models import ServiceAllocation, IPResource, IPResourceState class Command(BaseCommand): help = 'Détection des pannes' def handle(self, *args, **options): down = IPResource.objects.filter( category=IPResource.CATEGORY_PUBLIC, last_state__state=IPResourceState.STATE_DOWN, last_time_up__gt=timezone.now()-timedelta(minutes=5)) allocations = ServiceAllocation.objects.filter(resource__pk__in=down) #allocations = allocations.values('resource', 'route') allocations = sorted(allocations, key=lambda a: a.route.pk) for route, allocs in groupby(allocations, key=lambda a: a.route.pk): allocs = list(allocs) route = allocs[0].route print("%s: %d" % (route, len(allocs))) for alloc in allocs: print("\t%s" % alloc.resource) if len(allocs) >= 4: logger.info('%s %s' % (route, allocs)) self.stdout.write(self.style.SUCCESS('Aucune panne détectée.'))