Пример #1
0
    def create_management_access_token(self):
        """Does a POST request to /managementTokens.

        Use this api to get a new management api token.

        Returns:
            ManagementAccessToken: Response from the API. Successfully created
                new token.

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('create_management_access_token called.')

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for create_management_access_token.')
            _url_path = '/managementTokens'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare headers
            self.logger.info(
                'Preparing headers for create_management_access_token.')
            _headers = {'accept': 'application/json'}

            # Prepare and execute request
            self.logger.info(
                'Preparing and executing request for create_management_access_token.'
            )
            _request = self.http_client.post(_query_url, headers=_headers)
            CustomAuth.apply(_request)
            _context = self.execute_request(
                _request, name='create_management_access_token')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for create_management_access_token.')
            if _context.response.status_code == 401:
                raise APIException('Invalid token.', _context)
            elif _context.response.status_code == 500:
                raise ErrorException('Unexpected error.', _context)
            self.validate_response(_context)

            # Return appropriate type
            return APIHelper.json_deserialize(
                _context.response.raw_body,
                ManagementAccessToken.from_dictionary)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Пример #2
0
    def delete_volume(self,
                      volume_name):
        """Does a DELETE request to /volumes/{volumeName}.

        Delete a previously created persistent volume owned by this app.

        Args:
            volume_name (string): Name of the volume unique within the app
                instance.

        Returns:
            void: Response from the API. Successful Operation.

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('delete_volume called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for delete_volume.')
            _url_path = '/volumes/{volumeName}'
            _url_path = APIHelper.append_url_with_template_parameters(_url_path, {
                'volumeName': volume_name
            })
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare and execute request
            self.logger.info('Preparing and executing request for delete_volume.')
            _request = self.http_client.delete(_query_url)
            OAuth2.apply(_request)
            _context = self.execute_request(_request, name = 'delete_volume')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for delete_volume.')
            if _context.response.status_code == 400:
                raise APIException('Invalid parameters.', _context)
            elif _context.response.status_code == 401:
                raise APIException('Unauthorized.', _context)
            elif _context.response.status_code == 404:
                raise APIException('Volume doesn\'t exist.', _context)
            elif _context.response.status_code == 500:
                raise ErrorErrorException('Unexpected error.', _context)
            elif _context.response.status_code == 502:
                raise APIException('Bad Gateway.', _context)
            elif _context.response.status_code == 504:
                raise APIException('Gateway Timeout.', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
    def create_mount(self, mount_options):
        """Does a POST request to /mounts.

        Allows you to mount a view/namespace.

        Args:
            mount_options (MountOptions): TODO: type description here.
                Example: 

        Returns:
            void: Response from the API. Mount operation is successful.

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('create_mount called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for create_mount.')
            _url_path = '/mounts'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare headers
            self.logger.info('Preparing headers for create_mount.')
            _headers = {'content-type': 'application/json; charset=utf-8'}

            # Prepare and execute request
            self.logger.info(
                'Preparing and executing request for create_mount.')
            _request = self.http_client.post(
                _query_url,
                headers=_headers,
                parameters=APIHelper.json_serialize(mount_options))
            CustomAuth.apply(_request)
            _context = self.execute_request(_request, name='create_mount')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for create_mount.')
            if _context.response.status_code == 400:
                raise APIException('Validation errors.', _context)
            elif _context.response.status_code == 401:
                raise APIException('Invalid token.', _context)
            elif _context.response.status_code == 500:
                raise ErrorException('Unexpected error.', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Пример #4
0
    def get_app_settings(self):
        """Does a GET request to /appSettings.

        Returns app settings object.

        Returns:
            AppSettings: Response from the API. Successful operation

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('get_app_settings called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_app_settings.')
            _url_path = '/appSettings'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare headers
            self.logger.info('Preparing headers for get_app_settings.')
            _headers = {'accept': 'application/json'}

            # Prepare and execute request
            self.logger.info(
                'Preparing and executing request for get_app_settings.')
            _request = self.http_client.get(_query_url, headers=_headers)
            OAuth2.apply(_request)
            _context = self.execute_request(_request, name='get_app_settings')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_app_settings.')
            if _context.response.status_code == 401:
                raise APIException('Invalid token', _context)
            elif _context.response.status_code == 500:
                raise ErrorErrorException('Unexpected error', _context)
            elif _context.response.status_code == 502:
                raise APIException('Bad Gateway.', _context)
            elif _context.response.status_code == 504:
                raise APIException('Gateway Timeout.', _context)
            self.validate_response(_context)

            # Return appropriate type
            return APIHelper.json_deserialize(_context.response.raw_body,
                                              AppSettings.from_dictionary)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def add_query_parameter(self, name, value):
        """ Add a query parameter to the HttpRequest.

        Args:
	        name (string): The name of the query parameter.
            value (string): The value of the query parameter.

        """
        self.query_url = APIHelper.append_url_with_query_parameters(self.query_url,
                                                                    {name:value})
        self.query_url = APIHelper.clean_url(self.query_url)
    def delete_unmount(self, dir_name):
        """Does a DELETE request to /mounts/{dirName}.

        Unmount previously mounted view/namespace.

        Args:
            dir_name (string): Name of the mount directory.

        Returns:
            void: Response from the API. 

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('delete_unmount called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for delete_unmount.')
            _url_path = '/mounts/{dirName}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'dirName': dir_name})
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare and execute request
            self.logger.info(
                'Preparing and executing request for delete_unmount.')
            _request = self.http_client.delete(_query_url)
            CustomAuth.apply(_request)
            _context = self.execute_request(_request, name='delete_unmount')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for delete_unmount.')
            if _context.response.status_code == 400:
                raise APIException('Invalid parameters.', _context)
            elif _context.response.status_code == 401:
                raise APIException('Invalid token.', _context)
            elif _context.response.status_code == 404:
                raise APIException('Directory doesn\'t exist.', _context)
            elif _context.response.status_code == 500:
                raise ErrorException('Unexpected error.', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def __init__(self, reason, context):
        """Constructor for the ErrorException class

        Args:
            reason (string): The reason (or error message) for the Exception
                to be raised.
            context (HttpContext):  The HttpContext of the API call.

        """
        super(ErrorException, self).__init__(reason, context)
        dictionary = APIHelper.json_deserialize(self.context.response.raw_body)
        if isinstance(dictionary, dict):
            self.unbox(dictionary)
    def get_base_uri(cls, server=Server.DEFAULT):
        """Generates the appropriate base URI for the environment and the server.

        Args:
            server (Configuration.Server): The server enum for which the base URI is required.

        Returns:
            String: The base URI.

        """
        parameters = {
            "app_endpoint_ip": cls.app_endpoint_ip,
            "app_endpoint_port": cls.app_endpoint_port,
        }
        return APIHelper.append_url_with_template_parameters(
            cls.environments[cls.environment][server], parameters, False)
    def execute_request(self, request, binary=False, name=None):
        """Executes an HttpRequest.

        Args:
            request (HttpRequest): The HttpRequest to execute.
            binary (bool): A flag which should be set to True if
                a binary response is expected.

        Returns:
            HttpContext: The HttpContext of the request. It contains,
                both, the request itself and the HttpResponse object.

        """
        # Invoke the on before request HttpCallBack if specified
        if self.http_call_back != None:
            self.logger.info(
                "Calling the on_before_request method of http_call_back for {}."
                .format(name))
            self.http_call_back.on_before_request(request)

        # Add global headers to request
        self.logger.info(
            "Merging global headers with endpoint headers for {}.".format(
                name))
        request.headers = APIHelper.merge_dicts(self.global_headers,
                                                request.headers)

        # Invoke the API call to fetch the response.
        self.logger.debug("Raw request for {} is: {}".format(
            name, vars(request)))
        func = self.http_client.execute_as_binary if binary else self.http_client.execute_as_string
        response = func(request)
        self.logger.debug("Raw response for {} is: {}".format(
            name, vars(response)))
        self.logger.info(
            "Wrapping request and response in a context object for {}.".format(
                name))
        context = HttpContext(request, response)

        # Invoke the on after response HttpCallBack if specified
        if self.http_call_back != None:
            self.logger.info(
                "Calling on_after_response method of http_call_back for {}.".
                format(name))
            self.http_call_back.on_after_response(context)

        return context
Пример #10
0
    def get_volume(self,
                   volume_name):
        """Does a GET request to /volumes/{volumeName}.

        Gets the status of persistent volume owned by this app.

        Args:
            volume_name (string): Name of the volume unique within the app
                instance.

        Returns:
            VolumeInfo: Response from the API. Successful operation

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('get_volume called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_volume.')
            _url_path = '/volumes/{volumeName}'
            _url_path = APIHelper.append_url_with_template_parameters(_url_path, {
                'volumeName': volume_name
            })
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare headers
            self.logger.info('Preparing headers for get_volume.')
            _headers = {
                'accept': 'application/json'
            }

            # Prepare and execute request
            self.logger.info('Preparing and executing request for get_volume.')
            _request = self.http_client.get(_query_url, headers=_headers)
            OAuth2.apply(_request)
            _context = self.execute_request(_request, name = 'get_volume')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_volume.')
            if _context.response.status_code == 401:
                raise APIException('Unauthorized', _context)
            elif _context.response.status_code == 404:
                raise APIException('Volume doesn\'t exist.', _context)
            elif _context.response.status_code == 500:
                raise ErrorErrorException('Unexpected error', _context)
            elif _context.response.status_code == 502:
                raise APIException('Bad Gateway.', _context)
            elif _context.response.status_code == 504:
                raise APIException('Gateway Timeout.', _context)
            self.validate_response(_context)

            # Return appropriate type
            return APIHelper.json_deserialize(_context.response.raw_body, VolumeInfo.from_dictionary)

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
Пример #11
0
    def create_volume(self,
                      volume_name,
                      volume_spec):
        """Does a PUT request to /volumes/{volumeName}.

        Use this API to create a new kubernetes persistent volume backed up by
        cohesity view.

        Args:
            volume_name (string): Name of the volume unique within the app
                instance.
            volume_spec (VolumeSpec): TODO: type description here. Example:

        Returns:
            void: Response from the API. Created.

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('create_volume called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for create_volume.')
            _url_path = '/volumes/{volumeName}'
            _url_path = APIHelper.append_url_with_template_parameters(_url_path, {
                'volumeName': volume_name
            })
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare headers
            self.logger.info('Preparing headers for create_volume.')
            _headers = {
                'content-type': 'application/json; charset=utf-8'
            }

            # Prepare and execute request
            self.logger.info('Preparing and executing request for create_volume.')
            _request = self.http_client.put(_query_url, headers=_headers, parameters=APIHelper.json_serialize(volume_spec))
            OAuth2.apply(_request)
            _context = self.execute_request(_request, name = 'create_volume')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for create_volume.')
            if _context.response.status_code == 401:
                raise APIException('Unauthorized.', _context)
            elif _context.response.status_code == 409:
                raise APIException('Volume already exists with different parameters.', _context)
            elif _context.response.status_code == 500:
                raise ErrorErrorException('Unexpected error.', _context)
            elif _context.response.status_code == 502:
                raise APIException('Bad Gateway.', _context)
            elif _context.response.status_code == 504:
                raise APIException('Gateway Timeout.', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
Пример #12
0
    def get_protected_source_volume_info(self, source_id):
        """Does a GET request to /protectedSourceVolumeInfo/{sourceId}.

        Gets the list of volumes for a snapshot of a protected source.

        Args:
            source_id (int): Unique ID of the protected source.

        Returns:
            ProtectedSourceVolumeInfo: Response from the API. Successful
                operation

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """
        try:
            self.logger.info('get_protected_source_volume_info called.')

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for get_protected_source_volume_info.')
            _url_path = '/protectedSourceVolumeInfo/{sourceId}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'sourceId': source_id})
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

            # Prepare headers
            self.logger.info(
                'Preparing headers for get_protected_source_volume_info.')
            _headers = {'accept': 'application/json'}

            # Prepare and execute request
            self.logger.info(
                'Preparing and executing request for get_protected_source_volume_info.'
            )
            _request = self.http_client.get(_query_url, headers=_headers)
            OAuth2.apply(_request)
            _context = self.execute_request(
                _request, name='get_protected_source_volume_info')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for get_protected_source_volume_info.')
            if _context.response.status_code == 401:
                raise APIException('Unauthorized', _context)
            elif _context.response.status_code == 404:
                raise APIException('Snapshot does not exist.', _context)
            elif _context.response.status_code == 500:
                raise ErrorErrorException('Unexpected error', _context)
            elif _context.response.status_code == 502:
                raise APIException('Bad Gateway.', _context)
            elif _context.response.status_code == 504:
                raise APIException('Gateway Timeout.', _context)
            self.validate_response(_context)

            # Return appropriate type
            return APIHelper.json_deserialize(
                _context.response.raw_body,
                ProtectedSourceVolumeInfo.from_dictionary)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise