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'] = 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 = 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):
493 def add_interface(self, interface):
494 self.interfaces.add(interface)
495 d = json.loads(self.delta)
496 hid = self.hostnetworkrelation.host.labid
499 d[hid][interface.mac_address] = []
500 for vlan in interface.config.all():
501 d[hid][interface.mac_address].append({"vlan_id": vlan.vlan_id, "tagged": vlan.tagged})
502 self.delta = json.dumps(d)
505 def get_task(task_id):
506 for taskclass in [AccessRelation, SoftwareRelation, HostHardwareRelation, HostNetworkRelation]:
508 ret = taskclass.objects.get(task_id=task_id)
510 except taskclass.DoesNotExist:
512 from django.core.exceptions import ObjectDoesNotExist
513 raise ObjectDoesNotExist("Could not find matching TaskRelation instance")
517 return str(uuid.uuid4())
520 class TaskRelation(models.Model):
521 status = models.IntegerField(default=JobStatus.NEW)
522 job = models.ForeignKey(Job, on_delete=models.CASCADE)
523 config = models.OneToOneField(TaskConfig, on_delete=models.CASCADE)
524 task_id = models.CharField(default=get_task_uuid, max_length=37)
525 lab_token = models.CharField(default="null", max_length=50)
526 message = models.TextField(default="")
528 def delete(self, *args, **kwargs):
530 return super(self.__class__, self).delete(*args, **kwargs)
533 return "Generic Task"
539 class AccessRelation(TaskRelation):
540 config = models.OneToOneField(AccessConfig, on_delete=models.CASCADE)
545 def delete(self, *args, **kwargs):
547 return super(self.__class__, self).delete(*args, **kwargs)
550 class SoftwareRelation(TaskRelation):
551 config = models.OneToOneField(SoftwareConfig, on_delete=models.CASCADE)
554 return "Software Configuration Task"
556 def delete(self, *args, **kwargs):
558 return super(self.__class__, self).delete(*args, **kwargs)
561 class HostHardwareRelation(TaskRelation):
562 host = models.ForeignKey(Host, on_delete=models.CASCADE)
563 config = models.OneToOneField(HardwareConfig, on_delete=models.CASCADE)
566 return "Hardware Configuration Task"
569 return self.config.to_dict()
571 def delete(self, *args, **kwargs):
573 return super(self.__class__, self).delete(*args, **kwargs)
576 class HostNetworkRelation(TaskRelation):
577 host = models.ForeignKey(Host, on_delete=models.CASCADE)
578 config = models.OneToOneField(NetworkConfig, on_delete=models.CASCADE)
581 return "Network Configuration Task"
583 def delete(self, *args, **kwargs):
585 return super(self.__class__, self).delete(*args, **kwargs)
588 class JobFactory(object):
591 def makeCompleteJob(cls, booking):
592 hosts = Host.objects.filter(bundle=booking.resource)
595 job = Job.objects.get(booking=booking)
597 job = Job.objects.create(status=JobStatus.NEW, booking=booking)
598 cls.makeHardwareConfigs(
602 cls.makeNetworkConfigs(
610 cls.makeAccessConfig(
611 users=booking.collaborators.all(),
616 cls.makeAccessConfig(
617 users=[booking.owner],
624 def makeHardwareConfigs(cls, hosts=[], job=Job()):
626 hardware_config = None
628 hardware_config = HardwareConfig.objects.get(relation__host=host)
630 hardware_config = HardwareConfig()
632 relation = HostHardwareRelation()
635 relation.config = hardware_config
636 relation.config.save()
637 relation.config = relation.config
640 hardware_config.clear_delta()
641 hardware_config.set_image(host.config.image.lab_id)
642 hardware_config.set_hostname(host.template.resource.name)
643 hardware_config.set_power("on")
644 hardware_config.set_ipmi_create(True)
645 hardware_config.save()
648 def makeAccessConfig(cls, users, access_type, revoke=False, job=Job()):
650 relation = AccessRelation()
652 config = AccessConfig()
653 config.access_type = access_type
656 relation.config = config
659 config.set_access_type(access_type)
660 config.set_revoke(revoke)
661 config.set_user(user)
665 def makeNetworkConfigs(cls, hosts=[], job=Job()):
667 network_config = None
669 network_config = NetworkConfig.objects.get(relation__host=host)
671 network_config = NetworkConfig.objects.create()
673 relation = HostNetworkRelation()
676 network_config.save()
677 relation.config = network_config
679 network_config.clear_delta()
681 for interface in host.interfaces.all():
682 network_config.add_interface(interface)
683 network_config.save()
686 def makeSoftware(cls, hosts=[], job=Job()):
687 def init_config(host):
688 opnfv_config = OpnfvApiConfig()
690 opnfv = host.config.bundle.opnfv_config.first()
691 opnfv_config.installer = opnfv.installer.name
692 opnfv_config.scenario = opnfv.scenario.name
700 opnfv_config = init_config(host)
703 opnfv_config.roles.add(host)
704 software_config = SoftwareConfig.objects.create(opnfv=opnfv_config)
705 software_config.save()
706 software_relation = SoftwareRelation.objects.create(job=job, config=software_config)
707 software_relation.save()
708 return software_relation
712 def makeAccess(cls, user, access_type, revoke):