2020-02-21 15:33:37 +00:00
|
|
|
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
|
2020-02-21 15:33:37 +00:00
|
|
|
|
|
|
|
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:
|
2020-02-21 15:33:37 +00:00
|
|
|
success, response, *_ = rpc_client.one.vmpool.infoextended(
|
2020-02-21 23:22:42 +00:00
|
|
|
uncloud.secrets.OPENNEBULA_USER_PASS, -2, -1, -1, -1
|
2020-02-21 15:33:37 +00:00
|
|
|
)
|
|
|
|
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)
|
|
|
|
|
2020-02-23 10:42:03 +00:00
|
|
|
VMModel.objects.update_or_create(
|
|
|
|
defaults= { 'data': vm,
|
|
|
|
'owner': user },
|
|
|
|
vmid=vm_id
|
|
|
|
)
|
|
|
|
|
2020-02-21 15:33:37 +00:00
|
|
|
else:
|
|
|
|
print(response)
|