Esempio n. 1
0
 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 = requests.post(links[0].href,
                                               data=body,
                                               headers=headers,
                                               verify=self.verify)
                 if self.response.status_code == requests.codes.accepted:
                     return taskType.parseString(self.response.content,
                                                 True)
                 else:
                     print self.response.content
Esempio n. 2
0
 def deploy(self, powerOn=True):
     powerOnValue = 'true' if powerOn else 'false'
     deployVAppParams = vcloudType.DeployVAppParamsType()
     deployVAppParams.set_powerOn(powerOnValue)
     body = CommonUtils.convertPythonObjToStr(deployVAppParams, name = "DeployVAppParams",
             namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"')
     return self.execute("deploy", "post", body=body)
Esempio n. 3
0
    def undeploy(self, action='powerOff'):
        """
        Undeploy the vapp

        :param action: (bool, optional): Power on the vApp and its contained VMs after deployment.

                                       *  The valid values of action are

                                       -  **powerOff** (Power off the VMs. This is the default action if
                                          this attribute is missing or empty),

                                       -  **suspend** (Suspend the VMs), shutdown (Shut down the VMs),

                                       -  **force** (Attempt to power off the VMs. Failures in undeploying the VM or associated networks
                                          are ignored. All references to the vApp and its VMs are removed from the database),

                                       -  **default** (Use the actions, order, and delay specified in the StartupSection).

        :returns: (bool): True if the user was vApp was successfully deployed, False otherwise.

        """
        undeployVAppParams = vcloudType.UndeployVAppParamsType()

        undeployVAppParams.set_UndeployPowerAction(action)
        body = CommonUtils.convertPythonObjToStr(undeployVAppParams, name = "UndeployVAppParams",
                namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"')
        return self.execute("undeploy", "post", body=body)
Esempio n. 4
0
 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 = requests.post(links[0].href, data=body, headers=headers, verify=self.verify)
                 if self.response.status_code == requests.codes.accepted:
                     return taskType.parseString(self.response.content, True)
                 else:
                     print self.response.content
Esempio n. 5
0
 def modify_vm_cpu(self, vm_name, cpus):
     """
     Modify the virtual CPU allocation for VM.
    
     :param vm_name: (str): The name of the vm to be customized.
     :param cpus: (int): The number of virtual CPUs allocated to 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:
         vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
         if len(vms) == 1:
             sections = vm.get_Section()
             virtualHardwareSection = filter(
                 lambda section: section.__class__.__name__ ==
                 "VirtualHardwareSection_Type", sections)[0]
             items = virtualHardwareSection.get_Item()
             cpu = filter(
                 lambda item: (item.get_anyAttributes_().get(
                     '{http://www.vmware.com/vcloud/v1.5}href'
                 ) != None and item.get_anyAttributes_().get(
                     '{http://www.vmware.com/vcloud/v1.5}href').endswith(
                         '/virtualHardwareSection/cpu')), items)[0]
             href = cpu.get_anyAttributes_().get(
                 '{http://www.vmware.com/vcloud/v1.5}href')
             en = cpu.get_ElementName()
             en.set_valueOf_('%s virtual CPU(s)' % cpus)
             cpu.set_ElementName(en)
             vq = cpu.get_VirtualQuantity()
             vq.set_valueOf_(cpus)
             cpu.set_VirtualQuantity(vq)
             cpu_string = CommonUtils.convertPythonObjToStr(cpu, 'CPU')
             output = StringIO()
             cpu.export(
                 output,
                 0,
                 name_='Item',
                 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=True)
             body = output.getvalue().\
                 replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                 replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
             headers = self.headers
             headers[
                 'Content-type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
             self.response = Http.put(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:
                 raise Exception(self.response.status_code)
     raise Exception('can\'t find vm')
 def display_progress(self, task, cmd_proc=None, headers=None):
     progress = task.get_Progress()
     status = task.get_status()
     rnd = 0
     response = None
     while status != "success":
         if status == "error":
             error = task.get_Error()
             sys.stdout.write('\r' + ' ' * 120 + '\r')
             sys.stdout.flush()
             self.print_error(CommonUtils.convertPythonObjToStr(
                              error, name="Error"),
                              cmd_proc=cmd_proc)
             return None
         else:
             # some task doesn't not report progress
             if progress:
                 sys.stdout.write("\rprogress : [" + "*" *
                                  int(progress) + " " *
                                  (100 - int(progress - 1)) + "] " +
                                  str(progress) + " %")
             else:
                 sys.stdout.write("\rprogress : ")
                 if rnd % 4 == 0:
                     sys.stdout.write(
                         "[" + "*" * 25 + " " * 75 + "]")
                 elif rnd % 4 == 1:
                     sys.stdout.write(
                         "[" + " " * 25 + "*" * 25 + " " * 50 + "]")
                 elif rnd % 4 == 2:
                     sys.stdout.write(
                         "[" + " " * 50 + "*" * 25 + " " * 25 + "]")
                 elif rnd % 4 == 3:
                     sys.stdout.write(
                         "[" + " " * 75 + "*" * 25 + "]")
                 rnd += 1
             sys.stdout.flush()
             time.sleep(1)
             response = Http.get(task.get_href(), headers=headers,
                                 verify=cmd_proc.verify,
                                 logger=cmd_proc.logger)
             if response.status_code == requests.codes.ok:
                 task = parseString(response.content, True)
                 progress = task.get_Progress()
                 status = task.get_status()
             else:
                 Log.error(cmd_proc.logger, "can't get task")
                 return
     sys.stdout.write("\r" + " " * 120)
     sys.stdout.flush()
     if response is not None:
         if cmd_proc is not None and cmd_proc.json_output:
             sys.stdout.write("\r" +
                              self.task_to_json(response.content) + '\n')
         else:
             sys.stdout.write("\r" +
                              self.task_to_table(response.content) + '\n')
         sys.stdout.flush()
    def create_isolated_vdc_network(
        self,
        vdc_name,
        network_name,
        gateway_name,
        start_address,
        end_address,
        gateway_ip,
        netmask,
        dns1=None,
        dns2=None,
        dns_suffix=None,
    ):
        vdc = self.get_vdc(vdc_name)
        if vdc is None:
            LOG.error("Create isolated vdc network error, cannot get vdc:" "%s info", vdc_name)
            raise exceptions.VCloudDriverException(
                "Create isolated vdc" " network error, cannot" "find the vdc_name:" + vdc_name
            )
        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="isolated")
        net = OrgVdcNetworkType(
            name=network_name,
            Description="Network created name is " + network_name,
            EdgeGateway=None,
            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
        response = self._invoke_api(requests, "post", postlink, data=body, headers=headers, verify=self.verify)

        if response.status_code == requests.codes.forbidden:
            raise exceptions.ForbiddenException("Create_isolated_vdc_network" "error, network_name:" + network_name)
        if response.status_code == requests.codes.created:
            network = networkType.parseString(response.content, True)
            task = network.get_Tasks().get_Task()[0]
            return (True, task)
        else:
            return (False, response.content)
Esempio n. 8
0
 def deploy(self, powerOn=True):
     powerOnValue = 'true' if powerOn else 'false'
     deployVAppParams = vcloudType.DeployVAppParamsType()
     deployVAppParams.set_powerOn(powerOnValue)
     body = CommonUtils.convertPythonObjToStr(
         deployVAppParams,
         name="DeployVAppParams",
         namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5"')
     return self.execute("deploy", "post", body=body)
    def create_isolated_vdc_network(self, vdc_name, network_name, gateway_name,
                                    start_address, end_address, gateway_ip,
                                    netmask, dns1=None, dns2=None,
                                    dns_suffix=None):
        vdc = self.get_vdc(vdc_name)
        if vdc is None:
            LOG.error("Create isolated vdc network error, cannot get vdc:"
                      "%s info", vdc_name)
            raise exceptions.VCloudDriverException("Create isolated vdc"
                                                   " network error, cannot"
                                                   "find the vdc_name:" +
                                                   vdc_name)
        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="isolated")
        net = OrgVdcNetworkType(name=network_name,
                                Description="Network created name is " +
                                network_name,
                                EdgeGateway=None, 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
        response = self._invoke_api(requests, 'post',
                                    postlink,
                                    data=body,
                                    headers=headers,
                                    verify=self.verify)

        if response.status_code == requests.codes.forbidden:
            raise exceptions.ForbiddenException("Create_isolated_vdc_network"
                                                "error, network_name:" +
                                                network_name)
        if response.status_code == requests.codes.created:
            network = networkType.parseString(response.content, True)
            task = network.get_Tasks().get_Task()[0]
            return (True, task)
        else:
            return (False, response.content)
Esempio n. 10
0
 def undeploy(self, action='powerOff'):
     undeployVAppParams = vcloudType.UndeployVAppParamsType()
     # The valid values of action are powerOff (Power off the VMs. This is the default action if
     # this attribute is missing or empty), suspend (Suspend the VMs), shutdown (Shut down the VMs),
     # force (Attempt to power off the VMs. Failures in undeploying the VM or associated networks
     # are ignored. All references to the vApp and its VMs are removed from the database),
     # default (Use the actions, order, and delay specified in the StartupSection).
     undeployVAppParams.set_UndeployPowerAction(action)
     body = CommonUtils.convertPythonObjToStr(undeployVAppParams, name = "UndeployVAppParams",
             namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"')
     return self.execute("undeploy", "post", body=body)
Esempio n. 11
0
 def undeploy(self, action='powerOff'):
     undeployVAppParams = vcloudType.UndeployVAppParamsType()
     # The valid values of action are powerOff (Power off the VMs. This is the default action if
     # this attribute is missing or empty), suspend (Suspend the VMs), shutdown (Shut down the VMs),
     # force (Attempt to power off the VMs. Failures in undeploying the VM or associated networks
     # are ignored. All references to the vApp and its VMs are removed from the database),
     # default (Use the actions, order, and delay specified in the StartupSection).
     undeployVAppParams.set_UndeployPowerAction(action)
     body = CommonUtils.convertPythonObjToStr(
         undeployVAppParams,
         name="UndeployVAppParams",
         namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5"')
     return self.execute("undeploy", "post", body=body)
Esempio n. 12
0
    def create_snapshot(self):
        """
        Create a new snapshot of the vApp state.

        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """
        snapshot_name = '{}_snapshot_{}'.format(self.name, int(round(time.time() * 1000)))
        createSnapshotParams = vcloudType.CreateSnapshotParamsType()
        createSnapshotParams.set_name(snapshot_name)
        createSnapshotParams.set_Description(snapshot_name)
        body = CommonUtils.convertPythonObjToStr(createSnapshotParams, name="CreateSnapshotParams",
                                                 namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5"')
        return self.execute("snapshot:create", "post", body)
Esempio n. 13
0
    def deploy(self, powerOn=True):
        """
        Deploy the vapp

        :param powerOn: (bool, optional): Power on the vApp and its contained VMs after deployment.
        :return: (bool): True if the user was vApp was successfully deployed, False otherwise.

        """
        powerOnValue = 'true' if powerOn else 'false'
        deployVAppParams = vcloudType.DeployVAppParamsType()
        deployVAppParams.set_powerOn(powerOnValue)
        body = CommonUtils.convertPythonObjToStr(deployVAppParams, name = "DeployVAppParams",
                namespacedef = 'xmlns="http://www.vmware.com/vcloud/v1.5"')
        return self.execute("deploy", "post", body=body)
Esempio n. 14
0
    def modify_vm_memory(self, vm_name, new_size):
        """
        Modify the virtual Memory allocation for VM.

        :param vm_name: (str): The name of the vm to be customized.
        :param new_size: (int): The new memory allocation in MB.
        :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:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vm.get_Section()
                virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0]
                items = virtualHardwareSection.get_Item()
                memory = filter(lambda item: item.get_Description().get_valueOf_() == "Memory Size", items)[0]
                href = memory.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href')
                en = memory.get_ElementName()
                en.set_valueOf_('%s MB of memory' % new_size)
                memory.set_ElementName(en)
                vq = memory.get_VirtualQuantity()
                vq.set_valueOf_(new_size)
                memory.set_VirtualQuantity(vq)
                weight = memory.get_Weight()
                weight.set_valueOf_(str(int(new_size)*10))
                memory.set_Weight(weight)
                memory_string = CommonUtils.convertPythonObjToStr(memory, 'Memory')
                Log.debug(self.logger, "memory: \n%s" % memory_string)
                output = StringIO()
                memory.export(output,
                    0,
                    name_ = 'Item',
                    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 = True)
                body = output.getvalue().\
                    replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                    replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
                self.response = Http.put(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:
                    raise Exception(self.response.status_code)
        raise Exception('can\'t find vm')
Esempio n. 15
0
    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))
Esempio n. 16
0
    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 = requests.post(postlink,
                                      data=body,
                                      headers=headers,
                                      verify=self.verify)
        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)
Esempio n. 17
0
 def  modify_vm_memory(self, new_size):
     children = self.me.get_Children()
     if children:
         vms = children.get_Vm()
         for vm in vms:
             sections = vm.get_Section()
             virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0]
             items = virtualHardwareSection.get_Item()
             memory = filter(lambda item: item.get_Description().get_valueOf_() == "Memory Size", items)[0]
             href = memory.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href')
             en = memory.get_ElementName()
             en.set_valueOf_('%s MB of memory' % new_size)
             memory.set_ElementName(en)
             vq = memory.get_VirtualQuantity()
             vq.set_valueOf_(new_size)
             memory.set_VirtualQuantity(vq)
             weight = memory.get_Weight()
             weight.set_valueOf_(str(int(new_size)*10))
             memory.set_Weight(weight)
             memory_string = CommonUtils.convertPythonObjToStr(memory, 'Memory')
             output = StringIO()
             memory.export(output,
                 0,
                 name_ = 'Item',
                 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 = True)
             body = output.getvalue().\
                 replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                 replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
             response = self._invoke_api(requests, 'put',
                                         href,
                                         headers=self.headers,
                                         data=body,
                                         verify=self.verify)
             if response.status_code == requests.codes.accepted:
                 task = taskType.parseString(response.content, True)
                 return (True, task)
             else:
                 return (False, response.content)
     raise Exception('can\'t find vm')
Esempio n. 18
0
    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 = requests.post(postlink, data=body, headers=headers, verify=self.verify)
        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)
Esempio n. 19
0
 def modify_vm_cpu(self, cpus):
     children = self.me.get_Children()
     if children:
         vms = children.get_Vm()
         for vm in vms:
             sections = vm.get_Section()
             virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0]
             items = virtualHardwareSection.get_Item()
             cpu = filter(lambda item: (item.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href') != None and item.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href').endswith('/virtualHardwareSection/cpu')), items)[0]
             href = cpu.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href')
             en = cpu.get_ElementName()
             en.set_valueOf_('%s virtual CPU(s)' % cpus)
             cpu.set_ElementName(en)
             vq = cpu.get_VirtualQuantity()
             vq.set_valueOf_(cpus)
             cpu.set_VirtualQuantity(vq)
             cpu_string = CommonUtils.convertPythonObjToStr(cpu, 'CPU')
             output = StringIO()
             cpu.export(output,
                 0,
                 name_ = 'Item',
                 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 = True)
             body = output.getvalue().\
                 replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                 replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
             response = self._invoke_api(requests, 'put',
                                         href,
                                         headers=self.headers,
                                         data=body,
                                         verify=self.verify)
             if response.status_code == requests.codes.accepted:
                 task = taskType.parseString(response.content, True)
                 return (True, task)
             else:
                 return (False, response.content)
     raise Exception('can\'t find vm')
Esempio n. 20
0
    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))