OverHaul the Snapshot Workflow
[pharos-tools.git] / dashboard / src / workflow / workflow_manager.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.http import JsonResponse
12
13 import random
14
15 from booking.models import Booking
16 from workflow.workflow_factory import WorkflowFactory, MetaStep
17 from workflow.models import Repository
18 from resource_inventory.models import (
19     GenericResourceBundle,
20     ConfigBundle,
21     HostConfiguration,
22     OPNFVConfig
23 )
24
25 import logging
26 logger = logging.getLogger(__name__)
27
28
29 class SessionManager():
30     def active_workflow(self):
31         return self.workflows[-1]
32
33     def __init__(self, request=None):
34         self.workflows = []
35
36         self.owner = request.user
37
38         self.factory = WorkflowFactory()
39
40     def add_workflow(self, workflow_type=None, target_id=None, **kwargs):
41         if target_id is not None:
42             self.prefill_repo(target_id, workflow_type)
43
44         repo = Repository()
45         if(len(self.workflows) >= 1):
46             defaults = self.workflows[-1].repository.get_child_defaults()
47             repo.set_defaults(defaults)
48             repo.el[repo.HAS_RESULT] = False
49         repo.el[repo.SESSION_USER] = self.owner
50         self.workflows.append(self.factory.create_workflow(workflow_type=workflow_type, repo = repo))
51
52     def pop_workflow(self):
53         if( len(self.workflows) <= 1 ):
54             return False
55
56         if self.workflows[-1].repository.el[self.workflows[-1].repository.HAS_RESULT]:
57             key = self.workflows[-1].repository.el[self.workflows[-1].repository.RESULT_KEY]
58             result = self.workflows[-1].repository.el[self.workflows[-1].repository.RESULT]
59             self.workflows[-2].repository.el[key] = result
60         self.workflows.pop()
61         return True
62
63     def status(self, request):
64         try:
65             meta_steps = []
66             for step in self.active_workflow().metasteps:
67                 meta_steps.append(step.to_json())
68             responsejson = {}
69             responsejson["steps"] = meta_steps
70             responsejson["active"] = self.active_workflow().repository.el['active_step']
71             responsejson["workflow_count"] = len(self.workflows)
72             return JsonResponse(responsejson, safe=False)
73         except Exception as e:
74             pass
75
76     def render(self, request, **kwargs):
77         # filter out when a step needs to handle post/form data
78         # if 'workflow' in post data, this post request was meant for me, not step
79         if request.method == 'POST' and request.POST.get('workflow', None) is None:
80             return self.active_workflow().steps[self.active_workflow().active_index].post_render(request)
81         return self.active_workflow().steps[self.active_workflow().active_index].render(request)
82
83     def post_render(self, request):
84         return self.active_workflow().steps[self.active_workflow().active_index].post_render(request)
85
86     def goto(self, num, **kwargs):
87         self.active_workflow().repository.el['active_step'] = int(num)
88         self.active_workflow().active_index = int(num)
89         # TODO: change to include some checking
90
91     def prefill_repo(self, target_id, workflow_type):
92         self.repository.el[self.repository.EDIT] = True
93         edit_object = None
94         if workflow_type == 0:
95             edit_object = Booking.objects.get(pk=target_id)
96             self.prefill_booking(edit_object)
97         elif workflow_type == 1:
98             edit_object = GenericResourceBundle.objects.get(pk=target_id)
99             self.prefill_resource(edit_object)
100         elif workflow_type == 2:
101             edit_object = ConfigBundle.objects.get(pk=target_id)
102             self.prefill_config(edit_object)
103
104     def prefill_booking(self, booking):
105         models = self.make_booking_models(booking)
106         confirmation = self.make_booking_confirm(booking)
107         self.active_workflow().repository.el[self.active_workflow().repository.BOOKING_MODELS] = models
108         self.active_workflow().repository.el[self.active_workflow().repository.CONFIRMATION] = confirmation
109         self.active_workflow().repository.el[self.active_workflow().repository.GRESOURCE_BUNDLE_MODELS] = self.make_grb_models(booking.resource.template)
110         self.active_workflow().repository.el[self.active_workflow().repository.SELECTED_GRESOURCE_BUNDLE] = self.make_grb_models(booking.resource.template)['bundle']
111         self.active_workflow().repository.el[self.active_workflow().repository.CONFIG_MODELS] = self.make_config_models(booking.config_bundle)
112
113     def prefill_resource(self, resource):
114         models = self.make_grb_models(resource)
115         confirm = self.make_grb_confirm(resource)
116         self.active_workflow().repository.el[self.active_workflow().repository.GRESOURCE_BUNDLE_MODELS] = models
117         self.active_workflow().repository.el[self.active_workflow().repository.CONFIRMATION] = confirm
118
119     def prefill_config(self, config):
120         models = self.make_config_models(config)
121         confirm = self.make_config_confirm(config)
122         self.active_workflow().repository.el[self.active_workflow().repository.CONFIG_MODELS] = models
123         self.active_workflow().repository.el[self.active_workflow().repository.CONFIRMATION] = confirm
124         grb_models = self.make_grb_models(config.bundle)
125         self.active_workflow().repository.el[self.active_workflow().repository.GRESOURCE_BUNDLE_MODELS] = grb_models
126
127     def make_grb_models(self, resource):
128         models = self.active_workflow().repository.el.get(self.active_workflow().repository.GRESOURCE_BUNDLE_MODELS, {})
129         models['hosts'] = []
130         models['bundle'] = resource
131         models['interfaces'] = {}
132         models['vlans'] = {}
133         for host in resource.getHosts():
134             models['hosts'].append(host)
135             models['interfaces'][host.resource.name] = []
136             models['vlans'][host.resource.name] = {}
137             for interface in host.generic_interfaces.all():
138                 models['interfaces'][host.resource.name].append(interface)
139                 models['vlans'][host.resource.name][interface.profile.name] = []
140                 for vlan in interface.vlans.all():
141                     models['vlans'][host.resource.name][interface.profile.name].append(vlan)
142         return models
143
144     def make_grb_confirm(self, resource):
145         confirm = self.active_workflow().repository.el.get(self.active_workflow().repository.CONFIRMATION, {})
146         confirm['resource'] = {}
147         confirm['resource']['hosts'] = []
148         confirm['resource']['lab'] = resource.lab.lab_user.username
149         for host in resource.getHosts():
150             confirm['resource']['hosts'].append({"name": host.resource.name, "profile": host.profile.name})
151         return confirm
152
153     def make_config_models(self, config):
154         models = self.active_workflow().repository.el.get(self.active_workflow().repository.CONFIG_MODELS, {})
155         models['bundle'] = config
156         models['host_configs'] = []
157         for host_conf in HostConfiguration.objects.filter(bundle=config):
158             models['host_configs'].append(host_conf)
159         models['opnfv'] = OPNFVConfig.objects.filter(bundle=config).last()
160         return models
161
162     def make_config_confirm(self, config):
163         confirm = self.active_workflow().repository.el.get(self.active_workflow().repository.CONFIRMATION, {})
164         confirm['configuration'] = {}
165         confirm['configuration']['hosts'] = []
166         confirm['configuration']['name'] = config.name
167         confirm['configuration']['description'] = config.description
168         opnfv = OPNFVConfig.objects.filter(bundle=config).last()
169         confirm['configuration']['installer'] = opnfv.installer.name
170         confirm['configuration']['scenario'] = opnfv.scenario.name
171         for host_conf in HostConfiguration.objects.filter(bundle=config):
172             h = {"name": host_conf.host.resource.name, "image": host_conf.image.name, "role": host_conf.opnfvRole.name}
173             confirm['configuration']['hosts'].append(h)
174         return confirm
175
176     def make_booking_models(self, booking):
177         models = self.active_workflow().repository.el.get(self.active_workflow().repository.BOOKING_MODELS, {})
178         models['booking'] = booking
179         models['collaborators'] = []
180         for user in booking.collaborators.all():
181             models['collaborators'].append(user)
182         return models
183
184     def make_booking_confirm(self, booking):
185         confirm = self.active_workflow().repository.el.get(self.active_workflow().repository.CONFIRMATION, {})
186         confirm['booking'] = {}
187         confirm['booking']['length'] = (booking.end - booking.start).days
188         confirm['booking']['project'] = booking.project
189         confirm['booking']['purpose'] = booking.purpose
190         confirm['booking']['resource name'] = booking.resource.template.name
191         confirm['booking']['configuration name'] = booking.config_bundle.name
192         confirm['booking']['collaborators'] = []
193         for user in booking.collaborators.all():
194             confirm['booking']['collaborators'].append(user.username)
195         return confirm
196
197
198 class ManagerTracker():
199     instance = None
200
201     managers = {}
202
203     def __init__(self):
204         pass
205
206     @staticmethod
207     def getInstance():
208         if ManagerTracker.instance is None:
209             ManagerTracker.instance = ManagerTracker()
210         return ManagerTracker.instance