示例#1
0
def blueprint(cmd_proc, operation, blueprint, blueprint_file, include_plan):
    """Operations with Blueprints"""
    scoreclient = None
    if 'validate' != operation:
        scoreclient = _authorize(cmd_proc)
    else:
        scoreclient = Score(cmd_proc.host_score)
        Log.debug(cmd_proc.logger, 'using host score: %s' %
                  cmd_proc.host_score)
    if 'validate' == operation:
        _validate(cmd_proc, blueprint_file, scoreclient)
    elif 'list' == operation:
        _list_blueprints(cmd_proc, scoreclient)
    elif 'upload' == operation:
        _upload(cmd_proc, blueprint, blueprint_file, scoreclient)
    elif 'delete' == operation:
        _delete_blueprint(cmd_proc, blueprint, scoreclient)
    elif 'info' == operation:
        _info_blueprint(cmd_proc, scoreclient,
                        include_plan=include_plan)
    elif 'status' == operation:
        try:
            scoreclient = _authorize(cmd_proc)
            status = scoreclient.get_status()
            print_utils.print_dict(json.loads(status))
        except exceptions.ClientException as e:
            utils.print_error("Unable to get blueprinting service status. "
                              "Reason: {0}"
                              .format(str(e)), cmd_proc)
示例#2
0
 def block_until_completed(self, task):
     progress = task.get_Progress()
     status = task.get_status()
     rnd = 0
     while status != "success":
         if status == "error":
             error = task.get_Error()
             Log.error(self.logger, "task error, major=%s, minor=%s, message=%s" % (error.get_majorErrorCode(), error.get_minorErrorCode(), error.get_message()))
             return False
         else:
             # some task doesn't not report progress
             if progress:
                 pass
             else:
                 rnd += 1
             time.sleep(1)
             self.response = Http.get(task.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
             if self.response.status_code == requests.codes.ok:
                 task = taskType.parseString(self.response.content, True)
                 progress = task.get_Progress()
                 status = task.get_status()
             else:
                 Log.error(self.logger, "can't get task")
                 return False
     return True
示例#3
0
文件: cmd_proc.py 项目: namob/vca-cli
 def login(self,
           host,
           username,
           password,
           instance,
           org,
           version,
           save_password=True):
     self.vca = VCA(host=host,
                    username=username,
                    version=version,
                    verify=self.verify,
                    log=self.debug)
     service_type = self.vca.get_service_type()
     if service_type == VCA.VCA_SERVICE_TYPE_UNKNOWN:
         raise Exception('service type unknown')
     self.vca.service_type = service_type
     if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type and \
        org is None:
         self.error_message = 'Org can\'t be null'
         return False
     result = self.vca.login(password=password, org=org)
     if result:
         Log.debug(self.logger, 'logged in, org=%s' % self.vca.org)
         if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
             result = self.vca.vcloud_session.login(
                 token=self.vca.vcloud_session.token)
             assert result
         if save_password:
             self.password = password
         self.save_config(self.profile, self.profile_file)
     return result
示例#4
0
文件: score.py 项目: lasko/pyvcloud
 def list(self, deployment_id):
     params = {'deployment_id': deployment_id}
     self.score.response = Http.get(self.score.url + '/executions', headers=self.score.get_headers(), params=params,  verify=self.score.verify, logger=self.logger)
     if self.score.response.status_code == requests.codes.ok:
         return json.loads(self.score.response.content)
     else:
         Log.error(self.logger, 'list executions returned %s' % self.score.response.status_code)
示例#5
0
 def get_status(self):
     self.response = Http.get(self.url + '/status',
                              headers=self.get_headers(),
                              verify=self.verify, logger=self.logger)
     Log.debug(self.logger, self.response.status_code)
     Log.debug(self.logger, self.response.content)
     return self.response.content
示例#6
0
 def get_status(self):
     self.response = Http.get(self.url + '/status',
                              headers=self.get_headers(),
                              verify=self.verify,
                              logger=self.logger)
     Log.debug(self.logger, self.response.status_code)
     Log.debug(self.logger, self.response.content)
     return self.response.content
 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()
示例#8
0
def blueprint(cmd_proc, operation, blueprint_id, blueprint_file, include_plan):
    """Operations with Blueprints"""

    if "validate" != operation:
        scoreclient = _authorize(cmd_proc)
    else:
        scoreclient = Score(cmd_proc.host_score)
        Log.debug(cmd_proc.logger, "using host score: %s" % cmd_proc.host_score)

    _run_operation(cmd_proc, operation, blueprint_id, blueprint_file, include_plan, scoreclient)
示例#9
0
    def customize_guest_os(self, vm_name, customization_script=None,
                           computer_name=None, admin_password=None,
                           reset_password_required=False):
        """
        Associate a customization script with a guest OS and execute the script.
        The VMware tools must be installed in the Guest OS.

        :param vm_name: (str): The name of the vm to be customized.
        :param customization_script: (str, Optional): The path to a file on the local file system containing the customization script.
        :param computer_name: (str, Optional): A new value for the the computer name. A default value for the template is used if a value is not set.
        :param admin_password: (str, Optional): A password value for the admin/root user. A password is autogenerated if a value is not supplied.
        :param reset_password_required: (bool): Force the user to reset the password on first login.
        :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.

        """
        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()
                customization_section = [section for section in sections
                         if (section.__class__.__name__ ==
                             "GuestCustomizationSectionType")
                         ][0]
                customization_section.set_Enabled(True)
                customization_section.set_ResetPasswordRequired(
                    reset_password_required)
                customization_section.set_AdminAutoLogonEnabled(False)
                customization_section.set_AdminAutoLogonCount(0)
                if customization_script:
                    customization_section.set_CustomizationScript(
                        customization_script)
                if computer_name:
                    customization_section.set_ComputerName(computer_name)
                if admin_password:
                    customization_section.set_AdminPasswordEnabled(True)
                    customization_section.set_AdminPasswordAuto(False)
                    customization_section.set_AdminPassword(admin_password)
                output = StringIO()
                customization_section.export(output,
                    0,
                    name_ = 'GuestCustomizationSection',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                    pretty_print = True)
                body = output.getvalue().\
                    replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                    replace("/Info", "/ovf:Info")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.guestcustomizationsection+xml'
                self.response = Http.put(customization_section.Link[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, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text))
示例#10
0
文件: vapp.py 项目: nmishkin/pyvcloud
    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
示例#11
0
    def disconnect_vms(self, network_name=None):
        """
        Disconnect the vm from the vapp network. 

        :param network_name: (string): The name of the vApp network. If None, then disconnect from all the networks.
        :return: (bool): True if the user was vApp was successfully deployed, False otherwise.
            
        """
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                Log.debug(self.logger, "child VM name=%s" % vm.get_name())
                networkConnectionSection = [
                    section for section in vm.get_Section()
                    if isinstance(section, NetworkConnectionSectionType)
                ][0]
                found = -1
                if network_name is None:
                    networkConnectionSection.set_NetworkConnection([])
                    found = 1
                else:
                    for index, networkConnection in enumerate(
                            networkConnectionSection.get_NetworkConnection()):
                        if networkConnection.get_network() == network_name:
                            found = index
                            break
                    if found != -1:
                        networkConnectionSection.NetworkConnection.pop(found)
                if found != -1:
                    output = StringIO()
                    networkConnectionSection.export(
                        output,
                        0,
                        name_='NetworkConnectionSection',
                        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().replace("vmw:Info", "ovf:Info")
                    self.response = Http.put(vm.get_href() +
                                             "/networkConnectionSection/",
                                             data=body,
                                             headers=self.headers,
                                             verify=self.verify,
                                             logger=self.logger)
                    if self.response.status_code == requests.codes.accepted:
                        return taskType.parseString(self.response.content,
                                                    True)
        task = TaskType()
        task.set_status("success")
        task.set_Progress("100")
        return task
示例#12
0
def blueprint(cmd_proc, operation, blueprint_id, blueprint_file, include_plan):
    """Operations with Blueprints"""

    if 'validate' != operation:
        scoreclient = _authorize(cmd_proc)
    else:
        scoreclient = Score(cmd_proc.host_score)
        Log.debug(cmd_proc.logger, 'using host score: %s' %
                  cmd_proc.host_score)

    _run_operation(cmd_proc, operation,
                   blueprint_id, blueprint_file,
                   include_plan, scoreclient)
示例#13
0
 def list(self, deployment_id):
     params = {'deployment_id': deployment_id}
     self.score.response = Http.get(self.score.url + '/executions',
                                    headers=self.score.get_headers(),
                                    params=params,
                                    verify=self.score.verify,
                                    logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         Log.error(
             self.logger, 'list executions returned %s' %
             self.score.response.status_code)
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
示例#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')
示例#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))
示例#16
0
 def delete_vapp(self, vdc_name, vapp_name):
     self.vdc = self.get_vdc(vdc_name)
     if not self.vcloud_session or not self.vcloud_session.organization or not self.vdc: return False
     vapp = self.get_vapp(self.vdc, vapp_name)
     if not vapp: return False
     #undeploy and remove
     if vapp.me.deployed:
         task = vapp.undeploy()
         if task:
             self.block_until_completed(task)
         else:
             Log.debug(self.logger, "vapp.undeploy() didn't return a task")
             return False
     vapp = self.get_vapp(self.vdc, vapp_name)
     if vapp: return vapp.delete()
     Log.debug(self.logger, "no vApp")
示例#17
0
    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')
示例#18
0
文件: vapp.py 项目: nmishkin/pyvcloud
 def customize_guest_os(self, vm_name, customization_script=None,
                        computer_name=None, admin_password=None,
                        reset_password_required=False):
     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()
             customization_section = [section for section in sections
                      if (section.__class__.__name__ ==
                          "GuestCustomizationSectionType")
                      ][0]
             customization_section.set_Enabled(True)
             customization_section.set_ResetPasswordRequired(
                 reset_password_required)
             customization_section.set_AdminAutoLogonEnabled(False)
             customization_section.set_AdminAutoLogonCount(0)
             if customization_script:
                 customization_section.set_CustomizationScript(
                     customization_script)
             if computer_name:
                 customization_section.set_ComputerName(computer_name)
             if admin_password:
                 customization_section.set_AdminPasswordEnabled(True)
                 customization_section.set_AdminPasswordAuto(False)
                 customization_section.set_AdminPassword(admin_password)
             output = StringIO()
             customization_section.export(output,
                 0,
                 name_ = 'GuestCustomizationSection',
                 namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                 pretty_print = False)
             body = output.getvalue().\
                 replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                 replace("/Info", "/ovf:Info")
             headers = self.headers
             headers['Content-type'] = 'application/vnd.vmware.vcloud.guestcustomizationsection+xml'
             self.response = Http.put(customization_section.Link[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, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text))
示例#19
0
    def get_vms_details(self):
        """
        Return a list the details for all VMs contained in the vApp.

        :return: (list) a list, one entry per vm containing a (dict) of properties for the VM. \n
         Dictionary keys 'name','status','cpus','memory','memory_mb','os','owner','admin_password','reset_password_required'
        """

        result = []
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                name = vm.get_name()
                status = VCLOUD_STATUS_MAP[vm.get_status()]
                owner = self.me.get_Owner().get_User().get_name()
                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_Description().get_valueOf_() == "Number of Virtual CPUs", items)[0]
                cpu_capacity = int(cpu.get_ElementName().get_valueOf_().split(" virtual CPU(s)")[0])
                memory = filter(lambda item: item.get_Description().get_valueOf_() == "Memory Size", items)[0]
                memory_capacity_mb = int(memory.get_ElementName().get_valueOf_().split(" MB of memory")[0])
                memory_capacity = memory_capacity_mb / 1024
                operatingSystemSection = filter(lambda section: section.__class__.__name__== "OperatingSystemSection_Type", sections)[0]
                os = operatingSystemSection.get_Description().get_valueOf_()
                customization_section = filter(lambda section: section.__class__.__name__== "GuestCustomizationSectionType", sections)[0]
                result.append(
                    {'name': name,
                     'status': status,
                     'cpus': cpu_capacity,
                     'memory': memory_capacity,
                     'memory_mb': memory_capacity_mb,
                     'os': os,
                     'owner': owner,
                     'admin_password': customization_section.get_AdminPassword(),
                     'reset_password_required': customization_section.get_ResetPasswordRequired()
                     }
                )
        Log.debug(self.logger, "details of VMs: %s" % result)
        return result
示例#20
0
文件: vapp.py 项目: piraz/pyvcloud
    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
示例#21
0
    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
示例#22
0
文件: vapp.py 项目: kostya13/pyvcloud
    def disconnect_vms(self, network_name=None):
        """
        Disconnect the vm from the vapp network.

        :param network_name: (string): The name of the vApp network. If None, then disconnect from all the networks.
        :return: (bool): True if the user was vApp was successfully deployed, False otherwise.

        """
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                Log.debug(self.logger, "child VM name=%s" % vm.get_name())
                networkConnectionSection = [section for section in vm.get_Section() if isinstance(section, NetworkConnectionSectionType)][0]
                found = -1
                if network_name is None:
                    networkConnectionSection.set_NetworkConnection([])
                    found = 1
                else:
                    for index, networkConnection in enumerate(networkConnectionSection.get_NetworkConnection()):
                        if networkConnection.get_network() == network_name:
                            found = index
                            break
                    if found != -1:
                        networkConnectionSection.NetworkConnection.pop(found)
                if found != -1:
                    output = StringIO()
                    networkConnectionSection.export(output,
                        0,
                        name_ = 'NetworkConnectionSection',
                        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().replace("vmw:Info", "ovf:Info")
                    self.response = Http.put(vm.get_href() + "/networkConnectionSection/", data=body, headers=self.headers, verify=self.verify, logger=self.logger)
                    if self.response.status_code == requests.codes.accepted:
                        return taskType.parseString(self.response.content, True)
        task = TaskType()
        task.set_status("success")
        task.set_Progress("100")
        return task
示例#23
0
文件: vapp.py 项目: nmishkin/pyvcloud
 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))
示例#24
0
 def login(self, host, username, password, instance, org, version,
           save_password=True):
     self.vca = VCA(host=host, username=username, version=version,
                    verify=self.verify, log=self.debug)
     service_type = self.vca.get_service_type()
     if service_type == VCA.VCA_SERVICE_TYPE_UNKNOWN:
         raise Exception('service type unknown')
     self.vca.service_type = service_type
     if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type and \
        org is None:
         self.error_message = 'Org can\'t be null'
         return False
     result = self.vca.login(password=password, org=org)
     if result:
         Log.debug(self.logger, 'logged in, org=%s' % self.vca.org)
         if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
             result = self.vca.vcloud_session.login(token=self.vca.
                                                    vcloud_session.token)
             assert result
         if save_password:
             self.password = password
         self.save_config(self.profile, self.profile_file)
     return result
示例#25
0
文件: vapp.py 项目: kostya13/pyvcloud
    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))
示例#26
0
文件: vapp.py 项目: kostya13/pyvcloud
    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')
示例#27
0
 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
示例#28
0
文件: vapp.py 项目: kostya13/pyvcloud
    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
示例#29
0
文件: vapp.py 项目: nmishkin/pyvcloud
 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
示例#30
0
文件: cmd_proc.py 项目: namob/vca-cli
 def re_login_vcloud_session(self):
     Log.debug(self.logger,
               'about to re-login vcloud_session vca=%s' % self.vca)
     if self.vca.vcloud_session is not None:
         Log.debug(
             self.logger, 'about to re-login vcloud_session=%s' %
             self.vca.vcloud_session)
         if self.vca.vcloud_session.token is not None:
             Log.debug(
                 self.logger, 'about to re-login vcloud_session token=%s' %
                 self.vca.vcloud_session.token)
     if self.vca.vcloud_session is not None and \
        self.vca.vcloud_session.token is not None:
         result = self.vca.vcloud_session.login(
             token=self.vca.vcloud_session.token)
         if not result:
             Log.debug(self.logger,
                       'vcloud session invalid, getting a new one')
             if self.vca.service_type in [
                     VCA.VCA_SERVICE_TYPE_VCHS, 'subscription'
             ]:
                 result = self.vca.login_to_org(self.instance, self.vca.org)
             elif self.vca.service_type in [
                     VCA.VCA_SERVICE_TYPE_VCA, 'ondemand'
             ]:
                 result = self.vca.login_to_instance_sso(self.instance)
             if result:
                 Log.debug(self.logger,
                           'successfully retrieved a new vcloud session')
             else:
                 raise Exception("Couldn't retrieve a new vcloud session")
         else:
             Log.debug(self.logger, 'vcloud session is valid')
示例#31
0
def login(cmd_proc, user, host, password, do_not_save_password,
          service_version, instance, org, vdc, host_score):
    """Login to a vCloud service"""
    if not (host.startswith('https://') or host.startswith('http://')):
        host = 'https://' + host
    if not (host_score.startswith('https://')
            or host_score.startswith('http://')):
        host_score = 'https://' + host_score
    try:
        cmd_proc.logout()
        result = cmd_proc.login(host,
                                user,
                                password,
                                instance=instance,
                                org=org,
                                version=service_version,
                                save_password=(not do_not_save_password))
        if result:
            utils.print_message(
                "User '%s' logged in, profile '%s'" %
                (cmd_proc.vca.username, cmd_proc.profile), cmd_proc)
            if not do_not_save_password:
                utils.print_warning(
                    'Password encrypted and saved ' +
                    'in local profile. Use ' +
                    '--do-not-save-password to disable it.', cmd_proc)
            cmd_proc.host_score = host_score
            cmd_proc.save_current_config()
            if cmd_proc.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCA]:
                if instance is not None:
                    result = _use_instance(cmd_proc, instance)
                    if result:
                        if vdc is None:
                            vdcs = cmd_proc.vca.get_vdc_names()
                            if len(vdcs) > 0:
                                vdc = vdcs[0]
                        if vdc is not None:
                            the_vdc = cmd_proc.vca.get_vdc(vdc)
                            if the_vdc is not None:
                                utils.print_message(
                                    "Using VDC '%s'"
                                    ", profile '%s'" % (vdc, cmd_proc.profile),
                                    cmd_proc)
                                cmd_proc.vdc_name = vdc
                                cmd_proc.select_default_gateway()
                            else:
                                utils.print_error(
                                    "Unable to select VDC "
                                    "'%s', profile '%s'" %
                                    (vdc, cmd_proc.profile), cmd_proc)
                                sys.exit(1)
                        cmd_proc.save_current_config()
            elif cmd_proc.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCHS]:
                if instance is not None or org is not None:
                    result = _use_instance_org(cmd_proc, instance, org)
                    if result:
                        if vdc is None:
                            vdcs = cmd_proc.vca.get_vdc_names()
                            if len(vdcs) > 0:
                                vdc = vdcs[0]
                        if vdc is not None:
                            the_vdc = cmd_proc.vca.get_vdc(vdc)
                            if the_vdc is not None:
                                utils.print_message(
                                    "Using VDC '%s'"
                                    ", profile '%s'" % (vdc, cmd_proc.profile),
                                    cmd_proc)
                                cmd_proc.vdc_name = vdc
                                cmd_proc.select_default_gateway()
                            else:
                                utils.print_error(
                                    "Unable to select VDC "
                                    "'%s', profile '%s'" %
                                    (vdc, cmd_proc.profile), cmd_proc)
                                sys.exit(1)
                        cmd_proc.save_current_config()
            elif (cmd_proc.vca.service_type
                  in [VCA.VCA_SERVICE_TYPE_STANDALONE]):
                if vdc is None:
                    vdcs = cmd_proc.vca.get_vdc_names()
                    Log.debug(cmd_proc.logger, 'vdcs=%s' % vdcs)
                    if len(vdcs) > 0:
                        vdc = vdcs[0]
                if vdc is not None:
                    Log.debug(cmd_proc.logger, 'Select vdc=%s' % vdc)
                    cmd_proc.save_current_config()
                    result = cmd_proc.re_login()
                    the_vdc = cmd_proc.vca.get_vdc(vdc)
                    Log.debug(cmd_proc.logger, 'Select vdc=%s' % the_vdc)
                    if the_vdc is not None:
                        utils.print_message(
                            "Using VDC '%s'"
                            ", profile '%s'" % (vdc, cmd_proc.profile),
                            cmd_proc)
                        cmd_proc.vdc_name = vdc
                        cmd_proc.select_default_gateway()
                    else:
                        utils.print_error(
                            "Unable to select VDC "
                            "'%s' , profile '%s'" % (vdc, cmd_proc.profile),
                            cmd_proc)
                        sys.exit(1)
                cmd_proc.save_current_config()
        else:
            utils.print_error('Can\'t login', cmd_proc)
            sys.exit(1)
    except Exception as e:
        utils.print_error('Can\'t login: ' + str(e), cmd_proc)
        sys.exit(1)
示例#32
0
 def re_login_vcloud_session(self):
     Log.debug(self.logger, 'about to re-login vcloud_session vca=%s' %
               self.vca)
     if self.vca.vcloud_session is not None:
         Log.debug(self.logger, 'about to re-login vcloud_session=%s' %
                   self.vca.vcloud_session)
         if self.vca.vcloud_session.token is not None:
             Log.debug(self.logger,
                       'about to re-login vcloud_session token=%s' %
                       self.vca.vcloud_session.token)
     if self.vca.vcloud_session is not None and \
        self.vca.vcloud_session.token is not None:
         result = self.vca.vcloud_session.login(
             token=self.vca.vcloud_session.token)
         if not result:
             Log.debug(self.logger,
                       'vcloud session invalid, getting a new one')
             if self.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCHS,
                                          'subscription']:
                 result = self.vca.login_to_org(self.instance, self.vca.org)
             elif self.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCA,
                                            'ondemand']:
                 result = self.vca.login_to_instance_sso(self.instance)
             if result:
                 Log.debug(self.logger,
                           'successfully retrieved a new vcloud session')
             else:
                 raise Exception("Couldn't retrieve a new vcloud session")
         else:
             Log.debug(self.logger, 'vcloud session is valid')
示例#33
0
def login(cmd_proc, user, host, password, do_not_save_password,
          service_version, instance, org, vdc, host_score):
    """Login to a vCloud service"""
    if not (host.startswith('https://') or host.startswith('http://')):
        host = 'https://' + host
    if not (host_score.startswith('https://') or
            host_score.startswith('http://')):
        host_score = 'https://' + host_score
    try:
        cmd_proc.logout()
        result = cmd_proc.login(host, user, password,
                                instance=instance,
                                org=org,
                                version=service_version,
                                save_password=(not do_not_save_password))
        if result:
            utils.print_message("User '%s' logged in, profile '%s'" %
                                (cmd_proc.vca.username, cmd_proc.profile),
                                cmd_proc)
            if not do_not_save_password:
                utils.print_warning('Password encrypted and saved ' +
                                    'in local profile. Use ' +
                                    '--do-not-save-password to disable it.',
                                    cmd_proc)
            cmd_proc.host_score = host_score
            cmd_proc.save_current_config()
            if cmd_proc.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCA]:
                if instance is not None:
                    result = _use_instance(cmd_proc, instance)
                    if result:
                        if vdc is None:
                            vdcs = cmd_proc.vca.get_vdc_names()
                            if len(vdcs) > 0:
                                vdc = vdcs[0]
                        if vdc is not None:
                            the_vdc = cmd_proc.vca.get_vdc(vdc)
                            if the_vdc is not None:
                                utils.print_message("Using VDC '%s'"
                                                    ", profile '%s'" %
                                                    (vdc, cmd_proc.profile),
                                                    cmd_proc)
                                cmd_proc.vdc_name = vdc
                                cmd_proc.select_default_gateway()
                            else:
                                utils.print_error("Unable to select VDC "
                                                  "'%s', profile '%s'" %
                                                  (vdc, cmd_proc.profile),
                                                  cmd_proc)
                                sys.exit(1)
                        cmd_proc.save_current_config()
            elif cmd_proc.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCHS]:
                if instance is not None or org is not None:
                    result = _use_instance_org(cmd_proc, instance, org)
                    if result:
                        if vdc is None:
                            vdcs = cmd_proc.vca.get_vdc_names()
                            if len(vdcs) > 0:
                                vdc = vdcs[0]
                        if vdc is not None:
                            the_vdc = cmd_proc.vca.get_vdc(vdc)
                            if the_vdc is not None:
                                utils.print_message("Using VDC '%s'"
                                                    ", profile '%s'" %
                                                    (vdc, cmd_proc.profile),
                                                    cmd_proc)
                                cmd_proc.vdc_name = vdc
                                cmd_proc.select_default_gateway()
                            else:
                                utils.print_error("Unable to select VDC "
                                                  "'%s', profile '%s'" %
                                                  (vdc, cmd_proc.profile),
                                                  cmd_proc)
                                sys.exit(1)
                        cmd_proc.save_current_config()
            elif (cmd_proc.vca.service_type in
                  [VCA.VCA_SERVICE_TYPE_STANDALONE]):
                if vdc is None:
                    vdcs = cmd_proc.vca.get_vdc_names()
                    Log.debug(cmd_proc.logger, 'vdcs=%s' % vdcs)
                    if len(vdcs) > 0:
                        vdc = vdcs[0]
                if vdc is not None:
                    Log.debug(cmd_proc.logger, 'Select vdc=%s' % vdc)
                    cmd_proc.save_current_config()
                    result = cmd_proc.re_login()
                    the_vdc = cmd_proc.vca.get_vdc(vdc)
                    Log.debug(cmd_proc.logger, 'Select vdc=%s' % the_vdc)
                    if the_vdc is not None:
                        utils.print_message("Using VDC '%s'"
                                            ", profile '%s'" %
                                            (vdc, cmd_proc.profile),
                                            cmd_proc)
                        cmd_proc.vdc_name = vdc
                        cmd_proc.select_default_gateway()
                    else:
                        utils.print_error("Unable to select VDC "
                                          "'%s' , profile '%s'" %
                                          (vdc, cmd_proc.profile),
                                          cmd_proc)
                        sys.exit(1)
                cmd_proc.save_current_config()
        else:
            utils.print_error('Can\'t login', cmd_proc)
            sys.exit(1)
    except Exception as e:
        utils.print_error('Can\'t login: ' + str(e), cmd_proc)
        sys.exit(1)
示例#34
0
文件: cmd_proc.py 项目: namob/vca-cli
 def load_config(self, profile=None, profile_file='~/.vcarc'):
     self.config.read(os.path.expanduser(profile_file))
     if profile is not None:
         self.profile = profile
     else:
         section = 'Global'
         if self.config.has_option(section, 'profile'):
             self.profile = self.config.get(section, 'profile')
         else:
             self.profile = 'default'
     host = 'vca.vmware.com'
     user = None
     password = None
     token = None
     service_type = None
     version = None
     section = 'Profile-%s' % self.profile
     instance = None
     org = None
     org_url = None
     session_token = None
     session_uri = None
     vdc = None
     gateway = None
     host_score = 'score.vca.io'
     if self.config.has_section(section):
         if self.config.has_option(section, 'host'):
             host = self.config.get(section, 'host')
         if self.config.has_option(section, 'user'):
             user = self.config.get(section, 'user')
         if self.config.has_option(section, 'password'):
             password = self.config.get(section, 'password')
             if len(password) > 0:
                 cipher_suite = Fernet(self.crypto_key)
                 password = cipher_suite.decrypt(password)
         if self.config.has_option(section, 'token'):
             token = self.config.get(section, 'token')
         if self.config.has_option(section, 'service_type'):
             service_type = self.config.get(section, 'service_type')
         if self.config.has_option(section, 'service_version'):
             version = self.config.get(section, 'service_version')
         if self.config.has_option(section, 'instance'):
             instance = self.config.get(section, 'instance')
         if self.config.has_option(section, 'org'):
             org = self.config.get(section, 'org')
         if self.config.has_option(section, 'org_url'):
             org_url = self.config.get(section, 'org_url')
         if self.config.has_option(section, 'session_token'):
             session_token = self.config.get(section, 'session_token')
         if self.config.has_option(section, 'session_uri'):
             session_uri = self.config.get(section, 'session_uri')
         if self.config.has_option(section, 'vdc'):
             vdc = self.config.get(section, 'vdc')
         if self.config.has_option(section, 'gateway'):
             gateway = self.config.get(section, 'gateway')
         if self.config.has_option(section, 'host_score'):
             host_score = self.config.get(section, 'host_score')
     self.host_score = host_score
     self.vca = VCA(host=host,
                    username=user,
                    service_type=service_type,
                    version=version,
                    verify=self.verify,
                    log=self.debug)
     self.password = password
     self.vca.token = token
     self.vca.org = org
     self.instance = instance
     if session_token is not None:
         vcloud_session = VCS(url=session_uri,
                              username=user,
                              org=org,
                              instance=instance,
                              api_url=org_url,
                              org_url=org_url,
                              version=version,
                              verify=self.verify,
                              log=self.debug)
         vcloud_session.token = session_token
         self.vca.vcloud_session = vcloud_session
         self.vdc_name = vdc
         self.gateway = gateway
     Log.debug(self.logger, 'restored vca %s' % self.vca)
     if self.vca.vcloud_session is not None:
         Log.debug(self.logger,
                   'restored vcloud_session %s' % self.vca.vcloud_session)
         Log.debug(self.logger, 'restored org=%s' % self.vca.org)
         if self.vca.vcloud_session.token is not None:
             Log.debug(
                 self.logger, 'restored vcloud_session token %s' %
                 self.vca.vcloud_session.token)
示例#35
0
 def load_config(self, profile=None, profile_file='~/.vcarc'):
     self.config.read(os.path.expanduser(profile_file))
     if profile is not None:
         self.profile = profile
     else:
         section = 'Global'
         if self.config.has_option(section, 'profile'):
             self.profile = self.config.get(section, 'profile')
         else:
             self.profile = 'default'
     host = 'vca.vmware.com'
     user = None
     password = None
     token = None
     service_type = None
     version = None
     section = 'Profile-%s' % self.profile
     instance = None
     org = None
     org_url = None
     session_token = None
     session_uri = None
     vdc = None
     gateway = None
     host_score = 'score.vca.io'
     if self.config.has_section(section):
         if self.config.has_option(section, 'host'):
             host = self.config.get(section, 'host')
         if self.config.has_option(section, 'user'):
             user = self.config.get(section, 'user')
         if self.config.has_option(section, 'password'):
             password = self.config.get(section, 'password')
             if len(password) > 0:
                 cipher_suite = Fernet(self.crypto_key)
                 password = cipher_suite.decrypt(password)
         if self.config.has_option(section, 'token'):
             token = self.config.get(section, 'token')
         if self.config.has_option(section, 'service_type'):
             service_type = self.config.get(section, 'service_type')
         if self.config.has_option(section, 'service_version'):
             version = self.config.get(section, 'service_version')
         if self.config.has_option(section, 'instance'):
             instance = self.config.get(section, 'instance')
         if self.config.has_option(section, 'org'):
             org = self.config.get(section, 'org')
         if self.config.has_option(section, 'org_url'):
             org_url = self.config.get(section, 'org_url')
         if self.config.has_option(section, 'session_token'):
             session_token = self.config.get(section, 'session_token')
         if self.config.has_option(section, 'session_uri'):
             session_uri = self.config.get(section, 'session_uri')
         if self.config.has_option(section, 'vdc'):
             vdc = self.config.get(section, 'vdc')
         if self.config.has_option(section, 'gateway'):
             gateway = self.config.get(section, 'gateway')
         if self.config.has_option(section, 'host_score'):
             host_score = self.config.get(section, 'host_score')
     self.host_score = host_score
     self.vca = VCA(host=host, username=user,
                    service_type=service_type, version=version,
                    verify=self.verify, log=self.debug)
     self.password = password
     self.vca.token = token
     self.vca.org = org
     self.instance = instance
     if session_token is not None:
         vcloud_session = VCS(url=session_uri,
                              username=user,
                              org=org,
                              instance=instance,
                              api_url=org_url,
                              org_url=org_url,
                              version=version,
                              verify=self.verify,
                              log=self.debug)
         vcloud_session.token = session_token
         self.vca.vcloud_session = vcloud_session
         self.vdc_name = vdc
         self.gateway = gateway
     Log.debug(self.logger, 'restored vca %s' % self.vca)
     if self.vca.vcloud_session is not None:
         Log.debug(self.logger, 'restored vcloud_session %s' %
                   self.vca.vcloud_session)
         Log.debug(self.logger, 'restored org=%s' % self.vca.org)
         if self.vca.vcloud_session.token is not None:
             Log.debug(self.logger, 'restored vcloud_session token %s' %
                       self.vca.vcloud_session.token)
示例#36
0
文件: cmd_proc.py 项目: namob/vca-cli
 def re_login(self):
     if self.vca is None or \
        (self.vca.token is None and self.password is None):
         return False
     result = False
     try:
         Log.debug(
             self.logger,
             'about to re-login with ' + 'host=%s type=%s token=%s org=%s' %
             (self.vca.host, self.vca.service_type, self.vca.token,
              self.vca.org))
         org_url = None if self.vca.vcloud_session is None else \
             self.vca.vcloud_session.org_url
         result = self.vca.login(token=self.vca.token,
                                 org=self.vca.org,
                                 org_url=org_url)
         if result:
             Log.debug(self.logger, 'vca.login with token successful')
             self.re_login_vcloud_session()
         else:
             Log.debug(
                 self.logger, 'vca.login with token failed %s' %
                 self.vca.response.content)
             raise Exception('login with token failed')
     except Exception as e:
         Log.error(self.logger, str(e))
         tb = traceback.format_exc()
         Log.error(self.logger, tb)
         if self.password is not None and len(self.password) > 0:
             try:
                 Log.debug(self.logger, 'about to re-login with password')
                 result = self.vca.login(password=self.password,
                                         org=self.vca.org)
                 if result:
                     Log.debug(self.logger,
                               'about to re-login vcloud_session')
                     self.re_login_vcloud_session()
                     Log.debug(self.logger, 'after re-login vcloud_session')
                 self.save_config(self.profile, self.profile_file)
             except Exception:
                 return False
     return result
示例#37
0
 def re_login(self):
     if self.vca is None or \
        (self.vca.token is None and self.password is None):
         return False
     result = False
     try:
         Log.debug(self.logger,
                   'about to re-login with ' +
                   'host=%s type=%s token=%s org=%s' %
                   (self.vca.host, self.vca.service_type,
                    self.vca.token, self.vca.org))
         org_url = None if self.vca.vcloud_session is None else \
             self.vca.vcloud_session.org_url
         result = self.vca.login(token=self.vca.token,
                                 org=self.vca.org,
                                 org_url=org_url)
         if result:
             Log.debug(self.logger, 'vca.login with token successful')
             self.re_login_vcloud_session()
         else:
             Log.debug(self.logger, 'vca.login with token failed %s' %
                       self.vca.response.content)
             raise Exception('login with token failed')
     except Exception as e:
         Log.error(self.logger, str(e))
         tb = traceback.format_exc()
         Log.error(self.logger, tb)
         if self.password is not None and len(self.password) > 0:
             try:
                 Log.debug(self.logger, 'about to re-login with password')
                 result = self.vca.login(password=self.password,
                                         org=self.vca.org)
                 if result:
                     Log.debug(self.logger,
                               'about to re-login vcloud_session')
                     self.re_login_vcloud_session()
                     Log.debug(self.logger,
                               'after re-login vcloud_session')
                 self.save_config(self.profile, self.profile_file)
             except Exception:
                 return False
     return result