def org_to_dict(org): """Convert a lxml.objectify.ObjectifiedElement org object to a dict. :param lxml.objectify.ObjectifiedElement org: an object containing EntityType.ORG or EntityType.ADMIN_ORG XML data. :return: dictionary representation of the org. :rtype: dict """ result = {} result['name'] = org.get('name') result['id'] = extract_id(org.get('id')) result['full_name'] = str('%s' % org.FullName) result['description'] = str('%s' % org.Description) result['vdcs'] = [ str(n.name) for n in get_links(org, media_type=EntityType.VDC.value) ] result['org_networks'] = [ str(n.name) for n in get_links(org, media_type=EntityType.ORG_NETWORK.value) ] result['catalogs'] = [ str(n.name) for n in get_links(org, media_type=EntityType.CATALOG.value) ] return result
def org_to_dict_vdc_catalog(org, result): if org.client.get_api_version() < ApiVersion.VERSION_33.value: vdc_links = get_links(org, media_type=EntityType.VDC.value) catalog_links = get_links(org, media_type=EntityType.CATALOG.value) else: vdc_links = org.client.get_resource_link_from_query_object( org, media_type=EntityType.RECORDS.value, type='vdc') catalog_links = org.client.get_resource_link_from_query_object( org, media_type=EntityType.RECORDS.value, type='catalog') result['vdcs'] = [str(n.name) for n in vdc_links] result['catalogs'] = [str(n.name) for n in catalog_links]
def org_to_dict(org): result = {} result['name'] = org.get('name') result['id'] = extract_id(org.get('id')) result['full_name'] = str('%s' % org.FullName) result['description'] = str('%s' % org.Description) result['vdcs'] = [str(n.name) for n in get_links(org, media_type=EntityType.VDC.value)] result['org_networks'] = [str(n.name) for n in get_links(org, media_type=EntityType. ORG_NETWORK.value)] result['catalogs'] = [str(n.name) for n in get_links(org, media_type=EntityType.CATALOG.value)] return result
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] org_resource = client.get_org_by_name(name) in_use_vdc = '' vdc_href = '' in_use_vapp = '' vapp_href = '' for link in get_links(org_resource, media_type=EntityType.VDC.value): in_use_vdc = link.name vdc_href = link.href break ctx.obj['profiles'].set('org_in_use', str(name)) ctx.obj['profiles'].set('org_href', str(org_resource.get('href'))) ctx.obj['profiles'].set('vdc_in_use', str(in_use_vdc)) ctx.obj['profiles'].set('vdc_href', str(vdc_href)) ctx.obj['profiles'].set('vapp_in_use', str(in_use_vapp)) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp: \'%s\'.' \ % (name, in_use_vdc, in_use_vapp) stdout({ 'org': name, 'vdc': in_use_vdc, 'vapp': in_use_vapp }, ctx, message) except Exception as e: stderr(e, ctx)
def list_vdcs(self): if self.resource is None: self.resource = self.client.get_resource(self.href) result = [] for v in get_links(self.resource, media_type=EntityType.VDC.value): result.append({'name': v.name, 'href': v.href}) return result
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 Exception('Catalog not found.')
def list_vdcs(self): if self.org_resource is None: self.org_resource = self.client.get_resource(self.endpoint) result = [] for v in get_links(self.org_resource, media_type=EntityType.VDC.value): result.append({'name': v.name, 'href': v.href}) return result
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] org = client.get_org_by_name(name) resource = client.get_resource(org.get('href')) in_use_vdc = '' vdc_href = '' in_use_vapp = '' vapp_href = '' for v in get_links(resource, media_type=EntityType.VDC.value): in_use_vdc = v.name vdc_href = v.href break ctx.obj['profiles'].set('org_in_use', str(name)) ctx.obj['profiles'].set('org_href', str(org.get('href'))) ctx.obj['profiles'].set('vdc_in_use', str(in_use_vdc)) ctx.obj['profiles'].set('vdc_href', str(vdc_href)) ctx.obj['profiles'].set('vapp_in_use', str(in_use_vapp)) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp: \'%s\'.' \ % (name, in_use_vdc, in_use_vapp) stdout({ 'org': name, 'vdc': in_use_vdc, 'vapp': in_use_vapp }, ctx, message) except Exception as e: stderr(e, ctx)
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 Exception('Catalog not found.')
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') orgs = client.get_org_list() for org_resource in orgs: if org_resource.get('name').lower() == in_use_org_name.lower(): for link in get_links(org_resource, media_type=EntityType.VDC.value): if link.name == name: vdc_in_use = name vapp_in_use = '' vapp_href = '' client.get_resource(link.href) ctx.obj['profiles'].set('vdc_in_use', vdc_in_use) ctx.obj['profiles'].set('vdc_href', str(link.href)) ctx.obj['profiles'].set('vapp_in_use', vapp_in_use) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp:' \ ' \'%s\'.' % (in_use_org_name, vdc_in_use, vapp_in_use) stdout( { 'org': in_use_org_name, 'vdc': vdc_in_use, 'vapp': vapp_in_use }, ctx, message) return raise Exception('Org \'%s\' not found' % in_use_org_name) except Exception as e: stderr(e, ctx)
def list_vdc(ctx): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') in_use_vdc = ctx.obj['profiles'].get('vdc_in_use') orgs = client.get_org_list() result = [] for org_resouce in orgs: if org_resouce.get('name').lower() == in_use_org_name.lower(): if client.get_api_version() < ApiVersion.VERSION_33.value: links = get_links(org_resouce, media_type=EntityType.VDC.value) else: links = client.get_resource_link_from_query_object( org_resouce, media_type=EntityType.RECORDS.value, type='vdc') for link in links: result.append({ 'name': link.name, 'org': org_resouce.get('name'), 'in_use': in_use_vdc == link.name }) break stdout(result, ctx) except Exception as e: stderr(e, ctx)
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') orgs = client.get_org_list() for org_resource in orgs: if org_resource.get('name').lower() == in_use_org_name.lower(): for link in get_links(org_resource, media_type=EntityType.VDC.value): if link.name == name: vdc_in_use = name vapp_in_use = '' vapp_href = '' client.get_resource(link.href) ctx.obj['profiles'].set('vdc_in_use', vdc_in_use) ctx.obj['profiles'].set('vdc_href', str(link.href)) ctx.obj['profiles'].set('vapp_in_use', vapp_in_use) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp:' \ ' \'%s\'.' % (in_use_org_name, vdc_in_use, vapp_in_use) stdout({ 'org': in_use_org_name, 'vdc': vdc_in_use, 'vapp': vapp_in_use }, ctx, message) return raise Exception('Org \'%s\' not found' % in_use_org_name) except Exception as e: stderr(e, ctx)
def use(ctx, name): try: client = ctx.obj['client'] orgs = client.get_org_list() for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]: if name == org.get('name'): resource = client.get_resource(org.get('href')) in_use_vdc = '' vdc_href = '' in_use_vapp = '' vapp_href = '' for v in get_links(resource, media_type=EntityType.VDC.value): in_use_vdc = v.name vdc_href = v.href break ctx.obj['profiles'].set('org_in_use', str(name)) ctx.obj['profiles'].set('org_href', str(org.get('href'))) ctx.obj['profiles'].set('vdc_in_use', str(in_use_vdc)) ctx.obj['profiles'].set('vdc_href', str(vdc_href)) ctx.obj['profiles'].set('vapp_in_use', str(in_use_vapp)) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp: \'%s\'.' \ % (name, in_use_vdc, in_use_vapp) stdout({ 'org': name, 'vdc': in_use_vdc, 'vapp': in_use_vapp }, ctx, message) return raise Exception('not found') except Exception as e: stderr(e, ctx)
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] org_resource = client.get_org_by_name(name) in_use_vdc = '' vdc_href = '' in_use_vapp = '' vapp_href = '' links = [] if client.get_api_version() < ApiVersion.VERSION_33.value: links = get_links(org_resource, media_type=EntityType.VDC.value) else: links = client.get_resource_link_from_query_object( org_resource, media_type=EntityType.RECORDS.value, type='vdc') for link in links: in_use_vdc = link.name vdc_href = link.href break ctx.obj['profiles'].set('org_in_use', str(name)) ctx.obj['profiles'].set('org_href', str(org_resource.get('href'))) ctx.obj['profiles'].set('vdc_in_use', str(in_use_vdc)) ctx.obj['profiles'].set('vdc_href', str(vdc_href)) ctx.obj['profiles'].set('vapp_in_use', str(in_use_vapp)) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp: \'%s\'.' \ % (name, in_use_vdc, in_use_vapp) stdout({ 'org': name, 'vdc': in_use_vdc, 'vapp': in_use_vapp }, ctx, message) except Exception as e: stderr(e, ctx)
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') orgs = client.get_org_list() for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]: if org.get('name') == in_use_org_name: resource = client.get_resource(org.get('href')) for v in get_links(resource, media_type=EntityType.VDC.value): if v.name == name: vdc_in_use = name vapp_in_use = '' vapp_href = '' client.get_resource(v.href) ctx.obj['profiles'].set('vdc_in_use', vdc_in_use) ctx.obj['profiles'].set('vdc_href', str(v.href)) ctx.obj['profiles'].set('vapp_in_use', vapp_in_use) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp:' \ ' \'%s\'.' % (in_use_org_name, vdc_in_use, vapp_in_use) stdout( { 'org': in_use_org_name, 'vdc': vdc_in_use, 'vapp': vapp_in_use }, ctx, message) return raise Exception('not found') except Exception as e: stderr(e, ctx)
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)
def org_to_dict(org): result = {} result['name'] = org.get('name') result['id'] = extract_id(org.get('id')) result['full_name'] = str('%s' % org.FullName) result['description'] = str('%s' % org.Description) result['vdcs'] = [ str(n.name) for n in get_links(org, media_type=EntityType.VDC.value) ] result['org_networks'] = [ str(n.name) for n in get_links(org, media_type=EntityType.ORG_NETWORK.value) ] result['catalogs'] = [ str(n.name) for n in get_links(org, media_type=EntityType.CATALOG.value) ] return result
def get_catalog(self, name): org = self.client.get_resource(self.endpoint) links = get_links(org, rel=RelationType.DOWN, media_type=EntityType.CATALOG.value) for link in links: if name == link.name: return self.client.get_resource(link.href) raise Exception('Catalog not found.')
def get_vdc(self, name): if self.org_resource is None: self.org_resource = self.client.get_resource(self.endpoint) links = get_links(self.org_resource, rel=RelationType.DOWN, media_type=EntityType.VDC.value) for link in links: if name == link.name: return self.client.get_resource(link.href)
def get_vdc(self, name): if self.resource is None: self.resource = self.client.get_resource(self.href) links = get_links(self.resource, rel=RelationType.DOWN, media_type=EntityType.VDC.value) for link in links: if name == link.name: return self.client.get_resource(link.href) raise Exception("Vdc \'%s\' not found" % name)
def delete_catalog(self, name): org = self.client.get_resource(self.href) links = get_links( org, rel=RelationType.DOWN, media_type=EntityType.CATALOG.value) for link in links: if name == link.name: admin_href = link.href.replace('/api/catalog/', '/api/admin/catalog/') return self.client.delete_resource(admin_href) raise Exception('Catalog not found.')
def get_vdc(self, name): if self.resource is None: self.resource = self.client.get_resource(self.href) links = get_links( self.resource, rel=RelationType.DOWN, media_type=EntityType.VDC.value) for link in links: if name == link.name: return self.client.get_resource(link.href) raise Exception("Vdc \'%s\' not found" % name)
def get_catalog_resource(self, name, is_admin_operation=False): org = self.client.get_resource(self.href) links = get_links( org, rel=RelationType.DOWN, media_type=EntityType.CATALOG.value) for link in links: if name == link.name: href = link.href if is_admin_operation: href = href.replace('/api/catalog/', '/api/admin/catalog/') return self.client.get_resource(href) raise Exception('Catalog not found (or)' ' Access to resource is forbidden')
def list_vdc(ctx): try: client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') in_use_vdc = ctx.obj['profiles'].get('vdc_in_use') orgs = client.get_org_list() result = [] for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]: if org.get('name') == in_use_org_name: resource = client.get_resource(org.get('href')) for v in get_links(resource, media_type=EntityType.VDC.value): result.append({ 'name': v.name, 'org': in_use_org_name, 'in_use': in_use_vdc == v.name }) break stdout(result, ctx) except Exception as e: stderr(e, ctx)
def list_vdc(ctx): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') in_use_vdc = ctx.obj['profiles'].get('vdc_in_use') orgs = client.get_org_list() result = [] for org_resouce in orgs: if org_resouce.get('name').lower() == in_use_org_name.lower(): for link in get_links(org_resouce, media_type=EntityType.VDC.value): result.append({ 'name': link.name, 'org': org_resouce.get('name'), 'in_use': in_use_vdc == link.name }) break stdout(result, ctx) except Exception as e: stderr(e, ctx)
def use(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') orgs = client.get_org_list() for org_resource in orgs: if org_resource.get('name').lower() == in_use_org_name.lower(): if client.get_api_version() < ApiVersion.VERSION_33.value: links = get_links(org_resource, media_type=EntityType.VDC.value) else: links = client.get_resource_link_from_query_object( org_resource, media_type=EntityType.RECORDS.value, type='vdc') for link in links: if link.name == name: vdc_in_use = name vapp_in_use = '' vapp_href = '' client.get_resource(link.href) ctx.obj['profiles'].set('vdc_in_use', vdc_in_use) ctx.obj['profiles'].set('vdc_href', str(link.href)) ctx.obj['profiles'].set('vapp_in_use', vapp_in_use) ctx.obj['profiles'].set('vapp_href', vapp_href) message = 'now using org: \'%s\', vdc: \'%s\', vApp:' \ ' \'%s\'.' % (in_use_org_name, vdc_in_use, vapp_in_use) stdout( { 'org': in_use_org_name, 'vdc': vdc_in_use, 'vapp': vapp_in_use }, ctx, message) return raise Exception('Org Vdc \'%s\' not found in org \'%s\'' % (name, in_use_org_name)) except Exception as e: stderr(e, ctx)
def info(ctx, name): try: client = ctx.obj['client'] in_use_org_name = ctx.obj['profiles'].get('org_in_use') in_use_vdc = ctx.obj['profiles'].get('vdc_in_use') orgs = client.get_org_list() result = {} vdc_resource = None for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]: if org.get('name') == in_use_org_name: resource = client.get_resource(org.get('href')) for v in get_links(resource, media_type=EntityType.VDC.value): if v.name == name: vdc_resource = client.get_resource(v.href) result = vdc_to_dict(vdc_resource) result['in_use'] = in_use_vdc == name result['org'] = in_use_org_name break if vdc_resource is None: raise Exception('not found') stdout(result, ctx) except Exception as e: stderr(e, ctx)
def detach_resource_pools_from_provider_vdc(self, pvdc_name, resource_pool_names): """Disable & Detach Resource Pools from a Provider Virtual Datacenter. This function deletes resource pools (RPs) from a Provider Virtual Datacenter (PVDC). In order to do this, the input "user-friendly" RP names must be translated into RP hrefs. This is a multi-step process. 1) create a dictionary that maps RP names associated w/ this PVDC's backing VC to morefs. 2) create a list of morefs_to_delete, using the dictionary created in step 1 -- filtered by the input set of RP names. 3) create a dictionary that maps RP morefs associated w/ this PVDC to RP hrefs. 4) Use the list of morefs_to_delete (created in step 2) to filter the list of RP hrefs created as a dictionary in step 3 to create the final payload. Note that in order to delete a RP, it must first be disabled. This is done for each RP to be deleted if the disable link is present (which indicates that the RP is enabled). Caveat: The current implementation of this function takes a list of RP "basenames" as input. A basename is the last element of a full pathname. For example, given a pathname /a/b/c, the basename of that pathname is "c". Since RP names are only required to have unique pathnames but not unique basenames, this function may not work correctly if there are non-unique RP basenames. Therefore, in order to use this function, all RP basenames must be unique. It is therefore up to the user of this function to be aware of this limitation and name their RPs appropriately. This limitation will be fixed in a future version of this function. :param str pvdc_name: name of the Provider Virtual Datacenter. :param list resource_pool_names: list of resource pool names. :return: an object containing EntityType.TASK XML data which represents the async task that is deleting Resource Pools from the PVDC. :rtype: lxml.objectify.ObjectifiedElement :raises: EntityNotFoundException: if any resource_pool_name cannot be found. :raises: ValidationError: if primary resource pool is input for deletion. """ provider_vdc, pvdc_ext_href, pvdc_ext_resource = self.get_pvdc( pvdc_name) vc_name = pvdc_ext_resource.VimServer.get('name') # find the RPs in use that are associated with the backing VC name_filter = ('vcName', vc_name) query = self.client.get_typed_query( ResourceType.RESOURCE_POOL.value, query_result_format=QueryResultFormat.RECORDS, equality_filter=name_filter) res_pools_in_use = {} for res_pool in list(query.execute()): res_pools_in_use[res_pool.get('name')] = res_pool.get('moref') morefs_to_delete = [] for resource_pool_name in resource_pool_names: if resource_pool_name in res_pools_in_use.keys(): morefs_to_delete.append(res_pools_in_use[resource_pool_name]) else: raise EntityNotFoundException( 'resource pool \'%s\' not Found' % resource_pool_name) res_pools_in_pvdc = self.client.get_linked_resource( resource=pvdc_ext_resource, rel=RelationType.DOWN, media_type=EntityType.VMW_PROVIDER_VDC_RESOURCE_POOL_SET.value) pvdc_res_pools = {} if hasattr(res_pools_in_pvdc, '{' + NSMAP['vmext'] + '}VMWProviderVdcResourcePool'): for res_pool in res_pools_in_pvdc.VMWProviderVdcResourcePool: pvdc_res_pools[res_pool.ResourcePoolVimObjectRef.MoRef] = \ res_pool res_pool_to_delete_refs = [] for moref in morefs_to_delete: if moref not in pvdc_res_pools.keys(): raise EntityNotFoundException( 'resource pool with moref \'%s\' not Found' % moref) else: res_pool = pvdc_res_pools[moref] if res_pool.get('primary') == 'true': raise ValidationError( 'cannot delete primary respool with moref \'%s\' ' % res_pool.ResourcePoolVimObjectRef.MoRef) else: # disable the RP if it is enabled links = get_links(resource=res_pool, rel=RelationType.DISABLE) num_links = len(links) if num_links == 1: self.client.\ post_linked_resource(resource=res_pool, rel=RelationType.DISABLE, media_type=None, contents=None) res_pool_to_delete_refs.append(res_pool) payload = E_VMEXT.UpdateResourcePoolSetParams() for res_pool_ref in res_pool_to_delete_refs: del_item = E_VMEXT.DeleteItem( href=res_pool_ref.ResourcePoolRef.get('href'), type=EntityType.VMW_PROVIDER_VDC_RESOURCE_POOL.value) payload.append(del_item) return self.client.post_linked_resource( resource=pvdc_ext_resource, rel=RelationType.UPDATE_RESOURCE_POOLS, media_type=EntityType.RES_POOL_SET_UPDATE_PARAMS.value, contents=payload)
def login(ctx, user, host, password, api_version, org, verify_ssl_certs, disable_warnings, vdc, session_id, use_browser_session): """Login to vCloud Director \b Login to a vCloud Director service. \b Examples vcd login mysp.com org1 usr1 Login to host 'mysp.com'. \b vcd login test.mysp.com org1 usr1 -i -w Login to a host with self-signed SSL certificate. \b vcd login mysp.com org1 usr1 --use-browser-session Login using active session from browser. \b vcd login session list chrome List active session ids from browser. \b vcd login mysp.com org1 usr1 \\ --session-id ee968665bf3412d581bbc6192508eec4 Login using active session id. \b Environment Variables VCD_PASSWORD If this environment variable is set, the command will use its value as the password to login and will not ask for one. The --password option has precedence over the environment variable. """ if not verify_ssl_certs: if disable_warnings: pass else: click.secho( 'InsecureRequestWarning: ' 'Unverified HTTPS request is being made. ' 'Adding certificate verification is strongly ' 'advised.', fg='yellow', err=True) requests.packages.urllib3.disable_warnings() if host == 'session' and org == 'list': sessions = [] if user == 'chrome': cookies = browsercookie.chrome() for c in cookies: if c.name == 'vcloud_session_id': sessions.append({'host': c.domain, 'session_id': c.value}) stdout(sessions, ctx) return client = Client( host, api_version=api_version, verify_ssl_certs=verify_ssl_certs, log_file='vcd.log', log_requests=True, log_headers=True, log_bodies=True) try: if api_version is None: api_version = client.set_highest_supported_version() if session_id is not None or use_browser_session: if use_browser_session: browser_session_id = None cookies = browsercookie.chrome() for c in cookies: if c.name == 'vcloud_session_id' and \ c.domain == host: browser_session_id = c.value break if browser_session_id is None: raise Exception('Session not found in browser.') session_id = browser_session_id client.rehydrate_from_token(session_id) else: if password is None: password = click.prompt('Password', hide_input=True, type=str) client.set_credentials(BasicLoginCredentials(user, org, password)) wkep = {} for endpoint in _WellKnownEndpoint: if endpoint in client._session_endpoints: wkep[endpoint.name] = client._session_endpoints[endpoint] profiles = Profiles.load() logged_in_org = client.get_org() org_href = logged_in_org.get('href') vdc_href = '' in_use_vdc = '' if vdc is None: for v in get_links(logged_in_org, media_type=EntityType.VDC.value): in_use_vdc = v.name vdc_href = v.href break else: for v in get_links(logged_in_org, media_type=EntityType.VDC.value): if vdc == v.name: in_use_vdc = v.name vdc_href = v.href break if len(in_use_vdc) == 0: raise Exception('VDC not found') profiles.update( host, org, user, client._session.headers['x-vcloud-authorization'], api_version, wkep, verify_ssl_certs, disable_warnings, vdc=in_use_vdc, org_href=org_href, vdc_href=vdc_href, log_request=True, log_header=True, log_body=True, vapp='', vapp_href='') alt_text = '%s logged in, org: \'%s\', vdc: \'%s\'' % \ (user, org, in_use_vdc) stdout({ 'user': user, 'org': org, 'vdc': in_use_vdc, 'logged_in': True }, ctx, alt_text) except Exception as e: try: profiles = Profiles.load() profiles.set('token', '') except Exception: pass stderr(e, ctx)
def detach_resource_pools_from_provider_vdc(self, pvdc_name, resource_pool_names): """Disable & Detach Resource Pools from a Provider Virtual Datacenter. This function deletes resource pools (RPs) from a Provider Virtual Datacenter (PVDC). In order to do this, the input "user-friendly" RP names must be translated into RP hrefs. This is a multi-step process. 1) create a dictionary that maps RP names associated w/ this PVDC's backing VC to morefs. 2) create a list of morefs_to_delete, using the dictionary created in step 1 -- filtered by the input set of RP names. 3) create a dictionary that maps RP morefs associated w/ this PVDC to RP hrefs. 4) Use the list of morefs_to_delete (created in step 2) to filter the list of RP hrefs created as a dictionary in step 3 to create the final payload. Note that in order to delete a RP, it must first be disabled. This is done for each RP to be deleted if the disable link is present (which indicates that the RP is enabled). Caveat: The current implementation of this function takes a list of RP "basenames" as input. A basename is the last element of a full pathname. For example, given a pathname /a/b/c, the basename of that pathname is "c". Since RP names are only required to have unique pathnames but not unique basenames, this function may not work correctly if there are non-unique RP basenames. Therefore, in order to use this function, all RP basenames must be unique. It is therefore up to the user of this function to be aware of this limitation and name their RPs appropriately. This limitation will be fixed in a future version of this function. :param str pvdc_name: name of the Provider Virtual Datacenter. :param list resource_pool_names: list or resource pool names. :return: an object containing EntityType.TASK XML data which represents the async task that is deleting Resource Pools from the PVDC. :rtype: lxml.objectify.ObjectifiedElement :raises: EntityNotFoundException: if any resource_pool_name cannot be found. :raises: ValidationError: if primary resource pool is input for deletion. """ provider_vdc = self.get_ref_by_name(ResourceType.PROVIDER_VDC, pvdc_name) pvdc_ext_href = get_admin_extension_href(provider_vdc.get('href')) pvdc_ext_resource = self.client.get_resource(pvdc_ext_href) vc_name = pvdc_ext_resource.VimServer.get('name') # find the RPs in use that are associated with the backing VC name_filter = ('vcName', vc_name) query = self.client.get_typed_query( ResourceType.RESOURCE_POOL.value, query_result_format=QueryResultFormat.RECORDS, equality_filter=name_filter) res_pools_in_use = {} for res_pool in list(query.execute()): res_pools_in_use[res_pool.get('name')] = res_pool.get('moref') morefs_to_delete = [] for resource_pool_name in resource_pool_names: if resource_pool_name in res_pools_in_use.keys(): morefs_to_delete.append(res_pools_in_use[resource_pool_name]) else: raise EntityNotFoundException( 'resource pool \'%s\' not Found' % resource_pool_name) res_pools_in_pvdc = self.client.get_linked_resource( resource=pvdc_ext_resource, rel=RelationType.DOWN, media_type=EntityType.VMW_PROVIDER_VDC_RESOURCE_POOL_SET.value) pvdc_res_pools = {} if hasattr(res_pools_in_pvdc, '{' + NSMAP['vmext'] + '}VMWProviderVdcResourcePool'): for res_pool in res_pools_in_pvdc.VMWProviderVdcResourcePool: pvdc_res_pools[res_pool.ResourcePoolVimObjectRef.MoRef] = \ res_pool res_pool_to_delete_refs = [] for moref in morefs_to_delete: if moref not in pvdc_res_pools.keys(): raise EntityNotFoundException( 'resource pool with moref \'%s\' not Found' % moref) else: res_pool = pvdc_res_pools[moref] if res_pool.get('primary') == 'true': raise ValidationError( 'cannot delete primary respool with moref \'%s\' ' % res_pool.ResourcePoolVimObjectRef.MoRef) else: # disable the RP if it is enabled links = get_links(resource=res_pool, rel=RelationType.DISABLE) num_links = len(links) if num_links == 1: self.client.\ post_linked_resource(resource=res_pool, rel=RelationType.DISABLE, media_type=None, contents=None) res_pool_to_delete_refs.append(res_pool) payload = E_VMEXT.UpdateResourcePoolSetParams() for res_pool_ref in res_pool_to_delete_refs: del_item = E_VMEXT.DeleteItem( href=res_pool_ref.ResourcePoolRef.get('href'), type=EntityType.VMW_PROVIDER_VDC_RESOURCE_POOL.value) payload.append(del_item) return self.client.post_linked_resource( resource=pvdc_ext_resource, rel=RelationType.UPDATE_RESOURCE_POOLS, media_type=EntityType.RES_POOL_SET_UPDATE_PARAMS.value, contents=payload)
def login(ctx, user, host, password, api_version, org, verify_ssl_certs, disable_warnings, vdc, session_id, use_browser_session): """Login to vCloud Director \b Login to a vCloud Director service. \b Examples vcd login mysp.com org1 usr1 Login to host 'mysp.com'. \b vcd login test.mysp.com org1 usr1 -i -w Login to a host with self-signed SSL certificate. \b vcd login mysp.com org1 usr1 --use-browser-session Login using active session from browser. \b vcd login session list chrome List active session ids from browser. \b vcd login mysp.com org1 usr1 \\ --session-id ee968665bf3412d581bbc6192508eec4 Login using active session id. \b Environment Variables VCD_PASSWORD If this environment variable is set, the command will use its value as the password to login and will not ask for one. The --password option has precedence over the environment variable. """ if not verify_ssl_certs: if disable_warnings: pass else: click.secho('InsecureRequestWarning: ' 'Unverified HTTPS request is being made. ' 'Adding certificate verification is strongly ' 'advised.', fg='yellow', err=True) requests.packages.urllib3.disable_warnings() if host == 'session' and org == 'list': sessions = [] if user == 'chrome': cookies = browsercookie.chrome() for c in cookies: if c.name == 'vcloud_session_id': sessions.append({'host': c.domain, 'session_id': c.value}) stdout(sessions, ctx) return client = Client(host, api_version=api_version, verify_ssl_certs=verify_ssl_certs, log_file='vcd.log', log_requests=True, log_headers=True, log_bodies=True ) try: if api_version is None: api_version = client.set_highest_supported_version() if session_id is not None or use_browser_session: if use_browser_session: browser_session_id = None cookies = browsercookie.chrome() for c in cookies: if c.name == 'vcloud_session_id' and \ c.domain == host: browser_session_id = c.value break if browser_session_id is None: raise Exception('Session not found in browser.') session_id = browser_session_id client.rehydrate_from_token(session_id) else: if password is None: password = click.prompt('Password', hide_input=True, type=str) client.set_credentials(BasicLoginCredentials(user, org, password)) wkep = {} for endpoint in _WellKnownEndpoint: if endpoint in client._session_endpoints: wkep[endpoint.name] = client._session_endpoints[endpoint] profiles = Profiles.load() logged_in_org = client.get_org() org_href = logged_in_org.get('href') vdc_href = '' in_use_vdc = '' if vdc is None: for v in get_links(logged_in_org, media_type=EntityType.VDC.value): in_use_vdc = v.name vdc_href = v.href break else: for v in get_links(logged_in_org, media_type=EntityType.VDC.value): if vdc == v.name: in_use_vdc = v.name vdc_href = v.href break if len(in_use_vdc) == 0: raise Exception('VDC not found') profiles.update(host, org, user, client._session.headers['x-vcloud-authorization'], api_version, wkep, verify_ssl_certs, disable_warnings, vdc=in_use_vdc, org_href=org_href, vdc_href=vdc_href, log_request=profiles.get('log_request', default=False), log_header=profiles.get('log_header', default=False), log_body=profiles.get('log_body', default=False), vapp='', vapp_href='') alt_text = '%s logged in, org: \'%s\', vdc: \'%s\'' % \ (user, org, in_use_vdc) stdout({'user': user, 'org': org, 'vdc': in_use_vdc, 'logged_in': True}, ctx, alt_text) except Exception as e: try: profiles = Profiles.load() profiles.set('token', '') except Exception: pass stderr(e, ctx)
def login(ctx, user, host, password, api_version, org, verify_ssl_certs, disable_warnings, vdc, session_id, use_browser_session): """Login to vCloud Director \b Login to a vCloud Director service. \b Examples vcd login mysp.com org1 usr1 Login to host 'mysp.com'. \b vcd login test.mysp.com org1 usr1 -i -w Login to a host with self-signed SSL certificate. \b vcd login mysp.com org1 usr1 --use-browser-session Login using active session from browser. \b vcd login session list chrome List active session ids from browser. \b vcd login mysp.com org1 usr1 \\ --session-id ee968665bf3412d581bbc6192508eec4 Login using active session id. \b Environment Variables VCD_PASSWORD If this environment variable is set, the command will use its value as the password to login and will not ask for one. The --password option has precedence over the environment variable. """ if not verify_ssl_certs: if disable_warnings: pass else: click.secho( 'InsecureRequestWarning: ' 'Unverified HTTPS request is being made. ' 'Adding certificate verification is strongly ' 'advised.', fg='yellow', err=True) requests.packages.urllib3.disable_warnings() if host == 'session' and org == 'list': sessions = [] if user == 'chrome': cookies = browsercookie.chrome() for c in cookies: if c.name == 'vcloud_session_id': sessions.append({'host': c.domain, 'session_id': c.value}) stdout(sessions, ctx) return client = Client( host, api_version=api_version, verify_ssl_certs=verify_ssl_certs, log_file='vcd.log', log_requests=True, log_headers=True, log_bodies=True) try: if session_id is not None or use_browser_session: if use_browser_session: browser_session_id = None cookies = browsercookie.chrome() for c in cookies: if c.name == 'vcloud_session_id' and \ c.domain == host: browser_session_id = c.value break if browser_session_id is None: raise Exception('Session not found in browser.') session_id = browser_session_id client.rehydrate_from_token(session_id) else: if password is None: password = click.prompt('Password', hide_input=True, type=str) client.set_credentials(BasicLoginCredentials(user, org, password)) negotiated_api_version = client.get_api_version() profiles = Profiles.load() logged_in_org = client.get_org() org_href = logged_in_org.get('href') vdc_href = '' in_use_vdc = '' links = [] if float(negotiated_api_version) < float(ApiVersion.VERSION_33.value): links = get_links(logged_in_org, media_type=EntityType.VDC.value) else: if logged_in_org.get('name') != 'System': links = client.get_resource_link_from_query_object( logged_in_org, media_type=EntityType.RECORDS.value, type='vdc') if vdc is None: if len(links) > 0: in_use_vdc = links[0].name vdc_href = links[0].href else: for v in links: if vdc == v.name: in_use_vdc = v.name vdc_href = v.href break if len(in_use_vdc) == 0: raise Exception('VDC not found') token = client.get_access_token() is_jwt_token = True if not token: token = client.get_xvcloud_authorization_token() is_jwt_token = False profiles.update( host, org, user, token, negotiated_api_version, verify_ssl_certs, disable_warnings, vdc=in_use_vdc, org_href=org_href, vdc_href=vdc_href, log_request=True, log_header=True, log_body=True, vapp='', vapp_href='', is_jwt_token=is_jwt_token) alt_text = f"{user} logged in, org: '{org}', vdc: '{in_use_vdc}'" d = { 'user': user, 'org': org, 'vdc': in_use_vdc, 'logged_in': True } stdout(d, ctx, alt_text) except Exception as e: try: profiles = Profiles.load() profiles.set('token', '') except Exception: pass stderr(e, ctx)
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)