uncloud-mravi/uncloud/opennebula/models.py

60 lines
1.7 KiB
Python

import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
class VM(models.Model):
id = models.CharField(primary_key=True, editable=True, default=uuid.uuid4, unique=True, max_length=64)
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
data = JSONField()
def save(self, *args, **kwargs):
self.id = 'opennebula' + str(self.data.get("ID"))
super().save(*args, **kwargs)
@property
def cores(self):
return int(self.data['TEMPLATE']['VCPU'])
@property
def ram_in_gb(self):
return (int(self.data['TEMPLATE']['MEMORY'])/1024.)
@property
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.
"""
disks = []
if 'DISK' in self.data['TEMPLATE']:
if type(self.data['TEMPLATE']['DISK']) is dict:
disks = [ self.data['TEMPLATE']['DISK'] ]
else:
disks = self.data['TEMPLATE']['DISK']
disks = [
{
'size_in_gb': int(d['SIZE'])/1024. ,
'opennebula_source': d['SOURCE'],
'opennebula_name': d['IMAGE'],
}
for d in disks
]
return disks
@property
def last_host(self):
return ((self.data.get('HISTORY_RECORDS', {}) or {}).get('HISTORY', {}) or {}).get('HOSTNAME', None)
@property
def graphics(self):
return self.data.get('TEMPLATE', {}).get('GRAPHICS', {})