def validate_types(self, source_types, type): """Validate input param for valid type. :param list source_types: list of value:value_type. e.g., ExtNw:gatewayinterface :param str type: It can be source/destination :raise: InvalidParameterException: exception if input param is not valid. """ if source_types: valid_type_list = [ 'gatewayinterface', 'virtualmachine', 'network', 'ipset', 'securitygroup', 'ip' ] for source_type in source_types: if source_type.lower() == 'any': continue source_type_arr = source_type.split(':') if len(source_type_arr) <= 1: raise InvalidParameterException( type + " type should be in the format of " "value:value_type. for ex: " "ExtNw:gatewayinterface") valid_type = source_type_arr[1] if valid_type not in valid_type_list: valid_type_list_str = ','.join(valid_type_list) raise InvalidParameterException( valid_type + " param is not valid. It should be " "from " + valid_type_list_str)
def set_multiple_metadata(self, key_value_dict, domain=MetadataDomain.GENERAL, visibility=MetadataVisibility.READ_WRITE, metadata_value_type=MetadataValueType.STRING, use_admin_endpoint=False): """Add/update multiple metadata entries to/of the parent object. If an entry with the same key exists, it will be updated with the new value. All entries must have the same value type and will be written to the same domain with identical visibility. :param dict key_value_dict: a dict containing key-value pairs to be added/updated. :param client.MetadataDomain domain: domain where the new entries would be put. :param client.MetadataVisibility visibility: visibility of the metadata entries. :param client.MetadataValueType metadata_value_type: :param bool use_admin_endpoint: if True, will use the /api/admin endpoint to add new entries to the metadata object else will use the vanilla /api endpoint. :return: an object of type EntityType.TASK XML which represents the asynchronous task that is updating the metadata entries. :rtype: lxml.objectify.ObjectifiedElement """ if not isinstance(domain, MetadataDomain): raise InvalidParameterException('Invalid domain.') if not isinstance(visibility, MetadataVisibility): raise InvalidParameterException('Invalid visibility.') if not isinstance(metadata_value_type, MetadataValueType): raise InvalidParameterException('Invalid type of value.') metadata = self.get_all_metadata(use_admin_endpoint) new_metadata = E.Metadata() for k, v in key_value_dict.items(): entry = E.MetadataEntry( {'type': 'xs:string'}, E.Domain(domain.value, visibility=visibility.value), E.Key(k), E.TypedValue( {'{' + NSMAP['xsi'] + '}type': metadata_value_type.value}, E.Value(v))) new_metadata.append(entry) return self.client.post_linked_resource(metadata, RelationType.ADD, EntityType.METADATA.value, new_metadata)
def update_nat_type(self, nat_type='ipTranslation', policy='allowTrafficIn'): """Update NAT type to vApp network. :param str nat_type: NAT type (portForwarding/ipTranslation). :param str policy: policy type(allowTrafficIn/allowTraffic). :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 """ 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'): VappNat._makeNatServiceAttr(features) nat_service = features.NatService if nat_service.NatType != nat_type: VappNat._delete_all_nat_rule(nat_service) nat_service.NatType = E.NatType(nat_type) nat_service.Policy = E.Policy(policy) return self.client.put_linked_resource(self.resource, RelationType.EDIT, EntityType.vApp_Network.value, self.resource)
def enable_nat_service(self, isEnable): """Enable NAT service to vApp network. :param bool isEnable: True for enable and False for Disable. :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 """ 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'): VappNat._makeNatServiceAttr(features) nat_service = features.NatService nat_service.IsEnabled = E.IsEnabled(isEnable) return self.client.put_linked_resource(self.resource, RelationType.EDIT, EntityType.vApp_Network.value, self.resource)
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)
def __init__(self, client, gateway_name=None, rule_id=None, nat_href=None, resource=None): """Constructor for Nat objects. :param pyvcloud.vcd.client.Client client: the client that will be used to make REST calls to vCD. :param str gateway_name: name of the gateway entity. :param str rule_id: nat rule id. :param str nat_href: nat rule href. :param lxml.objectify.ObjectifiedElement resource: object containing EntityType.NAT XML data representing the nat rule. """ self.client = client self.gateway_name = gateway_name self.rule_id = rule_id if gateway_name is not None and \ rule_id is not None and \ nat_href is None and \ resource is None: self.__build_self_href() if nat_href is None and resource is None and self.href is None: raise InvalidParameterException( "NatRule initialization failed as arguments are either " "invalid or None") if nat_href is not None: self.rule_id = self.__extract_rule_id(nat_href) self.href = nat_href self.resource = resource
def add(self, name, network_cidr, next_hop_ip): """Add static route to vApp network. :param str name: name of route. :param str network_cidr: network CIDR. :param str next_hop_ip: next hop IP. :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: Add route to static route service failed as given network's connection is not routed """ self._get_resource() fence_mode = self.resource.Configuration.FenceMode if fence_mode != 'natRouted': raise InvalidParameterException( "Add route to static route service failed as given network's " "connection is not routed") features = self.resource.Configuration.Features if not hasattr(features, 'StaticRoutingService'): VappStaticRoute._makeStaticRouteServiceAttr(features) route_service = features.StaticRoutingService static_route = E.StaticRoute() static_route.append(E.Name(name)) static_route.append(E.Network(network_cidr)) static_route.append(E.NextHopIp(next_hop_ip)) route_service.append(static_route) return self.client.put_linked_resource(self.resource, RelationType.EDIT, EntityType.vApp_Network.value, self.resource)
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)
def __init__(self, client, name=None, href=None, resource=None): """Constructor for Gateway objects. :param pyvcloud.vcd.client.Client client: the client that will be used to make REST calls to vCD. :param str name: name of the entity. :param str href: URI of the entity. :param lxml.objectify.ObjectifiedElement resource: object containing EntityType.EDGE_GATEWAY XML data representing the gateway. """ self.client = client self.name = name if href is None: raise InvalidParameterException( "Gateway initialization failed as arguments are either " "invalid or None") self.href = href if resource is None: self.resource = None self.get_resource() self.resource = resource if resource is not None: self.name = resource.get('name') self.href = resource.get('href') self.href_admin = get_admin_href(self.href)
def edit_name_description_and_shared_state(self, name, description=None, is_shared=None): """Edit name, description and shared state of the org vdc network. :param str name: New name of org vdc network. It is mandatory. :param str description: New description of org vdc network :param bool is_shared: True if user want to share else False. :return: object containing EntityType.TASK XML data representing the asynchronous task. :rtype: lxml.objectify.ObjectifiedElement """ if name is None: raise InvalidParameterException("Name can't be None or empty") vdc_network = self.get_resource() vdc_network.set('name', name) if description is not None: vdc_network.Description = E.Description(description) if is_shared is not None: vdc_network.IsShared = E.IsShared(is_shared) return self.client.put_linked_resource( self.resource, RelationType.EDIT, EntityType.ORG_VDC_NETWORK.value, vdc_network)
def edit_name_and_description(self, name, description=None): """Edit name and description of the vApp. :param str name: New name of the vApp. It is mandatory. :param str description: New description of the vApp. :return: object containing EntityType.TASK XML data representing the asynchronous task. :rtype: lxml.objectify.ObjectifiedElement """ if name is None or name.isspace(): raise InvalidParameterException("Name can't be None or empty") vapp = self.get_resource() vapp.set('name', name.strip()) if description is not None: if hasattr(vapp, 'Description'): vapp.replace(vapp.Description, E.Description(description)) else: vapp.LeaseSettingsSection.addprevious( E.Description(description)) return self.client.put_linked_resource(self.resource, RelationType.EDIT, EntityType.VAPP.value, vapp)
def create_routed_vdc_network(ctx, name, gateway_name, subnet, description, primary_dns_ip, secondary_dns_ip, dns_suffix, ip_range, is_shared, is_guest_vlan_allowed, is_sub_interface, is_distributed_interface, is_retain_net_info_across_deployments): try: vdc = _get_vdc_ref(ctx) ip_range_start = None ip_range_end = None if ip_range is not None: ip_range_arr = ip_range.split('-') if len(ip_range_arr) != 2: raise InvalidParameterException( 'IP Range should in x.x.x.x-y.y.y.y format.') ip_range_start = ip_range_arr[0] ip_range_end = ip_range_arr[1] routed_network = vdc.create_routed_vdc_network( name, gateway_name, subnet, description, primary_dns_ip, secondary_dns_ip, dns_suffix, ip_range_start, ip_range_end, is_shared, is_guest_vlan_allowed, is_sub_interface, is_distributed_interface, is_retain_net_info_across_deployments) stdout(routed_network.Tasks.Task[0], ctx) stdout('Routed org vdc network created successfully.', ctx) except Exception as e: stderr(e, ctx)
def modify_form_factor(self, gateway_type): """Modify form factor. This operation can be performed by only System Administrators. :param str gateway_type: gateway config type, possible values are compact/full/full4/x-large. :return: object containing EntityType.TASK XML data representing the asynchronous task. :rtype: lxml.objectify.ObjectifiedElement :raises: InvalidParameterException: if provided gateway config type is not from list compact/full/full4/x-large. """ self.get_resource() try: GatewayBackingConfigType.__getitem__(gateway_type) except ValueError: raise InvalidParameterException('Provided %s is not valid. It ' 'should be from allowed list ' 'compact/full/full4/x-large' % gateway_type) gateway_form_factor = E.EdgeGatewayFormFactor() gateway_form_factor.append(E.gatewayType(gateway_type)) return self.client.post_linked_resource( self.resource, RelationType.MODIFY_FORM_FACTOR, EntityType.EDGE_GATEWAY_FORM_FACTOR.value, gateway_form_factor)
def get_metadata_value(self, key, domain=MetadataDomain.GENERAL, use_admin_endpoint=False): """Fetch a metadata value identified by the domain and key. :param str key: key of the value to be fetched. :param client.MetadataDomain domain: domain of the value to be fetched. :param bool use_admin_endpoint: if True, will use the /api/admin endpoint to retrieve the metadata value else will use the vanilla /api endpoint. :return: an object containing EntityType.METADATA_VALUE XML data which represents the metadata value corresponding to the provided key and domain. :rtype: lxml.objectify.ObjectifiedElement :raises: AccessForbiddenException: If there is no metadata entry corresponding to the key provided. """ if not isinstance(domain, MetadataDomain): raise InvalidParameterException('Invalid domain.') if not use_admin_endpoint: href = self.href else: href = get_admin_href(self.href) metadata_entry_href = \ f"{href}/{domain.value}/{key}" return self.client.get_resource(metadata_entry_href)
def add_firewall_rule(self, name, is_enabled=False, policy='drop', protocols=['Any'], source_port_range='Any', source_ip='Any', destination_port_range='Any', destination_ip='Any', enable_logging=False): """Add firewall rule on firewall services to vApp network. :param str name: name of firewall rule. :param str policy: policy on firewall rule. :param list protocols: list of protocols on firewall rule. :param str source_port_range: source port range for firewall rule. :param str source_ip: source IP. :param str destination_port_range:destination port range for firewall rule. :param str destination_ip: destination IP. :param str enable_logging: enable logging on firewall 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 firewall service failed as given network's connection is not routed """ self._get_resource() fence_mode = self.resource.Configuration.FenceMode if fence_mode != 'natRouted': raise InvalidParameterException( "Enable firewall service failed as given network's connection " "is not routed") firewall_service = self.resource.Configuration.Features.FirewallService firewall_rule = E.FirewallRule() firewall_rule.append(E.IsEnabled(is_enabled)) firewall_rule.append(E.Description(name)) firewall_rule.append(E.Policy(policy)) protocol = E.Protocols() for proto in protocols: if proto == 'Any': protocol.append(E.Any(True)) elif proto == 'Icmp': protocol.append(E.Icmp(True)) elif proto == 'Tcp': protocol.append(E.Tcp(True)) elif proto == 'Udp': protocol.append(E.Udp(True)) firewall_rule.append(protocol) firewall_rule.append(E.DestinationPortRange(destination_port_range)) firewall_rule.append(E.DestinationIp(destination_ip)) firewall_rule.append(E.SourcePortRange(source_port_range)) firewall_rule.append(E.SourceIp(source_ip)) firewall_rule.append(E.EnableLogging(enable_logging)) firewall_service.append(firewall_rule) return self.client.put_linked_resource(self.resource, RelationType.EDIT, EntityType.vApp_Network.value, self.resource)
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)
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)
def __init__(self, client, name=None, href=None, resource=None): self.client = client self.name = name if href is None and resource is None: raise InvalidParameterException( "VApp initialization failed as arguments are either invalid " "or None") self.href = href self.resource = resource if resource is not None: self.name = resource.get('name') self.href = resource.get('href')
def set_dhcp_service(self, ip_range, default_lease_time, max_lease_time): """Set DHCP to vApp network. :param str ip_range: IP range in StartAddress-EndAddress format. :param str default_lease_time: default lease time. :param str max_lease_time: max lease time :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: Set DHCP service failed as given network's connection is Direct """ self._get_resource() if self.resource.Configuration.FenceMode == 'bridged': raise InvalidParameterException( "Set DHCP service failed as given network's connection is " "Direct") ip_ranges = ip_range.split('-') if not hasattr(self.resource.Configuration, 'Features'): index = self.resource.Configuration.index( self.resource.Configuration.GuestVlanAllowed) self.resource.Configuration.insert(index, E.Features()) if not hasattr(self.resource.Configuration.Features, 'DhcpService'): self.resource.Configuration.Features.append(E.DhcpService()) dhcp = self.resource.Configuration.Features.DhcpService if hasattr(dhcp, 'IsEnabled'): dhcp.IsEnabled = E.IsEnabled(True) else: dhcp.append(E.IsEnabled(True)) if hasattr(dhcp, 'DefaultLeaseTime'): dhcp.DefaultLeaseTime = E.DefaultLeaseTime(default_lease_time) else: dhcp.append(E.DefaultLeaseTime(default_lease_time)) if hasattr(dhcp, 'MaxLeaseTime'): dhcp.MaxLeaseTime = E.MaxLeaseTime(max_lease_time) else: dhcp.append(E.MaxLeaseTime(max_lease_time)) if hasattr(dhcp, 'IpRange'): dhcp.IpRange.StartAddress = E.StartAddress(ip_ranges[0]) dhcp.IpRange.EndAddress = E.EndAddress(ip_ranges[1]) else: dhcp.append( E.IpRange(E.StartAddress(ip_ranges[0]), E.EndAddress(ip_ranges[1]))) return self.client.put_linked_resource(self.resource, RelationType.EDIT, EntityType.vApp_Network.value, self.resource)
def convert_access_settings_list_to_params(self, access_settings_list): """Convert access settings from one format to other. Convert dictionary representation of access settings to AccessSettings XML element. Please refer to schema definition of EntityType.CONTROL_ACCESS_PARAMS for more details. :param list access_settings_list: list of dictionaries, where each dictionary represents a single access setting. The dictionary structure is as follows, - type: (str): type of the subject. One of 'org' or 'user'. - name: (str): name of the user or org. - access_level: (str): access_level of the particular subject. Allowed values are 'ReadOnly', 'Change' or 'FullControl'. :return: an object containing AccessSettings XML data. :rtype: lxml.objectify.ObjectifiedElement """ access_settings_params = E.AccessSettings() for access_setting in access_settings_list: if access_setting["type"] == 'user': org_href = self.get_org_href() subject_href = self.client.get_user_in_org( access_setting['name'], org_href).get('href') subject_type = EntityType.USER.value elif access_setting["type"] == 'org': subject_href = get_admin_href( self.client.get_org_by_name( access_setting['name']).get('href')) subject_type = EntityType.ADMIN_ORG.value else: raise InvalidParameterException("Invalid subject type") subject_name = access_setting['name'] # Make 'ReadOnly' the default access_level if it is not specified. if 'access_level' in access_setting: access_level = access_setting['access_level'] else: access_level = 'ReadOnly' access_setting_params = E.AccessSetting( E.Subject(name=subject_name, href=subject_href, type=subject_type), E.AccessLevel(access_level)) access_settings_params.append(access_setting_params) return access_settings_params
def __init__(self, client, href=None, resource=None): """Constructor. :param client: (Client): The client object to communicate with vCD. :param href: (str): (optional) href of the VM. :param resource: (:class:`lxml.objectify.StringElement`): (optional) object describing the VM. """ self.client = client if href is None and resource is None: raise InvalidParameterException( "VM initialization failed as arguments " "are either invalid or None") self.href = href self.resource = resource if resource is not None: self.href = resource.get('href')
def get_disk(self, name=None, disk_id=None): """Return information for an independent disk. :param name: (str): The name of the disk. :param disk_id: (str): The id of the disk. :return: A :class:`lxml.objectify.StringElement` object describing the existing disk. :raises: Exception: If the named disk cannot be located or some other error occurs. """ if name is None and disk_id is None: raise InvalidParameterException( 'Unable to idendify disk without name or id.') if self.resource is None: self.resource = self.client.get_resource(self.href) disks = self.get_disks() result = None if disk_id is not None: if not disk_id.startswith('urn:vcloud:disk:'): disk_id = 'urn:vcloud:disk:' + disk_id for disk in disks: if disk.get('id') == disk_id: result = disk # disk-id's are unique so it's ok to break the loop # and stop looking further. break elif name is not None: for disk in disks: if disk.get('name') == name: if result is None: result = disk else: raise MultipleRecordsException( 'Found multiple disks with name %s' ', please identify disk via disk-id.' % disk.get('name')) if result is None: raise EntityNotFoundException( 'No disk found with the given name/id.') else: return result
def __init__(self, client, admin_href=None, admin_resource=None): """Constructor for System objects. :param client: (pyvcloud.vcd.client): The client. :param admin_href: URI representing _WellKnownEndpoint.ADMIN. :param admin_resource: (lxml.objectify.ObjectifiedElement): XML representation of admin_href. """ self.client = client if admin_href is None and admin_resource is None: raise InvalidParameterException( "System initialization failed as arguments are either " "invalid or None") self.admin_href = admin_href self.admin_resource = admin_resource if admin_resource is not None: self.admin_href = self.client.get_admin().get('href')
def __init__(self, client, href=None, resource=None): """Constructor for VM object. :param pyvcloud.vcd.client.Client client: the client that will be used to make REST calls to vCD. :param str href: href of the vm. :param lxml.objectify.ObjectifiedElement resource: object containing EntityType.VM XML data representing the vm. """ self.client = client if href is None and resource is None: raise InvalidParameterException( 'VM initialization failed as arguments are either invalid or' ' None') self.href = href self.resource = resource if resource is not None: self.href = resource.get('href')
def __init__(self, client, admin_href=None, admin_resource=None): """Constructor for System objects. :param pyvcloud.vcd.client.Client client: the client that will be used to make REST calls to vCD. :param str admin_href: URI representing _WellKnownEndpoint.ADMIN. :param lxml.objectify.ObjectifiedElement admin_resource: an object containing EntityType.ADMIN XML data. """ self.client = client if admin_href is None and admin_resource is None: raise InvalidParameterException( "System initialization failed as arguments are either " "invalid or None") self.admin_href = admin_href self.admin_resource = admin_resource if admin_resource is not None: self.admin_href = self.client.get_admin().get('href')
def __init__(self, client, href=None, resource=None): """Constructor for Role object. :param client: (pyvcloud.vcd.client): The client. :param href: URI of the Role entity :param resource: (lxml.objectify.ObjectifiedElement): XML representation of the entity. """ self.client = client if href is None and resource is None: raise InvalidParameterException( "Role initialization failed as arguments are either invalid " "or None") self.href = href self.resource = resource if resource is not None: self.href = resource.get('href') self.name = resource.get('name')
def __init__(self, client, href=None, resource=None): """Constructor for Org objects. :param client: (pyvcloud.vcd.client): The client. :param href: (str): URI of the entity. :param resource: (lxml.objectify.ObjectifiedElement): XML representation of the entity. """ self.client = client if href is None and resource is None: raise InvalidParameterException( "Org initialization failed as arguments" " are either invalid or None") self.href = href self.resource = resource if resource is not None: self.href = resource.get('href') self.href_admin = self.href.replace('/api/org/', '/api/admin/org/')
def __init__(self, client, href=None, resource=None): """Constructor for metadata object. :param pyvcloud.vcd.client.Client client: the client that will be used to make REST calls to vCD. :param str href: non admin URI of the metadata. With the exception of provider VDC related metadata objects, those will be initiated with admin href (since non admin href of pVDC doesn't exist). :param lxml.objectify.ObjectifiedElement resource: object containing EntityType.METADATA XML data representing metadata of a vCD object. """ self.client = client if href is None and resource is None: raise InvalidParameterException( "Metadata initialization failed as arguments are either " "invalid or None") self.href = href self.resource = resource if resource is not None: self.href = resource.get('href')
def __init__(self, client, href=None, resource=None): """Constructor for a PVDC object. :param pyvcloud.vcd.client.Client client: the client that will be used to make REST calls to vCD. :param str href: URI of the entity. :param lxml.objectify.ObjectifiedElement resource: object containing EntityType.PROVIDER_VDC XML data representing the provider vdc. """ self.client = client if href is None and resource is None: raise InvalidParameterException( "PVDC initialization failed as arguments are either invalid " "or None") self.href = href self.resource = resource if resource is not None: self.name = resource.get('name') self.href = resource.get('href') self.admin_resource = get_admin_href(self.href)
def tuple_to_dict(tup=()): """Convert list of tuples to dictionary. provided tuple should have atleast 3 elements and only first three elements will be considered in the method. :param tup: list of tuple e.g., (("a", 'India', '12'), ("b", 'USA', '23')) :return: converted dict in the format of {'a': {India: 12}, 'b': {'USA':'23}} :rtype: dict """ dic = {} for a in tup: if len(a) < 3: raise InvalidParameterException( "Length of provided parameter cannot be less than 3.") dic.setdefault(a[0], {a[1]: a[2]}) return dic