Add host detail view
[pharos-tools.git] / dashboard / src / dashboard / actions.py
1 ##############################################################################
2 # Copyright (c) 2019 Parker Berberian, Sawyer Bergeron, and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 from resource_inventory.models import Host, Vlan
11 from account.models import Lab
12 from booking.models import Booking
13 from datetime import timedelta
14 from django.utils import timezone
15
16
17 def free_leaked_hosts(free_old_bookings=False, old_booking_age=timedelta(days=1)):
18     bundles = [booking.resource for booking in Booking.objects.filter(end__gt=timezone.now())]
19     active_hosts = set()
20     for bundle in bundles:
21         active_hosts.update([host for host in bundle.hosts.all()])
22
23     marked_hosts = set(Host.objects.filter(booked=True))
24
25     for host in (marked_hosts - active_hosts):
26         host.booked = False
27         host.save()
28
29
30 def free_leaked_public_vlans():
31     booked_host_interfaces = []
32
33     for lab in Lab.objects.all():
34
35         for host in Host.objects.filter(booked=True).filter(lab=lab):
36             for interface in host.interfaces.all():
37                 booked_host_interfaces.append(interface)
38
39         in_use_vlans = Vlan.objects.filter(public=True).distinct('vlan_id').filter(interface__in=booked_host_interfaces)
40
41         manager = lab.vlan_manager
42
43         for vlan in Vlan.objects.all():
44             if vlan not in in_use_vlans:
45                 if vlan.public:
46                     manager.release_public_vlan(vlan.vlan_id)
47                 manager.release_vlans(vlan)