uncloud-mravi/uncloud/opennebula/management/commands/syncvm.py
2020-02-23 17:11:05 +01:00

46 lines
1.6 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_email = vm['UNAME']
try:
user = get_user_model().objects.get(email=vm_owner_email)
except get_user_model().DoesNotExist:
print("Skipping VM import for unknown user with email: {}".format(vm_owner_email))
continue
# user = get_user_model().objects.create_user(username=vm_owner)
VMModel.objects.update_or_create(
defaults= { 'data': vm,
'owner': user },
vmid=vm_id
)
else:
print(response)
print(uncloud.secrets.OPENNEBULA_USER_PASS)