コード例 #1
0
ファイル: user_tests.py プロジェクト: ATGE/softlayer-python
    def test_create_user_handle_paas_exception(self):
        user_template = {"username": "******", "email": "*****@*****.**"}

        self.manager.user_service = mock.Mock()

        # FaultCode IS NOT SoftLayer_Exception_User_Customer_DelegateIamIdInvitationToPaas
        any_error = exceptions.SoftLayerAPIError(
            "SoftLayer_Exception_User_Customer",
            "This exception indicates an error")

        self.manager.user_service.createObject.side_effect = any_error

        try:
            self.manager.create_user(user_template, "Pass@123")
        except exceptions.SoftLayerAPIError as ex:
            self.assertEqual(ex.faultCode, "SoftLayer_Exception_User_Customer")
            self.assertEqual(ex.faultString,
                             "This exception indicates an error")

        # FaultCode is SoftLayer_Exception_User_Customer_DelegateIamIdInvitationToPaas
        paas_error = exceptions.SoftLayerAPIError(
            "SoftLayer_Exception_User_Customer_DelegateIamIdInvitationToPaas",
            "This exception does NOT indicate an error")

        self.manager.user_service.createObject.side_effect = paas_error

        try:
            self.manager.create_user(user_template, "Pass@123")
        except exceptions.SoftLayerError as ex:
            self.assertEqual(
                ex.args[0],
                "Your request for a new user was received, but it needs to be processed by "
                "the Platform Services API first. Barring any errors on the Platform Services "
                "side, your new user should be created shortly.")
コード例 #2
0
def make_rest_api_call(method,
                       url,
                       http_headers=None,
                       timeout=None,
                       proxy=None):
    """Makes a SoftLayer API call against the REST endpoint.

    :param string method: HTTP method: GET, POST, PUT, DELETE
    :param string url: endpoint URL
    :param dict http_headers: HTTP headers to use for the request
    :param int timeout: number of seconds to use as a timeout
    """
    LOGGER.info('%s %s', method, url)
    try:
        resp = requests.request(method,
                                url,
                                headers=http_headers,
                                timeout=timeout,
                                proxies=_proxies_dict(proxy))
        resp.raise_for_status()
        LOGGER.debug(resp.content)
        if url.endswith('.json'):
            return json.loads(resp.content)
        else:
            return resp.text
    except requests.HTTPError as ex:
        if url.endswith('.json'):
            content = json.loads(ex.response.content)
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               content['error'])
        else:
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               ex.response.text)
    except requests.RequestException as ex:
        raise exceptions.TransportError(0, str(ex))
コード例 #3
0
    def test_cancel_fail(self, cancel_lbaas):
        fault_string = 'Id must be string'
        cancel_lbaas.side_effect = exceptions.SoftLayerAPIError(
            mock.ANY, fault_string)
        result = self.run_command(['loadbal', 'cancel', '11111'])

        self.assertIn("ERROR: {}".format(fault_string), result.output)
コード例 #4
0
 def test_lb_member_del_fails(self, delete):
     lbaas_id = '1111111'
     lbaas_member_uuid = "x123x123-123x-123x-123x-123a123b123c"
     delete.side_effect = exceptions.SoftLayerAPIError(mock.ANY, mock.ANY)
     result = self.run_command(
         ['loadbal', 'member-del', '-m', lbaas_member_uuid, lbaas_id])
     self.assertIn("ERROR:", result.output)
コード例 #5
0
    def __call__(self, request):
        """Makes a SoftLayer API call against the REST endpoint.

        This currently only works with GET requests

        :param request request: Request object
        """
        url_parts = [request.endpoint, request.service, request.method]
        if request.identifier is not None:
            url_parts.append(str(request.identifier))

        url = '%s.%s' % ('/'.join(url_parts), 'json')

        LOGGER.debug("=== REQUEST ===")
        LOGGER.info(url)
        LOGGER.debug(request.transport_headers)
        try:
            resp = requests.request('GET', url,
                                    headers=request.transport_headers,
                                    timeout=request.timeout,
                                    proxies=_proxies_dict(request.proxy))
            LOGGER.debug("=== RESPONSE ===")
            LOGGER.debug(resp.headers)
            LOGGER.debug(resp.content)
            resp.raise_for_status()
            return json.loads(resp.content)
        except requests.HTTPError as ex:
            content = json.loads(ex.response.content)
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               content['error'])
        except requests.RequestException as ex:
            raise exceptions.TransportError(0, str(ex))
コード例 #6
0
    def test_lb_health_update_fails(self, update_lb_health_monitors):
        update_lb_health_monitors.side_effect = exceptions.SoftLayerAPIError(
            mock.ANY, mock.ANY)

        result = self.run_command([
            'lb', 'health', '1111111', '--uuid',
            '222222ab-bbcc-4f32-9b31-1b6d3a1959c8', '-i', '60', '-r', '10',
            '-t', '10', '-u', '/'
        ])
        self.assertIn("ERROR:", result.output)
コード例 #7
0
 def test_volume_set_lun_id_not_in_range(self):
     value = '-1'
     lun_mock = self.set_mock('SoftLayer_Network_Storage',
                              'createOrUpdateLunId')
     lun_mock.side_effect = exceptions.SoftLayerAPIError(
         'SoftLayer_Exception_Network_Storage_Iscsi_InvalidLunId',
         'The LUN ID specified is out of the valid range: %s [min: 0 max: 4095]'
         % (value))
     result = self.run_command('block volume-set-lun-id 1234 42'.split())
     self.assertIsNotNone(result.exception)
     self.assertIn('The LUN ID specified is out of the valid range',
                   result.exception.faultString)
コード例 #8
0
ファイル: user.py プロジェクト: leibaogit/softlayer-python
    def vpn_subnet_remove(self, user_id, subnet_ids):
        """Remove subnets for a user.

        :param int user_id: User to edit.
        :param list subnet_ids: list of subnet Ids.
        """
        overrides = self.get_overrides_list(user_id, subnet_ids)
        return_value = self.override_service.deleteObjects(overrides)
        update_success = self.user_service.updateVpnUser(id=user_id)
        if not update_success:
            raise exceptions.SoftLayerAPIError(
                "Overrides deleted, but unable to update VPN user")
        return return_value
コード例 #9
0
 def test_lb_member_add_private_fails(self, add_lb_member):
     lbaas_id = '1111111'
     member_ip_address = '10.0.0.1'
     fault_string = 'privateIpAddress must be a string'
     add_lb_member.side_effect = exceptions.SoftLayerAPIError(
         mock.ANY, fault_string)
     result = self.run_command([
         'loadbal', 'member-add', '--private', '-m', member_ip_address,
         lbaas_id
     ])
     self.assertIn(
         'This LB requires a Private IP address for its members and none was supplied',
         result.output)
     self.assertIn("ERROR: {}".format(fault_string), result.output)
コード例 #10
0
ファイル: user.py プロジェクト: leibaogit/softlayer-python
    def vpn_subnet_add(self, user_id, subnet_ids):
        """Add subnets for a user.

        :param int user_id: User to edit.
        :param list subnet_ids: list of subnet Ids.
        """
        overrides = [{
            "userId": user_id,
            "subnetId": subnet_id
        } for subnet_id in subnet_ids]
        return_value = self.override_service.createObjects(overrides)
        update_success = self.user_service.updateVpnUser(id=user_id)
        if not update_success:
            raise exceptions.SoftLayerAPIError(
                "Overrides created, but unable to update VPN user")
        return return_value
コード例 #11
0
    def __call__(self, request):
        """Makes a SoftLayer API call against the REST endpoint.

        This currently only works with GET requests

        :param request request: Request object
        """
        url_parts = [self.endpoint_url, request.service]
        if request.identifier is not None:
            url_parts.append(str(request.identifier))
        if request.method is not None:
            url_parts.append(request.method)
        for arg in request.args:
            url_parts.append(str(arg))

        request.transport_headers.setdefault('Content-Type',
                                             'application/json')
        request.transport_headers.setdefault('User-Agent', self.user_agent)

        url = '%s.%s' % ('/'.join(url_parts), 'json')

        LOGGER.debug("=== REQUEST ===")
        LOGGER.info(url)
        LOGGER.debug(request.transport_headers)
        try:
            resp = requests.request('GET',
                                    url,
                                    headers=request.transport_headers,
                                    timeout=self.timeout,
                                    verify=request.verify,
                                    cert=request.cert,
                                    proxies=_proxies_dict(self.proxy))
            LOGGER.debug("=== RESPONSE ===")
            LOGGER.debug(resp.headers)
            LOGGER.debug(resp.content)
            resp.raise_for_status()
            return json.loads(resp.content)
        except requests.HTTPError as ex:
            content = json.loads(ex.response.content)
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               content['error'])
        except requests.RequestException as ex:
            raise exceptions.TransportError(0, str(ex))
コード例 #12
0
    def _make_request(self, method, path, **kwargs):
        """Make request. Generally not called directly.

        :param method: HTTP Method
        :param path: resource Path
        :param dict \\*\\*kwargs: extra request arguments
        """
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': consts.USER_AGENT,
        }
        headers.update(kwargs.get('headers', {}))
        kwargs['headers'] = headers
        kwargs['auth'] = self.auth

        url = '/'.join((self.endpoint, 'v1', self.account_id, path))
        resp = requests.request(method, url, **kwargs)
        try:
            resp.raise_for_status()
        except requests.HTTPError as ex:
            content = json.loads(ex.response.content)
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               content['message'])
        return resp
コード例 #13
0
    def __call__(self, request):
        """Makes a SoftLayer API call against the REST endpoint.

        This currently only works with GET requests

        :param request request: Request object
        """
        request.transport_headers.setdefault('Content-Type',
                                             'application/json')
        request.transport_headers.setdefault('User-Agent', self.user_agent)

        params = request.headers.copy()
        if request.mask:
            params['objectMask'] = _format_object_mask(request.mask)

        if request.limit:
            params['limit'] = request.limit

        if request.offset:
            params['offset'] = request.offset

        if request.filter:
            params['objectFilter'] = json.dumps(request.filter)

        auth = None
        if request.transport_user:
            auth = requests.auth.HTTPBasicAuth(
                request.transport_user,
                request.transport_password,
            )

        method = REST_SPECIAL_METHODS.get(request.method)
        is_special_method = True
        if method is None:
            is_special_method = False
            method = 'GET'

        body = {}
        if request.args:
            # NOTE(kmcdonald): force POST when there are arguments because
            # the request body is ignored otherwise.
            method = 'POST'
            body['parameters'] = request.args

        raw_body = None
        if body:
            raw_body = json.dumps(body)

        url_parts = [self.endpoint_url, request.service]
        if request.identifier is not None:
            url_parts.append(str(request.identifier))

        # Special methods (createObject, editObject, etc) use the HTTP verb
        # to determine the action on the resource
        if request.method is not None and not is_special_method:
            url_parts.append(request.method)

        url = '%s.%s' % ('/'.join(url_parts), 'json')

        LOGGER.debug("=== REQUEST ===")
        LOGGER.info(url)
        LOGGER.debug(request.transport_headers)
        LOGGER.debug(raw_body)
        try:
            resp = requests.request(method,
                                    url,
                                    auth=auth,
                                    headers=request.transport_headers,
                                    params=params,
                                    data=raw_body,
                                    timeout=self.timeout,
                                    verify=request.verify,
                                    cert=request.cert,
                                    proxies=_proxies_dict(self.proxy))
            LOGGER.debug("=== RESPONSE ===")
            LOGGER.debug(resp.headers)
            LOGGER.debug(resp.content)
            resp.raise_for_status()
            result = json.loads(resp.content)

            if isinstance(result, list):
                return SoftLayerListResult(
                    result, int(resp.headers.get('softlayer-total-items', 0)))
            else:
                return result
        except requests.HTTPError as ex:
            content = json.loads(ex.response.content)
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               content['error'])
        except requests.RequestException as ex:
            raise exceptions.TransportError(0, str(ex))
コード例 #14
0
ファイル: transports.py プロジェクト: jbernh/softlayer-python
    def __call__(self, request):
        """Makes a SoftLayer API call against the REST endpoint.

        REST calls should mostly work, but is not fully tested.
        XML-RPC should be used when in doubt

        :param request request: Request object
        """
        params = request.headers.copy()
        if request.mask:
            request.mask = _format_object_mask(request.mask)
            params['objectMask'] = request.mask

        if request.limit or request.offset:
            limit = request.limit or 0
            offset = request.offset or 0
            params['resultLimit'] = "%d,%d" % (offset, limit)

        if request.filter:
            params['objectFilter'] = json.dumps(request.filter)

        request.params = params

        auth = None
        if request.transport_user:
            auth = requests.auth.HTTPBasicAuth(
                request.transport_user,
                request.transport_password,
            )

        method = REST_SPECIAL_METHODS.get(request.method)

        if method is None:
            method = 'GET'

        body = {}
        if request.args:
            # NOTE(kmcdonald): force POST when there are arguments because
            # the request body is ignored otherwise.
            method = 'POST'
            body['parameters'] = request.args

        if body:
            request.payload = json.dumps(body, cls=ComplexEncoder)

        url_parts = [self.endpoint_url, request.service]
        if request.identifier is not None:
            url_parts.append(str(request.identifier))

        if request.method is not None:
            url_parts.append(request.method)

        request.url = '%s.%s' % ('/'.join(url_parts), 'json')

        # Prefer the request setting, if it's not None

        if request.verify is None:
            request.verify = self.verify

        try:
            resp = self.client.request(method, request.url,
                                       auth=auth,
                                       headers=request.transport_headers,
                                       params=request.params,
                                       data=request.payload,
                                       timeout=self.timeout,
                                       verify=request.verify,
                                       cert=request.cert,
                                       proxies=_proxies_dict(self.proxy))

            request.url = resp.url

            resp.raise_for_status()

            if resp.text != "":
                try:
                    result = json.loads(resp.text)
                except ValueError as json_ex:
                    raise exceptions.SoftLayerAPIError(resp.status_code, str(json_ex))
            else:
                raise exceptions.SoftLayerAPIError(resp.status_code, "Empty response.")

            request.result = result

            if isinstance(result, list):
                return SoftLayerListResult(
                    result, int(resp.headers.get('softlayer-total-items', 0)))
            else:
                return result
        except requests.HTTPError as ex:
            try:
                message = json.loads(ex.response.text)['error']
                request.url = ex.response.url
            except ValueError as json_ex:
                if ex.response.text == "":
                    raise exceptions.SoftLayerAPIError(resp.status_code, "Empty response.")

                raise exceptions.SoftLayerAPIError(resp.status_code, str(json_ex))

            raise exceptions.SoftLayerAPIError(ex.response.status_code, message)
        except requests.RequestException as ex:
            raise exceptions.TransportError(0, str(ex))
コード例 #15
0
    def __call__(self, request):
        """Makes a SoftLayer API call against the REST endpoint.

        REST calls should mostly work, but is not fully tested.
        XML-RPC should be used when in doubt

        :param request request: Request object
        """
        request.transport_headers.setdefault('Content-Type',
                                             'application/json')
        request.transport_headers.setdefault('User-Agent', self.user_agent)

        params = request.headers.copy()
        if request.mask:
            params['objectMask'] = _format_object_mask(request.mask)

        if request.limit:
            params['limit'] = request.limit

        if request.offset:
            params['offset'] = request.offset

        if request.filter:
            params['objectFilter'] = json.dumps(request.filter)

        auth = None
        if request.transport_user:
            auth = requests.auth.HTTPBasicAuth(
                request.transport_user,
                request.transport_password,
            )

        method = REST_SPECIAL_METHODS.get(request.method)

        if method is None:
            method = 'GET'

        body = {}
        if request.args:
            # NOTE(kmcdonald): force POST when there are arguments because
            # the request body is ignored otherwise.
            method = 'POST'
            body['parameters'] = request.args

        raw_body = None
        if body:
            raw_body = json.dumps(body)

        url_parts = [self.endpoint_url, request.service]
        if request.identifier is not None:
            url_parts.append(str(request.identifier))

        if request.method is not None:
            url_parts.append(request.method)

        url = '%s.%s' % ('/'.join(url_parts), 'json')

        # Prefer the request setting, if it's not None
        verify = request.verify
        if verify is None:
            verify = self.verify

        LOGGER.debug("=== REQUEST ===")
        LOGGER.info(url)
        LOGGER.debug(request.transport_headers)
        LOGGER.debug(raw_body)
        try:
            resp = requests.request(method,
                                    url,
                                    auth=auth,
                                    headers=request.transport_headers,
                                    params=params,
                                    data=raw_body,
                                    timeout=self.timeout,
                                    verify=verify,
                                    cert=request.cert,
                                    proxies=_proxies_dict(self.proxy))
            LOGGER.debug("=== RESPONSE ===")
            LOGGER.debug(resp.headers)
            LOGGER.debug(resp.text)
            resp.raise_for_status()
            result = json.loads(resp.text)

            if isinstance(result, list):
                return SoftLayerListResult(
                    result, int(resp.headers.get('softlayer-total-items', 0)))
            else:
                return result
        except requests.HTTPError as ex:
            message = json.loads(ex.response.text)['error']
            raise exceptions.SoftLayerAPIError(ex.response.status_code,
                                               message)
        except requests.RequestException as ex:
            raise exceptions.TransportError(0, str(ex))