Fix all flake8 errors
[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 = GenericHost.objects.get(pk=host_data['host_id'])
73             excluded_images = Image.objects.exclude(owner=user).exclude(public=True)
74             excluded_images = excluded_images | Image.objects.exclude(host_type=host.profile)
75             lab = self.repo_get(self.repo.SWCONF_SELECTED_GRB).lab
76             excluded_images = excluded_images | Image.objects.exclude(from_lab=lab)
77             filter_data["id_form-" + str(i) + "-image"] = []
78             for image in excluded_images:
79                 filter_data["id_form-" + str(i) + "-image"].append(image.name)
80             i += 1
81
82         return host_formset, filter_data
83
84     def get_host_list(self, grb=None):
85         if grb is None:
86             grb = self.repo_get(self.repo.SWCONF_SELECTED_GRB, False)
87             if not grb:
88                 return []
89         if grb.id:
90             return GenericHost.objects.filter(resource__bundle=grb)
91         generic_hosts = self.repo_get(self.repo.GRESOURCE_BUNDLE_MODELS, {}).get("hosts", [])
92         return generic_hosts
93
94     def get_context(self):
95         context = super(Define_Software, self).get_context()
96
97         grb = self.repo_get(self.repo.SWCONF_SELECTED_GRB, False)
98
99         if grb:
100             context["grb"] = grb
101             formset, filter_data = self.create_hostformset(self.get_host_list(grb))
102             context["formset"] = formset
103             context["filter_data"] = filter_data
104         else:
105             context["error"] = "Please select a resource first"
106             self.metastep.set_invalid("Step requires information that is not yet provided by previous step")
107
108         return context
109
110     def post_render(self, request):
111         models = self.repo_get(self.repo.CONFIG_MODELS, {})
112         if "bundle" not in models:
113             models['bundle'] = ConfigBundle(owner=self.repo_get(self.repo.SESSION_USER))
114
115         confirm = self.repo_get(self.repo.CONFIRMATION, {})
116
117         HostFormset = formset_factory(HostSoftwareDefinitionForm, extra=0)
118         formset = HostFormset(request.POST)
119         hosts = self.get_host_list()
120         if formset.is_valid():
121             models['host_configs'] = []
122             i = 0
123             confirm_hosts = []
124             for form in formset:
125                 host = hosts[i]
126                 i += 1
127                 image = form.cleaned_data['image']
128                 # checks image compatability
129                 grb = self.repo_get(self.repo.SWCONF_SELECTED_GRB)
130                 lab = None
131                 if grb:
132                     lab = grb.lab
133                 try:
134                     owner = self.repo_get(self.repo.SESSION_USER)
135                     q = Image.objects.filter(owner=owner) | Image.objects.filter(public=True)
136                     q.filter(host_type=host.profile)
137                     q.filter(from_lab=lab)
138                     q.get(id=image.id)  # will throw exception if image is not in q
139                 except:
140                     self.metastep.set_invalid("Image " + image.name + " is not compatible with host " + host.resource.name)
141                 role = form.cleaned_data['role']
142                 bundle = models['bundle']
143                 hostConfig = HostConfiguration(
144                     host=host,
145                     image=image,
146                     bundle=bundle,
147                     opnfvRole=role
148                 )
149                 models['host_configs'].append(hostConfig)
150                 confirm_host = {"name": host.resource.name, "image": image.name, "role": role.name}
151                 confirm_hosts.append(confirm_host)
152
153             self.repo_put(self.repo.CONFIG_MODELS, models)
154             if "configuration" not in confirm:
155                 confirm['configuration'] = {}
156             confirm['configuration']['hosts'] = confirm_hosts
157             self.repo_put(self.repo.CONFIRMATION, confirm)
158             self.metastep.set_valid("Completed")
159         else:
160             self.metastep.set_invalid("Please complete all fields")
161
162         return self.render(request)
163
164
165 class Config_Software(WorkflowStep):
166     template = 'config_bundle/steps/config_software.html'
167     form = SoftwareConfigurationForm
168     context = {'workspace_form': form}
169     title = "Other Info"
170     description = "Give your software config a name, description, and other stuff"
171     short_title = "config info"
172
173     def get_context(self):
174         context = super(Config_Software, self).get_context()
175
176         initial = {}
177         models = self.repo_get(self.repo.CONFIG_MODELS, {})
178         bundle = models.get("bundle", False)
179         if bundle:
180             initial['name'] = bundle.name
181             initial['description'] = bundle.description
182         opnfv = models.get("opnfv", False)
183         if opnfv:
184             initial['installer'] = opnfv.installer
185             initial['scenario'] = opnfv.scenario
186         else:
187             initial['opnfv'] = False
188         supported = {}
189         for installer in Installer.objects.all():
190             supported[str(installer)] = []
191             for scenario in installer.sup_scenarios.all():
192                 supported[str(installer)].append(str(scenario))
193
194         context["form"] = SoftwareConfigurationForm(initial=initial)
195         context['supported'] = supported
196
197         return context
198
199     def post_render(self, request):
200         try:
201             models = self.repo_get(self.repo.CONFIG_MODELS, {})
202             if "bundle" not in models:
203                 models['bundle'] = ConfigBundle(owner=self.repo_get(self.repo.SESSION_USER))
204
205             confirm = self.repo_get(self.repo.CONFIRMATION, {})
206             if "configuration" not in confirm:
207                 confirm['configuration'] = {}
208
209             form = self.form(request.POST)
210             if form.is_valid():
211                 models['bundle'].name = form.cleaned_data['name']
212                 models['bundle'].description = form.cleaned_data['description']
213                 if form.cleaned_data['opnfv']:
214                     installer = form.cleaned_data['installer']
215                     scenario = form.cleaned_data['scenario']
216                     opnfv = OPNFVConfig(
217                         bundle=models['bundle'],
218                         installer=installer,
219                         scenario=scenario
220                     )
221                     models['opnfv'] = opnfv
222                     confirm['configuration']['installer'] = form.cleaned_data['installer'].name
223                     confirm['configuration']['scenario'] = form.cleaned_data['scenario'].name
224
225                 confirm['configuration']['name'] = form.cleaned_data['name']
226                 confirm['configuration']['description'] = form.cleaned_data['description']
227                 self.metastep.set_valid("Complete")
228             else:
229                 self.metastep.set_invalid("Please correct the errors shown below")
230
231             self.repo_put(self.repo.CONFIG_MODELS, models)
232             self.repo_put(self.repo.CONFIRMATION, confirm)
233
234         except Exception:
235             pass
236         return self.render(request)