Beispiel #1
0
 def parse_error(self):
     if self.status in [httplib.UNAUTHORIZED, httplib.FORBIDDEN]:
         raise InvalidCredsError(self.body)
     elif self.status == httplib.MOVED_PERMANENTLY:
         raise LibcloudError('This bucket is located in a different ' +
                             'region. Please use the correct driver.',
                             driver=S3StorageDriver)
     raise LibcloudError('Unknown error. Status code: %d' % (self.status),
                         driver=S3StorageDriver)
Beispiel #2
0
 def parse_error(self):
     if self.status == 403:
         raise InvalidCredsError(self.body)
     elif self.status == 301:
         raise LibcloudError('This bucket is located in a different ' +
                             'region. Please use the correct driver.',
                             driver=S3StorageDriver)
     raise LibcloudError('Unknown error. Status code: %d' % (self.status),
                         driver=S3StorageDriver)
Beispiel #3
0
    def parse_error(self):
        response = super(OvhResponse, self).parse_body()
        response = response or {}

        if response.get('errorCode', None) == 'INVALID_SIGNATURE':
            raise InvalidCredsError('Signature validation failed, probably '
                                    'using invalid credentials')

        return self.body
Beispiel #4
0
 def _api_parse_error(self, response):
     if 'data' in response:
         if response['data'] == 'invalid_api_key':
             raise InvalidCredsError(
                 "Oops!  You've entered an invalid API key")
         else:
             raise DreamhostAPIException(response['data'])
     else:
         raise DreamhostAPIException("Unknown problem: %s" % (self.body))
Beispiel #5
0
 def test_unauthorized_response(self):
     http_response = MockResponse(httplib.UNAUTHORIZED,
                                  OpenNebula_ResponseTests.XML,
                                  headers={'content-type':
                                           'application/xml'})
     try:
         OpenNebulaResponse(http_response, None).parse_body()
     except InvalidCredsError:
         exceptionType = sys.exc_info()[0]
         self.assertEqual(exceptionType, type(InvalidCredsError()))
Beispiel #6
0
 def parse_error(self):
     if self.status == httplib.OK:
         body = self.parse_body()
         return body
     elif self.status == httplib.FORBIDDEN:
         raise InvalidCredsError(self.body)
     elif self.status == httplib.SERVICE_UNAVAILABLE:
         raise ServiceUnavailableError(self.body)
     else:
         raise LibcloudError(self.body)
Beispiel #7
0
 def parse_error(self):
     body = self.parse_body()
     if self.status == httplib.UNAUTHORIZED:
         raise InvalidCredsError(body['detail'])
     else:
         # We are taking the first issue here. There might be multiple ones,
         # but that doesn't really matter. It's nicer if the error is just
         # one error (because it's a Python API and there's only one
         # exception.
         return next(iter(body.values()))
Beispiel #8
0
    def _make_excp(self, error):
        """Convert an API error to a LinodeException instance

        @keyword error: JSON object containing C{ERRORCODE} and C{ERRORMESSAGE}
        @type error: dict"""
        if "ERRORCODE" not in error or "ERRORMESSAGE" not in error:
            return None
        if error["ERRORCODE"] == 4:
            return InvalidCredsError(error["ERRORMESSAGE"])
        return LinodeException(error["ERRORCODE"], error["ERRORMESSAGE"])
Beispiel #9
0
    def parse_error(self):
        response = super(OvhResponse, self).parse_body()
        response = response or {}

        if response.get("errorCode", None) == "INVALID_SIGNATURE":
            raise InvalidCredsError(
                "Signature validation failed, probably " "using invalid credentials"
            )

        return self.body
Beispiel #10
0
    def __init__(
        self,
        key,
        secret,
        secure=True,
        host="localhost",
        port=4243,
        key_file="",
        cert_file="",
        **kwargs,
    ):

        super(DockertlsConnection, self).__init__(
            key_file=key_file,
            cert_file=cert_file,
            secure=secure,
            host=host,
            port=port,
            url=None,
            proxy_url=None,
            timeout=None,
            backoff=None,
            retry_delay=None,
        )
        if key_file:
            keypath = os.path.expanduser(key_file)
            is_file_path = os.path.exists(keypath) and os.path.isfile(keypath)
            if not is_file_path:
                raise InvalidCredsError(
                    "You need an key PEM file to authenticate with "
                    "Docker tls. This can be found in the server."
                )
            self.key_file = key_file

            certpath = os.path.expanduser(cert_file)
            is_file_path = os.path.exists(certpath) and os.path.isfile(certpath)
            if not is_file_path:
                raise InvalidCredsError(
                    "You need an certificate PEM file to authenticate with "
                    "Docker tls. This can be found in the server."
                )
            self.cert_file = cert_file
Beispiel #11
0
 def parse_error(self):
     if self.status == httplib.UNAUTHORIZED:
         body = self.parse_body()
         raise InvalidCredsError(body["message"])
     else:
         body = self.parse_body()
         if "message" in body:
             error = "%s (code: %s)" % (body["message"], self.status)
         else:
             error = body
         return error
Beispiel #12
0
 def __new__(cls, key, secret=None, api_version="v2", **kwargs):
     if cls is DigitalOceanNodeDriver:
         if api_version == "v1" or secret is not None:
             if secret is not None and api_version == "v2":
                 raise InvalidCredsError("secret not accepted for v2 authentication")
             raise DigitalOcean_v1_Error()
         elif api_version == "v2":
             cls = DigitalOcean_v2_NodeDriver
         else:
             raise NotImplementedError("Unsupported API version: %s" % (api_version))
     return super(DigitalOceanNodeDriver, cls).__new__(cls, **kwargs)
Beispiel #13
0
    def parse_error(self):
        body = super().parse_error()

        # INFO: пример ответа: {"code":401,"message":"Unauthorized","details":"..."}
        code = body["code"]
        if code == 401:
            raise InvalidCredsError(value=body["details"])

        # TODO: ServiceUnavailableError и RateLimitReachedError

        return body
 def parse_error(self):
     if self.status == httplib.UNAUTHORIZED:
         body = self.parse_body()
         raise InvalidCredsError(body['message'])
     else:
         body = self.parse_body()
         if 'message' in body:
             error = '%s (code: %s)' % (body['message'], self.status)
         else:
             error = body
         return error
Beispiel #15
0
    def request(self, method, *args, **kwargs):
        sl = self.proxyCls(user=self.user, key=self.key, secure=self.secure,
                           host=self.host, port=self.port, driver=self.driver)

        try:
            return getattr(sl, method)(*args)
        except xmlrpclib.Fault:
            e = sys.exc_info()[1]
            if e.faultCode == 'VCL_Account':
                raise InvalidCredsError(e.faultString)
            raise LibcloudError(e, driver=self.driver)
Beispiel #16
0
    def parse_error(self):
        """
        Check if response contains any errors.

        @raise: :class:`InvalidCredsError`

        :rtype:  :class:`ElementTree`
        :return: Contents of HTTP response body.
        """
        if int(self.status) == httplib.UNAUTHORIZED:
            raise InvalidCredsError(self.body)
        return self.body
Beispiel #17
0
 def parse_error(self):
     if self.status in [httplib.UNAUTHORIZED, httplib.FORBIDDEN]:
         raise InvalidCredsError(self.body)
     elif self.status == httplib.MOVED_PERMANENTLY:
         raise LibcloudError('This bucket is located in a different ' +
                             'region. Please use the correct driver.',
                             driver=OSSStorageDriver)
     elif self.status == httplib.METHOD_NOT_ALLOWED:
         raise LibcloudError('The method is not allowed. Status code: %d, '
                             'headers: %s' % (self.status, self.headers))
     raise LibcloudError('Unknown error. Status code: %d, body: %s' %
                         (self.status, self.body),
                         driver=OSSStorageDriver)
Beispiel #18
0
 def parse_error(self):
     if self.status in [httplib.UNAUTHORIZED, httplib.FORBIDDEN]:
         raise InvalidCredsError(self.body)
     elif self.status == httplib.MOVED_PERMANENTLY:
         bucket_region = self.headers.get('x-amz-bucket-region', None)
         used_region = self.connection.driver.region
         raise LibcloudError('This bucket is located in a different '
                             'region. Please use the correct driver. '
                             'Bucket region "%s", used region "%s".' %
                             (bucket_region, used_region),
                             driver=S3StorageDriver)
     raise LibcloudError('Unknown error. Status code: %d' % (self.status),
                         driver=S3StorageDriver)
Beispiel #19
0
    def parse_error(self):
        body = super().parse_error()

        # error codes https://ruvds.com/en-usd/use_api # sign-insection
        reject_reason = body["rejectReason"]
        if reject_reason in (1, 2, 3, 6, 7):
            raise InvalidCredsError(value=body["errMessage"])
        elif reject_reason == 5:
            raise ServiceUnavailableError()
        elif reject_reason == 8:
            raise RateLimitReachedError()

        return body
Beispiel #20
0
    def parse_error(self):
        if self.status == 401:
            raise InvalidCredsError(self.body)

        if self.status == 403:
            raise InvalidCredsError(self.body)

        try:
            body = ET.XML(self.body)
        except:
            raise MalformedResponseError("Failed to parse XML",
                                         body=self.body,
                                         driver=OpsourceNodeDriver)

        if self.status == 400:
            code = findtext(body, 'resultCode', SERVER_NS)
            message = findtext(body, 'resultDetail', SERVER_NS)
            raise OpsourceAPIException(code,
                                       message,
                                       driver=OpsourceNodeDriver)

        return self.body
Beispiel #21
0
    def _auth(self):
        """ OpenStack needs first to get an authentication token """

        self.connection.request(method='GET',
                                url=self.api_version,
                                headers={
                                    'X-Auth-User': self.user_id,
                                    'X-Auth-Key': self.key
                                })

        resp = self.connection.getresponse()

        if resp.status != httplib.NO_CONTENT:
            raise InvalidCredsError()

        headers = dict(resp.getheaders())

        try:
            self.server_url = headers['x-server-management-url']
            self.auth_token = headers['x-auth-token']
        except KeyError:
            raise InvalidCredsError()
Beispiel #22
0
    def parse_error(self) -> str:
        http_code = int(self.status)
        if http_code == httplib.FORBIDDEN:
            raise InvalidCredsError("Invalid credentials")

        body = super().parse_error()

        if http_code == httplib.INTERNAL_SERVER_ERROR:
            return body["error"]["message"]

        if http_code in (httplib.CONFLICT, httplib.NOT_FOUND):
            raise ProviderError(value=body["error"], http_code=http_code)

        return body["error"]
Beispiel #23
0
    def __init__(self, host, username, password, verify_ssl=True):
        context = ssl.create_default_context()
        if not verify_ssl:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE

        try:
            self.conn = connect.SmartConnect(host=host,
                                             user=username,
                                             pwd=password,
                                             sslContext=context)
        except Exception as e:
            if isinstance(e, vim.fault.InvalidLogin):
                raise InvalidCredsError("username/password not acepted")
            raise LibcloudError(str(e), driver=self)
Beispiel #24
0
    def parse_error(self):
        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError(self.body)
        elif self.status == httplib.FORBIDDEN:
            raise InvalidCredsError(self.body)

        body = self.parse_body()

        if self.status == httplib.BAD_REQUEST:
            code = findtext(body, 'responseCode', SERVER_NS)
            if code is None:
                code = findtext(body, 'responseCode', TYPES_URN)
            message = findtext(body, 'message', SERVER_NS)
            if message is None:
                message = findtext(body, 'message', TYPES_URN)
            raise DimensionDataAPIException(code=code,
                                            msg=message,
                                            driver=self.connection.driver)
        if self.status is not httplib.OK:
            raise DimensionDataAPIException(code=self.status,
                                            msg=body,
                                            driver=self.connection.driver)

        return self.body
Beispiel #25
0
    def request(self, service, method, *args, **kwargs):
        sl = self.proxyCls(service, self._user_agent())

        headers = {}
        headers.update(self._get_auth_headers())
        headers.update(self._get_init_params(service, kwargs.get('id')))
        headers.update(
            self._get_object_mask(service, kwargs.get('object_mask')))
        params = [{'headers': headers}] + list(args)

        try:
            return getattr(sl, method)(*params)
        except xmlrpclib.Fault, e:
            if e.faultCode == "SoftLayer_Account":
                raise InvalidCredsError(e.faultString)
            raise SoftLayerException(e)
Beispiel #26
0
 def parse_error(self):
     err_list = []
     if not self.body:
         return None
     if self.parsed is None:
         self.parsed = super(VoxelResponse, self).parse_body()
     for err in self.parsed.findall("err"):
         code = err.get("code")
         err_list.append("(%s) %s" % (code, err.get("msg")))
         # From voxel docs:
         # 1: Invalid login or password
         # 9: Permission denied: user lacks access rights for this method
         if code == "1" or code == "9":
             # sucks, but only way to detect
             # bad authentication tokens so far
             raise InvalidCredsError(err_list[-1])
     return "\n".join(err_list)
Beispiel #27
0
    def parse_error(self):
        """
        Parse the error messages.

        Response body can easily be handled by this class parent
        :class:`XmlResponse`, but there are use cases which Abiquo API
        does not respond an XML but an HTML. So we need to
        handle these special cases.
        """
        if self.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError(driver=self.connection.driver)
        elif self.status == httplib.FORBIDDEN:
            raise ForbiddenError(self.connection.driver)
        else:
            errors = self.parse_body().findall('error')
            # Most of the exceptions only have one error
            raise LibcloudError(errors[0].findtext('message'))
Beispiel #28
0
 def parse_error(self):
     err_list = []
     if not self.body:
         return None
     if not self.parsed:
         self.parsed = ET.XML(self.body)
     for err in self.parsed.findall('err'):
         code = err.get('code')
         err_list.append("(%s) %s" % (code, err.get('msg')))
         # From voxel docs:
         # 1: Invalid login or password
         # 9: Permission denied: user lacks access rights for this method
         if code == "1" or code == "9":
             # sucks, but only way to detect
             # bad authentication tokens so far
             raise InvalidCredsError(err_list[-1])
     return "\n".join(err_list)
Beispiel #29
0
def get_esh_instance(request, provider_id, identity_id, instance_id):
    esh_driver = prepare_driver(request, provider_id, identity_id)
    if not esh_driver:
        raise InvalidCredsError("Provider_id && identity_id "
                                "did not produce a valid combination")
    esh_instance = esh_driver.get_instance(instance_id)
    if not esh_instance:
        try:
            core_inst = CoreInstance.objects.get(
                provider_alias=instance_id,
                provider_machine__provider__id=provider_id,
                created_by_identity__id=identity_id)
            core_inst.end_date_all()
        except CoreInstance.DoesNotExist:
            pass
        return esh_instance
    return esh_instance
Beispiel #30
0
    def _get_auth_token(self):
        if not self.token:
            conn = self.conn_classes[self.secure](self.host, self.port)
            conn.request(method='POST',
                         url='/api/v0.8/login',
                         headers=self._get_auth_headers())

            resp = conn.getresponse()
            headers = dict(resp.getheaders())
            body = ET.XML(resp.read())

            try:
                self.token = headers['set-cookie']
            except KeyError:
                raise InvalidCredsError()

            self.driver.org = get_url_path(
                body.find(fixxpath(body, 'Org')).get('href'))