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.contrib.auth.models import User
12 from django.db import models
13 from django.core.exceptions import PermissionDenied
18 from booking.models import Booking
19 from resource_inventory.models import (
28 class JobStatus(object):
35 class LabManagerTracker(object):
38 def get(cls, lab_name, token):
40 Takes in a lab name (from a url path)
41 returns a lab manager instance for that lab, if it exists
44 lab = Lab.objects.get(name=lab_name)
46 raise PermissionDenied("Lab not found")
47 if lab.api_token == token:
48 return LabManager(lab)
49 raise PermissionDenied("Lab not authorized")
52 class LabManager(object):
54 This is the class that will ultimately handle all REST calls to
56 handles jobs, inventory, status, etc
57 may need to create helper classes
60 def __init__(self, lab):
63 def get_profile(self):
65 prof['name'] = self.lab.name
67 "phone": self.lab.contact_phone,
68 "email": self.lab.contact_email
70 prof['host_count'] = []
71 for host in HostProfile.objects.filter(labs=self.lab):
72 count = Host.objects.filter(profile=host, lab=self.lab).count()
73 prof['host_count'].append(
81 def get_inventory(self):
83 hosts = Host.objects.filter(lab=self.lab)
84 images = Image.objects.filter(from_lab=self.lab)
85 profiles = HostProfile.objects.filter(labs=self.lab)
86 inventory['hosts'] = self.serialize_hosts(hosts)
87 inventory['images'] = self.serialize_images(images)
88 inventory['host_types'] = self.serialize_host_profiles(profiles)
92 return {"status": self.lab.status}
94 def set_status(self, payload):
97 def get_current_jobs(self):
98 jobs = Job.objects.filter(booking__lab=self.lab)
100 return self.serialize_jobs(jobs, status=JobStatus.CURRENT)
102 def get_new_jobs(self):
103 jobs = Job.objects.filter(booking__lab=self.lab)
105 return self.serialize_jobs(jobs, status=JobStatus.NEW)
107 def get_done_jobs(self):
108 jobs = Job.objects.filter(booking__lab=self.lab)
110 return self.serialize_jobs(jobs, status=JobStatus.DONE)
112 def get_job(self, jobid):
113 return Job.objects.get(pk=jobid).to_dict()
115 def update_job(self, jobid, data):
118 def serialize_jobs(self, jobs, status=JobStatus.NEW):
121 jsonized_job = job.get_delta(status)
122 if len(jsonized_job['payload']) < 1:
124 job_ser.append(jsonized_job)
128 def serialize_hosts(self, hosts):
133 h['hostname'] = host.name
134 h['host_type'] = host.profile.name
135 for iface in host.interfaces.all():
137 eth['mac'] = iface.mac_address
138 eth['busaddr'] = iface.bus_address
139 eth['name'] = iface.name
140 eth['switchport'] = {"switch_name": iface.switch_name, "port_name": iface.port_name}
141 h['interfaces'].append(eth)
144 def serialize_images(self, images):
150 "lab_id": image.lab_id,
151 "dashboard_id": image.id
156 def serialize_host_profiles(self, profiles):
158 for profile in profiles:
161 "cores": profile.cpuprofile.first().cores,
162 "arch": profile.cpuprofile.first().architecture,
163 "cpus": profile.cpuprofile.first().cpus,
166 for disk in profile.storageprofile.all():
169 "type": disk.media_type,
173 p['description'] = profile.description
175 for iface in profile.interfaceprofile.all():
176 p['interfaces'].append(
178 "speed": iface.speed,
183 p['ram'] = {"amount": profile.ramprofile.first().amount}
184 p['name'] = profile.name
185 profile_ser.append(p)
189 class Job(models.Model):
191 This is the class that is serialized and put into the api
193 booking = models.OneToOneField(Booking, on_delete=models.CASCADE, null=True)
194 status = models.IntegerField(default=JobStatus.NEW)
195 complete = models.BooleanField(default=False)
201 for relation in AccessRelation.objects.filter(job=self):
202 if 'access' not in d:
204 d['access'][relation.task_id] = relation.config.to_dict()
205 for relation in SoftwareRelation.objects.filter(job=self):
206 if 'software' not in d:
208 d['software'][relation.task_id] = relation.config.to_dict()
209 for relation in HostHardwareRelation.objects.filter(job=self):
210 if 'hardware' not in d:
212 d['hardware'][relation.task_id] = relation.config.to_dict()
213 for relation in HostNetworkRelation.objects.filter(job=self):
214 if 'network' not in d:
216 d['network'][relation.task_id] = relation.config.to_dict()
222 def get_tasklist(self, status="all"):
224 clist = [HostHardwareRelation, AccessRelation, HostNetworkRelation, SoftwareRelation]
227 tasklist += list(cls.objects.filter(job=self))
230 tasklist += list(cls.objects.filter(job=self).filter(status=status))
233 def is_fulfilled(self):
235 This method should return true if all of the job's tasks are done,
238 my_tasks = self.get_tasklist()
239 for task in my_tasks:
240 if task.status != JobStatus.DONE:
244 def get_delta(self, status):
248 for relation in AccessRelation.objects.filter(job=self).filter(status=status):
249 if 'access' not in d:
251 d['access'][relation.task_id] = relation.config.get_delta()
252 for relation in SoftwareRelation.objects.filter(job=self).filter(status=status):
253 if 'software' not in d:
255 d['software'][relation.task_id] = relation.config.get_delta()
256 for relation in HostHardwareRelation.objects.filter(job=self).filter(status=status):
257 if 'hardware' not in d:
259 d['hardware'][relation.task_id] = relation.config.get_delta()
260 for relation in HostNetworkRelation.objects.filter(job=self).filter(status=status):
261 if 'network' not in d:
263 d['network'][relation.task_id] = relation.config.get_delta()
269 return json.dumps(self.to_dict())
272 class TaskConfig(models.Model):
280 return json.dumps(self.to_dict())
282 def clear_delta(self):
286 class OpnfvApiConfig(models.Model):
288 installer = models.CharField(max_length=100)
289 scenario = models.CharField(max_length=100)
290 roles = models.ManyToManyField(Host)
291 delta = models.TextField()
296 d['installer'] = self.installer
298 d['scenario'] = self.scenario
300 hosts = self.roles.all()
303 for host in self.roles.all():
304 d['roles'].append({host.labid: host.config.opnfvRole.name})
309 return json.dumps(self.to_dict())
311 def set_installer(self, installer):
312 self.installer = installer
313 d = json.loads(self.delta)
314 d['installer'] = installer
315 self.delta = json.dumps(d)
317 def set_scenario(self, scenario):
318 self.scenario = scenario
319 d = json.loads(self.delta)
320 d['scenario'] = scenario
321 self.delta = json.dumps(d)
323 def add_role(self, host):
325 d = json.loads(self.delta)
328 d['roles'].append({host.labid: host.config.opnfvRole.name})
329 self.delta = json.dumps(d)
331 def clear_delta(self):
336 self.delta = self.to_json()
338 return json.loads(self.delta)
341 class AccessConfig(TaskConfig):
342 access_type = models.CharField(max_length=50)
343 user = models.ForeignKey(User, on_delete=models.CASCADE)
344 revoke = models.BooleanField(default=False)
345 context = models.TextField(default="")
346 delta = models.TextField(default="{}")
350 d['access_type'] = self.access_type
351 d['user'] = self.user.id
352 d['revoke'] = self.revoke
353 d['context'] = json.loads(self.context)
358 self.delta = self.to_json()
360 d = json.loads(self.delta)
361 d["lab_token"] = self.accessrelation.lab_token
366 return json.dumps(self.to_dict())
368 def clear_delta(self):
370 d["lab_token"] = self.accessrelation.lab_token
371 self.delta = json.dumps(d)
373 def set_access_type(self, access_type):
374 self.access_type = access_type
375 d = json.loads(self.delta)
376 d['access_type'] = access_type
377 self.delta = json.dumps(d)
379 def set_user(self, user):
381 d = json.loads(self.delta)
382 d['user'] = self.user.id
383 self.delta = json.dumps(d)
385 def set_revoke(self, revoke):
387 d = json.loads(self.delta)
389 self.delta = json.dumps(d)
391 def set_context(self, context):
392 self.context = json.dumps(context)
393 d = json.loads(self.delta)
394 d['context'] = context
395 self.delta = json.dumps(d)
398 class SoftwareConfig(TaskConfig):
400 handled opnfv installations, etc
402 opnfv = models.ForeignKey(OpnfvApiConfig, on_delete=models.CASCADE)
407 d['opnfv'] = self.opnfv.to_dict()
409 d["lab_token"] = self.softwarerelation.lab_token
410 self.delta = json.dumps(d)
416 d['opnfv'] = self.opnfv.get_delta()
417 d['lab_token'] = self.softwarerelation.lab_token
421 def clear_delta(self):
422 self.opnfv.clear_delta()
425 return json.dumps(self.to_dict())
428 class HardwareConfig(TaskConfig):
430 handles imaging, user accounts, etc
432 image = models.CharField(max_length=100, default="defimage")
433 power = models.CharField(max_length=100, default="off")
434 hostname = models.CharField(max_length=100, default="hostname")
435 ipmi_create = models.BooleanField(default=False)
436 delta = models.TextField()
440 d['image'] = self.image
441 d['power'] = self.power
442 d['hostname'] = self.hostname
443 d['ipmi_create'] = str(self.ipmi_create)
444 d['id'] = self.hosthardwarerelation.host.labid
448 return json.dumps(self.to_dict())
452 self.delta = self.to_json()
454 d = json.loads(self.delta)
455 d['lab_token'] = self.hosthardwarerelation.lab_token
458 def clear_delta(self):
460 d["id"] = self.hosthardwarerelation.host.labid
461 d["lab_token"] = self.hosthardwarerelation.lab_token
462 self.delta = json.dumps(d)
464 def set_image(self, image):
466 d = json.loads(self.delta)
467 d['image'] = self.image
468 self.delta = json.dumps(d)
470 def set_power(self, power):
472 d = json.loads(self.delta)
474 self.delta = json.dumps(d)
476 def set_hostname(self, hostname):
477 self.hostname = hostname
478 d = json.loads(self.delta)
479 d['hostname'] = hostname
480 self.delta = json.dumps(d)
482 def set_ipmi_create(self, ipmi_create):
483 self.ipmi_create = ipmi_create
484 d = json.loads(self.delta)
485 d['ipmi_create'] = ipmi_create
486 self.delta = json.dumps(d)
489 class NetworkConfig(TaskConfig):
491 handles network configuration
493 interfaces = models.ManyToManyField(Interface)
494 delta = models.TextField()
498 hid = self.hostnetworkrelation.host.labid
500 for interface in self.interfaces.all():
501 d[hid][interface.mac_address] = []
502 for vlan in interface.config.all():
503 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
508 return json.dumps(self.to_dict())
512 self.delta = self.to_json()
514 d = json.loads(self.delta)
515 d['lab_token'] = self.hostnetworkrelation.lab_token
518 def clear_delta(self):
519 self.delta = json.dumps(self.to_dict())
522 def add_interface(self, interface):
523 self.interfaces.add(interface)
524 d = json.loads(self.delta)
525 hid = self.hostnetworkrelation.host.labid
528 d[hid][interface.mac_address] = []
529 for vlan in interface.config.all():
530 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
531 self.delta = json.dumps(d)
534 def get_task(task_id):
535 for taskclass in [AccessRelation, SoftwareRelation, HostHardwareRelation, HostNetworkRelation]:
537 ret = taskclass.objects.get(task_id=task_id)
539 except taskclass.DoesNotExist:
541 from django.core.exceptions import ObjectDoesNotExist
542 raise ObjectDoesNotExist("Could not find matching TaskRelation instance")
546 return str(uuid.uuid4())
549 class TaskRelation(models.Model):
550 status = models.IntegerField(default=JobStatus.NEW)
551 job = models.ForeignKey(Job, on_delete=models.CASCADE)
552 config = models.OneToOneField(TaskConfig, on_delete=models.CASCADE)
553 task_id = models.CharField(default=get_task_uuid, max_length=37)
554 lab_token = models.CharField(default="null", max_length=50)
555 message = models.TextField(default="")
557 def delete(self, *args, **kwargs):
559 return super(self.__class__, self).delete(*args, **kwargs)
562 return "Generic Task"
568 class AccessRelation(TaskRelation):
569 config = models.OneToOneField(AccessConfig, on_delete=models.CASCADE)
574 def delete(self, *args, **kwargs):
576 return super(self.__class__, self).delete(*args, **kwargs)
579 class SoftwareRelation(TaskRelation):
580 config = models.OneToOneField(SoftwareConfig, on_delete=models.CASCADE)
583 return "Software Configuration Task"
585 def delete(self, *args, **kwargs):
587 return super(self.__class__, self).delete(*args, **kwargs)
590 class HostHardwareRelation(TaskRelation):
591 host = models.ForeignKey(Host, on_delete=models.CASCADE)
592 config = models.OneToOneField(HardwareConfig, on_delete=models.CASCADE)
595 return "Hardware Configuration Task"
598 return self.config.to_dict()
600 def delete(self, *args, **kwargs):
602 return super(self.__class__, self).delete(*args, **kwargs)
605 class HostNetworkRelation(TaskRelation):
606 host = models.ForeignKey(Host, on_delete=models.CASCADE)
607 config = models.OneToOneField(NetworkConfig, on_delete=models.CASCADE)
610 return "Network Configuration Task"
612 def delete(self, *args, **kwargs):
614 return super(self.__class__, self).delete(*args, **kwargs)
617 class JobFactory(object):
620 def makeCompleteJob(cls, booking):
621 hosts = Host.objects.filter(bundle=booking.resource)
624 job = Job.objects.get(booking=booking)
626 job = Job.objects.create(status=JobStatus.NEW, booking=booking)
627 cls.makeHardwareConfigs(
631 cls.makeNetworkConfigs(
639 all_users = list(booking.collaborators.all())
640 all_users.append(booking.owner)
641 cls.makeAccessConfig(
647 for user in all_users:
649 cls.makeAccessConfig(
655 "key": user.userprofile.ssh_public_key.open().read().decode(encoding="UTF-8"),
656 "hosts": [host.labid for host in hosts]
663 def makeHardwareConfigs(cls, hosts=[], job=Job()):
665 hardware_config = None
667 hardware_config = HardwareConfig.objects.get(relation__host=host)
669 hardware_config = HardwareConfig()
671 relation = HostHardwareRelation()
674 relation.config = hardware_config
675 relation.config.save()
676 relation.config = relation.config
679 hardware_config.clear_delta()
680 hardware_config.set_image(host.config.image.lab_id)
681 hardware_config.set_hostname(host.template.resource.name)
682 hardware_config.set_power("on")
683 hardware_config.set_ipmi_create(True)
684 hardware_config.save()
687 def makeAccessConfig(cls, users, access_type, revoke=False, job=Job(), context=False):
689 relation = AccessRelation()
691 config = AccessConfig()
692 config.access_type = access_type
695 relation.config = config
699 config.set_context(context)
700 config.set_access_type(access_type)
701 config.set_revoke(revoke)
702 config.set_user(user)
706 def makeNetworkConfigs(cls, hosts=[], job=Job()):
708 network_config = None
710 network_config = NetworkConfig.objects.get(relation__host=host)
712 network_config = NetworkConfig.objects.create()
714 relation = HostNetworkRelation()
717 network_config.save()
718 relation.config = network_config
720 network_config.clear_delta()
722 for interface in host.interfaces.all():
723 network_config.add_interface(interface)
724 network_config.save()
727 def makeSoftware(cls, hosts=[], job=Job()):
728 def init_config(host):
729 opnfv_config = OpnfvApiConfig()
731 opnfv = host.config.bundle.opnfv_config.first()
732 opnfv_config.installer = opnfv.installer.name
733 opnfv_config.scenario = opnfv.scenario.name
741 opnfv_config = init_config(host)
744 opnfv_config.roles.add(host)
745 software_config = SoftwareConfig.objects.create(opnfv=opnfv_config)
746 software_config.save()
747 software_relation = SoftwareRelation.objects.create(job=job, config=software_config)
748 software_relation.save()
749 return software_relation