Пример #1
0
def _create_vm(ova_file, machine_name, template, username, vm_kind, logger):
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        ova = Ova(ova_file)
        try:
            net_map = _get_network_mapping(vcenter, ova, vm_kind, username)
            the_vm = virtual_machine.deploy_from_ova(vcenter=vcenter,
                                                     ova=ova,
                                                     network_map=net_map,
                                                     username=username,
                                                     machine_name=machine_name,
                                                     logger=logger)
        finally:
            ova.close()

        meta_data = {'component' : template,
                     'created' : time.time(),
                     'deployment': True,
                     'version' : 'n/a',
                     'configured' : True,
                     'generation' : 1}
        virtual_machine.set_meta(the_vm, meta_data)
        if vm_kind.lower() == 'onefs':
            info = virtual_machine.get_info(vcenter, the_vm, username, ensure_ip=False)
        else:
            info = virtual_machine.get_info(vcenter, the_vm, username, ensure_ip=True)
        return {the_vm.name: info}
Пример #2
0
def _make_ova(username, machine_name, template_dir, logger):
    """Export a VM to an OVA.

    :param username: The user creating a new deployment template.
    :type username: String

    :param machine_name: The name of the VM to include in the deployment template.
    :type machine_name: String

    :param template_dir: The folder to save the new VM OVA in.
    :type template_dir: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    new_ova = ''
    kind = ''
    error = ''
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        for vm in folder.childEntity:
            if vm.name == machine_name:
                # Avoids VM names getting crazy long as a result of users making
                # new templates from existing deployments.
                info = virtual_machine.get_info(vcenter, vm, username)
                kind = info['meta']['component']
                ova_name = vm.name.replace(VM_NAME_APPEND, '')
                new_ova = virtual_machine.make_ova(vcenter, vm, template_dir, logger, ova_name=ova_name)
                break
        else:
            error = 'No VM named {} found.'.format(machine_name)
    return new_ova, kind, error
Пример #3
0
def delete_windows(username, machine_name, logger):
    """Unregister and destroy a user's Windows

    :Returns: None

    :param username: The user who wants to delete their jumpbox
    :type username: String

    :param machine_name: The name of the VM to delete
    :type machine_name: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        for entity in folder.childEntity:
            if entity.name == machine_name:
                info = virtual_machine.get_info(vcenter, entity, username)
                if info['meta']['component'] == 'Windows':
                    logger.debug('powering off VM')
                    virtual_machine.power(entity, state='off')
                    delete_task = entity.Destroy_Task()
                    logger.debug('blocking while VM is being destroyed')
                    consume_task(delete_task)
                    break
        else:
            raise ValueError('No {} named {} found'.format(
                'windows', machine_name))
Пример #4
0
    def test_get_info_note_none(self, fake_get_vm_console_url, fake_get_vm_ips,
                                fake_get_networks):
        """``virtual_machine`` - TODO"""
        fake_get_vm_ips.return_value = ['192.168.1.1']
        fake_get_networks.return_value = ['network1', 'network2']
        fake_get_vm_console_url.return_value = 'https://test-vm-url'
        vm = MagicMock()
        vm.runtime.powerState = 'poweredOn'
        vm.config.annotation = None
        vm._moId = 'vm-1234'
        vcenter = MagicMock()

        info = virtual_machine.get_info(vcenter, vm, 'alice')
        expected_info = {
            'state': 'poweredOn',
            'console': 'https://test-vm-url',
            'ips': ['192.168.1.1'],
            'networks': ['network1', 'network2'],
            'moid': 'vm-1234',
            'meta': {
                'component': 'Unknown',
                'created': 0,
                'version': 'Unknown',
                'generation': 0,
                'configured': False
            }
        }

        self.assertEqual(info, expected_info)
Пример #5
0
def create_jumpbox(username, network, image_name='jumpBox-Ubuntu18.04.ova'):
    """Make a new jumpbox so a user can connect to their lab

    :Returns: Dictionary

    :param username: The user who wants to delete their jumpbox
    :type username: String

    :param network: The name of the network the jumpbox connects to
    :type network: string
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        ova = Ova(os.path.join(const.VLAB_JUMPBOX_IMAGES_DIR, image_name))
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova,
                                                     [network_map], username,
                                                     'jumpBox', logger)
        finally:
            ova.close()
        _setup_jumpbox(vcenter, the_vm, username)
        # VMTools will be ready long before the full network stack is up.
        # Pause for a moment here so we can return an IP
        time.sleep(70)
        return virtual_machine.get_info(vcenter, the_vm)
Пример #6
0
    def test_get_info(self, fake_get_vm_console_url, fake_get_vm_ips,
                      fake_get_networks):
        """``virtual_machine`` - get_info returns the expected data"""
        fake_get_vm_ips.return_value = ['192.168.1.1']
        fake_get_networks.return_value = ['network1', 'network2']
        fake_get_vm_console_url.return_value = 'https://test-vm-url'
        vm = MagicMock()
        vm.runtime.powerState = 'poweredOn'
        vm.config.annotation = '{"json": true}'
        vm._moId = 'vm-1234'
        vcenter = MagicMock()

        info = virtual_machine.get_info(vcenter, vm, 'alice')
        expected_info = {
            'state': 'poweredOn',
            'console': 'https://test-vm-url',
            'ips': ['192.168.1.1'],
            'moid': 'vm-1234',
            'networks': ['network1', 'network2'],
            'meta': {
                'json': True
            }
        }

        self.assertEqual(info, expected_info)
Пример #7
0
def delete_deployment(username, machine_name, logger):
    """Unregister and destroy a user's Deployment

    :Returns: None

    :param username: The user who wants to delete their jumpbox
    :type username: String

    :param machine_name: The name of the VM to delete
    :type machine_name: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        tasks = []
        for entity in folder.childEntity:
            info = virtual_machine.get_info(vcenter, entity, username)
            if info['meta'].get('deployment', False) == True:
                logger.debug('powering off VM %s', entity.name)
                virtual_machine.power(entity, state='off')
                delete_task = entity.Destroy_Task()
                tasks.append(delete_task)
        if tasks:
            logger.debug('blocking while VMs are being destroyed')
            for task in tasks:
                consume_task(task)

        else:
            raise ValueError('No {} named {} found'.format('deployment', machine_name))
Пример #8
0
def update_network(username, machine_name, new_network):
    """Implements the VM network update

    :param username: The name of the user who owns the virtual machine
    :type username: String

    :param machine_name: The name of the virtual machine
    :type machine_name: String

    :param new_network: The name of the new network to connect the VM to
    :type new_network: String
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        for entity in folder.childEntity:
            if entity.name == machine_name:
                info = virtual_machine.get_info(vcenter, entity, username)
                if info['meta']['component'] == 'Windows':
                    the_vm = entity
                    break
        else:
            error = 'No VM named {} found'.format(machine_name)
            raise ValueError(error)

        try:
            network = vcenter.networks[new_network]
        except KeyError:
            error = 'No VM named {} found'.format(machine_name)
            raise ValueError(error)
        else:
            virtual_machine.change_network(the_vm, network)
Пример #9
0
def create_windows(username, machine_name, image, network, logger):
    """Deploy a new instance of Windows

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new Windows
    :type username: String

    :param machine_name: The name of the new instance of Windows
    :type machine_name: String

    :param image: The image/version of Windows to create
    :type image: String

    :param network: The name of the network to connect the new Windows instance up to
    :type network: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER,
                 user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image_name)
        try:
            ova = Ova(os.path.join(const.VLAB_WINDOWS_IMAGES_DIR, image_name))
        except FileNotFoundError:
            error = "Invalid verison of Windows supplied: {}".format(image)
            raise ValueError(error)
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova,
                                                     [network_map], username,
                                                     machine_name, logger)
        finally:
            ova.close()
        meta_data = {
            'component': "Windows",
            'created': time.time(),
            'version': image,
            'configured': False,
            'generation': 1,
        }
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter,
                                        the_vm,
                                        username,
                                        ensure_ip=True)
        return {the_vm.name: info}
Пример #10
0
def create_esxi(username, machine_name, image, network, logger):
    """Deploy a new instance of ESXi

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new ESXi
    :type username: String

    :param machine_name: The name of the new instance of ESXi
    :type machine_name: String

    :param image: The image/version of ESXi to create
    :type image: String

    :param network: The name of the network to connect the new ESXi instance up to
    :type network: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image_name)
        ova = Ova(os.path.join(const.VLAB_ESXI_IMAGES_DIR, image_name))
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter=vcenter,
                                                     ova=ova,
                                                     network_map=[network_map],
                                                     username=username,
                                                     machine_name=machine_name,
                                                     logger=logger,
                                                     power_on=False)
        finally:
            ova.close()
        config_vm(the_vm)
        virtual_machine.power(the_vm, state='on')
        meta_data = {'component' : "ESXi",
                     'created': time.time(),
                     'version': image,
                     'configured': False,
                     'generation': 1,
                    }
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter, the_vm, username, ensure_ip=True)
        return {the_vm.name: info}
Пример #11
0
def create_kemp(username, machine_name, image, network, logger):
    """Deploy a new instance of Kemp

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new Kemp
    :type username: String

    :param machine_name: The name of the new instance of Kemp
    :type machine_name: String

    :param image: The image/version of Kemp to create
    :type image: String

    :param network: The name of the network to connect the new Kemp instance up to
    :type network: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER,
                 user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image_name)
        ova = Ova(os.path.join(const.VLAB_KEMP_IMAGES_DIR, image_name))
        network_map = _get_nic_network_map(network, vcenter.networks,
                                           ova.networks)
        try:
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova, network_map,
                                                     username, machine_name,
                                                     logger)
        finally:
            ova.close()

        meta_data = {
            'component': "Kemp",
            'created': time.time(),
            'version': image,
            'configured': False,
            'generation': 1
        }
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter,
                                        the_vm,
                                        username,
                                        ensure_ip=True)
        return {the_vm.name: info}
Пример #12
0
def create_router(username, machine_name, image, requested_networks, logger):
    """Deploy a new instance of Router

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new Router
    :type username: String

    :param machine_name: The name of the new instance of Router
    :type machine_name: String

    :param image: The image/version of Router to create
    :type image: String

    :param requested_networks: The name of the networks to connect the new Router instance up to
    :type requested_networks: List

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER,
                 user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image_name)
        try:
            ova = Ova(os.path.join(const.VLAB_ROUTER_IMAGES_DIR, image_name))
        except FileNotFoundError:
            error = "Invalid version of Router supplied: {}".format(image)
            raise ValueError(error)
        try:
            networks = map_networks(ova.networks, requested_networks,
                                    vcenter.networks)
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova, networks,
                                                     username, machine_name,
                                                     logger)
        finally:
            ova.close()
        meta_data = {
            'component': "Router",
            'created': time.time(),
            'version': image,
            'configured': False,
            'generation': 1,
        }
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter, the_vm, username)
        return {the_vm.name: info}
Пример #13
0
def show_inventory(username):
    """Return some basic information about all VMs a user owns

    :Returns: Dictionary

    :param username: The name of the user to create a folder for
    :type username: String
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,\
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        vms = {}
        for entity in folder.childEntity:
            info = virtual_machine.get_info(vcenter, entity, username)
            vms[entity.name] = info
    return vms
Пример #14
0
def show_windows(username):
    """Obtain basic information about Windows

    :Returns: Dictionary

    :param username: The user requesting info about their Windows
    :type username: String
    """
    windows_vms = {}
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        for vm in folder.childEntity:
            info = virtual_machine.get_info(vcenter, vm, username)
            if info['meta']['component'] == 'Windows':
                windows_vms[vm.name] = info
    return windows_vms
Пример #15
0
def show_gateway(username):
    """Obtain basic information about the defaultGateway

    :Returns: Dictionary

    :param username: The user requesting info about their defaultGateway
    :type username: String
    """
    info = {}
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        for vm in folder.childEntity:
            if vm.name == COMPONENT_NAME:
                info = virtual_machine.get_info(vcenter, vm, username)
                break
    return info
Пример #16
0
def show_deployment(username):
    """Obtain basic information about Deployment

    :Returns: Dictionary

    :param username: The user requesting info about their Deployment
    :type username: String
    """
    info = {}
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        deployment_vms = {}
        for vm in folder.childEntity:
            info = virtual_machine.get_info(vcenter, vm, username)
            if info['meta'].get('deployment', False) == True:
                deployment_vms[vm.name] = info
    return deployment_vms
Пример #17
0
def _check_for_deployment(username):
    """For many reasons, only 1 deployment per lab is allowed. This function
    checks if a deployment already exists.

    :Returns: String

    :param username: The name of the user who wants to create a new Deployment
    :type username: String
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        folder = vcenter.get_by_name(name=username, vimtype=vim.Folder)
        current_deployment = ''
        for vm in folder.childEntity:
            info = virtual_machine.get_info(vcenter, vm, username)
            if info['meta'].get('deployment', False):
                current_deployment = info['meta']['component']
                break
    return current_deployment
Пример #18
0
def create_gateway(username,
                   wan,
                   lan,
                   logger,
                   image_name='defaultgateway-IPAM.ova'):
    """Deploy the defaultGateway from an OVA

    :Returns: None

    :param username: The user who wants to create a new defaultGateway
    :type username: String

    :param wan: The name of the network to use in vCenter for the WAN network
    :type wan: String

    :param lan: The name of the network to use in vCenter for the LAN network
    :type lan: String

    :param image_name: The of the OVA to deploy
    :type image_name: String

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        ova = Ova(os.path.join(const.VLAB_GATEWAY_IMAGES_DIR, image_name))
        try:
            network_map = _create_network_map(vcenter, ova, wan, lan, logger)
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova, network_map,
                                                     username, COMPONENT_NAME,
                                                     logger)
        finally:
            ova.close()
        _setup_gateway(vcenter,
                       the_vm,
                       username,
                       gateway_version='1.0.0',
                       logger=logger)
        return virtual_machine.get_info(vcenter,
                                        the_vm,
                                        username,
                                        ensure_ip=True)
Пример #19
0
def destroy_vms(user, vcenter):
    """Delete enough VMs to resolve the soft-quota violation.

    The VMs deleted are randomly chosen, and this function returns a list of VM
    names that were deleted.

    :Returns: List

    :param user: The user that's getting some VMs deleted
    :type user: String

    :param vcenter: An object for interacting with the vCenter API.
    :type vcenter: vlab_inf_common.vmaware.vCenter
    """
    user_folder = vcenter.get_by_name(name=user, vimtype=vim.Folder)
    user_vms = set(
        [x for x in user_folder.childEntity if not x.name == 'defaultGateway'])
    deleted_vms = []
    while len(user_vms) > const.VLAB_QUOTA_LIMIT:
        unlucky_vm = random.sample(user_vms,
                                   1)[0]  # b/c random.sample returns a list
        vm_info = virtual_machine.get_info(vcenter, unlucky_vm, user)
        vm_name = unlucky_vm.name
        if vm_info['meta']['component'] == 'Unknown':
            log.info(
                "Skipping VM %s owned by %s: VM cannot be deleted at this time",
                vm_name, user)
        else:
            _delete_portmap_rules(user, vm_name)
            log.info("Delete portmapping rules for VM %s owned by %s", vm_name,
                     user)
            _delete_vm(user, vm_name, vm_info['meta']['component'].lower())
            deleted_vms.append(vm_name)
            log.info("Deleted VM %s, owned by %s", vm_name, user)
            # Removing the VM from the set *only* if we delete it avoids an
            # edge case where a user is over by 1 VM, and the one we randomly
            # choose to delete is either deploying or a failed deployment.
            # While this could potentially create an infinite loop, if it did
            # we'd probably have "bigger problems" going on, and fixing those
            # "bigger problems" would resolve the infinite loop.
            user_vms.discard(unlucky_vm)
    return deleted_vms
Пример #20
0
def create_centos(username, machine_name, image, network, desktop, ram, cpu_count, logger):
    """Deploy a new instance of CentOS

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new CentOS
    :type username: String

    :param machine_name: The name of the new instance of CentOS
    :type machine_name: String

    :param image: The image/version of CentOS to create
    :type image: String

    :param network: The name of the network to connect the new CentOS instance up to
    :type network: String

    :param network: The name of the network to connect the new CentOS instance up to
    :type network: String

    :param desktop: Deploy the VM with a GUI
    :type desktop: Boolean

    :param ram: The number of GB of RAM to allocate for the VM
    :type ram: Integer

    :param cpu_count: The number of CPU cores to allocate for the VM
    :type cpu_count: Integer

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image, desktop=desktop)
        logger.info(image_name)
        try:
            ova = Ova(os.path.join(const.VLAB_CENTOS_IMAGES_DIR, image_name))
        except FileNotFoundError:
            error = "Invalid version of CentOS supplied: {}".format(image)
            raise ValueError(error)
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova, [network_map],
                                                     username, machine_name, logger,
                                                     power_on=False)
        finally:
            ova.close()
        mb_of_ram = ram * 1024
        virtual_machine.adjust_ram(the_vm, mb_of_ram)
        virtual_machine.adjust_cpu(the_vm, cpu_count)
        virtual_machine.power(the_vm, state='on')
        meta_data = {'component' : "CentOS",
                     'created': time.time(),
                     'version': image,
                     'configured': False,
                     'generation': 1,
                    }
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter, the_vm, username, ensure_ip=True)
        return {the_vm.name: info}
Пример #21
0
def create_winserver(username, machine_name, image, network, ip_config, logger):
    """Deploy a new instance of WinServer

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new WinServer
    :type username: String

    :param machine_name: The name of the new instance of WinServer
    :type machine_name: String

    :param image: The image/version of WinServer to create
    :type image: String

    :param network: The name of the network to connect the new WinServer instance up to
    :type network: String

    :param ip_config: The IPv4 network configuration for the WinServer instance
    :type ip_config: Dictionary

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image_name)
        try:
            ova = Ova(os.path.join(const.VLAB_WINSERVER_IMAGES_DIR, image_name))
        except FileNotFoundError:
            error = 'Invalid version of Windows Server supplied: {}'.format(image)
            raise ValueError(error)
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova, [network_map],
                                                     username, machine_name, logger)
        finally:
            ova.close()
        if ip_config['static-ip']:
            # Hack - The VM will walk through the C:\unattend.xml answer file
            # and then reboot. We wont have valid login creds until after the
            # reboot. Trying to *notice* the reboot is a race condition nightmare
            time.sleep(300)
            virtual_machine.config_static_ip(vcenter,
                                             the_vm,
                                             ip_config['static-ip'],
                                             ip_config['default-gateway'],
                                             ip_config['netmask'],
                                             ip_config['dns'],
                                             user='******',
                                             password='******',
                                             logger=logger,
                                             os='windows')
        meta_data = {'component' : "WinServer",
                     'created': time.time(),
                     'version': image,
                     'configured': False,
                     'generation': 1,
                    }
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter, the_vm, username, ensure_ip=True)
        return {the_vm.name: info}
Пример #22
0
def create_dataiq(username, machine_name, image, network, static_ip,
                  default_gateway, netmask, dns, disk_size, cpu_count, ram, logger):
    """Deploy a new instance of DataIQ

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new DataIQ
    :type username: String

    :param machine_name: The name of the new instance of DataIQ
    :type machine_name: String

    :param image: The image/version of DataIQ to create
    :type image: String

    :param network: The name of the network to connect the new DataIQ instance up to
    :type network: String

    :param static_ip: The IPv4 address to assign to the VM
    :type static_ip: String

    :param default_gateway: The IPv4 address of the network gateway
    :type default_gateway: String

    :param netmask: The subnet mask of the network, i.e. 255.255.255.0
    :type netmask: String

    :param dns: A list of DNS servers to use.
    :type dns: List

    :param disk_size: The number of GB to allocate for the DataIQ database
    :type disk_size: Integer

    :param cpu_count: Thenumber of CPU cores to allocate to the DataIQ machine
    :type cpu_count: Integer

    :param ram: The number of GB of RAM to allocate to the VM
    :type ram: Integer

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image)
        ova = Ova(os.path.join(const.VLAB_DATAIQ_IMAGES_DIR, image_name))
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter=vcenter,
                                                     ova=ova,
                                                     network_map=[network_map],
                                                     username=username,
                                                     machine_name=machine_name,
                                                     logger=logger,
                                                     power_on=False)
        finally:
            ova.close()
        mb_of_ram = ram * 1024
        virtual_machine.adjust_ram(the_vm, mb_of_ram)
        virtual_machine.adjust_cpu(the_vm, cpu_count)
        virtual_machine.power(the_vm, state='on')
        meta_data = {'component' : "DataIQ",
                     'created' : time.time(),
                     'version' : image,
                     'configured' : False,
                     'generation' : 1}
        virtual_machine.set_meta(the_vm, meta_data)
        logger.info("Adding DB VMDK")
        _add_database_disk(the_vm, disk_size)
        logger.info("Configuring network")
        _config_network(vcenter, the_vm, static_ip, default_gateway, netmask, dns, logger)
        logger.info("Adding GUI")
        _add_gui(vcenter, the_vm, logger)
        logger.info("Acquiring machine info")
        info = virtual_machine.get_info(vcenter, the_vm, username, ensure_ip=True)
        return  {the_vm.name: info}
Пример #23
0
def create_onefs(username, machine_name, image, front_end, back_end, ram,
                 cpu_count, logger):
    """Deploy a OneFS node

    :Returns: Dictionary

    :param username: The user who wants to delete a OneFS node
    :type username: String

    :param machine_name: The name of the OneFS node
    :type machine_name: String

    :param image: The version/image of the OneFS node to create
    :type image: String

    :param front_end: The network to hook up the external network to
    :type front_end: String

    :param back_end: The network to hook the internal network to
    :type back_end: String

    :param ram: The number of GB of memory to provision the node with
    :type ram: Integer

    :param cpu_count: The number of CPU cores to allocate to the vOneFS node
    :type cpu_count: Integer

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER, user=const.INF_VCENTER_USER, \
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        ova_name = convert_name(image)
        try:
            ova = Ova(os.path.join(const.VLAB_ONEFS_IMAGES_DIR, ova_name))
        except FileNotFoundError:
            error = 'Invalid version of OneFS: {}'.format(image)
            raise ValueError(error)
        try:
            network_map = make_network_map(vcenter.networks, front_end,
                                           back_end)
            the_vm = virtual_machine.deploy_from_ova(vcenter=vcenter,
                                                     ova=ova,
                                                     network_map=network_map,
                                                     username=username,
                                                     machine_name=machine_name,
                                                     logger=logger,
                                                     power_on=False)
        finally:
            ova.close()
        # ram is supplied in GB
        mb_of_ram = ram * 1024
        virtual_machine.adjust_ram(the_vm, mb_of_ram=mb_of_ram)
        virtual_machine.adjust_cpu(the_vm, cpu_count)
        virtual_machine.power(the_vm, state='on')
        meta_data = {
            'component': 'OneFS',
            'created': time.time(),
            'version': image,
            'configured': False,
            'generation': 1
        }  # Versioning of the VM itself
        virtual_machine.set_meta(the_vm, meta_data)
        info = virtual_machine.get_info(vcenter, the_vm, username)
        return {the_vm.name: info}
Пример #24
0
def create_dns(username, machine_name, image, network, static_ip,
               default_gateway, netmask, dns, logger):
    """Deploy a new instance of Dns

    :Returns: Dictionary

    :param username: The name of the user who wants to create a new Dns
    :type username: String

    :param machine_name: The name of the new instance of Dns
    :type machine_name: String

    :param image: The image/version of Dns to create
    :type image: String

    :param network: The name of the network to connect the new Dns instance up to
    :type network: String

    :param static_ip: The IPv4 address to assign to the VM
    :type static_ip: String

    :param default_gateway: The IPv4 address of the network gateway
    :type default_gateway: String

    :param netmask: The subnet mask of the network, i.e. 255.255.255.0
    :type netmask: String

    :param dns: A list of DNS servers to use.
    :type dns: List

    :param logger: An object for logging messages
    :type logger: logging.LoggerAdapter
    """
    with vCenter(host=const.INF_VCENTER_SERVER,
                 user=const.INF_VCENTER_USER,
                 password=const.INF_VCENTER_PASSWORD) as vcenter:
        image_name = convert_name(image)
        logger.info(image_name)
        ova = Ova(os.path.join(const.VLAB_DNS_IMAGES_DIR, image_name))
        try:
            network_map = vim.OvfManager.NetworkMapping()
            network_map.name = ova.networks[0]
            try:
                network_map.network = vcenter.networks[network]
            except KeyError:
                raise ValueError('No such network named {}'.format(network))
            the_vm = virtual_machine.deploy_from_ova(vcenter, ova,
                                                     [network_map], username,
                                                     machine_name, logger)
        finally:
            ova.close()

        meta_data = {
            'component': "Dns",
            'created': time.time(),
            'version': image,
            'configured': False,
            'generation': 1
        }
        virtual_machine.set_meta(the_vm, meta_data)

        if image.lower().startswith('windows'):
            vm_user, vm_password, the_os = const.VLAB_DNS_WINDOWS_ADMIN, const.VLAB_DNS_WINDOWS_PW, 'windows'
        else:
            vm_user, vm_password, the_os = const.VLAB_DNS_BIND9_ADMIN, const.VLAB_DNS_BIND9_PW, 'centos8'
        virtual_machine.config_static_ip(vcenter,
                                         the_vm,
                                         static_ip,
                                         default_gateway,
                                         netmask,
                                         dns,
                                         vm_user,
                                         vm_password,
                                         logger,
                                         os=the_os)
        if the_os == 'centos8':
            _finish_bind_config(vcenter, the_vm, static_ip, logger)

        info = virtual_machine.get_info(vcenter,
                                        the_vm,
                                        username,
                                        ensure_ip=True)
        return {the_vm.name: info}