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
354 d['context'] = json.loads(self.context)
361 self.delta = self.to_json()
363 d = json.loads(self.delta)
364 d["lab_token"] = self.accessrelation.lab_token
369 return json.dumps(self.to_dict())
371 def clear_delta(self):
373 d["lab_token"] = self.accessrelation.lab_token
374 self.delta = json.dumps(d)
376 def set_access_type(self, access_type):
377 self.access_type = access_type
378 d = json.loads(self.delta)
379 d['access_type'] = access_type
380 self.delta = json.dumps(d)
382 def set_user(self, user):
384 d = json.loads(self.delta)
385 d['user'] = self.user.id
386 self.delta = json.dumps(d)
388 def set_revoke(self, revoke):
390 d = json.loads(self.delta)
392 self.delta = json.dumps(d)
394 def set_context(self, context):
395 self.context = json.dumps(context)
396 d = json.loads(self.delta)
397 d['context'] = context
398 self.delta = json.dumps(d)
401 class SoftwareConfig(TaskConfig):
403 handled opnfv installations, etc
405 opnfv = models.ForeignKey(OpnfvApiConfig, on_delete=models.CASCADE)
410 d['opnfv'] = self.opnfv.to_dict()
412 d["lab_token"] = self.softwarerelation.lab_token
413 self.delta = json.dumps(d)
419 d['opnfv'] = self.opnfv.get_delta()
420 d['lab_token'] = self.softwarerelation.lab_token
424 def clear_delta(self):
425 self.opnfv.clear_delta()
428 return json.dumps(self.to_dict())
431 class HardwareConfig(TaskConfig):
433 handles imaging, user accounts, etc
435 image = models.CharField(max_length=100, default="defimage")
436 power = models.CharField(max_length=100, default="off")
437 hostname = models.CharField(max_length=100, default="hostname")
438 ipmi_create = models.BooleanField(default=False)
439 delta = models.TextField()
443 d['image'] = self.image
444 d['power'] = self.power
445 d['hostname'] = self.hostname
446 d['ipmi_create'] = str(self.ipmi_create)
447 d['id'] = self.hosthardwarerelation.host.labid
451 return json.dumps(self.to_dict())
455 self.delta = self.to_json()
457 d = json.loads(self.delta)
458 d['lab_token'] = self.hosthardwarerelation.lab_token
461 def clear_delta(self):
463 d["id"] = self.hosthardwarerelation.host.labid
464 d["lab_token"] = self.hosthardwarerelation.lab_token
465 self.delta = json.dumps(d)
467 def set_image(self, image):
469 d = json.loads(self.delta)
470 d['image'] = self.image
471 self.delta = json.dumps(d)
473 def set_power(self, power):
475 d = json.loads(self.delta)
477 self.delta = json.dumps(d)
479 def set_hostname(self, hostname):
480 self.hostname = hostname
481 d = json.loads(self.delta)
482 d['hostname'] = hostname
483 self.delta = json.dumps(d)
485 def set_ipmi_create(self, ipmi_create):
486 self.ipmi_create = ipmi_create
487 d = json.loads(self.delta)
488 d['ipmi_create'] = ipmi_create
489 self.delta = json.dumps(d)
492 class NetworkConfig(TaskConfig):
494 handles network configuration
496 interfaces = models.ManyToManyField(Interface)
497 delta = models.TextField()
501 hid = self.hostnetworkrelation.host.labid
503 for interface in self.interfaces.all():
504 d[hid][interface.mac_address] = []
505 for vlan in interface.config.all():
506 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
511 return json.dumps(self.to_dict())
515 self.delta = self.to_json()
517 d = json.loads(self.delta)
518 d['lab_token'] = self.hostnetworkrelation.lab_token
521 def clear_delta(self):
522 self.delta = json.dumps(self.to_dict())
525 def add_interface(self, interface):
526 self.interfaces.add(interface)
527 d = json.loads(self.delta)
528 hid = self.hostnetworkrelation.host.labid
531 d[hid][interface.mac_address] = []
532 for vlan in interface.config.all():
533 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
534 self.delta = json.dumps(d)
537 def get_task(task_id):
538 for taskclass in [AccessRelation, SoftwareRelation, HostHardwareRelation, HostNetworkRelation]:
540 ret = taskclass.objects.get(task_id=task_id)
542 except taskclass.DoesNotExist:
544 from django.core.exceptions import ObjectDoesNotExist
545 raise ObjectDoesNotExist("Could not find matching TaskRelation instance")
549 return str(uuid.uuid4())
552 class TaskRelation(models.Model):
553 status = models.IntegerField(default=JobStatus.NEW)
554 job = models.ForeignKey(Job, on_delete=models.CASCADE)
555 config = models.OneToOneField(TaskConfig, on_delete=models.CASCADE)
556 task_id = models.CharField(default=get_task_uuid, max_length=37)
557 lab_token = models.CharField(default="null", max_length=50)
558 message = models.TextField(default="")
560 def delete(self, *args, **kwargs):
562 return super(self.__class__, self).delete(*args, **kwargs)
565 return "Generic Task"
571 class AccessRelation(TaskRelation):
572 config = models.OneToOneField(AccessConfig, on_delete=models.CASCADE)
577 def delete(self, *args, **kwargs):
579 return super(self.__class__, self).delete(*args, **kwargs)
582 class SoftwareRelation(TaskRelation):
583 config = models.OneToOneField(SoftwareConfig, on_delete=models.CASCADE)
586 return "Software Configuration Task"
588 def delete(self, *args, **kwargs):
590 return super(self.__class__, self).delete(*args, **kwargs)
593 class HostHardwareRelation(TaskRelation):
594 host = models.ForeignKey(Host, on_delete=models.CASCADE)
595 config = models.OneToOneField(HardwareConfig, on_delete=models.CASCADE)
598 return "Hardware Configuration Task"
601 return self.config.to_dict()
603 def delete(self, *args, **kwargs):
605 return super(self.__class__, self).delete(*args, **kwargs)
608 class HostNetworkRelation(TaskRelation):
609 host = models.ForeignKey(Host, on_delete=models.CASCADE)
610 config = models.OneToOneField(NetworkConfig, on_delete=models.CASCADE)
613 return "Network Configuration Task"
615 def delete(self, *args, **kwargs):
617 return super(self.__class__, self).delete(*args, **kwargs)
620 class JobFactory(object):
623 def makeCompleteJob(cls, booking):
624 hosts = Host.objects.filter(bundle=booking.resource)
627 job = Job.objects.get(booking=booking)
629 job = Job.objects.create(status=JobStatus.NEW, booking=booking)
630 cls.makeHardwareConfigs(
634 cls.makeNetworkConfigs(
642 all_users = list(booking.collaborators.all())
643 all_users.append(booking.owner)
644 cls.makeAccessConfig(
650 for user in all_users:
652 cls.makeAccessConfig(
658 "key": user.userprofile.ssh_public_key.open().read().decode(encoding="UTF-8"),
659 "hosts": [host.labid for host in hosts]
666 def makeHardwareConfigs(cls, hosts=[], job=Job()):
668 hardware_config = None
670 hardware_config = HardwareConfig.objects.get(relation__host=host)
672 hardware_config = HardwareConfig()
674 relation = HostHardwareRelation()
677 relation.config = hardware_config
678 relation.config.save()
679 relation.config = relation.config
682 hardware_config.clear_delta()
683 hardware_config.set_image(host.config.image.lab_id)
684 hardware_config.set_hostname(host.template.resource.name)
685 hardware_config.set_power("on")
686 hardware_config.set_ipmi_create(True)
687 hardware_config.save()
690 def makeAccessConfig(cls, users, access_type, revoke=False, job=Job(), context=False):
692 relation = AccessRelation()
694 config = AccessConfig()
695 config.access_type = access_type
698 relation.config = config
702 config.set_context(context)
703 config.set_access_type(access_type)
704 config.set_revoke(revoke)
705 config.set_user(user)
709 def makeNetworkConfigs(cls, hosts=[], job=Job()):
711 network_config = None
713 network_config = NetworkConfig.objects.get(relation__host=host)
715 network_config = NetworkConfig.objects.create()
717 relation = HostNetworkRelation()
720 network_config.save()
721 relation.config = network_config
723 network_config.clear_delta()
725 for interface in host.interfaces.all():
726 network_config.add_interface(interface)
727 network_config.save()
730 def makeSoftware(cls, hosts=[], job=Job()):
731 def init_config(host):
732 opnfv_config = OpnfvApiConfig()
734 opnfv = host.config.bundle.opnfv_config.first()
735 opnfv_config.installer = opnfv.installer.name
736 opnfv_config.scenario = opnfv.scenario.name
744 opnfv_config = init_config(host)
747 opnfv_config.roles.add(host)
748 software_config = SoftwareConfig.objects.create(opnfv=opnfv_config)
749 software_config.save()
750 software_relation = SoftwareRelation.objects.create(job=job, config=software_config)
751 software_relation.save()
752 return software_relation