26ade22291b5dd813c4a944521fae25683a3b0dd
[pharos-tools.git] / dashboard / src / workflow / sw_bundle_workflow.py
1 ##############################################################################
2 # Copyright (c) 2018 Sawyer Bergeron, Parker Berberian, 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.forms import formset_factory
12
13 from workflow.models import WorkflowStep
14 from workflow.forms import SoftwareConfigurationForm, HostSoftwareDefinitionForm
15 from workflow.booking_workflow import Resource_Select
16 from resource_inventory.models import Image, GenericHost, ConfigBundle, HostConfiguration, Installer, OPNFVConfig
17
18
19 # resource selection step is reused from Booking workflow
20 class SWConf_Resource_Select(Resource_Select):
21     def __init__(self, *args, **kwargs):
22         super(SWConf_Resource_Select, self).__init__(*args, **kwargs)
23         self.repo_key = self.repo.SWCONF_SELECTED_GRB
24         self.confirm_key = "configuration"
25
26     def get_default_entry(self):
27         booking_grb = self.repo_get(self.repo.BOOKING_SELECTED_GRB)
28         if booking_grb:
29             return booking_grb
30         created_grb = self.repo_get(self.repo.GRESOURCE_BUNDLE_MODELS, {}).get("bundle", None)
31         return created_grb
32
33     def post_render(self, request):
34         response = super(SWConf_Resource_Select, self).post_render(request)
35         models = self.repo_get(self.repo.CONFIG_MODELS, {})
36         bundle = models.get("bundle", ConfigBundle(owner=self.repo_get(self.repo.SESSION_USER)))
37         bundle.bundle = self.repo_get(self.repo_key)  # super put grb here
38         models['bundle'] = bundle
39         self.repo_put(self.repo.CONFIG_MODELS, models)
40         return response
41
42
43 class Define_Software(WorkflowStep):
44     template = 'config_bundle/steps/define_software.html'
45     title = "Pick Software"
46     description = "Choose the opnfv and image of your machines"
47     short_title = "host config"
48
49     def create_hostformset(self, hostlist):
50         hosts_initial = []
51         host_configs = self.repo_get(self.repo.CONFIG_MODELS, {}).get("host_configs", False)
52         if host_configs:
53             for config in host_configs:
54                 host_initial = {'host_id': config.host.id, 'host_name': config.host.resource.name}
55                 host_initial['role'] = config.opnfvRole
56                 host_initial['image'] = config.image
57                 hosts_initial.append(host_initial)
58
59         else:
60             for host in hostlist:
61                 host_initial = {'host_id': host.id, 'host_name': host.resource.name}
62
63                 hosts_initial.append(host_initial)
64
65         HostFormset = formset_factory(HostSoftwareDefinitionForm, extra=0)
66         host_formset = HostFormset(initial=hosts_initial)
67
68         filter_data = {}
69         user = self.repo_get(self.repo.SESSION_USER)
70         i = 0
71         for host_data in hosts_initial:
72             host_profile = None
73             try:
74                 host = GenericHost.objects.get(pk=host_data['host_id'])
75                 host_profile = host.profile
76             except Exception:
77                 for host in hostlist:
78                     if host.resource.name == host_data['host_name']:
79                         host_profile = host.profile
80                         break
81             excluded_images = Image.objects.exclude(owner=user).exclude(public=True)
82             excluded_images = excluded_images | Image.objects.exclude(host_type=host.profile)
83             lab = self.repo_get(self.repo.SWCONF_SELECTED_GRB).lab
84             excluded_images = excluded_images | Image.objects.exclude(from_lab=lab)
85             filter_data["id_form-" + str(i) + "-image"] = []
86             for image in excluded_images:
87                 filter_data["id_form-" + str(i) + "-image"].append(image.name)
88             i += 1
89
90         return host_formset, filter_data
91
92     def get_host_list(self, grb=None):
93         if grb is None:
94             grb = self.repo_get(self.repo.SWCONF_SELECTED_GRB, False)
95             if not grb:
96                 return []
97         if grb.id:
98             return GenericHost.objects.filter(resource__bundle=grb)
99         generic_hosts = self.repo_get(self.repo.GRESOURCE_BUNDLE_MODELS, {}).get("hosts", [])
100         return generic_hosts
101
102     def get_context(self):
103         context = super(Define_Software, self).get_context()
104
105         grb = self.repo_get(self.repo.SWCONF_SELECTED_GRB, False)
106
107         if grb:
108             context["grb"] = grb
109             formset, filter_data = self.create_hostformset(self.get_host_list(grb))
110             context["formset"] = formset
111             context["filter_data"] = filter_data
112         else:
113             context["error"] = "Please select a resource first"
114             self.metastep.set_invalid("Step requires information that is not yet provided by previous step")
115
116         return context
117
118     def post_render(self, request):
119         models = self.repo_get(self.repo.CONFIG_MODELS, {})
120         if "bundle" not in models:
121             models['bundle'] = ConfigBundle(owner=self.repo_get(self.repo.SESSION_USER))
122
123         confirm = self.repo_get(self.repo.CONFIRMATION, {})
124
125         HostFormset = formset_factory(HostSoftwareDefinitionForm, extra=0)
126         formset = HostFormset(request.POST)
127         hosts = self.get_host_list()
128         if formset.is_valid():
129             models['host_configs'] = []
130             i = 0
131             confirm_hosts = []
132             for form in formset:
133                 host = hosts[i]
134                 i += 1
135                 image = form.cleaned_data['image']
136                 # checks image compatability
137                 grb = self.repo_get(self.repo.SWCONF_SELECTED_GRB)
138                 lab = None
139                 if grb:
140                     lab = grb.lab
141                 try:
142                     owner = self.repo_get(self.repo.SESSION_USER)
143                     q = Image.objects.filter(owner=owner) | Image.objects.filter(public=True)
144                     q.filter(host_type=host.profile)
145                     q.filter(from_lab=lab)
146                     q.get(id=image.id)  # will throw exception if image is not in q
147                 except:
148                     self.metastep.set_invalid("Image " + image.name + " is not compatible with host " + host.resource.name)
149                 role = form.cleaned_data['role']
150                 bundle = models['bundle']
151                 hostConfig = HostConfiguration(
152                     host=host,
153                     image=image,
154                     bundle=bundle,
155                     opnfvRole=role
156                 )
157                 models['host_configs'].append(hostConfig)
158                 confirm_host = {"name": host.resource.name, "image": image.name, "role": role.name}
159                 confirm_hosts.append(confirm_host)
160
161             self.repo_put(self.repo.CONFIG_MODELS, models)
162             if "configuration" not in confirm:
163                 confirm['configuration'] = {}
164             confirm['configuration']['hosts'] = confirm_hosts
165             self.repo_put(self.repo.CONFIRMATION, confirm)
166             self.metastep.set_valid("Completed")
167         else:
168             self.metastep.set_invalid("Please complete all fields")
169
170         return self.render(request)
171
172
173 class Config_Software(WorkflowStep):
174     template = 'config_bundle/steps/config_software.html'
175     form = SoftwareConfigurationForm
176     context = {'workspace_form': form}
177     title = "Other Info"
178     description = "Give your software config a name, description, and other stuff"
179     short_title = "config info"
180
181     def get_context(self):
182         context = super(Config_Software, self).get_context()
183
184         initial = {}
185         models = self.repo_get(self.repo.CONFIG_MODELS, {})
186         bundle = models.get("bundle", False)
187         if bundle:
188             initial['name'] = bundle.name
189             initial['description'] = bundle.description
190         opnfv = models.get("opnfv", False)
191         if opnfv:
192             initial['installer'] = opnfv.installer
193             initial['scenario'] = opnfv.scenario
194         else:
195             initial['opnfv'] = False
196         supported = {}
197         for installer in Installer.objects.all():
198             supported[str(installer)] = []
199             for scenario in installer.sup_scenarios.all():
200                 supported[str(installer)].append(str(scenario))
201
202         context["form"] = SoftwareConfigurationForm(initial=initial)
203         context['supported'] = supported
204
205         return context
206
207     def post_render(self, request):
208         try:
209             models = self.repo_get(self.repo.CONFIG_MODELS, {})
210             if "bundle" not in models:
211                 models['bundle'] = ConfigBundle(owner=self.repo_get(self.repo.SESSION_USER))
212
213             confirm = self.repo_get(self.repo.CONFIRMATION, {})
214             if "configuration" not in confirm:
215                 confirm['configuration'] = {}
216
217             form = self.form(request.POST)
218             if form.is_valid():
219                 models['bundle'].name = form.cleaned_data['name']
220                 models['bundle'].description = form.cleaned_data['description']
221                 if form.cleaned_data['opnfv']:
222                     installer = form.cleaned_data['installer']
223                     scenario = form.cleaned_data['scenario']
224                     opnfv = OPNFVConfig(
225                         bundle=models['bundle'],
226                         installer=installer,
227                         scenario=scenario
228                     )
229                     models['opnfv'] = opnfv
230                     confirm['configuration']['installer'] = form.cleaned_data['installer'].name
231                     confirm['configuration']['scenario'] = form.cleaned_data['scenario'].name
232
233                 confirm['configuration']['name'] = form.cleaned_data['name']
234                 confirm['configuration']['description'] = form.cleaned_data['description']
235                 self.metastep.set_valid("Complete")
236             else:
237                 self.metastep.set_invalid("Please correct the errors shown below")
238
239             self.repo_put(self.repo.CONFIG_MODELS, models)
240             self.repo_put(self.repo.CONFIRMATION, confirm)
241
242         except Exception:
243             pass
244         return self.render(request)