uncloud-mravi/nicohack202002/uncloud/opennebula/management/commands/syncvm.py
2020-02-22 00:22:42 +01:00

38 lines
1.3 KiB
Python

import os
import json
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from xmlrpc.client import ServerProxy as RPCClient
from xmltodict import parse
from opennebula.models import VM as VMModel
import uncloud.secrets
class Command(BaseCommand):
help = 'Syncronize VM information from OpenNebula'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
with RPCClient(uncloud.secrets.OPENNEBULA_URL) as rpc_client:
success, response, *_ = rpc_client.one.vmpool.infoextended(
uncloud.secrets.OPENNEBULA_USER_PASS, -2, -1, -1, -1
)
if success:
vms = json.loads(json.dumps(parse(response)))['VM_POOL']['VM']
for i, vm in enumerate(vms):
vm_id = vm['ID']
vm_owner = vm['UNAME']
try:
user = get_user_model().objects.get(username=vm_owner)
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()
else:
print(response)