Пример #1
0
 def test_0003_get_vc_negative(self):
     try:
         platform = Platform(self.client)
         platform.get_vcenter(self.config['vcd']['vcenter_invalid'])
         assert False
     except Exception as e:
         assert 'not found' in str(e).lower()
Пример #2
0
 def test_0030_get_vc_negative(self):
     """Platform.get_vcenter does not find a non-existent vcenter."""
     try:
         platform = Platform(TestVC._client)
         platform.get_vcenter(TestVC._vcenter_invalid)
         self.fail('Should not be able to find VC that does not exist ' +
                   TestVC._vcenter_invalid)
     except EntityNotFoundException as e:
         return
Пример #3
0
 def test_0030_get_vc_negative(self):
     """Platform.get_vcenter does not find a non-existent vcenter."""
     try:
         platform = Platform(TestVC._client)
         platform.get_vcenter(TestVC._vcenter_invalid)
         self.fail('Should not be able to find VC that does not exist ' +
                   TestVC._vcenter_invalid)
     except EntityNotFoundException as e:
         return
Пример #4
0
    def test_0080_detach_vc(self):
        """Platform.detach_vcenter unregisters (detaches) a vcenter.

        Wait for async command to complete before checking result.
        """
        platform = Platform(TestVC._client)

        task = platform.detach_vcenter(vc_name=TestVC._vcServerName)
        TestVC._client.get_task_monitor().wait_for_success(task=task)
        try:
            platform.get_vcenter(name=TestVC._vcServerName)
            self.fail('Should not be able to find detached VC ' +
                      TestVC._vcServerName)
        except EntityNotFoundException as e:
            return
Пример #5
0
    def test_0080_detach_vc(self):
        """Platform.detach_vcenter unregisters (detaches) a vcenter.

        Wait for async command to complete before checking result.
        """
        platform = Platform(TestVC._client)

        task = platform.detach_vcenter(vc_name=TestVC._vcServerName)
        TestVC._client.get_task_monitor().wait_for_success(task=task)
        try:
            platform.get_vcenter(name=TestVC._vcServerName)
            self.fail('Should not be able to find detached VC ' +
                      TestVC._vcServerName)
        except EntityNotFoundException as e:
            return
Пример #6
0
    def test_0061_detach_port_group(self):
        """Detach a portgroup from an external network
       This test passes if the portgroup from another vCenter is removed
       from external network successfully.
       """
        if TestExtNet._vc2_host_ip is None or TestExtNet._vc2_host_ip == '':
            return
        logger = Environment.get_default_logger()
        platform = Platform(TestExtNet._sys_admin_client)
        vc_name = TestExtNet._config['vc2']['vcenter_host_name']
        port_group_helper = PortgroupHelper(TestExtNet._sys_admin_client)
        pg_name = port_group_helper.get_ext_net_portgroup_name(vc_name,
                                                               self._name)

        ext_net = self._get_ext_net(platform).detach_port_group(vc_name,
                                                                pg_name)
        task = ext_net['{' + NSMAP['vcloud'] + '}Tasks'].Task[0]
        TestExtNet._sys_admin_client.get_task_monitor().wait_for_success(
            task=task)
        logger.debug(
            'Detach a portgroup from an external network' + TestExtNet._name)
        ext_net = platform.get_external_network(self._name)
        self.assertIsNotNone(ext_net)
        vc_record = platform.get_vcenter(vc_name)
        vc_href = vc_record.get('href')
        vim_port_group_ref = ext_net.VimPortGroupRef
        vc_href_found = False

        if vim_port_group_ref.VimServerRef.get('href') == vc_href:
            vc_href_found = True
        self.assertFalse(vc_href_found)
Пример #7
0
def info(ctx, name):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.get_vcenter(name=name), ctx)
    except Exception as e:
        stderr(e, ctx)
Пример #8
0
    def test_0060_attach_port_group(self):
        """Attach a portgroup to an external network
       This test passes if the portgroup from another vCenter is added
       to external network successfully.
       """
        if TestExtNet._vc2_host_ip is None or TestExtNet._vc2_host_ip == '':
            return
        logger = Environment.get_default_logger()
        platform = Platform(TestExtNet._sys_admin_client)
        vc_name = TestExtNet._config['vc2']['vcenter_host_name']
        portgrouphelper = PortgroupHelper(TestExtNet._sys_admin_client)
        pg_name = portgrouphelper.get_available_portgroup_name(
            vc_name, TestExtNet._portgroupType)

        ext_net = self._get_ext_net(platform).attach_port_group(
            vc_name,
            pg_name)
        task = ext_net['{' + NSMAP['vcloud'] + '}Tasks'].Task[0]
        TestExtNet._sys_admin_client.get_task_monitor().wait_for_success(
            task=task)
        logger.debug(
            'Attach a portgroup to an external network'
            + TestExtNet._name + '.')
        ext_net = platform.get_external_network(self._name)
        self.assertIsNotNone(ext_net)
        vc_record = platform.get_vcenter(vc_name)
        vc_href = vc_record.get('href')
        vim_port_group_refs = \
            ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRefs']
        vc_href_found = False
        for vim_obj_ref in vim_port_group_refs.VimObjectRef:
            if vim_obj_ref.VimServerRef.get('href') == vc_href:
                vc_href_found = True
                break
        self.assertTrue(vc_href_found)
Пример #9
0
    def test_0061_detach_port_group(self):
        """Detach a portgroup from an external network
       This test passes if the portgroup from another vCenter is removed
       from external network successfully.
       """
        if TestExtNet._vc2_host_ip is None or TestExtNet._vc2_host_ip == '':
            return
        logger = Environment.get_default_logger()
        platform = Platform(TestExtNet._sys_admin_client)
        vc_name = TestExtNet._config['vc2']['vcenter_host_name']
        port_group_helper = PortgroupHelper(TestExtNet._sys_admin_client)
        pg_name = port_group_helper.get_ext_net_portgroup_name(
            vc_name, self._name)

        ext_net = self._get_ext_net(platform).detach_port_group(
            vc_name, pg_name)
        task = ext_net['{' + NSMAP['vcloud'] + '}Tasks'].Task[0]
        TestExtNet._sys_admin_client.get_task_monitor().wait_for_success(
            task=task)
        logger.debug('Detach a portgroup from an external network' +
                     TestExtNet._name)
        ext_net = platform.get_external_network(self._name)
        self.assertIsNotNone(ext_net)
        vc_record = platform.get_vcenter(vc_name)
        vc_href = vc_record.get('href')
        vim_port_group_ref = ext_net.VimPortGroupRef
        vc_href_found = False

        if vim_port_group_ref.VimServerRef.get('href') == vc_href:
            vc_href_found = True
        self.assertFalse(vc_href_found)
Пример #10
0
    def test_0060_attach_port_group(self):
        """Attach a portgroup to an external network
       This test passes if the portgroup from another vCenter is added
       to external network successfully.
       """
        if TestExtNet._vc2_host_ip is None or TestExtNet._vc2_host_ip == '':
            return
        logger = Environment.get_default_logger()
        platform = Platform(TestExtNet._sys_admin_client)
        vc_name = TestExtNet._config['vc2']['vcenter_host_name']
        portgrouphelper = PortgroupHelper(TestExtNet._sys_admin_client)
        pg_name = portgrouphelper.get_available_portgroup_name(
            vc_name, TestExtNet._portgroupType)

        ext_net = self._get_ext_net(platform).attach_port_group(
            vc_name, pg_name)
        task = ext_net['{' + NSMAP['vcloud'] + '}Tasks'].Task[0]
        TestExtNet._sys_admin_client.get_task_monitor().wait_for_success(
            task=task)
        logger.debug('Attach a portgroup to an external network' +
                     TestExtNet._name + '.')
        ext_net = platform.get_external_network(self._name)
        self.assertIsNotNone(ext_net)
        vc_record = platform.get_vcenter(vc_name)
        vc_href = vc_record.get('href')
        vim_port_group_refs = \
            ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRefs']
        vc_href_found = False
        for vim_obj_ref in vim_port_group_refs.VimObjectRef:
            if vim_obj_ref.VimServerRef.get('href') == vc_href:
                vc_href_found = True
                break
        self.assertTrue(vc_href_found)
Пример #11
0
def info(ctx, name):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.get_vcenter(name), ctx)
    except Exception as e:
        stderr(e, ctx)
Пример #12
0
 def test_0020_get_vc(self):
     """Platform.get_vcenter finds a known vcenter."""
     logger = Environment.get_default_logger()
     platform = Platform(TestVC._client)
     vcenter = platform.get_vcenter(TestVC._vcenter_host_name)
     logger.debug('vCenter: name=%s, url=%s' %
                  (vcenter.get('name'), vcenter.Url.text))
     self.assertIsNotNone(vcenter)
Пример #13
0
 def test_0020_get_vc(self):
     """Platform.get_vcenter finds a known vcenter."""
     logger = Environment.get_default_logger()
     platform = Platform(TestVC._client)
     vcenter = platform.get_vcenter(TestVC._vcenter_host_name)
     logger.debug('vCenter: name=%s, url=%s' %
                  (vcenter.get('name'), vcenter.Url.text))
     self.assertIsNotNone(vcenter)
Пример #14
0
    def attach_port_group(self, vim_server_name, port_group_name):
        """Attach a portgroup to an external network.

        :param str vc_name: name of vc where portgroup is present.
        :param str pg_name: name of the portgroup to be attached to
             external network.

        return: object containing vmext:VMWExternalNetwork XML element that
             representing the external network.
        :rtype: lxml.objectify.ObjectifiedElement
        """
        ext_net = self.get_resource()
        platform = Platform(self.client)

        if not vim_server_name or not port_group_name:
            raise InvalidParameterException(
                "Either vCenter Server name is none or portgroup name is none")

        vc_record = platform.get_vcenter(vim_server_name)
        vc_href = vc_record.get('href')
        pg_moref_types = \
            platform.get_port_group_moref_types(vim_server_name,
                                                port_group_name)

        if hasattr(ext_net, '{' + NSMAP['vmext'] + '}VimPortGroupRef'):
            vim_port_group_refs = E_VMEXT.VimPortGroupRefs()
            vim_object_ref1 = self.__create_vimobj_ref(vc_href,
                                                       pg_moref_types[0],
                                                       pg_moref_types[1])

            # Create a new VimObjectRef using vc href, portgroup moref and type
            # from existing VimPortGroupRef. Add the VimObjectRef to
            # VimPortGroupRefs and then delete VimPortGroupRef
            # from external network.
            vim_pg_ref = ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRef']
            vc2_href = vim_pg_ref.VimServerRef.get('href')
            vim_object_ref2 = self.__create_vimobj_ref(
                vc2_href, vim_pg_ref.MoRef.text, vim_pg_ref.VimObjectType.text)

            vim_port_group_refs.append(vim_object_ref1)
            vim_port_group_refs.append(vim_object_ref2)
            ext_net.remove(vim_pg_ref)
            ext_net.append(vim_port_group_refs)
        else:
            vim_port_group_refs = \
                ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRefs']
            vim_object_ref1 = self.__create_vimobj_ref(vc_href,
                                                       pg_moref_types[0],
                                                       pg_moref_types[1])
            vim_port_group_refs.append(vim_object_ref1)

        return self.client. \
            put_linked_resource(ext_net, rel=RelationType.EDIT,
                                media_type=EntityType.
                                EXTERNAL_NETWORK.value,
                                contents=ext_net)
Пример #15
0
    def attach_port_group(self, vim_server_name, port_group_name):
        """Attach a portgroup to an external network.

        :param str vc_name: name of vc where portgroup is present.
        :param str pg_name: name of the portgroup to be attached to
             external network.

        return: object containing vmext:VMWExternalNetwork XML element that
             representing the external network.
        :rtype: lxml.objectify.ObjectifiedElement
        """
        ext_net = self.get_resource()
        platform = Platform(self.client)

        if not vim_server_name or not port_group_name:
            raise InvalidParameterException(
                "Either vCenter Server name is none or portgroup name is none")

        vc_record = platform.get_vcenter(vim_server_name)
        vc_href = vc_record.get('href')
        pg_moref_types = \
            platform.get_port_group_moref_types(vim_server_name,
                                                port_group_name)

        if hasattr(ext_net, '{' + NSMAP['vmext'] + '}VimPortGroupRef'):
            vim_port_group_refs = E_VMEXT.VimPortGroupRefs()
            vim_object_ref1 = self.__create_vimobj_ref(
                vc_href, pg_moref_types[0], pg_moref_types[1])

            # Create a new VimObjectRef using vc href, portgroup moref and type
            # from existing VimPortGroupRef. Add the VimObjectRef to
            # VimPortGroupRefs and then delete VimPortGroupRef
            # from external network.
            vim_pg_ref = ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRef']
            vc2_href = vim_pg_ref.VimServerRef.get('href')
            vim_object_ref2 = self.__create_vimobj_ref(
                vc2_href, vim_pg_ref.MoRef.text, vim_pg_ref.VimObjectType.text)

            vim_port_group_refs.append(vim_object_ref1)
            vim_port_group_refs.append(vim_object_ref2)
            ext_net.remove(vim_pg_ref)
            ext_net.append(vim_port_group_refs)
        else:
            vim_port_group_refs = \
                ext_net['{' + NSMAP['vmext'] + '}VimPortGroupRefs']
            vim_object_ref1 = self.__create_vimobj_ref(
                vc_href, pg_moref_types[0], pg_moref_types[1])
            vim_port_group_refs.append(vim_object_ref1)

        return self.client. \
            put_linked_resource(ext_net, rel=RelationType.EDIT,
                                media_type=EntityType.
                                EXTERNAL_NETWORK.value,
                                contents=ext_net)
Пример #16
0
    def test_0050_enable_vc(self):
        """Platform.enable_vcenter enables a vcenter.

        Wait for async command to complete before checking result.
        """
        platform = Platform(TestVC._client)

        task = platform.enable_disable_vcenter(
            vc_name=TestVC._vcServerName, enable_flag=True)
        TestVC._client.get_task_monitor().wait_for_success(task=task)
        vc = platform.get_vcenter(name=TestVC._vcServerName)
        self.assertTrue(vc.IsEnabled)
Пример #17
0
    def test_0050_enable_vc(self):
        """Platform.enable_vcenter enables a vcenter.

        Wait for async command to complete before checking result.
        """
        platform = Platform(TestVC._client)

        task = platform.enable_disable_vcenter(vc_name=TestVC._vcServerName,
                                               enable_flag=True)
        TestVC._client.get_task_monitor().wait_for_success(task=task)
        vc = platform.get_vcenter(name=TestVC._vcServerName)
        self.assertTrue(vc.IsEnabled)
def get_vsphere(config, vapp, vm_name, logger=None):
    """Get the VSphere object for a specific VM inside a VApp.

    :param dict config: CSE config as a dictionary
    :param pyvcloud.vcd.vapp.VApp vapp: VApp used to get the VM ID.
    :param str vm_name:
    :param logging.Logger logger: optional logger to log with.

    :return: VSphere object for a specific VM inside a VApp

    :rtype: vsphere_guest_run.vsphere.VSphere
    """
    global cache

    # get vm id from vm resource
    vm_id = vapp.get_vm(vm_name).get('id')
    if vm_id not in cache:
        client = Client(uri=config['vcd']['host'],
                        api_version=config['vcd']['api_version'],
                        verify_ssl_certs=config['vcd']['verify'],
                        log_headers=True,
                        log_bodies=True)
        credentials = BasicLoginCredentials(config['vcd']['username'],
                                            SYSTEM_ORG_NAME,
                                            config['vcd']['password'])
        client.set_credentials(credentials)

        # must recreate vapp, or cluster creation fails
        vapp = VApp(client, href=vapp.href)
        vm_resource = vapp.get_vm(vm_name)
        vm_sys = VM(client, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(client)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'port': vcenter_url.port
        }
        for vc in config['vcs']:
            if vc['name'] == vcenter_name:
                cache_item['username'] = vc['username']
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item

    if logger:
        logger.debug(f"VM ID: {vm_id}, Hostname: {cache[vm_id]['hostname']}")

    return VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                   cache[vm_id]['password'], cache[vm_id]['port'])
def get_vsphere(config, vapp, vm_name):
    """Get the VSphere object for a specific VM inside a VApp.

    :param dict config: CSE config as a dictionary
    :param pyvcloud.vcd.vapp.VApp vapp:
    :param str vm_name:

    :return: VSphere object for a specific VM inside a VApp

    :rtype: vsphere_guest_run.vsphere.VSphere
    """
    global cache
    vm_resource = vapp.get_vm(vm_name)
    vm_id = vm_resource.get('id')
    if vm_id not in cache:
        client = Client(uri=config['vcd']['host'],
                        api_version=config['vcd']['api_version'],
                        verify_ssl_certs=config['vcd']['verify'],
                        log_headers=True,
                        log_bodies=True)
        credentials = BasicLoginCredentials(config['vcd']['username'],
                                            SYSTEM_ORG_NAME,
                                            config['vcd']['password'])
        client.set_credentials(credentials)

        vm_sys = VM(client, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(client)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'port': vcenter_url.port
        }
        for vc in config['vcs']:
            if vc['name'] == vcenter_name:
                cache_item['username'] = vc['username']
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item
    else:
        LOGGER.debug(f"vCenter retrieved from cache\nVM ID: {vm_id}"
                     f"\nHostname: {cache[vm_id]['hostname']}")

    return VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                   cache[vm_id]['password'], cache[vm_id]['port'])
def get_vsphere(sys_admin_client, vapp, vm_name, logger=NULL_LOGGER):
    """Get the VSphere object for a specific VM inside a VApp.

    :param pyvcloud.vcd.client.Client sys_admin_client:
    :param pyvcloud.vcd.vapp.VApp vapp: VApp used to get the VM ID.
    :param str vm_name:
    :param logging.Logger logger: logger to log with.

    :return: VSphere object for a specific VM inside a VApp

    :rtype: vsphere_guest_run.vsphere.VSphere
    """
    global cache
    global vsphere_list

    # get vm id from vm resource
    vm_id = vapp.get_vm(vm_name).get('id')
    if vm_id not in cache:
        # recreate vapp with sys admin client
        vapp = VApp(sys_admin_client, href=vapp.href)
        vm_resource = vapp.get_vm(vm_name)
        vm_sys = VM(sys_admin_client, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(sys_admin_client)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'port': vcenter_url.port
        }
        if not vsphere_list:
            raise Exception("Global list of vSphere info not set.")

        for vc in vsphere_list:
            if vc['name'] == vcenter_name:
                cache_item['username'] = vc['username']
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item

    logger.debug(f"VM ID: {vm_id}, Hostname: {cache[vm_id]['hostname']}")

    return VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                   cache[vm_id]['password'], cache[vm_id]['port'])
Пример #21
0
    def detach_port_group(self, vim_server_name, port_group_name):
        """Detach a portgroup from an external network.

        :param str vim_server_name: name of vim server where
        portgroup is present.
        :param str port_group_name: name of the portgroup to be detached from
             external network.

        return: object containing vmext:VMWExternalNetwork XML element that
             representing the external network.
        :rtype: lxml.objectify.ObjectifiedElement
        """
        ext_net = self.get_resource()
        platform = Platform(self.client)

        if not vim_server_name or not port_group_name:
            raise InvalidParameterException(
                "Either vCenter Server name is none or portgroup name is none")

        vc_record = platform.get_vcenter(vim_server_name)
        vc_href = vc_record.get('href')
        if hasattr(ext_net, 'VimPortGroupRefs'):
            pg_moref_types = \
                platform.get_port_group_moref_types(vim_server_name,
                                                    port_group_name)
        else:
            raise \
                InvalidParameterException("External network"
                                          " has only one port group")

        vim_port_group_refs = ext_net.VimPortGroupRefs
        vim_obj_refs = vim_port_group_refs.VimObjectRef
        for vim_obj_ref in vim_obj_refs:
            if vim_obj_ref.VimServerRef.get('href') == vc_href \
                    and vim_obj_ref.MoRef == pg_moref_types[0] \
                    and vim_obj_ref.VimObjectType == pg_moref_types[1]:
                vim_port_group_refs.remove(vim_obj_ref)

        return self.client. \
            put_linked_resource(ext_net, rel=RelationType.EDIT,
                                media_type=EntityType.
                                EXTERNAL_NETWORK.value,
                                contents=ext_net)
Пример #22
0
    def detach_port_group(self, vim_server_name, port_group_name):
        """Detach a portgroup from an external network.

        :param str vim_server_name: name of vim server where
        portgroup is present.
        :param str port_group_name: name of the portgroup to be detached from
             external network.

        return: object containing vmext:VMWExternalNetwork XML element that
             representing the external network.
        :rtype: lxml.objectify.ObjectifiedElement
        """
        ext_net = self.get_resource()
        platform = Platform(self.client)

        if not vim_server_name or not port_group_name:
            raise InvalidParameterException(
                "Either vCenter Server name is none or portgroup name is none")

        vc_record = platform.get_vcenter(vim_server_name)
        vc_href = vc_record.get('href')
        if hasattr(ext_net, 'VimPortGroupRefs'):
            pg_moref_types = \
                platform.get_port_group_moref_types(vim_server_name,
                                                    port_group_name)
        else:
            raise \
                InvalidParameterException("External network"
                                          " has only one port group")

        vim_port_group_refs = ext_net.VimPortGroupRefs
        vim_obj_refs = vim_port_group_refs.VimObjectRef
        for vim_obj_ref in vim_obj_refs:
            if vim_obj_ref.VimServerRef.get('href') == vc_href \
                    and vim_obj_ref.MoRef == pg_moref_types[0] \
                    and vim_obj_ref.VimObjectType == pg_moref_types[1]:
                vim_port_group_refs.remove(vim_obj_ref)

        return self.client. \
            put_linked_resource(ext_net, rel=RelationType.EDIT,
                                media_type=EntityType.
                                EXTERNAL_NETWORK.value,
                                contents=ext_net)
Пример #23
0
def get_vsphere(config, vapp, vm_name):
    global cache
    vm_resource = vapp.get_vm(vm_name)
    vm_id = vm_resource.get('id')
    if vm_id not in cache:
        client_sysadmin = Client(uri=config['vcd']['host'],
                                 api_version=config['vcd']['api_version'],
                                 verify_ssl_certs=config['vcd']['verify'],
                                 log_headers=True,
                                 log_bodies=True)
        client_sysadmin.set_credentials(
            BasicLoginCredentials(config['vcd']['username'], 'System',
                                  config['vcd']['password']))

        vapp_sys = VApp(client_sysadmin, href=vapp.href)
        vm_resource = vapp_sys.get_vm(vm_name)
        vm_sys = VM(client_sysadmin, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(client_sysadmin)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'username': vcenter.Username.text,
            'port': vcenter_url.port
        }
        for vc in config['vcs']:
            if vc['name'] == vcenter_name:
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item
    else:
        LOGGER.debug('vCenter retrieved from cache: %s / %s' %
                     (vm_id, cache[vm_id]['hostname']))

    v = VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                cache[vm_id]['password'], cache[vm_id]['port'])

    return v
Пример #24
0
def validate_vcd_and_vcs_config(vcd_dict, vcs):
    """Ensures that 'vcd' and vcs' section of config are correct.

    Checks that 'vcd' and 'vcs' section of config have correct keys and value
    types. Also checks that vCD and all registered VCs in vCD are accessible.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :param list vcs: 'vcs' section of config file as a list of dicts.

    :raises KeyError: if @vcd_dict or a vc in @vcs has missing or
        extra properties.
    :raises: ValueError: if the value type for a @vcd_dict or vc property
        is incorrect, or if vCD has a VC that is not listed in the config file.
    """
    check_keys_and_value_types(vcd_dict,
                               SAMPLE_VCD_CONFIG['vcd'],
                               location="config file 'vcd' section")
    if not vcd_dict['verify']:
        click.secho(
            'InsecureRequestWarning: Unverified HTTPS request is '
            'being made. Adding certificate verification is '
            'strongly advised.',
            fg='yellow',
            err=True)
        requests.packages.urllib3.disable_warnings()

    client = None
    try:
        client = Client(vcd_dict['host'],
                        api_version=vcd_dict['api_version'],
                        verify_ssl_certs=vcd_dict['verify'])
        client.set_credentials(
            BasicLoginCredentials(vcd_dict['username'], SYSTEM_ORG_NAME,
                                  vcd_dict['password']))
        click.secho(
            f"Connected to vCloud Director "
            f"({vcd_dict['host']}:{vcd_dict['port']})",
            fg='green')

        for index, vc in enumerate(vcs, 1):
            check_keys_and_value_types(vc,
                                       SAMPLE_VCS_CONFIG['vcs'][0],
                                       location=f"config file 'vcs' section, "
                                       f"vc #{index}")

        # Check that all registered VCs in vCD are listed in config file
        platform = Platform(client)
        config_vc_names = [vc['name'] for vc in vcs]
        for platform_vc in platform.list_vcenters():
            platform_vc_name = platform_vc.get('name')
            if platform_vc_name not in config_vc_names:
                raise ValueError(f"vCenter '{platform_vc_name}' registered in "
                                 f"vCD but not found in config file")

        # Check that all VCs listed in config file are registered in vCD
        for vc in vcs:
            vcenter = platform.get_vcenter(vc['name'])
            vsphere_url = urlparse(vcenter.Url.text)
            v = VSphere(vsphere_url.hostname, vc['username'], vc['password'],
                        vsphere_url.port)
            v.connect()
            click.secho(
                f"Connected to vCenter Server '{vc['name']}' as "
                f"'{vc['username']}' ({vsphere_url.hostname}:"
                f"{vsphere_url.port})",
                fg='green')
    finally:
        if client is not None:
            client.logout()
def _validate_vcd_and_vcs_config(vcd_dict, vcs, msg_update_callback=None):
    """Ensure that 'vcd' and vcs' section of config are correct.

    Checks that 'vcd' and 'vcs' section of config have correct keys and value
    types. Also checks that vCD and all registered VCs in vCD are accessible.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :param list vcs: 'vcs' section of config file as a list of dicts.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object
        that writes messages onto console.

    :raises KeyError: if @vcd_dict or a vc in @vcs has missing or
        extra properties.
    :raises TypeError: if the value type for a @vcd_dict or vc property
        is incorrect.
    :raises ValueError: if vCD has a VC that is not listed in the config file.
    """
    check_keys_and_value_types(vcd_dict,
                               SAMPLE_VCD_CONFIG['vcd'],
                               location="config file 'vcd' section",
                               msg_update_callback=msg_update_callback)
    if not vcd_dict['verify']:
        if msg_update_callback:
            msg_update_callback.general(
                'InsecureRequestWarning: Unverified HTTPS request is '
                'being made. Adding certificate verification is '
                'strongly advised.')
        requests.packages.urllib3.disable_warnings()

    client = None
    try:
        # TODO() we get an error during client initialization if the specified
        # logfile points to the directory which doesn't exist. This issue
        # should be fixed in pyvcloud, where the logging setup creates
        # directories used in the log filepath if they do not exist yet.
        setup_log_file_directory()
        client = Client(vcd_dict['host'],
                        api_version=vcd_dict['api_version'],
                        verify_ssl_certs=vcd_dict['verify'],
                        log_file=SERVER_DEBUG_WIRELOG_FILEPATH,
                        log_requests=True,
                        log_headers=True,
                        log_bodies=True)
        client.set_credentials(
            BasicLoginCredentials(vcd_dict['username'], SYSTEM_ORG_NAME,
                                  vcd_dict['password']))
        if msg_update_callback:
            msg_update_callback.general(
                "Connected to vCloud Director "
                f"({vcd_dict['host']}:{vcd_dict['port']})")

        for index, vc in enumerate(vcs, 1):
            check_keys_and_value_types(
                vc,
                SAMPLE_VCS_CONFIG['vcs'][0],
                location=f"config file 'vcs' section, vc #{index}",
                msg_update_callback=msg_update_callback)

        # Check that all registered VCs in vCD are listed in config file
        platform = Platform(client)
        config_vc_names = [vc['name'] for vc in vcs]
        for platform_vc in platform.list_vcenters():
            platform_vc_name = platform_vc.get('name')
            if platform_vc_name not in config_vc_names:
                raise ValueError(f"vCenter '{platform_vc_name}' registered in "
                                 f"vCD but not found in config file")

        # Check that all VCs listed in config file are registered in vCD
        for vc in vcs:
            vcenter = platform.get_vcenter(vc['name'])
            vsphere_url = urlparse(vcenter.Url.text)
            v = VSphere(vsphere_url.hostname, vc['username'], vc['password'],
                        vsphere_url.port)
            v.connect()
            if msg_update_callback:
                msg_update_callback.general(
                    f"Connected to vCenter Server '{vc['name']}' as "
                    f"'{vc['username']}' ({vsphere_url.hostname}:"
                    f"{vsphere_url.port})")
    finally:
        if client is not None:
            client.logout()
Пример #26
0
def check_config(config_file_name, template=None):
    click.secho('Validating CSE on vCD from file: %s' % config_file_name)
    if sys.version_info.major >= 3 and sys.version_info.minor >= 6:
        python_valid = True
    else:
        python_valid = False
    click.echo('Python version >= 3.6 (installed: %s.%s.%s): %s' %
               (sys.version_info.major, sys.version_info.minor,
                sys.version_info.micro, bool_to_msg(python_valid)))
    if not python_valid:
        raise Exception('Python version not supported')
    config = get_config(config_file_name)
    validate_broker_config_elements(config['broker'])
    amqp = config['amqp']
    credentials = pika.PlainCredentials(amqp['username'], amqp['password'])
    parameters = pika.ConnectionParameters(amqp['host'],
                                           amqp['port'],
                                           '/',
                                           credentials,
                                           ssl=amqp['ssl'])
    connection = pika.BlockingConnection(parameters)
    click.echo('Connected to AMQP server (%s:%s): %s' %
               (amqp['host'], amqp['port'], bool_to_msg(connection.is_open)))
    connection.close()

    if not config['vcd']['verify']:
        click.secho(
            'InsecureRequestWarning: '
            'Unverified HTTPS request is being made. '
            'Adding certificate verification is strongly '
            'advised.',
            fg='yellow',
            err=True)
        requests.packages.urllib3.disable_warnings()
    client = Client(config['vcd']['host'],
                    api_version=config['vcd']['api_version'],
                    verify_ssl_certs=config['vcd']['verify'],
                    log_file='cse-check.log',
                    log_headers=True,
                    log_bodies=True)
    client.set_credentials(
        BasicLoginCredentials(config['vcd']['username'], 'System',
                              config['vcd']['password']))
    click.echo(
        'Connected to vCloud Director as system '
        'administrator (%s:%s): %s' %
        (config['vcd']['host'], config['vcd']['port'], bool_to_msg(True)))
    platform = Platform(client)
    for vc in platform.list_vcenters():
        found = False
        for config_vc in config['vcs']:
            if vc.get('name') == config_vc.get('name'):
                found = True
                break
        if not found:
            raise Exception('vCenter \'%s\' defined in vCloud Director '
                            'but not in CSE config file' % vc.get('name'))
            return None

    for vc in config['vcs']:
        vcenter = platform.get_vcenter(vc['name'])
        vsphere_url = urlparse(vcenter.Url.text)
        v = VSphere(vsphere_url.hostname, vcenter.Username.text,
                    vc['password'], vsphere_url.port)
        v.connect()
        click.echo('Connected to vCenter Server %s as %s '
                   '(%s:%s): %s' %
                   (vc['name'], vcenter.Username.text, vsphere_url.hostname,
                    vsphere_url.port, bool_to_msg(True)))

    if template is None:
        pass
    else:
        click.secho('Validating \'%s\' service broker' %
                    config['broker']['type'])
        if config['broker']['type'] == 'default':
            validate_broker_config_content(config, client, template)

    return config
Пример #27
0
 def test_0002_get_vc(self):
     platform = Platform(self.client)
     vcenter = platform.get_vcenter(self.config['vcd']['vcenter'])
     self.logger.debug('vCenter: name=%s, url=%s' %
                       (vcenter.get('name'), vcenter.Url.text))
     assert vcenter is not None
def _validate_vcd_and_vcs_config(
        vcd_dict,
        vcs,
        msg_update_callback=NullPrinter(),
        log_file=None,
        log_wire=False
):
    """Ensure that 'vcd' and vcs' section of config are correct.

    Checks that
        * 'vcd' and 'vcs' section of config have correct keys and value types.
        * vCD and all registered VCs in vCD are accessible.
        * api version specified for vcd is supported by CSE.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :param list vcs: 'vcs' section of config file as a list of dicts.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object.
    :param str log_file: log_file for pyvcloud wire log.
    :param bool log_wire: If pyvcloud requests should be logged.

    :raises KeyError: if @vcd_dict or a vc in @vcs has missing or
        extra properties.
    :raises TypeError: if the value type for a @vcd_dict or vc property
        is incorrect.
    :raises ValueError: if vCD has a VC that is not listed in the config file.
    """
    check_keys_and_value_types(vcd_dict, SAMPLE_VCD_CONFIG['vcd'],
                               location="config file 'vcd' section",
                               msg_update_callback=msg_update_callback)
    if not vcd_dict['verify']:
        msg_update_callback.general(
            'InsecureRequestWarning: Unverified HTTPS request is '
            'being made. Adding certificate verification is '
            'strongly advised.'
        )
        requests.packages.urllib3.disable_warnings()

    client = None
    try:
        _validate_vcd_url_scheme(vcd_dict['host'])
        client = Client(
            vcd_dict['host'],
            verify_ssl_certs=vcd_dict['verify'],
            log_file=log_file,
            log_requests=log_wire,
            log_headers=log_wire,
            log_bodies=log_wire
        )
        client.set_credentials(
            BasicLoginCredentials(
                vcd_dict['username'],
                SYSTEM_ORG_NAME,
                vcd_dict['password']
            )
        )
        msg_update_callback.general(
            "Connected to vCloud Director "
            f"({vcd_dict['host']}:{vcd_dict['port']})"
        )

        for index, vc in enumerate(vcs, 1):
            check_keys_and_value_types(
                vc,
                SAMPLE_VCS_CONFIG['vcs'][0],
                location=f"config file 'vcs' section, vc #{index}",
                msg_update_callback=msg_update_callback
            )

        # Check that all registered VCs in vCD are listed in config file
        platform = Platform(client)
        config_vc_names = [vc['name'] for vc in vcs]
        for platform_vc in platform.list_vcenters():
            platform_vc_name = platform_vc.get('name')
            if platform_vc_name not in config_vc_names:
                raise ValueError(
                    f"vCenter '{platform_vc_name}' registered in "
                    "vCD but not found in config file"
                )

        # Check that all VCs listed in config file are registered in vCD
        for vc in vcs:
            vcenter = platform.get_vcenter(vc['name'])
            if not (hasattr(vcenter, 'IsConnected') and vcenter.IsConnected):
                msg = f"vCenter Server '{vc['name']}' not available"
                msg_update_callback.info(msg)
                continue
            vsphere_url = urlparse(vcenter.Url.text)
            vsphere_url_port = vsphere_url.port
            if vsphere_url_port:
                v = VSphere(
                    vsphere_url.hostname,
                    vc['username'],
                    vc['password'],
                    vsphere_url.port
                )
            else:
                v = VSphere(
                    vsphere_url.hostname,
                    vc['username'],
                    vc['password']
                )
            v.connect()
            msg = f"Connected to vCenter Server '{vc['name']}' as " \
                f"'{vc['username']}' ({vsphere_url.hostname}"
            if vsphere_url_port:
                msg += f":{vsphere_url.port}"
            msg += ")"
            msg_update_callback.general(msg)
    finally:
        if client is not None:
            client.logout()
Пример #29
0
 def test_0002_get_vc(self):
     platform = Platform(self.client)
     vcenter = platform.get_vcenter(self.config['vcd']['vcenter'])
     self.logger.debug('vCenter: name=%s, url=%s' %
                       (vcenter.get('name'), vcenter.Url.text))
     assert vcenter is not None