From f588691f0d9bebf08e775334fddeceeb1b695fa7 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Sun, 23 Feb 2020 11:42:03 +0100 Subject: [PATCH] [opennebula] add json, add helper functions --- .../opennebula/management/commands/syncvm.py | 8 ++++-- nicohack202002/uncloud/opennebula/models.py | 28 +++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/nicohack202002/uncloud/opennebula/management/commands/syncvm.py b/nicohack202002/uncloud/opennebula/management/commands/syncvm.py index 205b066..136e145 100644 --- a/nicohack202002/uncloud/opennebula/management/commands/syncvm.py +++ b/nicohack202002/uncloud/opennebula/management/commands/syncvm.py @@ -32,7 +32,11 @@ class Command(BaseCommand): except get_user_model().DoesNotExist: user = get_user_model().objects.create_user(username=vm_owner) - vm_object = VMModel.objects.create(vmid=vm_id, owner=user, data=vm) - vm_object.save() + VMModel.objects.update_or_create( + defaults= { 'data': vm, + 'owner': user }, + vmid=vm_id + ) + else: print(response) diff --git a/nicohack202002/uncloud/opennebula/models.py b/nicohack202002/uncloud/opennebula/models.py index cd1a044..babba26 100644 --- a/nicohack202002/uncloud/opennebula/models.py +++ b/nicohack202002/uncloud/opennebula/models.py @@ -1,8 +1,32 @@ from django.db import models from django.contrib.auth import get_user_model +from django.contrib.postgres.fields import JSONField class VM(models.Model): - vmid = models.IntegerField() + vmid = models.IntegerField(primary_key=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) - data = models.CharField(max_length=65536, null=True) + data = JSONField() + + + def cores(self): + return self.data['TEMPLATE']['VCPU'] + + def ram_in_gb(self): + return (int(self.data['TEMPLATE']['MEMORY'])/1024.) + + def disks(self): + """ + If there is no disk then the key DISK does not exist. + + If there is only one disk, we have a dictionary in the database. + + If there are multiple disks, we have a list of dictionaries in the database. + """ + + if not 'DISK' in self.data['TEMPLATE']['DISK']: + return [] + elif type(self.data['TEMPLATE']['DISK']) is dict: + return [ self.data['TEMPLATE']['DISK'] ] + else: + return self.data['TEMPLATE']['DISK']