def set_syslog_conf(self, syslog_server_ip): headers = self.headers headers['Accept'] = 'application/*+xml;version=5.11' headers['Content-Type'] = 'application/vnd.vmware.vcloud.SyslogSettings+xml;version=5.11' # content_type = "application/vnd.vmware.vcloud.SyslogSettings+xml" body = '' if '' == syslog_server_ip: body = """ <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd"> <TenantSyslogServerSettings> </TenantSyslogServerSettings> </SyslogServerSettings> """ else: body = """ <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd"> <TenantSyslogServerSettings> <SyslogServerIp>%s</SyslogServerIp> </TenantSyslogServerSettings> </SyslogServerSettings> """ % syslog_server_ip # '<SyslogServerSettings><TenantSyslogServerSettings><SyslogServerIp>%s</SyslogServerIp></TenantSyslogServerSettings></SyslogServerSettings>' % syslog_server_ip # link = filter(lambda link: link.get_type() == content_type, self.me.get_Link()) self.response = Http.post(self.me.href+'/action/configureSyslogServerSettings', data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return task
def register_extension(self, name, namespace, routing_key, patterns): api_filters = '' for pattern in patterns: api_filters += """ <vmext:ApiFilter> <vmext:UrlPattern>/api%s</vmext:UrlPattern> </vmext:ApiFilter> """ % pattern extension_metadata = """ <vmext:Service xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5" name="%s"> <vmext:Namespace>%s</vmext:Namespace> <vmext:Enabled>true</vmext:Enabled> <vmext:RoutingKey>%s</vmext:RoutingKey> <vmext:Exchange>vcdext</vmext:Exchange> <vmext:ApiFilters> %s </vmext:ApiFilters> </vmext:Service> """ % (name, namespace, routing_key, api_filters) content_type = 'application/vnd.vmware.admin.vmwExtension+xml' link = [ link for link in self.vcloud_session.get_Link() if link.get_type() == content_type ] self.response = Http.post( link[0].get_href() + '/service', headers=self.vcloud_session.get_vcloud_headers(), data=extension_metadata, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: doc = ET.fromstring(self.response.content.decode('utf-8')) return doc else: raise Exception(self.response.status_code)
def set_syslog_conf(self, syslog_server_ip): headers = self.headers headers['Accept'] = 'application/*+xml;version=5.11' headers[ 'Content-Type'] = 'application/vnd.vmware.vcloud.SyslogSettings+xml;version=5.11' # content_type = "application/vnd.vmware.vcloud.SyslogSettings+xml" body = '' if '' == syslog_server_ip: body = """ <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd"> <TenantSyslogServerSettings> </TenantSyslogServerSettings> </SyslogServerSettings> """ else: body = """ <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd"> <TenantSyslogServerSettings> <SyslogServerIp>%s</SyslogServerIp> </TenantSyslogServerSettings> </SyslogServerSettings> """ % syslog_server_ip # '<SyslogServerSettings><TenantSyslogServerSettings><SyslogServerIp>%s</SyslogServerIp></TenantSyslogServerSettings></SyslogServerSettings>' % syslog_server_ip # link = filter(lambda link: link.get_type() == content_type, self.me.get_Link()) self.response = Http.post(self.me.href + '/action/configureSyslogServerSettings', data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return task
def execute(self, operation, http, body=None, targetVM=None): """ Execute an operation against a VM as an Asychronous Task. :param operation: (str): The command to execute :param http: (str): The http operation. :param body: (str, optional): a body for the http request :param targetVM: (str, optional): The name of the VM that will be the target of the request. :return: (TaskType or Bool) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n Or False if the request failed, error and debug level messages are logged. """ vApp = targetVM if targetVM else self.me link = filter(lambda link: link.get_rel() == operation, vApp.get_Link()) if not link: Log.error(self.logger, "link not found; rel=%s" % operation) Log.debug( self.logger, "vApp href=%s, name=%s" % (vApp.get_href(), vApp.get_name())) return False else: if http == "post": headers = self.headers if body and body.startswith('<DeployVAppParams '): headers[ 'Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml' elif body and body.startswith('<UndeployVAppParams '): headers[ 'Content-type'] = 'application/vnd.vmware.vcloud.undeployVAppParams+xml' elif body and body.startswith('<CreateSnapshotParams '): headers[ 'Content-type'] = 'application/vnd.vmware.vcloud.createSnapshotParams+xml' self.response = Http.post(link[0].get_href(), data=body, headers=headers, verify=self.verify, logger=self.logger) elif http == "put": self.response = Http.put(link[0].get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger) else: self.response = Http.delete(link[0].get_href(), headers=self.headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: Log.debug( self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text)) return False
def create_vapp(self, vdc_name, vapp_name, template_name, catalog_name, network_name=None, network_mode='bridged', vm_name=None, vm_cpus=None, vm_memory=None, deploy='false', poweron='false'): self.vdc = self.get_vdc(vdc_name) if not self.vcloud_session or not self.vcloud_session.organization or not self.vdc: #"Select an organization and datacenter first" return False if '' == vm_name: vm_name = None catalogs = filter(lambda link: catalog_name == link.get_name() and link.get_type() == "application/vnd.vmware.vcloud.catalog+xml", self.vcloud_session.organization.get_Link()) if len(catalogs) == 1: self.response = Http.get(catalogs[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: catalog = catalogType.parseString(self.response.content, True) catalog_items = filter(lambda catalogItemRef: catalogItemRef.get_name() == template_name, catalog.get_CatalogItems().get_CatalogItem()) if len(catalog_items) == 1: self.response = Http.get(catalog_items[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) # use ElementTree instead because none of the types inside resources (not even catalogItemType) is able to parse the response correctly catalogItem = ET.fromstring(self.response.content) entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0] vm_href = None if vm_name: self.response = Http.get(entity.get('href'), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: vAppTemplate = ET.fromstring(self.response.content) for vm in vAppTemplate.iter('{http://www.vmware.com/vcloud/v1.5}Vm'): vm_href = vm.get('href') template_params = self._create_instantiateVAppTemplateParams( vapp_name, entity.get("href"), vm_name=vm_name, vm_href=vm_href, vm_cpus=vm_cpus, vm_memory=vm_memory, deploy=deploy, power=poweron) if network_name: pass output = StringIO() template_params.export(output, 0, name_ = 'InstantiateVAppTemplateParams', namespacedef_ = '''xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"''', pretty_print = False) body = '<?xml version="1.0" encoding="UTF-8"?>' + \ output.getvalue().replace('class:', 'rasd:')\ .replace(' xmlns:vmw="http://www.vmware.com/vcloud/v1.5"', '')\ .replace('vmw:', 'rasd:')\ .replace('Info>', "ovf:Info>") content_type = "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml" link = filter(lambda link: link.get_type() == content_type, self.vdc.get_Link()) self.response = Http.post(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, data=body, logger=self.logger) if self.response.status_code == requests.codes.created: vApp = vAppType.parseString(self.response.content, True) task = vApp.get_Tasks().get_Task()[0] return task return False
def save_services_configuration(self): edgeGatewayServiceConfiguration = self.me.get_Configuration().get_EdgeGatewayServiceConfiguration() body = '<?xml version="1.0" encoding="UTF-8"?>' + \ CommonUtils.convertPythonObjToStr(self.me.get_Configuration().get_EdgeGatewayServiceConfiguration(), name='EdgeGatewayServiceConfiguration', namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ') content_type = "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml" link = filter(lambda link: link.get_type() == content_type, self.me.get_Link()) self.response = Http.post(link[0].get_href(), data=body, headers=self.headers, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return task
def customize_on_next_poweron(self): vm = self._get_vms()[0] link = filter(lambda link: link.get_rel() == "customizeAtNextPowerOn", vm.get_Link()) if link: self.response = Http.post(link[0].get_href(), data=None, headers=self.headers, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True Log.error(self.logger, "link not found") return False
def create_cluster(self, name, worker_count=2): headers = self.vcloud_session.get_vcloud_headers() data = {'name': name, 'worker_count': worker_count} self.response = Http.post(self.api_url, headers=headers, data=json.dumps(data), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return json.loads(self.response.content) else: raise Exception(self.response.status_code)
def _post(self, href, body, content_type): headers = self._session.vca.vcloud_session.get_vcloud_headers() headers['Content-type'] = content_type response = Http.post( href, data=body, headers=headers, verify=CONF.vcloud.verify) print response.content if response.status_code == requests.codes.accepted: return taskType.parseString(response.content, True) return None
def create_catalog(self, catalog_name, description): refs = filter(lambda ref: ref.rel == 'add' and ref.type_ == 'application/vnd.vmware.admin.catalog+xml', self.vcloud_session.organization.Link) if len(refs) == 1: data = """<?xml version="1.0" encoding="UTF-8"?> <AdminCatalog xmlns="http://www.vmware.com/vcloud/v1.5" name="%s"> <Description>%s</Description> </AdminCatalog> """ % (catalog_name, description) self.response = Http.post(refs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, data=data, logger=self.logger) if self.response.status_code == requests.codes.created: task = vCloudEntities.parseString(self.response.content, True) return task.get_Tasks().get_Task()[0]
def cancel(self, execution_id, force=False): data = {'execution_id': execution_id, 'force': force} headers = self.score.get_headers() headers['Content-type'] = 'application/json' self.score.response = Http.post(self.score.url + '/executions/' + execution_id, headers=headers, data=json.dumps(data), verify=self.score.verify, logger=self.logger) if self.score.response.status_code != requests.codes.ok: raise exceptions.from_response(self.score.response) return json.loads(self.score.response.content)
def add_disk(self, vdc_name, name, size): data = """ <vcloud:DiskCreateParams xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"> <vcloud:Disk name="%s" size="%s"/> </vcloud:DiskCreateParams> """ % (name, size) vdc = self.get_vdc(vdc_name) content_type = "application/vnd.vmware.vcloud.diskCreateParams+xml" link = filter(lambda link: link.get_type() == content_type, vdc.get_Link()) self.response = Http.post(link[0].get_href(), data=data, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: disk = self._parse_disk(self.response.content) return(True, disk) else: return(False, self.response.content)
def force_customization(self, vm_name, power_on=True): """ Force the guest OS customization script to be run for a specific vm in the vApp. A customization script must have been previously associated with the VM using the pyvcloud customize_guest_os method or using the vCD console The VMware tools must be installed in the Guest OS. :param vm_name: (str): The name of the vm to be customized. :param power_on (bool): Wether to power the vm on after customization or not :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.b\n if the task cannot be created a debug level log message is generated detailing the reason. """ children = self.me.get_Children() if children: vms = [vm for vm in children.get_Vm() if vm.name == vm_name] if len(vms) == 1: sections = vms[0].get_Section() links = filter(lambda link: link.rel == "deploy", vms[0].Link) if len(links) == 1: forceCustomizationValue = 'true' deployVAppParams = vcloudType.DeployVAppParamsType() if power_on: deployVAppParams.set_powerOn('true') else: deployVAppParams.set_powerOn('false') deployVAppParams.set_deploymentLeaseSeconds(0) deployVAppParams.set_forceCustomization('true') body = CommonUtils.convertPythonObjToStr( deployVAppParams, name="DeployVAppParams", namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5"' ) headers = self.headers headers[ 'Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml' self.response = Http.post(links[0].href, data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: Log.debug( self.logger, "response status=%d, content=%s" % (self.response.status_code, self.response.text))
def start(self, deployment_id, workflow_id, parameters=None, allow_custom_parameters=False, force=False): assert deployment_id assert workflow_id data = { 'deployment_id': deployment_id, 'workflow_id': workflow_id, 'parameters': parameters, 'allow_custom_parameters': str(allow_custom_parameters).lower(), 'force': str(force).lower() } headers = self.score.get_headers() headers['Content-type'] = 'application/json' self.score.response = Http.post(self.score.url + '/executions', headers=headers, data=json.dumps(data), verify=self.score.verify, logger=self.logger) if self.score.response.status_code == requests.codes.ok: return json.loads(self.score.response.content)
def cancel(self, execution_id, force=False): data = { 'execution_id': execution_id, 'force': force } headers = self.score.get_headers() headers['Content-type'] = 'application/json' self.score.response = Http.post( self.score.url + '/executions/' + execution_id, headers=headers, data=json.dumps(data), verify=self.score.verify, logger=self.logger ) if self.score.response.status_code != requests.codes.ok: raise exceptions.from_response(self.score.response) return json.loads(self.score.response.content)
def save_services_configuration(self): edgeGatewayServiceConfiguration = self.me.get_Configuration( ).get_EdgeGatewayServiceConfiguration() body = '<?xml version="1.0" encoding="UTF-8"?>' + \ CommonUtils.convertPythonObjToStr(self.me.get_Configuration().get_EdgeGatewayServiceConfiguration(), name='EdgeGatewayServiceConfiguration', namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ') content_type = "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml" link = filter(lambda link: link.get_type() == content_type, self.me.get_Link()) self.response = Http.post(link[0].get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: task = taskType.parseString(self.response.content, True) return task
def modify_vm_name(self, vm_index, vm_name): """ Modify the name of a VM in a vApp :param vm_index: (int):The index of the VM in the vApp 1==first VM :param vm_name: (str): The new name of the VM. :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n if the task cannot be created a debug level log message is generated detailing the reason. :raises: Exception: If the named VM cannot be located or another error occured. """ children = self.me.get_Children() if children: assert len(children.get_Vm()) >= vm_index vm = children.get_Vm()[vm_index - 1] assert vm href = vm.get_href() vm_name_old = vm.get_name() Log.debug( self.logger, "VM name change (%s) %s -> %s" % (vm_index, vm_name_old, vm_name)) vm.set_name(vm_name) vm.set_Section([]) output = StringIO() vm.export( output, 0, name_='Vm', namespacedef_= 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"', pretty_print=True) body = output.getvalue() headers = self.headers headers['Content-type'] = 'application/vnd.vmware.vcloud.vm+xml' self.response = Http.post(href + '/action/reconfigureVm', data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: raise Exception(self.response.status_code) raise Exception('can\'t find vm')
def start(self, deployment_id, workflow_id, parameters=None, allow_custom_parameters=False, force=False): data = { 'deployment_id': deployment_id, 'workflow_id': workflow_id, 'parameters': parameters, 'allow_custom_parameters': allow_custom_parameters, 'force': force, } headers = self.score.get_headers() headers['Content-type'] = 'application/json' self.score.response = Http.post(self.score.url + '/executions', headers=headers, data=json.dumps(data), verify=self.score.verify, logger=self.logger) if self.score.response.status_code != requests.codes.ok: raise exceptions.from_response(self.score.response) return json.loads(self.score.response.content)
def customize_on_next_poweron(self): """ Force the guest OS customization script to be run for the first VM in the vApp. A customization script must have been previously associated with the VM using the pyvcloud customize_guest_os method or using the vCD console The VMware tools must be installed in the Guest OS. :return: (bool) True if the request was accepted, False otherwise. If False an error level log message is generated. """ vm = self._get_vms()[0] link = filter(lambda link: link.get_rel() == "customizeAtNextPowerOn", vm.get_Link()) if link: self.response = Http.post(link[0].get_href(), data=None, headers=self.headers, logger=self.logger) if self.response.status_code == requests.codes.no_content: return True Log.error(self.logger, "link not found") return False
def login_to_org(self, service, org_name): vdcReference = self.get_vdc_reference(service, org_name) if vdcReference: link = filter(lambda link: link.get_type() == "application/xml;class=vnd.vmware.vchs.vcloudsession", vdcReference.get_Link())[0] self.response = Http.post(link.get_href(), headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: vchs = vchsType.parseString(self.response.content, True) vdcLink = vchs.get_VdcLink() headers = {} headers[vdcLink.authorizationHeader] = vdcLink.authorizationToken headers["Accept"] = "application/*+xml;version=" + self.version self.response = Http.get(vdcLink.href, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: self.vdc = vdcType.parseString(self.response.content, True) self.org = self.vdc.name org_url = filter(lambda link: link.get_type() == "application/vnd.vmware.vcloud.org+xml", self.vdc.get_Link())[0].href vcloud_session = VCS(org_url, self.username, self.org, None, org_url, org_url, version=self.version, verify=self.verify, log=self.log) if vcloud_session.login(password=None, token=vdcLink.authorizationToken): self.vcloud_session = vcloud_session return True return False
def create_vdc_network(self, vdc_name, network_name, gateway_name, start_address, end_address, gateway_ip, netmask, dns1, dns2, dns_suffix): vdc = self.get_vdc(vdc_name) gateway = ReferenceType(href=self.get_gateway(vdc_name, gateway_name).me.href) gateway.original_tagname_ = "EdgeGateway" iprange = IpRangeType(StartAddress=start_address, EndAddress=end_address) ipranges = IpRangesType(IpRange=[iprange]) ipscope = IpScopeType(IsInherited=False, Gateway=gateway_ip, Netmask=netmask, Dns1=dns1, Dns2=dns2, DnsSuffix=dns_suffix, IpRanges=ipranges) ipscopes = IpScopesType(IpScope=[ipscope]) configuration = NetworkConfigurationType(IpScopes=ipscopes, FenceMode="natRouted") net = OrgVdcNetworkType(name=network_name, Description="Network created by pyvcloud", EdgeGateway=gateway, Configuration=configuration, IsShared=False) namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"' content_type = "application/vnd.vmware.vcloud.orgVdcNetwork+xml" body = '<?xml version="1.0" encoding="UTF-8"?>{0}'.format( CommonUtils.convertPythonObjToStr(net, name='OrgVdcNetwork', namespacedef=namespacedef)) postlink = filter(lambda link: link.get_type() == content_type, vdc.get_Link())[0].href headers = self.vcloud_session.get_vcloud_headers() headers["Content-Type"] = content_type self.response = Http.post(postlink, data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: network = networkType.parseString(self.response.content, True) task = network.get_Tasks().get_Task()[0] return (True, task) else: return (False, self.response.content)
def force_customization(self, vm_name): children = self.me.get_Children() if children: vms = [vm for vm in children.get_Vm() if vm.name == vm_name] if len(vms) == 1: sections = vms[0].get_Section() links = filter(lambda link: link.rel== "deploy", vms[0].Link) if len(links) == 1: forceCustomizationValue = 'true' deployVAppParams = vcloudType.DeployVAppParamsType() deployVAppParams.set_powerOn('true') deployVAppParams.set_deploymentLeaseSeconds(0) deployVAppParams.set_forceCustomization('true') body = CommonUtils.convertPythonObjToStr(deployVAppParams, name = "DeployVAppParams", namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"') headers = self.headers headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml' self.response = Http.post(links[0].href, data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: Log.debug(self.logger, "response status=%d, content=%s" % (self.response.status_code, self.response.text))
def login(self, password=None, token=None): if token: headers = {} headers["x-vcloud-authorization"] = token headers["Accept"] = "application/*+xml;version=" + self.version self.response = Http.get(self.org_url, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: self.token = token self.organization = organizationType.parseString(self.response.content, True) return True else: return False else: headers = {} headers["Accept"] = "application/*+xml;version=" + self.version self.response = Http.post(self.url, headers=headers, auth=(self.username + "@" + self.org, password), verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: self.token = self.response.headers["x-vcloud-authorization"] self.session = sessionType.parseString(self.response.content, True) self.org_url = filter(lambda link: link.type_ == 'application/vnd.vmware.vcloud.org+xml', self.session.Link)[0].href return True else: return False
def force_customization(self, vm_name, power_on=True): """ Force the guest OS customization script to be run for a specific vm in the vApp. A customization script must have been previously associated with the VM using the pyvcloud customize_guest_os method or using the vCD console The VMware tools must be installed in the Guest OS. :param vm_name: (str): The name of the vm to be customized. :param power_on (bool): Wether to power the vm on after customization or not :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.b\n if the task cannot be created a debug level log message is generated detailing the reason. """ children = self.me.get_Children() if children: vms = [vm for vm in children.get_Vm() if vm.name == vm_name] if len(vms) == 1: sections = vms[0].get_Section() links = filter(lambda link: link.rel== "deploy", vms[0].Link) if len(links) == 1: forceCustomizationValue = 'true' deployVAppParams = vcloudType.DeployVAppParamsType() if power_on: deployVAppParams.set_powerOn('true') else: deployVAppParams.set_powerOn('false') deployVAppParams.set_deploymentLeaseSeconds(0) deployVAppParams.set_forceCustomization('true') body = CommonUtils.convertPythonObjToStr(deployVAppParams, name = "DeployVAppParams", namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"') headers = self.headers headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml' self.response = Http.post(links[0].href, data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: Log.debug(self.logger, "response status=%d, content=%s" % (self.response.status_code, self.response.text))
def execute(self, operation, http, body=None, targetVM=None): """ Execute an operation against a VM as an Asychronous Task. :param operation: (str): The command to execute :param http: (str): The http operation. :param body: (str, optional): a body for the http request :param targetVM: (str, optional): The name of the VM that will be the target of the request. :return: (TaskType or Bool) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n Or False if the request failed, error and debug level messages are logged. """ vApp = targetVM if targetVM else self.me link = filter(lambda link: link.get_rel() == operation, vApp.get_Link()) if not link: Log.error(self.logger, "link not found; rel=%s" % operation) Log.debug(self.logger, "vApp href=%s, name=%s" % (vApp.get_href(), vApp.get_name())) return False else: if http == "post": headers = self.headers if body and body.startswith('<DeployVAppParams '): headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml' elif body and body.startswith('<UndeployVAppParams '): headers['Content-type'] = 'application/vnd.vmware.vcloud.undeployVAppParams+xml' elif body and body.startswith('<CreateSnapshotParams '): headers['Content-type'] = 'application/vnd.vmware.vcloud.createSnapshotParams+xml' self.response = Http.post(link[0].get_href(), data=body, headers=headers, verify=self.verify, logger=self.logger) elif http == "put": self.response = Http.put(link[0].get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger) else: self.response = Http.delete(link[0].get_href(), headers=self.headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: Log.debug(self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text)) return False
def execute(self, operation, http, body=None, targetVM=None): vApp = targetVM if targetVM else self.me link = filter(lambda link: link.get_rel() == operation, vApp.get_Link()) if not link: Log.error(self.logger, "link not found; rel=%s" % operation) Log.debug(self.logger, "vApp href=%s, name=%s" % (vApp.get_href(), vApp.get_name())) return False else: if http == "post": headers = self.headers if body and body.startswith('<DeployVAppParams '): headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml' elif body and body.startswith('<UndeployVAppParams '): headers['Content-type'] = 'application/vnd.vmware.vcloud.undeployVAppParams+xml' self.response = Http.post(link[0].get_href(), data = body, headers=headers, verify=self.verify, logger=self.logger) elif http == "put": self.response = Http.put(link[0].get_href(), data = body, headers=self.headers, verify=self.verify, logger=self.logger) else: self.response = Http.delete(link[0].get_href(), headers=self.headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: Log.debug(self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, response.text)) return False
def modify_vm_name(self, vm_index, vm_name): """ Modify the name of a VM in a vApp :param vm_index: (int):The index of the VM in the vApp 1==first VM :param vm_name: (str): The new name of the VM. :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n if the task cannot be created a debug level log message is generated detailing the reason. :raises: Exception: If the named VM cannot be located or another error occured. """ children = self.me.get_Children() if children: assert len(children.get_Vm()) >= vm_index vm = children.get_Vm()[vm_index-1] assert vm href = vm.get_href() vm_name_old = vm.get_name() Log.debug(self.logger, "VM name change (%s) %s -> %s" % (vm_index, vm_name_old, vm_name)) vm.set_name(vm_name) vm.set_Section([]) output = StringIO() vm.export(output, 0, name_ = 'Vm', namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"', pretty_print = True) body = output.getvalue() headers = self.headers headers['Content-type'] = 'application/vnd.vmware.vcloud.vm+xml' self.response = Http.post(href+'/action/reconfigureVm', data=body, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.accepted: return taskType.parseString(self.response.content, True) else: raise Exception(self.response.status_code) raise Exception('can\'t find vm')
def login(self, password=None, token=None, org=None, org_url=None): """ Request to login to vCloud Air :param password: The password. :param token: The token from a previous successful login, None if this is a new login request. :return: True if the user was successfully logged in, False otherwise. """ if self.service_type == 'subscription': if token: headers = {} headers["x-vchs-authorization"] = token headers["Accept"] = "application/xml;version=" + self.version self.response = Http.get(self.host + "/api/vchs/services", headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.ok: self.services = serviceType.parseString(self.response.content, True) self.token = token return True else: return False else: url = self.host + "/api/vchs/sessions" encode = "Basic " + base64.standard_b64encode(self.username + ":" + password) headers = {} headers["Authorization"] = encode.rstrip() headers["Accept"] = "application/xml;version=" + self.version self.response = Http.post(url, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: self.token = self.response.headers["x-vchs-authorization"] self.services = self._get_services() return True else: return False elif self.service_type == 'ondemand': if token: self.token = token self.instances = self.get_instances() return self.instances != None else: url = self.host + "/api/iam/login" encode = "Basic " + base64.standard_b64encode(self.username + ":" + password) headers = {} headers["Authorization"] = encode.rstrip() headers["Accept"] = "application/json;version=%s" % self.version self.response = Http.post(url, headers=headers, verify=self.verify, logger=self.logger) if self.response.status_code == requests.codes.created: self.token = self.response.headers["vchs-authorization"] self.instances = self.get_instances() return True else: return False elif self.service_type == 'vcd': if token: url = self.host + '/api/sessions' vcloud_session = VCS(url, self.username, org, None, org_url, org_url, version=self.version, verify=self.verify, log=self.log) result = vcloud_session.login(token=token) if result: self.org = org self.vcloud_session = vcloud_session return result else: url = self.host + '/api/sessions' vcloud_session = VCS(url, self.username, org, None, org_url, org_url, version=self.version, verify=self.verify, log=self.log) result = vcloud_session.login(password=password) if result: self.token = vcloud_session.token self.org = org self.vcloud_session = vcloud_session return result else: return False return False
def create_or_update_task(self, status, namespace, operation_name, operation_description, owner_href, owner_name, owner_type, user_id, user_name, progress, details, org_id=None, task_id=None): if self.vcloud_session: o = urlparse(self.vcloud_session.url) api_url = '%s://%s%s' % (o.scheme, o.netloc, '/api') if progress is None: progress_indicator = '' else: progress_indicator = 'progress="%s"' % progress data = """ <Task xmlns="http://www.vmware.com/vcloud/v1.5" status="{status}" serviceNamespace="{namespace}" type="application/vnd.vmware.vcloud.task+xml" operation="{operation_description}" operationName="{operation_name}" {progress_indicator} name="task"> <Owner href="{owner_href}" name="{owner_name}" type="{owner_type}"/> <User href="{api_url}/admin/user/{user_id}" name="{user_name}" type="application/vnd.vmware.admin.user+xml"/> <Details>"{details}"</Details> </Task> """.format(status=status, namespace=namespace, operation_description=operation_description, operation_name=operation_name, progress_indicator=progress_indicator, api_url=api_url, details=details, owner_href=owner_href, owner_name=owner_name, owner_type=owner_type, user_id=user_id, user_name=user_name) if task_id is None: link = '%s/tasksList/%s' % (api_url, org_id) self.response = Http.post( link, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger, data=data) else: link = '%s/task/%s' % (api_url, task_id) self.response = Http.put( link, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger, data=data) if self.response.status_code == requests.codes.ok: return taskType.parseString(self.response.content, True) else: raise Exception(self.response.status_code) return None