import json import uncloud.secrets as secrets from xmlrpc.client import ServerProxy as RPCClient from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from xmltodict import parse from ungleich_common.ldap.ldap_manager import LdapManager from opennebula.models import VM as VMModel def find_user_based_on_email(users, email): for user in users: if email in user.mail.values: return user class Command(BaseCommand): help = 'Syncronize VM information from OpenNebula' def add_arguments(self, parser): pass def handle(self, *args, **options): ldap_server_uri = secrets.LDAP_SERVER_URI.split(',')[0] ldap_manager = LdapManager( server=ldap_server_uri, admin_dn=secrets.LDAP_ADMIN_DN, admin_password=secrets.LDAP_ADMIN_PASSWORD, ) users = ldap_manager.get('') # Get all users with RPCClient(secrets.OPENNEBULA_URL) as rpc_client: success, response, *_ = rpc_client.one.vmpool.infoextended( secrets.OPENNEBULA_USER_PASS, -2, -1, -1, -1 ) if success: vms = json.loads(json.dumps(parse(response)))['VM_POOL']['VM'] unknown_user_with_email = set() for vm in vms: vm_id = vm['ID'] vm_owner_email = vm['UNAME'] user = find_user_based_on_email(users, vm_owner_email) if not user: unknown_user_with_email.add(vm_owner_email) else: try: user_in_db = get_user_model().objects.get(email=vm_owner_email) except get_user_model().DoesNotExist: user_in_db = get_user_model().objects.create_user(username=user.uid, email=vm_owner_email) VMModel.objects.update_or_create( defaults={'data': vm, 'owner': user_in_db}, vmid=vm_id ) print('User with email but not found in ldap:', unknown_user_with_email) else: print(response) print(secrets.OPENNEBULA_USER_PASS)