コード例 #1
0
    def delete(self, name):
        """Delete static route from vApp network.

        :param str name: name of static route.
        :return: an object containing EntityType.TASK XML data which represents
            the asynchronous task that is updating the vApp network.
        :rtype: lxml.objectify.ObjectifiedElement
        :raises: InvalidParameterException:  Delete route to static route
            service failed as given network's connection is not routed
        :raises: EntityNotFoundException: if the static route not exist of
            given name.
        """
        self._get_resource()
        fence_mode = self.resource.Configuration.FenceMode
        if fence_mode != 'natRouted':
            raise InvalidParameterException(
                "Delete route to static route service failed as given "
                "network's connection is not routed")
        features = self.resource.Configuration.Features
        if not hasattr(features, 'StaticRoutingService'):
            raise EntityNotFoundException('static route ' + name +
                                          ' doesn\'t exist.')
        route_service = features.StaticRoutingService
        is_deleted = False
        for route in route_service.StaticRoute:
            if route.Name == name:
                route_service.remove(route)
                is_deleted = True
        if not is_deleted:
            raise EntityNotFoundException('static route ' + name +
                                          ' doesn\'t exist.')
        else:
            return self.client.put_linked_resource(
                self.resource, RelationType.EDIT,
                EntityType.vApp_Network.value, self.resource)
コード例 #2
0
    def delete_nat_rule(self, id):
        """Delete NAT rules from vApp network.

        :param str id: id of NAT rule.
        :return: an object containing EntityType.TASK XML data which represents
            the asynchronous task that is updating the vApp network.
        :rtype: lxml.objectify.ObjectifiedElement
        :raises: InvalidParameterException: Enable NAT service failed as
            given network's connection is not routed
        :raises: EntityNotFoundException: if the NAT rule not exist of give id.
        """
        list_of_nat_rules = []
        self._get_resource()
        fence_mode = self.resource.Configuration.FenceMode
        if fence_mode != 'natRouted':
            raise InvalidParameterException(
                "Enable NAT service failed as given network's connection "
                "is not routed")
        features = self.resource.Configuration.Features
        if not hasattr(features, 'NatService'):
            return list_of_nat_rules
        nat_service = features.NatService
        is_deleted = False
        for nat_rule in nat_service.NatRule:
            if nat_rule.Id == int(id):
                nat_service.remove(nat_rule)
                is_deleted = True
        if not is_deleted:
            raise EntityNotFoundException('NAT rule ' + id +
                                          ' doesn\'t exist.')
        else:
            return self.client.put_linked_resource(
                self.resource, RelationType.EDIT,
                EntityType.vApp_Network.value, self.resource)
コード例 #3
0
    def get_available_portgroup_name(self, vim_server_name, portgroupType):
        """Fetches portgroup name using portgroup type(DV_PORTGROUP or NETWORK).

        Query uses vCenter Server name as filter and returns the first available
        portgroup

        :param str vim_server_name: vCenter server name
        :param str portgroupType: type of port group
        :return: name of the portgroup
        :rtype: str
        :raises: EntityNotFoundException: if any port group cannot be found.
        """
        name_filter = ('vcName', vim_server_name)
        query = self.client.get_typed_query(
            ResourceType.PORT_GROUP.value,
            query_result_format=QueryResultFormat.RECORDS,
            equality_filter=name_filter)
        pgroup_name = ''
        for record in list(query.execute()):
            if record.get('networkName') == '--':
                if record.get('portgroupType') == portgroupType  \
                   and not record.get('name').startswith('vxw-'):
                    pgroup_name = record.get('name')
                    break
        if not pgroup_name:
            raise EntityNotFoundException('port group not found in'
                                          'vCenter : ' + vim_server_name)

        return pgroup_name
コード例 #4
0
    def delete_disk(self):
        vm = self.get_vm()
        disks = self.params.get('disks')
        disks_to_remove = [disk.get("name") for disk in disks]
        response = dict()
        response['changed'] = False

        disks = self.client.get_resource(
            vm.resource.get('href') + '/virtualHardwareSection/disks')

        for disk in disks.Item:
            if disk['{' + NSMAP['rasd'] + '}ElementName'] in disks_to_remove:
                disks.remove(disk)
                disks_to_remove.remove(disk['{' + NSMAP['rasd'] +
                                            '}ElementName'])

        if len(disks_to_remove) > 0:
            error = 'VM disk(s) with name {0} was not found.'
            error = error.format(','.join(disks_to_remove))
            raise EntityNotFoundException(error)

        remove_disk_task = self.client.put_resource(
            vm.resource.get('href') + '/virtualHardwareSection/disks', disks,
            EntityType.RASD_ITEMS_LIST.value)
        self.execute_task(remove_disk_task)
        response['msg'] = 'VM disk(s) has been deleted.'
        response['changed'] = True

        return response
コード例 #5
0
    def get_vdc_compute_policy(self, policy_name, is_placement_policy=False):
        """Get CSE created VDC compute policy by name.

        :param str policy_name: name of the compute policy
        :param boolean is_placement_policy: True if the VDC compute policy is a
            VDC placement policy

        :return: dictionary containing policy details
        :rtype: dict
        :raises: EntityNotFoundException: if compute policy is not found
        """
        # NOTE If multiple policies with the same name exist, this function
        # returns the first found.
        # 'System Default' is the only case where multiple compute
        # policies with the same name may exist.
        self._raise_error_if_not_supported()
        filters = \
            {
                # CSE created policy will have a prefix
                'name': policy_name,
                'isSizingOnly': str(not is_placement_policy).lower()
            }
        for policy_dict in self.get_all_vdc_compute_policies(filters=filters):
            if policy_dict.get('name') == policy_name:
                policy_dict['href'] = self._get_policy_href(policy_dict['id'])
                return policy_dict

        raise EntityNotFoundException(f"Compute policy '{policy_name}'"
                                      f" does not exist.")
コード例 #6
0
    def update_vapp_network(self, network_name, new_net_name, new_net_desc):
        """Update a vApp network.

        :param str network_name: name of vApp network to be updated.
        :param str new_net_name: name of vApp network to be updated.
        :param str new_net_desc: description of vApp network to be updated.
        :return: an object containing EntityType.TASK XML data which represents
            the asynchronous task that is updating the vApp network.
        :rtype: lxml.objectify.ObjectifiedElement
        """
        # find the required network
        for network_config in self.resource.NetworkConfigSection.NetworkConfig:
            if network_config.get("networkName") == network_name:
                if new_net_name:
                    network_config.set('networkName', new_net_name)
                if new_net_desc:
                    if hasattr(network_config, 'Description'):
                        network_config.Description = E.Description(
                            new_net_desc)
                    else:
                        network_config.insert(0, E.Description(new_net_desc))
                return self.client.put_linked_resource(
                    self.resource.NetworkConfigSection, RelationType.EDIT,
                    EntityType.NETWORK_CONFIG_SECTION.value,
                    self.resource.NetworkConfigSection)
        raise EntityNotFoundException('Can\'t find network \'%s\'' %
                                      network_name)
コード例 #7
0
ファイル: platform.py プロジェクト: jondwaite/pyvcloud
    def get_vxlan_network_pool(self, vxlan_network_pool_name):
        """[Deprecated] Fetch a vxlan_network_pool by its name.

        :param str vxlan_network_pool_name: name of the vxlan_network_pool.

        :return: an object containing NetworkPoolRecord XML element which
            represents a vxlan_network_pool.

        :rtype: lxml.objectify.ObjectifiedElement

        :raises: EntityNotFoundException: If the named vxlan_network_pool
            cannot be found.
        """
        name_filter = ('name', vxlan_network_pool_name)
        query = self.client.get_typed_query(
            ResourceType.NETWORK_POOL,
            query_result_format=QueryResultFormat.RECORDS,
            equality_filter=name_filter)
        records = list(query.execute())
        vxlan_network_pool_record = None
        for record in records:
            if vxlan_network_pool_name == record.get('name'):
                vxlan_network_pool_record = record
                break
        if vxlan_network_pool_record is not None:
            return vxlan_network_pool_record
        raise EntityNotFoundException('vxlan_network_pool \'%s\' not found' %
                                      vxlan_network_pool_name)
コード例 #8
0
ファイル: platform.py プロジェクト: hodgesrm/pyvcloud
    def get_resource_pool_morefs(self, vc_name, vc_href, resource_pool_names):
        """Fetch list of morefs for a given list of resource_pool_names.

        :param str vc_name: vim_server name.
        :param str vc_href: vim_server href.
        :param list resource_pool_names: resource pool names as a list of
            strings.

        :return: morefs of resource pools.

        :rtype: list

        :raises: EntityNotFoundException: if any resource_pool_name cannot be
            found.
        """
        morefs = []
        resource_pool_list = self.client.get_resource(vc_href +
                                                      '/resourcePoolList')
        if hasattr(resource_pool_list, 'ResourcePool'):
            for resource_pool_name in resource_pool_names:
                res_pool_found = False
                for resource_pool in resource_pool_list.ResourcePool:
                    if resource_pool.DataStoreRefs.VimObjectRef.VimServerRef.\
                       get('name') == vc_name:  # rp belongs to VC
                        name = resource_pool.get('name')
                        moref = resource_pool.MoRef.text
                        if name == resource_pool_name:
                            morefs.append(moref)
                            res_pool_found = True
                            break
                if not res_pool_found:
                    raise EntityNotFoundException(
                        'resource pool \'%s\' not Found' % resource_pool_name)
        return morefs
コード例 #9
0
    def update_nic(self):
        vm = self.get_vm()
        nic_id = self.params.get('nic_id')
        network = self.params.get('network')
        response = dict()
        response['changed'] = False

        nics = self.client.get_resource(vm.resource.get('href') + '/networkConnectionSection')
        index = -1

        for i, nic in enumerate(nics.NetworkConnection):
            if nic.NetworkConnectionIndex == nic_id:
                index = i

        if index < 0:
            EntityNotFoundException('Can\'t find the specified VM nic')

        if network:
            nics.NetworkConnection[index].set('network', network)
            response['changed'] = True

        if response['changed']:
            update_nic_task = self.client.put_resource(
                vm.resource.get('href') + '/networkConnectionSection', nics,
                EntityType.NETWORK_CONNECTION_SECTION.value)
            self.execute_task(update_nic_task)
            response['msg'] = 'Vapp VM nic has been updated.'

        return response
コード例 #10
0
def get_vdc(client,
            vdc_name,
            org=None,
            org_name=None,
            is_admin_operation=False):
    """Get the specified VDC object.

    :param pyvcloud.vcd.client.Client client:
    :param str vdc_name:
    :param pyvcloud.vcd.org.Org org: specific org to use.
    :param str org_name: specific org to use if @org is not given.
        If None, uses currently logged-in org from @client.
    :param bool is_admin_operation: if set True, will return the admin
            view of the org vdc resource.

    :return: pyvcloud VDC object

    :rtype: pyvcloud.vcd.vdc.VDC

    :raises EntityNotFoundException: if the vdc could not be found.
    """
    if org is None:
        org = get_org(client, org_name=org_name)
    resource = org.get_vdc(vdc_name, is_admin_operation=is_admin_operation)
    # TODO() org.get_vdc() should throw exception if vdc not found in the org.
    # This should be handled in pyvcloud. For now, it is handled here.
    if resource is None:
        raise EntityNotFoundException(f"VDC '{vdc_name}' not found")
    vdc = VDC(client, resource=resource)
    return vdc
コード例 #11
0
    def delete_nic(self):
        vm = self.get_vm()
        nic_ids = self.params.get('nic_ids')
        response = defaultdict(dict)
        response['changed'] = False
        uri = vm.resource.get('href') + '/networkConnectionSection'

        nics = self.get_vm_nics()
        for nic in nics.NetworkConnection:
            if nic.NetworkConnectionIndex in nic_ids:
                nics.remove(nic)
                nic_ids.remove(nic.NetworkConnectionIndex)

        if len(nic_ids) > 0:
            nic_ids = [str(nic_id) for nic_id in nic_ids]
            err_msg = 'Can\'t find the specified VM nic(s) {0}'.format(
                ','.join(nic_ids))
            raise EntityNotFoundException(err_msg)

        remove_nic_task = self.client.put_resource(
            uri, nics, EntityType.NETWORK_CONNECTION_SECTION.value)
        self.execute_task(remove_nic_task)
        response['msg'] = 'VM nic(s) has been deleted.'
        response['changed'] = True

        return response
コード例 #12
0
    def share_catalog(cls):
        """Shares the test catalog with all members in the test organization.

        :return: Nothing

        :raises: Exception: if the class variable _org_href is not populated.
        :raises: EntityNotFoundException: if the catalog in question is
            missing.
        """
        cls._basic_check()
        if cls._org_href is None:
            raise Exception('Org ' + cls._config['vcd']['default_org_name'] +
                            ' doesn\'t exist.')

        org = Org(cls._sys_admin_client, href=cls._org_href)
        catalog_name = cls._config['vcd']['default_catalog_name']
        catalog_records = org.list_catalogs()
        for catalog_record in catalog_records:
            if catalog_record.get('name').lower() == catalog_name.lower():
                cls._logger.debug('Sharing catalog ' + catalog_name +
                                  ' to all members of org ' + org.get_name())
                org.share_catalog_with_org_members(catalog_name=catalog_name)
                return

        raise EntityNotFoundException('Catalog ' + catalog_name + 'doesn\'t'
                                      'exists.')
コード例 #13
0
    def get_gateway(self, gateway_name):
        gateway = self.vdc.get_gateway(gateway_name)
        if gateway is None:
            raise EntityNotFoundException(
                "Edge gateway {0} is not present".format(gateway_name))

        return gateway
コード例 #14
0
    def get_pvdc_compute_policy(self, policy_name):
        """Get the CSE created PVDC compute policy by name.

        Note: This function can only be used to fetch PVDC compute policies
            created by CSE.

        :param str policy_name: name of the pvdc compute policy

        :return pvdc compute policy details
        :rtype: dict
        :raises: EntityNotFoundException if pvdc compute policy is not found
        """
        # NOTE if multiple pvdc compute policy exists, this function returns
        # the first one found.
        self._raise_error_if_not_supported()
        # CSE created policy will have a prefix
        filters = {'name': self._get_cse_policy_name(policy_name)}
        for policy_dict in self.get_all_pvdc_compute_policies(filters=filters):
            if policy_dict.get('display_name') == policy_name:
                policy_dict['href'] = self._get_policy_href(
                    policy_dict['id'],
                    is_pvdc_compute_policy=True)  # noqa: E501
                return policy_dict

        raise EntityNotFoundException(f"Compute policy '{policy_name}'"
                                      f" does not exist.")
コード例 #15
0
ファイル: platform.py プロジェクト: jondwaite/pyvcloud
    def get_resource_pool_morefs(self, vc_href, resource_pool_names):
        """Fetch list of morefs for a given list of resource_pool_names.

        :param str vc_href: vim_server href.
        :param list resource_pool_names: resource pool names as a list of
            strings.

        :return: morefs of resource pools.

        :rtype: list

        :raises: EntityNotFoundException: if any resource_pool_name cannot be
            found.
        """
        morefs = []
        vc_resource = self.client.get_resource(vc_href)
        resource_pool_list = self.client.get_linked_resource(
            resource=vc_resource,
            rel=RelationType.DOWN,
            media_type=EntityType.RESOURCE_POOL_LIST.value)
        if hasattr(resource_pool_list, 'ResourcePool'):
            for resource_pool_name in resource_pool_names:
                res_pool_found = False
                for resource_pool in resource_pool_list.ResourcePool:
                    name = resource_pool.get('name')
                    moref = resource_pool.MoRef.text
                    if name == resource_pool_name:
                        morefs.append(moref)
                        res_pool_found = True
                        break
                if not res_pool_found:
                    raise EntityNotFoundException(
                        'resource pool \'%s\' not Found' % resource_pool_name)
        return morefs
コード例 #16
0
ファイル: client.py プロジェクト: anusuyar/pyvcloud
    def get_user_in_org(self, user_name, org_href):
        """Retrieve user from a particular org.

        :param user_name: user name to be retrieved.
        :param org_href: org where the user belongs.

        :return:  A :class:`lxml.objectify.StringElement` object
            representing the user
        """
        resource_type = 'user'
        org_filter = None
        if self.is_sysadmin():
            resource_type = 'adminUser'
            org_filter = 'org==%s' % org_href
        query = self.get_typed_query(
            resource_type,
            query_result_format=QueryResultFormat.REFERENCES,
            equality_filter=('name', user_name),
            qfilter=org_filter)
        records = list(query.execute())
        if len(records) == 0:
            raise EntityNotFoundException('user \'%s\' not found' % user_name)
        elif len(records) > 1:
            raise MultipleRecordsException('multiple users found')
        return self.get_resource(records[0].get('href'))
コード例 #17
0
ファイル: org.py プロジェクト: anusuyar/pyvcloud
    def update_catalog(self, old_catalog_name, new_catalog_name, description):
        """Update the name and/or description of a catalog.

        :param old_catalog_name: (str): The current name of the catalog.
        :param new_catalog_name: (str): The new name of the catalog.
        :param description: (str): The new description of the catalog.
        :return:  A :class:`lxml.objectify.StringElement` object describing
            the updated catalog.
        """
        if self.resource is None:
            self.resource = self.client.get_resource(self.href)
        org = self.resource
        links = get_links(
            org, rel=RelationType.DOWN, media_type=EntityType.CATALOG.value)
        for link in links:
            if old_catalog_name == link.name:
                catalog = self.client.get_resource(link.href)
                href = catalog.get('href')
                admin_href = href.replace('/api/catalog/',
                                          '/api/admin/catalog/')
                admin_view_of_catalog = self.client.get_resource(admin_href)
                if new_catalog_name is not None:
                    admin_view_of_catalog.set('name', new_catalog_name)
                if description is not None:
                    admin_view_of_catalog['Description'] = E.Description(
                        description)
                return self.client.put_resource(
                    admin_href,
                    admin_view_of_catalog,
                    media_type=EntityType.ADMIN_CATALOG.value)
        raise EntityNotFoundException('Catalog not found.')
コード例 #18
0
ファイル: platform.py プロジェクト: jondwaite/pyvcloud
    def get_ref_by_name(self, resource_type, resource_name):
        """Fetch a reference to a resource by its name.

        :param pyvcloud.vcd.client.ResourceType resource_type: type of the
            resource.
        :param str resource_name: name of the resource.

        :return: an object containing sub-type of
            QueryResultFormat.REFERENCES XML data representing a reference to
            the resource.

        :rtype: lxml.objectify.ObjectifiedElement

        :raises: EntityNotFoundException: if the named resource cannot be
            found.
        """
        name_filter = ('name', resource_name)
        record = self.client.get_typed_query(
            resource_type.value,
            query_result_format=QueryResultFormat.REFERENCES,
            equality_filter=name_filter).find_unique()
        if resource_name == record.get('name'):
            return record
        else:
            raise EntityNotFoundException(
                'resource: \'%s\' name: \'%s\' not found' %
                resource_type.value, resource_name)
コード例 #19
0
ファイル: platform.py プロジェクト: dev-dom/pyvcloud
    def get_port_group_morefs(self, port_group_names):
        """Fetches moref and type for a given list of port group names.

        :return: list of tuples containing port group moref and type.

        :rtype: list

        :raises: EntityNotFoundException: if any port group names cannot be
            found.
        """
        query = self.client.get_typed_query(
            ResourceType.PORT_GROUP.value,
            query_result_format=QueryResultFormat.RECORDS)
        records = list(query.execute())
        port_groups = {}
        for record in records:
            port_groups[record.get('name')] = ((record.get('moref'),
                                                record.get('portgroupType')))
        port_group_morefs = []
        for port_group_name in port_group_names:
            port_group_found = False
            if port_group_name in port_groups:
                    port_group_found = True
                    port_group_morefs.append(port_groups[port_group_name])
            if not port_group_found:
                raise EntityNotFoundException(
                    'port group \'%s\' not Found' % port_group_name)
        return port_group_morefs
コード例 #20
0
ファイル: platform.py プロジェクト: vyankteshyadav/pyvcloud
    def list_available_port_group_names(self, vim_server_name):
        """Fetches the list of portgroup name in a particular vCenter.

        :return: list of available portgroup name. ex- VM Network

        :rtype: list

        :raises: EntityNotFoundException: if any port group name cannot be
        found.
        """
        vcfilter = 'vcName==%s' % urllib.parse.quote_plus(vim_server_name)
        query = self.client.get_typed_query(
            ResourceType.PORT_GROUP.value,
            qfilter=vcfilter,
            query_result_format=QueryResultFormat.RECORDS)
        records = list(query.execute())

        port_group_names = [
            record.get('name') for record in records
            if (record.get('networkName') == '--'
                and not record.get('name').startswith('vxw-'))
        ]
        if not port_group_names:
            raise EntityNotFoundException('No port group name found')
        return port_group_names
コード例 #21
0
ファイル: platform.py プロジェクト: dev-dom/pyvcloud
    def get_port_group_moref_types(self, vim_server_name, port_group_name):
        """Fetches portgroup moref and portgroup type(DV_PORTGROUP or NETWORK).

        Using portgroup name in particular vCenter.

        :return: list of tuples containing port group moref and type.

        :rtype: list

        :raises: EntityNotFoundException: if any port group name cannot be
        found.
        """
        vcfilter = 'vcName==%s' % urllib.parse.quote_plus(vim_server_name)
        query = self.client.get_typed_query(
            ResourceType.PORT_GROUP.value,
            qfilter=vcfilter,
            query_result_format=QueryResultFormat.RECORDS)
        records = list(query.execute())

        port_group_moref_types = []
        for record in records:
            if record.get('name') == port_group_name:
                port_group_moref_types.append(record.get('moref'))
                port_group_moref_types.append(record.get('portgroupType'))
                break
        if not port_group_moref_types:
            raise EntityNotFoundException(
                'port group \'%s\' not Found' % port_group_name)
        return port_group_moref_types
コード例 #22
0
ファイル: environment.py プロジェクト: relent0r/pyvcloud
    def share_catalog(cls):
        """Shares the test catalog with all members in the test organization.

        :raises: Exception: if the class variable _org_href is not populated.
        :raises: EntityNotFoundException: if the catalog in question is
            missing.
        """
        cls._basic_check()
        if cls._org_href is None:
            raise Exception('Org ' + cls._config['vcd']['default_org_name'] +
                            ' doesn\'t exist.')

        try:
            catalog_author_client = Environment.get_client_in_default_org(
                CommonRoles.CATALOG_AUTHOR)
            org = Org(catalog_author_client, href=cls._org_href)
            catalog_name = cls._config['vcd']['default_catalog_name']
            catalog_records = org.list_catalogs()
            for catalog_record in catalog_records:
                if catalog_record.get('name') == catalog_name:
                    cls._logger.debug('Sharing catalog ' + catalog_name + ' to'
                                      ' all members of org ' + org.get_name())
                    org.share_catalog_with_org_members(
                        catalog_name=catalog_name)
                    return
            raise EntityNotFoundException('Catalog ' + catalog_name +
                                          'doesn\'t exist.')
        finally:
            catalog_author_client.logout()
コード例 #23
0
    def add_network(self):
        network_name = self.params.get('network')
        fence_mode = self.params.get('fence_mode')
        parent_network = self.params.get('parent_network')
        ip_scope = self.params.get('ip_scope')

        response = dict()
        response['changed'] = False

        try:
            self.get_network()
        except EntityNotFoundException:
            network_config_section = self.vapp.resource.NetworkConfigSection
            config = E.Configuration()
            if parent_network:
                vdc = self.params.get('vdc')
                org_resource = Org(self.client, resource=self.client.get_org())
                vdc_resource = VDC(self.client,
                                   resource=org_resource.get_vdc(vdc))
                orgvdc_networks = vdc_resource.list_orgvdc_network_resources(
                    parent_network)
                parent = next((network for network in orgvdc_networks
                               if network.get('name') == parent_network), None)
                if parent:
                    config.append(E.ParentNetwork(href=parent.get('href')))
                else:
                    raise EntityNotFoundException(
                        'Parent network \'%s\' does not exist'.format(
                            parent_network))
            elif ip_scope:
                scope = E.IpScope(
                    E.IsInherited('false'),
                    E.Gateway(
                        str(
                            ip_network(ip_scope, strict=False).network_address
                            + 1)),
                    E.Netmask(str(ip_network(ip_scope, strict=False).netmask)))
                config.append(E.IpScopes(scope))
            else:
                raise VappNetworkCreateError(
                    'Either parent_network or ip_scope must be set')
            config.append(E.FenceMode(fence_mode))

            network_config = E.NetworkConfig(config, networkName=network_name)
            network_config_section.append(network_config)

            add_network_task = self.client.put_linked_resource(
                self.vapp.resource.NetworkConfigSection, RelationType.EDIT,
                EntityType.NETWORK_CONFIG_SECTION.value,
                network_config_section)
            self.execute_task(add_network_task)
            response['msg'] = 'Vapp Network {} has been added'.format(
                network_name)
            response['changed'] = True
        else:
            response[
                'warnings'] = 'Vapp Network {} is already present.'.format(
                    network_name)

        return response
コード例 #24
0
 def get_network(self):
     network_name = self.params.get('network')
     networks = self.vapp.get_all_networks()
     for network in networks:
         if network.get('{' + NSMAP['ovf'] + '}name') == network_name:
             return network
     raise EntityNotFoundException('Can\'t find the specified vApp network')
コード例 #25
0
ファイル: platform.py プロジェクト: vyankteshyadav/pyvcloud
    def pvdc_del_storage_profile(self, pvdc_name, storage_profile_names):
        """Delete storage profiles from a PVDC.

        :param str pvdc_name: name of the Provider Virtual Datacenter.
        :param list storage_profile_names: list of storage profile names.

        :return: an object containing EntityType.TASK XML data which represents
            the async task that is deleting storage profiles from the PVDC.

        :rtype: lxml.objectify.ObjectifiedElement

        :raises: EntityNotFoundException: if any storage_profile_name is not
            associated with the specified PVDC.
        """
        provider_vdc, pvdc_ext_href, pvdc_ext_resource = self.get_pvdc(
            pvdc_name)
        sp_map = {}
        if hasattr(pvdc_ext_resource,
                   '{' + NSMAP['vcloud'] + '}StorageProfiles'):
            stor_profs = \
                pvdc_ext_resource['{' + NSMAP['vcloud'] + '}StorageProfiles']
            if hasattr(stor_profs,
                       '{' + NSMAP['vcloud'] + '}ProviderVdcStorageProfile'):
                for stor_prof in stor_profs.ProviderVdcStorageProfile:
                    sp_map[stor_prof.get('name')] = stor_prof.get('href')
        payload = E_VMEXT.UpdateProviderVdcStorageProfiles()
        for sp_name in storage_profile_names:
            if sp_name not in sp_map.keys():
                raise EntityNotFoundException(
                    'storage profile: \'%s\' not in this PVDC' % sp_name)
            sp_href = sp_map[sp_name]
            payload.append(E_VMEXT.RemoveStorageProfile(href=sp_href))
            sp_resource = self.client.get_resource(sp_href)
            links = get_links(
                resource=sp_resource,
                rel=RelationType.EDIT,
                media_type=EntityType.VMW_PVDC_STORAGE_PROFILE.value)
            num_links = len(links)
            if num_links == 1:
                if hasattr(sp_resource, '{' + NSMAP['vcloud'] + '}Units'):
                    units = \
                        sp_resource['{' + NSMAP['vcloud'] + '}Units']
                    disable_payload = \
                        E_VMEXT.VMWProviderVdcStorageProfile(
                            name=sp_name,
                            href=sp_href
                        )
                    disable_payload.append(E.Enabled('false'))
                    disable_payload.append(units)
                    self.client.put_linked_resource(
                        resource=sp_resource,
                        rel=RelationType.EDIT,
                        media_type=EntityType.VMW_PVDC_STORAGE_PROFILE.value,
                        contents=disable_payload)
        return self.client.post_linked_resource(
            resource=pvdc_ext_resource,
            rel=RelationType.EDIT,
            media_type=EntityType.UPDATE_PROVIDER_VDC_STORAGE_PROFILES.value,
            contents=payload)
コード例 #26
0
    def connect_org_vdc_network(self,
                                orgvdc_network_name,
                                retain_ip=None,
                                is_deployed=None,
                                fence_mode=FenceMode.BRIDGED.value):
        """Connect the vapp to an orgvdc network.

        :param orgvdc_network_name: (str): name of the orgvdc network to be
            connected
        :param retain_ip: (bool): True if  the network resources such as
            IP/MAC of router will be retained across deployments.
        :param is_deployed: (bool): True if this orgvdc network has been
            deployed.
        :param fence_mode: (str): Controls connectivity to the parent
            network. One of bridged, isolated or natRouted. bridged by default.

        :return:  A :class:`lxml.objectify.StringElement` object representing
            the asynchronous task that is connecting the network.

        :raises: Exception: If orgvdc network does not exist in the vdc or if
        it is already connected to the vapp.
        """
        vdc = VDC(self.client,
                  href=find_link(self.resource, RelationType.UP,
                                 EntityType.VDC.value).href)
        orgvdc_networks = \
            vdc.list_orgvdc_network_resources(orgvdc_network_name)
        if len(orgvdc_networks) == 0:
            raise EntityNotFoundException(
                "Orgvdc network \'%s\' does not exist in vdc "
                "\'%s\'" %
                (orgvdc_network_name, vdc.get_resource().get('name')))
        orgvdc_network_href = orgvdc_networks[0].get('href')

        network_configuration_section = \
            deepcopy(self.resource.NetworkConfigSection)

        matched_orgvdc_network_config = \
            self._search_for_network_config_by_name(
                orgvdc_network_name, network_configuration_section)
        if matched_orgvdc_network_config is not None:
            raise InvalidStateException(
                "Orgvdc network \'%s\' is already connected to "
                "vapp." % orgvdc_network_name)

        configuration = E.Configuration(
            E.ParentNetwork(href=orgvdc_network_href), E.FenceMode(fence_mode))
        if retain_ip is not None:
            configuration.append(E.RetainNetInfoAcrossDeployments(retain_ip))
        network_config = E.NetworkConfig(configuration,
                                         networkName=orgvdc_network_name)
        if is_deployed is not None:
            network_config.append(E.IsDeployed(is_deployed))
        network_configuration_section.append(network_config)

        return self.client.put_linked_resource(
            self.resource.NetworkConfigSection, RelationType.EDIT,
            EntityType.NETWORK_CONFIG_SECTION.value,
            network_configuration_section)
コード例 #27
0
    def get_gateway(self, gateway_name):
        gateway = self.vdc.get_gateway(gateway_name)
        if gateway is None:
            msg = "Gateway {0} not found".format(gateway_name)
            raise EntityNotFoundException(msg)

        extra_args = {"name": gateway_name, "href": gateway.get("href")}
        return Gateway(self.client, **extra_args)
コード例 #28
0
    def create_vapp(self,
                    name,
                    description=None,
                    network=None,
                    fence_mode=FenceMode.BRIDGED.value,
                    accept_all_eulas=None):
        """Create a new vApp in this vdc.

        :param name: (str) Name of the new vApp.
        :param description: (str) Description of the new vApp.
        :param network: (str) Name of the OrgVDC network the vApp will
            connect to.
        :param fence_mode: (str): Network fence mode.
            Possible values are `bridged` and `natRouted`
        :param accept_all_eulas: (bool): True confirms acceptance of all EULAs
            in a vApp template.
        :return:  A :class:`lxml.objectify.StringElement` object representing a
            sparsely populated vApp element in the target vdc.
        """
        if self.resource is None:
            self.resource = self.client.get_resource(self.href)

        network_href = network_name = None
        if network is not None:
            if hasattr(self.resource, 'AvailableNetworks') and \
               hasattr(self.resource.AvailableNetworks, 'Network'):
                for n in self.resource.AvailableNetworks.Network:
                    if network == n.get('name'):
                        network_href = n.get('href')
                        network_name = n.get('name')
                        break
            if network_href is None:
                raise EntityNotFoundException(
                    'Network \'%s\' not found in the Virtual Datacenter.' %
                    network)

        vapp_instantiation_param = None
        if network_name is not None:
            network_configuration = E.Configuration(
                E.ParentNetwork(href=network_href), E.FenceMode(fence_mode))

            vapp_instantiation_param = E.InstantiationParams(
                E.NetworkConfigSection(
                    E_OVF.Info('Configuration for logical networks'),
                    E.NetworkConfig(network_configuration,
                                    networkName=network_name)))

        params = E.ComposeVAppParams(name=name)
        if description is not None:
            params.append(E.Description(description))
        if vapp_instantiation_param is not None:
            params.append(vapp_instantiation_param)
        if accept_all_eulas is not None:
            params.append(E.AllEULAsAccepted(accept_all_eulas))

        return self.client.post_linked_resource(
            self.resource, RelationType.ADD,
            EntityType.COMPOSE_VAPP_PARAMS.value, params)
コード例 #29
0
    def get_gateway(self, gateway_name):
        gateway = self.vdc.get_gateway(gateway_name)
        if gateway is not None:
            for key, value in gateway.items():
                if key == "href":
                    return Gateway(self.client, name=gateway_name, href=value)

        msg = "Edge gateway {0} is not present"
        raise EntityNotFoundException(msg.format(gateway_name))
コード例 #30
0
ファイル: external_network.py プロジェクト: triqster/pyvcloud
 def __execute_gateway_query_api(self, filter=None):
     query = self.client.get_typed_query(
         ResourceType.EDGE_GATEWAY.value,
         query_result_format=QueryResultFormat.RECORDS,
         qfilter=filter)
     query_records = query.execute()
     if query_records is None:
         raise EntityNotFoundException('No Gateway found associated')
     return query_records