1 ##############################################################################
2 # Copyright (c) 2018 Sawyer Bergeron, Parker Berberian, and others.
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 ##############################################################################
11 from django.db import models
12 from django.core.exceptions import PermissionDenied
17 from resource_inventory.models import *
18 from booking.models import Booking
21 class JobStatus(object):
28 class LabManagerTracker(object):
31 def get(cls, lab_name, token):
33 Takes in a lab name (from a url path)
34 returns a lab manager instance for that lab, if it exists
37 lab = Lab.objects.get(name=lab_name)
39 raise PermissionDenied("Lab not found")
40 if lab.api_token == token:
41 return LabManager(lab)
42 raise PermissionDenied("Lab not authorized")
45 class LabManager(object):
47 This is the class that will ultimately handle all REST calls to
49 handles jobs, inventory, status, etc
50 may need to create helper classes
53 def __init__(self, lab):
56 def get_profile(self):
58 prof['name'] = self.lab.name
60 "phone": self.lab.contact_phone,
61 "email": self.lab.contact_email
63 prof['host_count'] = []
64 for host in HostProfile.objects.filter(labs=self.lab):
65 count = Host.objects.filter(profile=host, lab=self.lab).count()
66 prof['host_count'].append({
72 def get_inventory(self):
74 hosts = Host.objects.filter(lab=self.lab)
75 images = Image.objects.filter(from_lab=self.lab)
76 profiles = HostProfile.objects.filter(labs=self.lab)
77 inventory['hosts'] = self.serialize_hosts(hosts)
78 inventory['images'] = self.serialize_images(images)
79 inventory['host_types'] = self.serialize_host_profiles(profiles)
83 return {"status": self.lab.status}
85 def set_status(self, payload):
88 def get_current_jobs(self):
89 jobs = Job.objects.filter(booking__lab=self.lab)
91 return self.serialize_jobs(jobs, status=JobStatus.CURRENT)
93 def get_new_jobs(self):
94 jobs = Job.objects.filter(booking__lab=self.lab)
96 return self.serialize_jobs(jobs, status=JobStatus.NEW)
98 def get_done_jobs(self):
99 jobs = Job.objects.filter(booking__lab=self.lab)
101 return self.serialize_jobs(jobs, status=JobStatus.DONE)
103 def get_job(self, jobid):
104 return Job.objects.get(pk=jobid).to_dict()
106 def update_job(self, jobid, data):
109 def serialize_jobs(self, jobs, status=JobStatus.NEW):
112 jsonized_job = job.get_delta(status)
113 if len(jsonized_job['payload']) < 1:
115 job_ser.append(jsonized_job)
119 def serialize_hosts(self, hosts):
124 h['hostname'] = host.name
125 h['host_type'] = host.profile.name
126 for iface in host.interfaces.all():
128 eth['mac'] = iface.mac_address
129 eth['busaddr'] = iface.bus_address
130 eth['name'] = iface.name
131 eth['switchport'] = {"switch_name": iface.switch_name, "port_name": iface.port_name}
132 h['interfaces'].append(eth)
135 def serialize_images(self, images):
140 "lab_id": image.lab_id,
141 "dashboard_id": image.id
145 def serialize_host_profiles(self, profiles):
147 for profile in profiles:
150 "cores": profile.cpuprofile.first().cores,
151 "arch": profile.cpuprofile.first().architecture,
152 "cpus": profile.cpuprofile.first().cpus,
155 for disk in profile.storageprofile.all():
158 "type": disk.media_type,
162 p['description'] = profile.description
164 for iface in profile.interfaceprofile.all():
165 p['interfaces'].append({
166 "speed": iface.speed,
170 p['ram'] = {"amount": profile.ramprofile.first().amount}
171 p['name'] = profile.name
172 profile_ser.append(p)
176 class Job(models.Model):
178 This is the class that is serialized and put into the api
180 booking = models.OneToOneField(Booking, on_delete=models.CASCADE, null=True)
181 status = models.IntegerField(default=JobStatus.NEW)
182 complete = models.BooleanField(default=False)
188 for relation in AccessRelation.objects.filter(job=self):
189 if 'access' not in d:
191 d['access'][relation.task_id] = relation.config.to_dict()
192 for relation in SoftwareRelation.objects.filter(job=self):
193 if 'software' not in d:
195 d['software'][relation.task_id] = relation.config.to_dict()
196 for relation in HostHardwareRelation.objects.filter(job=self):
197 if 'hardware' not in d:
199 d['hardware'][relation.task_id] = relation.config.to_dict()
200 for relation in HostNetworkRelation.objects.filter(job=self):
201 if 'network' not in d:
203 d['network'][relation.task_id] = relation.config.to_dict()
209 def get_tasklist(self, status="all"):
211 clist = [HostHardwareRelation, AccessRelation, HostNetworkRelation, SoftwareRelation]
214 tasklist += list(cls.objects.filter(job=self))
217 tasklist += list(cls.objects.filter(job=self).filter(status=status))
220 def get_delta(self, status):
224 for relation in AccessRelation.objects.filter(job=self).filter(status=status):
225 if 'access' not in d:
227 d['access'][relation.task_id] = relation.config.get_delta()
228 for relation in SoftwareRelation.objects.filter(job=self).filter(status=status):
229 if 'software' not in d:
231 d['software'][relation.task_id] = relation.config.get_delta()
232 for relation in HostHardwareRelation.objects.filter(job=self).filter(status=status):
233 if 'hardware' not in d:
235 d['hardware'][relation.task_id] = relation.config.get_delta()
236 for relation in HostNetworkRelation.objects.filter(job=self).filter(status=status):
237 if 'network' not in d:
239 d['network'][relation.task_id] = relation.config.get_delta()
245 return json.dumps(self.to_dict())
248 class TaskConfig(models.Model):
256 return json.dumps(self.to_dict())
258 def clear_delta(self):
261 class OpnfvApiConfig(models.Model):
263 installer = models.CharField(max_length=100)
264 scenario = models.CharField(max_length=100)
265 roles = models.ManyToManyField(Host)
266 delta = models.TextField()
271 d['installer'] = self.installer
273 d['scenario'] = self.scenario
275 hosts = self.roles.all()
278 for host in self.roles.all():
279 d['roles'].append({host.labid: host.config.opnfvRole.name})
284 return json.dumps(self.to_dict())
286 def set_installer(self, installer):
287 self.installer = installer
288 d = json.loads(self.delta)
289 d['installer'] = installer
290 self.delta = json.dumps(d)
292 def set_scenario(self, scenario):
293 self.scenario = scenario
294 d = json.loads(self.delta)
295 d['scenario'] = scenario
296 self.delta = json.dumps(d)
298 def add_role(self, host):
300 d = json.loads(self.delta)
303 d['roles'].append({host.labid: host.config.opnfvRole.name})
304 self.delta = json.dumps(d)
306 def clear_delta(self):
311 self.delta = self.to_json()
313 return json.loads(self.delta)
315 class AccessConfig(TaskConfig):
316 access_type = models.CharField(max_length=50)
317 user = models.ForeignKey(User, on_delete=models.CASCADE)
318 revoke = models.BooleanField(default=False)
319 context = models.TextField(default="")
320 delta = models.TextField()
324 d['access_type'] = self.access_type
325 d['user'] = self.user.id
326 d['revoke'] = self.revoke
327 d['context'] = json.loads(self.context)
332 self.delta = self.to_json()
334 d = json.loads(self.delta)
335 d["lab_token"] = self.accessrelation.lab_token
340 return json.dumps(self.to_dict())
342 def clear_delta(self):
344 d["lab_token"] = self.accessrelation.lab_token
345 self.delta = json.dumps(d)
347 def set_access_type(self, access_type):
348 self.access_type = access_type
349 d = json.loads(self.delta)
350 d['access_type'] = access_type
351 self.delta = json.dumps(d)
353 def set_user(self, user):
355 d = json.loads(self.delta)
356 d['user'] = self.user.id
357 self.delta = json.dumps(d)
359 def set_revoke(self, revoke):
361 d = json.loads(self.delta)
363 self.delta = json.dumps(d)
365 def set_context(self, context):
366 self.context = json.dumps(context)
367 d = json.loads(self.delta)
368 d['context'] = context
369 self.delta = json.dumps(d)
371 class SoftwareConfig(TaskConfig):
373 handled opnfv installations, etc
375 opnfv = models.ForeignKey(OpnfvApiConfig, on_delete=models.CASCADE)
380 d['opnfv'] = self.opnfv.to_dict()
382 d["lab_token"] = self.softwarerelation.lab_token
383 self.delta = json.dumps(d)
389 d['opnfv'] = self.opnfv.get_delta()
390 d['lab_token'] = self.softwarerelation.lab_token
394 def clear_delta(self):
395 self.opnfv.clear_delta()
398 return json.dumps(self.to_dict())
400 class HardwareConfig(TaskConfig):
402 handles imaging, user accounts, etc
404 image = models.CharField(max_length=100, default="defimage")
405 power = models.CharField(max_length=100, default="off")
406 hostname = models.CharField(max_length=100, default="hostname")
407 ipmi_create = models.BooleanField(default=False)
408 delta = models.TextField()
412 d['image'] = self.image
413 d['power'] = self.power
414 d['hostname'] = self.hostname
415 d['ipmi_create'] = str(self.ipmi_create)
416 d['id'] = self.hosthardwarerelation.host.labid
420 return json.dumps(self.to_dict())
424 self.delta = self.to_json()
426 d = json.loads(self.delta)
427 d['lab_token'] = self.hosthardwarerelation.lab_token
430 def clear_delta(self):
432 d["id"] = self.hosthardwarerelation.host.labid
433 d["lab_token"] = self.hosthardwarerelation.lab_token
434 self.delta = json.dumps(d)
436 def set_image(self, image):
438 d = json.loads(self.delta)
439 d['image'] = self.image
440 self.delta = json.dumps(d)
442 def set_power(self, power):
444 d = json.loads(self.delta)
446 self.delta = json.dumps(d)
448 def set_hostname(self, hostname):
449 self.hostname = hostname
450 d = json.loads(self.delta)
451 d['hostname'] = hostname
452 self.delta = json.dumps(d)
454 def set_ipmi_create(self, ipmi_create):
455 self.ipmi_create = ipmi_create
456 d = json.loads(self.delta)
457 d['ipmi_create'] = ipmi_create
458 self.delta = json.dumps(d)
461 class NetworkConfig(TaskConfig):
463 handles network configuration
465 interfaces = models.ManyToManyField(Interface)
466 delta = models.TextField()
470 hid = self.hostnetworkrelation.host.labid
472 for interface in self.interfaces.all():
473 d[hid][interface.mac_address] = []
474 for vlan in interface.config.all():
475 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
480 return json.dumps(self.to_dict())
484 self.delta = self.to_json()
486 d = json.loads(self.delta)
487 d['lab_token'] = self.hostnetworkrelation.lab_token
490 def clear_delta(self):
491 self.delta = json.dumps(self.to_dict())
494 def add_interface(self, interface):
495 self.interfaces.add(interface)
496 d = json.loads(self.delta)
497 hid = self.hostnetworkrelation.host.labid
500 d[hid][interface.mac_address] = []
501 for vlan in interface.config.all():
502 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
503 self.delta = json.dumps(d)
506 def get_task(task_id):
507 for taskclass in [AccessRelation, SoftwareRelation, HostHardwareRelation, HostNetworkRelation]:
509 ret = taskclass.objects.get(task_id=task_id)
511 except taskclass.DoesNotExist:
513 from django.core.exceptions import ObjectDoesNotExist
514 raise ObjectDoesNotExist("Could not find matching TaskRelation instance")
518 return str(uuid.uuid4())
521 class TaskRelation(models.Model):
522 status = models.IntegerField(default=JobStatus.NEW)
523 job = models.ForeignKey(Job, on_delete=models.CASCADE)
524 config = models.OneToOneField(TaskConfig, on_delete=models.CASCADE)
525 task_id = models.CharField(default=get_task_uuid, max_length=37)
526 lab_token = models.CharField(default="null", max_length=50)
527 message = models.TextField(default="")
529 def delete(self, *args, **kwargs):
531 return super(self.__class__, self).delete(*args, **kwargs)
534 return "Generic Task"
540 class AccessRelation(TaskRelation):
541 config = models.OneToOneField(AccessConfig, on_delete=models.CASCADE)
546 def delete(self, *args, **kwargs):
548 return super(self.__class__, self).delete(*args, **kwargs)
551 class SoftwareRelation(TaskRelation):
552 config = models.OneToOneField(SoftwareConfig, on_delete=models.CASCADE)
555 return "Software Configuration Task"
557 def delete(self, *args, **kwargs):
559 return super(self.__class__, self).delete(*args, **kwargs)
562 class HostHardwareRelation(TaskRelation):
563 host = models.ForeignKey(Host, on_delete=models.CASCADE)
564 config = models.OneToOneField(HardwareConfig, on_delete=models.CASCADE)
567 return "Hardware Configuration Task"
570 return self.config.to_dict()
572 def delete(self, *args, **kwargs):
574 return super(self.__class__, self).delete(*args, **kwargs)
577 class HostNetworkRelation(TaskRelation):
578 host = models.ForeignKey(Host, on_delete=models.CASCADE)
579 config = models.OneToOneField(NetworkConfig, on_delete=models.CASCADE)
582 return "Network Configuration Task"
584 def delete(self, *args, **kwargs):
586 return super(self.__class__, self).delete(*args, **kwargs)
589 class JobFactory(object):
592 def makeCompleteJob(cls, booking):
593 hosts = Host.objects.filter(bundle=booking.resource)
596 job = Job.objects.get(booking=booking)
598 job = Job.objects.create(status=JobStatus.NEW, booking=booking)
599 cls.makeHardwareConfigs(
603 cls.makeNetworkConfigs(
611 all_users = list(booking.collaborators.all())
612 all_users.append(booking.owner)
613 cls.makeAccessConfig(
619 for user in all_users:
621 cls.makeAccessConfig(
627 "key": user.userprofile.ssh_public_key.read(),
628 "hosts": [host.labid for host in hosts]
635 def makeHardwareConfigs(cls, hosts=[], job=Job()):
637 hardware_config = None
639 hardware_config = HardwareConfig.objects.get(relation__host=host)
641 hardware_config = HardwareConfig()
643 relation = HostHardwareRelation()
646 relation.config = hardware_config
647 relation.config.save()
648 relation.config = relation.config
651 hardware_config.clear_delta()
652 hardware_config.set_image(host.config.image.lab_id)
653 hardware_config.set_hostname(host.template.resource.name)
654 hardware_config.set_power("on")
655 hardware_config.set_ipmi_create(True)
656 hardware_config.save()
659 def makeAccessConfig(cls, users, access_type, revoke=False, job=Job(), context=False):
661 relation = AccessRelation()
663 config = AccessConfig()
664 config.access_type = access_type
667 config.set_context(context)
669 relation.config = config
672 config.set_access_type(access_type)
673 config.set_revoke(revoke)
674 config.set_user(user)
678 def makeNetworkConfigs(cls, hosts=[], job=Job()):
680 network_config = None
682 network_config = NetworkConfig.objects.get(relation__host=host)
684 network_config = NetworkConfig.objects.create()
686 relation = HostNetworkRelation()
689 network_config.save()
690 relation.config = network_config
692 network_config.clear_delta()
694 for interface in host.interfaces.all():
695 network_config.add_interface(interface)
696 network_config.save()
699 def makeSoftware(cls, hosts=[], job=Job()):
700 def init_config(host):
701 opnfv_config = OpnfvApiConfig()
703 opnfv = host.config.bundle.opnfv_config.first()
704 opnfv_config.installer = opnfv.installer.name
705 opnfv_config.scenario = opnfv.scenario.name
713 opnfv_config = init_config(host)
716 opnfv_config.roles.add(host)
717 software_config = SoftwareConfig.objects.create(opnfv=opnfv_config)
718 software_config.save()
719 software_relation = SoftwareRelation.objects.create(job=job, config=software_config)
720 software_relation.save()
721 return software_relation