Esempio n. 1
0
    def _create_session(self):
        """Establish session with the server."""

        if self._session_id and self.is_current_session_active():
            LOG.debug("Current session: %s is active.", self._session_id)
            return

        # Login and create new session with the server for making API calls.
        LOG.debug("Logging in with username = %s.", self._server_username)
        result = self.vca.login(password=self._server_password, org=self._org)
        if not result:
            raise exceptions.VCloudDriverException(
                "Logging error with username:%s " % self._server_username)
        result = self.vca.login(token=self.vca.token,
                                org=self._org,
                                org_url=self.vca.vcloud_session.org_url)
        if not result:
            raise exceptions.VCloudDriverException(
                "Logging error with username:%s with token " %
                self._server_username)

        self._session_id = self.vca.token

        # We need to save the username in the session since we may need it
        # later to check active session. The SessionIsActive method requires
        # the username parameter to be exactly same as that in the session
        # object. We can't use the username used for login since the Login
        # method ignores the case.
        self._session_username = self.vca.username
        LOG.info("Successfully established new session; session ID is %s.",
                 self._session_id)
Esempio n. 2
0
    def _poll_task(self, task):
        """Poll the given task until completion.

        If the task completes successfully, the method returns the task info
        using the input event (param done). In case of any error, appropriate
        exception is set in the event.

        :param task: managed object reference of the task
        """
        LOG.debug("Invoking VCA API to read info of task: %s.", task)
        try:
            task_info = self.invoke_api(self.vca, "get_task_result", task)
        except exceptions.VCloudDriverException:
            with excutils.save_and_reraise_exception():
                LOG.exception(
                    "Error occurred while reading info of "
                    "task: %s.", task)
        else:
            if task_info['status'] in ['queued', 'running']:
                if hasattr(task_info, 'progress'):
                    LOG.debug("Task: %(task)s progress is %(progress)s%%.", {
                        'task': task,
                        'progress': task_info.progress
                    })
            elif task_info['status'] == 'success':
                LOG.debug("Task: %s status is success.", task)
                raise loopingcall.LoopingCallDone(task_info)
            else:
                raise exceptions.VCloudDriverException(
                    "Task execute failed, task:%s", task)
Esempio n. 3
0
    def get_isolated_network_href(self, vdc_name, network_name):
        vdc = self.get_vdc(vdc_name)
        if vdc is None:
            LOG.error(
                "Get_isolated_network_href error, cannot get vdc:"
                "%s info", vdc_name)
            excep_msg = "Get_isolated_network_href error, cannot find the "\
                "vdc:%s" % (vdc_name)
            raise exceptions.VCloudDriverException(excep_msg)

        link = filter(lambda link: link.get_rel() == "orgVdcNetworks",
                      vdc.get_Link())
        vcloud_headers = self.vcloud_session.get_vcloud_headers()
        response = self._invoke_api(requests,
                                    'get',
                                    link[0].get_href(),
                                    headers=vcloud_headers,
                                    verify=self.verify)
        queryResultRecords = queryRecordViewType.parseString(
            response.content, True)
        if response.status_code == requests.codes.forbidden:
            excep_msg = "Get_isolated_network_href error, network_name:%s"\
                % (network_name)
            raise exceptions.ForbiddenException(excep_msg)
        if response.status_code == requests.codes.ok:
            for record in queryResultRecords.get_Record():
                if record.name == network_name:
                    return record.href
        elif response.status_code == requests.codes.forbidden:
            excep_msg = "Get_isolated_network_href forbidden, network_name:%s"\
                % (network_name)
            raise exceptions.ForbiddenException(excep_msg)
        else:
            excep_msg = "Get_isolated_network_href failed response:%s"\
                % (response)
            raise exceptions.VCloudDriverException(excep_msg)
Esempio n. 4
0
def delete_orgvdcnetwork_with_name(session, org_vdc_name, network_name):
    """delete the org vdc network with given name """
    result, task = session._call_method(session.vca, "delete_isolated_vdc_network",
                                        org_vdc_name, network_name)

    # check the task is success or not
    if not result:
        raise exceptions.VCloudDriverException(
            "Delete_org_network error, task:" +
            task)
    if task is None:
        LOG.debug("Delete_org_network finished, task is none, network_name:"
                  "%s", network_name)
        return

    session._wait_for_task(task)
Esempio n. 5
0
def create_orgvdcnetwork_with_name(session, org_vdc_name, network_name):
    gateway_name = ''
    start_address = '192.168.0.1'
    end_address = '192.168.0.253'
    gateway_ip = '192.168.0.254'
    netmask = '255.255.255.0'
    result, task = session._call_method(session.vca,
                                        "create_isolated_vdc_network",
                                        org_vdc_name, network_name,
                                        gateway_name, start_address,
                                        end_address, gateway_ip, netmask)

    # check the task is success or not
    if not result:
        raise exceptions.VCloudDriverException(
            "Create_org_network error, task:" + task)

    session._wait_for_task(task)
Esempio n. 6
0
 def _invoke_api(self, module, method, *args, **kwargs):
     try:
         api_method = getattr(module, method)
         return api_method(*args, **kwargs)
     except requests_excep.SSLError as excep:
         excep_msg = ("Invoking method SSLError %(module)s.%(method)s" % {
             'module': module,
             'method': method
         })
         LOG.error(excep_msg, exc_info=True)
         raise exceptions.SSLError(excep_msg)
     except requests_excep.RequestException as re:
         excep_msg = ("Invoking method request error"
                      "%(module)s.%(method)s" % {
                          'module': module,
                          'method': method
                      })
         LOG.error(excep_msg, exc_info=True)
         raise exceptions.VCloudDriverException(re)
Esempio n. 7
0
 def get_vdc(self, vdc_name):
     if self.vcloud_session and self.vcloud_session.organization:
         refs = filter(
             lambda ref: ref.name == vdc_name and ref.type_ ==
             'application/vnd.vmware.vcloud.vdc+xml',
             self.vcloud_session.organization.Link)
         if len(refs) == 1:
             headers = self.vcloud_session.get_vcloud_headers()
             response = self._invoke_api(requests,
                                         'get',
                                         refs[0].href,
                                         headers=headers,
                                         verify=self.verify)
             if response.status_code == requests.codes.ok:
                 return vdcType.parseString(response.content, True)
             elif response.status_code == requests.codes.forbidden:
                 excep_msg = "Get_vdc forbidden, vdc_name:%s" % (vdc_name)
                 raise exceptions.ForbiddenException(excep_msg)
             else:
                 excep_msg = "Get_vdc failed, response:%s" % (response)
                 raise exceptions.VCloudDriverException(excep_msg)
Esempio n. 8
0
    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)