uncloud-mravi/uncloud/opennebula/management/commands/syncvm.py

43 lines
1.4 KiB
Python
Raw Normal View History

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
2020-02-21 23:22:42 +00:00
import uncloud.secrets
class Command(BaseCommand):
help = 'Syncronize VM information from OpenNebula'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
2020-02-21 23:22:42 +00:00
with RPCClient(uncloud.secrets.OPENNEBULA_URL) as rpc_client:
success, response, *_ = rpc_client.one.vmpool.infoextended(
2020-02-21 23:22:42 +00:00
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)
VMModel.objects.update_or_create(
defaults= { 'data': vm,
'owner': user },
vmid=vm_id
)
else:
print(response)