Merge "Fix Multiple Select Filter Widget"
[laas.git] / src / resource_inventory / resource_manager.py
1 ##############################################################################
2 # Copyright (c) 2018 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
11 from django.template.loader import render_to_string
12
13 import booking
14 from dashboard.exceptions import (
15     ResourceExistenceException,
16     ResourceAvailabilityException,
17     ResourceProvisioningException,
18     ModelValidationException,
19 )
20 from resource_inventory.models import Host, HostConfiguration, ResourceBundle
21
22
23 class ResourceManager:
24
25     instance = None
26
27     def __init__(self):
28         pass
29
30     @staticmethod
31     def getInstance():
32         if ResourceManager.instance is None:
33             ResourceManager.instance = ResourceManager()
34         return ResourceManager.instance
35
36     # public interface
37     def deleteResourceBundle(self, resourceBundle):
38         for host in Host.objects.filter(bundle=resourceBundle):
39             self.releaseHost(host)
40         resourceBundle.delete()
41
42     def convertResourceBundle(self, genericResourceBundle, lab=None, config=None):
43         """
44         Takes in a GenericResourceBundle and 'converts' it into a ResourceBundle
45         """
46         resource_bundle = ResourceBundle()
47         resource_bundle.template = genericResourceBundle
48         resource_bundle.save()
49
50         hosts = genericResourceBundle.getHosts()
51
52         # current supported case: user creating new booking
53         # currently unsupported: editing existing booking
54
55         physical_hosts = []
56
57         for host in hosts:
58             host_config = None
59             if config:
60                 host_config = HostConfiguration.objects.get(bundle=config, host=host)
61             try:
62                 physical_host = self.acquireHost(host, genericResourceBundle.lab.name)
63             except ResourceAvailabilityException:
64                 self.fail_acquire(physical_hosts)
65                 raise ResourceAvailabilityException("Could not provision hosts, not enough available")
66             try:
67                 physical_host.bundle = resource_bundle
68                 physical_host.template = host
69                 physical_host.config = host_config
70                 physical_hosts.append(physical_host)
71
72                 self.configureNetworking(physical_host)
73             except:
74                 self.fail_acquire(physical_hosts)
75                 raise ResourceProvisioningException("Network configuration failed.")
76             try:
77                 physical_host.save()
78             except:
79                 self.fail_acquire(physical_hosts)
80                 raise ModelValidationException("Saving hosts failed")
81
82         return resource_bundle
83
84     def configureNetworking(self, host):
85         generic_interfaces = list(host.template.generic_interfaces.all())
86         for int_num, physical_interface in enumerate(host.interfaces.all()):
87             generic_interface = generic_interfaces[int_num]
88             physical_interface.config.clear()
89             for vlan in generic_interface.vlans.all():
90                 physical_interface.config.add(vlan)
91
92     # private interface
93     def acquireHost(self, genericHost, labName):
94         host_full_set = Host.objects.filter(lab__name__exact=labName, profile=genericHost.profile)
95         if not host_full_set.first():
96             raise ResourceExistenceException("No matching servers found")
97         host_set = host_full_set.filter(booked=False)
98         if not host_set.first():
99             raise ResourceAvailabilityException("No unbooked hosts match requested hosts")
100         host = host_set.first()
101         host.booked = True
102         host.template = genericHost
103         host.save()
104         return host
105
106     def releaseHost(self, host):
107         host.template = None
108         host.bundle = None
109         host.booked = False
110         host.save()
111
112     def fail_acquire(self, hosts):
113         for host in hosts:
114             self.releaseHost(host)
115
116     def makePDF(self, resource):
117         """
118         fills the pod descriptor file template with info about the resource
119         """
120         template = "dashboard/pdf.yaml"
121         info = {}
122         info['details'] = self.get_pdf_details(resource)
123         info['jumphost'] = self.get_pdf_jumphost(resource)
124         info['nodes'] = self.get_pdf_nodes(resource)
125
126         return render_to_string(template, context=info)
127
128     def get_pdf_details(self, resource):
129         details = {}
130         owner = "Anon"
131         email = "email@mail.com"
132         resource_lab = resource.template.lab
133         lab = resource_lab.name
134         location = resource_lab.location
135         pod_type = "development"
136         link = "https://wiki.opnfv.org/display/INF/Pharos+Laas"
137
138         try:
139             # try to get more specific info that may fail, we dont care if it does
140             booking_owner = booking.models.Booking.objects.get(resource=resource).owner
141             owner = booking_owner.username
142             email = booking_owner.userprofile.email_addr
143         except Exception:
144             pass
145
146         details['owner'] = owner
147         details['email'] = email
148         details['lab'] = lab
149         details['location'] = location
150         details['type'] = pod_type
151         details['link'] = link
152
153         return details
154
155     def get_pdf_jumphost(self, resource):
156         jumphost = Host.objects.get(bundle=resource, config__opnfvRole__name__iexact="jumphost")
157         return self.get_pdf_host(jumphost)
158
159     def get_pdf_nodes(self, resource):
160         pdf_nodes = []
161         nodes = Host.objects.filter(bundle=resource).exclude(config__opnfvRole__name__iexact="jumphost")
162         for node in nodes:
163             pdf_nodes.append(self.get_pdf_host(node))
164
165         return pdf_nodes
166
167     def get_pdf_host(self, host):
168         host_info = {}
169         host_info['name'] = host.template.resource.name
170         host_info['node'] = {}
171         host_info['node']['type'] = "baremetal"
172         host_info['node']['vendor'] = host.vendor
173         host_info['node']['model'] = host.model
174         host_info['node']['arch'] = host.profile.cpuprofile.first().architecture
175         host_info['node']['cpus'] = host.profile.cpuprofile.first().cpus
176         host_info['node']['cores'] = host.profile.cpuprofile.first().cores
177         cflags = host.profile.cpuprofile.first().cflags
178         if cflags and cflags.strip():
179             host_info['node']['cpu_cflags'] = cflags
180         host_info['node']['memory'] = str(host.profile.ramprofile.first().amount) + "G"
181         host_info['disks'] = []
182         for disk in host.profile.storageprofile.all():
183             disk_info = {}
184             disk_info['name'] = disk.name
185             disk_info['capacity'] = str(disk.size) + "G"
186             disk_info['type'] = disk.media_type
187             disk_info['interface'] = disk.interface
188             disk_info['rotation'] = disk.rotation
189             host_info['disks'].append(disk_info)
190
191         host_info['interfaces'] = []
192         for interface in host.interfaces.all():
193             iface_info = {}
194             iface_info['name'] = interface.name
195             iface_info['address'] = "unknown"
196             iface_info['mac_address'] = interface.mac_address
197             vlans = "|".join([str(vlan.vlan_id) for vlan in interface.config.all()])
198             iface_info['vlans'] = vlans
199             host_info['interfaces'].append(iface_info)
200
201         return host_info