def search_protection_runs(self, uuid):
        """Does a GET request to /public/search/protectionRuns.

        Returns the information of latest snapshot of a particular object
        across
        all snapshot target locations.

        Args:
            uuid (string): Specifies the unique id of the Protection Source.

        Returns:
            ProtectionRunResponse: Response from the API. Success

        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('search_protection_runs called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for search_protection_runs.')
            self.validate_parameters(uuid=uuid)

            # Prepare query URL
            self.logger.info('Preparing query URL for search_protection_runs.')
            _url_path = '/public/search/protectionRuns'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {'uuid': uuid}
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for search_protection_runs.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Ejemplo n.º 2
0
    def create_group(self, body=None):
        """Does a POST request to /public/groups.

        If an Active Directory domain is specified, a new group is added to
        the
        Cohesity Cluster for the specified Active Directory group principal.
        If the LOCAL domain is specified, a new group is created directly in
        the default LOCAL domain on the Cohesity Cluster.
        Returns the created or added group.

        Args:
            body (GroupRequest, optional): Request to add or create a Group.

        Returns:
            GroupDetails: Response from the API. Success

        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_group called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for create_group.')
            _url_path = '/public/groups'
            _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_group.')
            _headers = {
                'accept': 'application/json',
                'content-type': 'application/json; charset=utf-8'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for create_group.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Ejemplo n.º 3
0
    def launch_app_instance(self, body):
        """Does a POST request to /public/appInstances.

        Starts the application instance launch on the cluster.
        Only installed apps can be launched.

        Args:
            body (LaunchAppInstance): TODO: type description
                here. Example:

        Returns:
            AppInstanceIdParameter: Response from the API. Success

        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('launch_app_instance called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for launch_app_instance.')
            self.validate_parameters(body=body)

            # Prepare query URL
            self.logger.info('Preparing query URL for launch_app_instance.')
            _url_path = '/public/appInstances'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for launch_app_instance.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def delete_protection_job(self, id, body=None):
        """Does a DELETE request to /public/protectionJobs/{id}.

        Returns Success if the Protection Job is deleted.

        Args:
            id (long|int): Specifies a unique id of the Protection Job.
            body (DeleteProtectionJobParam, optional): Request to delete a
                protection job.

        Returns:
            void: Response from the API. No Content

        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_protection_job called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for delete_protection_job.')
            self.validate_parameters(id=id)

            # Prepare query URL
            self.logger.info('Preparing query URL for delete_protection_job.')
            _url_path = '/public/protectionJobs/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': id})
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

            # Prepare and execute request
            self.logger.info(
                'Preparing and executing request for delete_protection_job.')
            _request = self.http_client.delete(
                _query_url,
                headers=_headers,
                parameters=APIHelper.json_serialize(body))
            AuthManager.apply(_request, self.config)
            _context = self.execute_request(_request,
                                            name='delete_protection_job')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for delete_protection_job.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_protection_jobs(self,
                            ids=None,
                            names=None,
                            policy_ids=None,
                            environments=None,
                            is_active=None,
                            is_deleted=None,
                            only_return_basic_summary=None,
                            include_last_run_and_stats=None,
                            include_rpo_snapshots=None,
                            is_last_run_sla_violated=None,
                            only_return_data_migration_jobs=None,
                            prune_excluded_source_ids=None,
                            tenant_ids=None,
                            all_under_hierarchy=None):
        """Does a GET request to /public/protectionJobs.

        If no parameters are specified, all Protection Jobs currently
        on the Cohesity Cluster are returned.
        Specifying parameters filters the results that are returned.

        Args:
            ids (list of long|int, optional): Filter by a list of Protection
                Job ids.
            names (list of string, optional): Filter by a list of Protection
                Job names.
            policy_ids (list of string, optional): Filter by Policy ids that
                are associated with Protection Jobs. Only Jobs associated with
                the specified Policy ids, are returned.
            environments (list of EnvironmentGetProtectionJobsEnum, optional):
                Filter by environment types such as 'kVMware', 'kView', etc.
                Only Jobs protecting the specified environment types are
                returned. NOTE: 'kPuppeteer' refers to Cohesity's Remote
                Adapter.
            is_active (bool, optional): Filter by Inactive or Active Jobs. If
                not set, all Inactive and Active Jobs are returned. If true,
                only Active Jobs are returned. If false, only Inactive Jobs
                are returned. When you create a Protection Job on a Primary
                Cluster with a replication schedule, the Cluster creates an
                Inactive copy of the Job on the Remote Cluster. In addition,
                when an Active and running Job is deactivated, the Job becomes
                Inactive.
            is_deleted (bool, optional): If true, return only Protection Jobs
                that have been deleted but still have Snapshots associated
                with them. If false, return all Protection Jobs except those
                Jobs that have been deleted and still have Snapshots
                associated with them. A Job that is deleted with all its
                Snapshots is not returned for either of these cases.
            only_return_basic_summary (bool, optional): if true then only job
                descriptions and the most recent run of the job will be
                returned.
            include_last_run_and_stats (bool, optional): If true, return the
                last Protection Run of the Job and the summary stats.
            include_rpo_snapshots (bool, optional): If true, then the
                Protected Objects protected by RPO policies will also be
                returned.
            is_last_run_sla_violated (bool, optional): IsLastRunSlaViolated is
                the parameter to filter the Protection Jobs based on the SLA
                violation status of the last Protection Run.
            only_return_data_migration_jobs (bool, optional):
                OnlyReturnDataMigrationJobs specifies if only data migration
                jobs should be returned. If not set, no data migration job
                will be returned.
            prune_excluded_source_ids (bool, optional): If true, the list of
                exclusion sources will be omitted from the response. This can
                be used to improve performance when the exclusion sources are
                not needed.
            tenant_ids (list of string, optional): TenantIds contains ids of
                the tenants for which objects are to be returned.
            all_under_hierarchy (bool, optional): AllUnderHierarchy specifies
                if objects of all the tenants under the hierarchy of the
                logged in user's organization should be returned.

        Returns:
            list of ProtectionJob: Response from the API. Success

        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_protection_jobs called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_protection_jobs.')
            _url_path = '/public/protectionJobs'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'ids': ids,
                'names': names,
                'policyIds': policy_ids,
                'environments': environments,
                'isActive': is_active,
                'isDeleted': is_deleted,
                'onlyReturnBasicSummary': only_return_basic_summary,
                'includeLastRunAndStats': include_last_run_and_stats,
                'includeRpoSnapshots': include_rpo_snapshots,
                'isLastRunSlaViolated': is_last_run_sla_violated,
                'onlyReturnDataMigrationJobs': only_return_data_migration_jobs,
                'pruneExcludedSourceIds': prune_excluded_source_ids,
                'tenantIds': tenant_ids,
                'allUnderHierarchy': all_under_hierarchy
            }
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_protection_jobs.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def change_protection_job_state(self, id, body=None):
        """Does a POST request to /public/protectionJobState/{id}.

        If the Protection Job is currently running (not paused) and true is
        passed in,
        this operation stops any new Runs of this Protection Job
        from stating and executing.
        However, any existing Runs that were already executing will continue
        to run.
        If this Projection Job is paused and false is passed in, this
        operation
        restores the Job to a running state and new Runs are started as
        defined
        by the schedule in the Policy associated with the Job.
        Returns success if the paused state is changed.

        Args:
            id (long|int): Specifies a unique id of the Protection Job.
            body (ChangeProtectionJobStateParam, optional): TODO: type
                description here. Example:

        Returns:
            void: Response from the API. No Content

        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('change_protection_job_state called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for change_protection_job_state.'
            )
            self.validate_parameters(id=id)

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for change_protection_job_state.')
            _url_path = '/public/protectionJobState/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': id})
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for change_protection_job_state.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def create_run_protection_job(self, id, body):
        """Does a POST request to /public/protectionJobs/run/{id}.

        Immediately execute a single Job Run and ignore the schedule defined
        in the Policy.
        A Protection Policy associated with the Job may define up to three
        backup run types:
        1) Regular (CBT utilized), 2) Full (CBT not utilized) and 3) Log.
        The passed in run type defines what type of backup is done by the Job
        Run.
        The schedule defined in the Policy for the backup run type is ignored
        but
        other settings such as the snapshot retention and retry settings are
        used.
        Returns success if the Job Run starts.

        Args:
            id (long|int): Specifies a unique id of the Protection Job.
            body (RunProtectionJobParam): Specifies the type of backup. If not
                specified, the 'kRegular' backup is run.

        Returns:
            void: Response from the API. No Content

        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_run_protection_job called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for create_run_protection_job.'
            )
            self.validate_parameters(id=id, body=body)

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for create_run_protection_job.')
            _url_path = '/public/protectionJobs/run/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': id})
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for create_run_protection_job.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_time_series_stats(self,
                              schema_name,
                              entity_id,
                              metric_name,
                              start_time_msecs,
                              rollup_function=None,
                              rollup_interval_secs=None,
                              end_time_msecs=None):
        """Does a GET request to /public/statistics/timeSeriesStats.

        A Metric specifies a data point (such as CPU usage and IOPS) to track
        over a
        period of time.
        For example for a disk in the Cluster, you can report on the 'Disk
        Health'
        (kDiskAwaitTimeMsecs) Metric of the 'Disk Health Metrics'
        (kSentryDiskStats)
        Schema for the last week.
        You must specify the 'k' names as input and not the descriptive
        names.
        You must also specify the id of the entity that you are reporting on
        such as
        a Cluster, disk drive, job, etc.
        Get the entityId by running the GET /public/statistics/entities
        operation.
        In the Cohesity Dashboard, similar functionality is provided in
        Advanced
        Diagnostics.

        Args:
            schema_name (string): Specifies the name of entity schema such as
                'kIceboxJobVaultStats'.
            entity_id (string): Specifies the id of the entity represented as
                a string. Get the entityId by running the GET
                public/statistics/entities operation.
            metric_name (string): Specifies the name of the metric such as the
                'kDiskAwaitTimeMsecs' which is displayed as 'Disk Health' in
                Advanced Diagnostics of the Cohesity Dashboard.
            start_time_msecs (long|int): Specifies the start time for the
                series of metric data. Specify the start time as a Unix epoch
                Timestamp (in milliseconds).
            rollup_function (string, optional): Specifies the rollup function
                to apply to the data points for the time interval specified by
                rollupInternalSecs. The following rollup functions are
                available: sum, average, count, max, min, median,
                percentile95, latest, and rate. For more information about the
                functions, see the Advanced Diagnostics in the Cohesity online
                help. If not specified, raw data is returned.
            rollup_interval_secs (int, optional): Specifies the time interval
                granularity (in seconds) for the specified rollup function.
                Only specify a value if Rollup function is also specified.
            end_time_msecs (long|int, optional): Specifies the end time for
                the series of metric data. Specify the end time as a Unix
                epoch Timestamp (in milliseconds). If not specified, the data
                points up to the current time are returned.

        Returns:
            MetricDataBlock: Response from the API. Success

        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_time_series_stats called.')

            # Validate required parameters
            self.logger.info('Validating required parameters for get_time_series_stats.')
            self.validate_parameters(schema_name=schema_name,
                                     entity_id=entity_id,
                                     metric_name=metric_name,
                                     start_time_msecs=start_time_msecs)

            # Prepare query URL
            self.logger.info('Preparing query URL for get_time_series_stats.')
            _url_path = '/public/statistics/timeSeriesStats'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'schemaName': schema_name,
                'entityId': entity_id,
                'metricName': metric_name,
                'startTimeMsecs': start_time_msecs,
                'rollupFunction': rollup_function,
                'rollupIntervalSecs': rollup_interval_secs,
                'endTimeMsecs': end_time_msecs
            }
            _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
                _query_parameters, Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_time_series_stats.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
    def get_entities(self,
                     schema_name,
                     include_aggr_metric_sources=None,
                     metric_names=None):
        """Does a GET request to /public/statistics/entities.

        An entity is an object found on the Cohesity Cluster, such as a disk
        or a
        Node.
        In the Cohesity Dashboard, similar functionality is provided in
        Advanced
        Diagnostics.

        Args:
            schema_name (string): Specifies the entity schema to search for
                entities.
            include_aggr_metric_sources (bool, optional): Specifies whether to
                include the sources of aggregate metrics of an entity.
            metric_names (list of string, optional): Specifies the list of
                metric names to return such as 'kRandomIos' which corresponds
                to 'Random IOs' in Advanced Diagnostics of the Cohesity
                Dashboard.

        Returns:
            list of Entity: Response from the API. Success

        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_entities called.')

            # Validate required parameters
            self.logger.info('Validating required parameters for get_entities.')
            self.validate_parameters(schema_name=schema_name)

            # Prepare query URL
            self.logger.info('Preparing query URL for get_entities.')
            _url_path = '/public/statistics/entities'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'schemaName': schema_name,
                'includeAggrMetricSources': include_aggr_metric_sources,
                'metricNames': metric_names
            }
            _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
                _query_parameters, Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_entities.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
Ejemplo n.º 10
0
    def get_vlan_by_id(self, id):
        """Does a GET request to /public/vlans/{id}.

        Returns the VLAN corresponding to the specified VLAN ID or a
        specified
        InterfaceName.<VLAN ID>.
        Example 1: /public/vlans/10
        Example 2: /public/vlans/bond0.20
        Example 3: /public/vlans/bond1.20

        Args:
            id (int): Specifies the id of the VLAN.

        Returns:
            VLAN: Response from the API. Success

        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_vlan_by_id called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for get_vlan_by_id.')
            self.validate_parameters(id=id)

            # Prepare query URL
            self.logger.info('Preparing query URL for get_vlan_by_id.')
            _url_path = '/public/vlans/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': 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_vlan_by_id.')
            _headers = {'accept': 'application/json'}

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_vlan_by_id.')
            if _context.response.status_code == 404:
                raise APIException('Not Found', _context)
            elif (_context.response.status_code <
                  200) or (_context.response.status_code > 208):
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_entity_schema_by_name(self,
                                  schema_name):
        """Does a GET request to /public/statistics/entitiesSchema/{schemaName}.

        An entity schema specifies the meta-data associated with entity such
        as the
        list of attributes and a time series of data.
        For example for a Disk entity, the entity schema specifies the Node
        that is
        using this Disk, the type of the Disk, and Metrics about the Disk such
        as
        Space Usage, Read IOs and Write IOs. Metrics define data points (time
        series
        data) to track over a period of time for a specific interval.
        In the Cohesity Dashboard, similar functionality is provided in
        Advanced
        Diagnostics.

        Args:
            schema_name (string): Name of the Schema

        Returns:
            list of EntitySchema: Response from the API. Success

        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_entity_schema_by_name called.')

            # Validate required parameters
            self.logger.info('Validating required parameters for get_entity_schema_by_name.')
            self.validate_parameters(schema_name=schema_name)

            # Prepare query URL
            self.logger.info('Preparing query URL for get_entity_schema_by_name.')
            _url_path = '/public/statistics/entitiesSchema/{schemaName}'
            _url_path = APIHelper.append_url_with_template_parameters(_url_path, {
                'schemaName': schema_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_entity_schema_by_name.')
            _headers = {
                'accept': 'application/json'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_entity_schema_by_name.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
Ejemplo n.º 12
0
    def update_vlan(self, id, body=None):
        """Does a PUT request to /public/vlans/{id}.

        Returns the created or updated VLAN on the Cohesity Cluster.

        Args:
            id (int): Specifies the id of the VLAN.
            body (VLAN, optional): TODO: type description here. Example: 

        Returns:
            VLAN: Response from the API. Success

        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('update_vlan called.')

            # Validate required parameters
            self.logger.info('Validating required parameters for update_vlan.')
            self.validate_parameters(id=id)

            # Prepare query URL
            self.logger.info('Preparing query URL for update_vlan.')
            _url_path = '/public/vlans/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': 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 update_vlan.')
            _headers = {
                'accept': 'application/json',
                'content-type': 'application/json; charset=utf-8'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for update_vlan.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Ejemplo n.º 13
0
    def create_generate_access_token(self, body):
        """Does a POST request to /public/accessTokens.

        Before making other REST API requests, your REST client must make a
        'POST /public/accessToken' request with a valid Cohesity username and
        password. This POST request returns an access token and type
        in the response that is generated by the Cohesity Cluster.
        Subsequent requests to other Cohesity REST API operations must
        specify the returned access token and type by setting 'Authorization'
        in the http header in the following format:
        Authorization: token_type access_token
        The generated token is valid for 24 hours. If a request is made with
        an expired token, the 'Token expired' error message is returned.
        Add code to your REST client to check for this error and request
        another access token before reissuing the request.

        Args:
            body (CreateAccessTokenCredentialRequest): Request to generate
                access token.

        Returns:
            AccessToken: Response from the API. Success

        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_generate_access_token called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for create_generate_access_token.'
            )
            self.validate_parameters(body=body)

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for create_generate_access_token.')
            _url_path = '/public/accessTokens'
            _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_generate_access_token.')
            _headers = {
                'accept': 'application/json',
                'content-type': 'application/json; charset=utf-8'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for create_generate_access_token.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def search_protection_sources(self,
                                  office_365_protection_source_types=None,
                                  department_list=None,
                                  title_list=None,
                                  country_list=None,
                                  search_string=None,
                                  protection_status=None,
                                  environments=None,
                                  last_protection_job_run_status=None,
                                  physical_server_host_types=None,
                                  registered_source_uuids=None,
                                  start_index=None,
                                  page_count=None):
        """Does a GET request to /public/search/protectionSources.

        Returns list of all the objects along with the protection status
        information.

        Args:
            office_365_protection_source_types (
                Office365ProtectionSourceTypesEnum, optional): Specifies the
                Array of Office365 source types. Specifies the type of Office
                365 entity
            department_list (list of string, optional): Specifies the list of
                departments to which an Office365 user may belong.
            title_list (list of string, optional): Specifies the list of
                titles/desgination applicable to Office365 users.
            country_list (list of string, optional): Specifies the list of
                countries to which Office365 user belongs.
            search_string (string, optional): Specifies the search string to
                query the name of the Protection Source or the name of the job
                protecting a Protection Source.
            protection_status (list of string, optional): Specifies the
                protection status of the object. If specified, the objects are
                filtered based on current protection status of that object on
                the cluster. Possible values that can be passed are
                "protected", "unprotected" or both. If not specified, all the
                objects are returned irrespective of protection status of the
                object.
            environments (list of EnvironmentSearchProtectionSourcesEnum,
                optional): Specifies the environment type by which Protection
                Sources will be filtered. Supported environment types such as
                'kView', 'kSQL', 'kVMware', etc. NOTE: 'kPuppeteer' refers to
                Cohesity's Remote Adapter. 'kVMware' indicates the VMware
                Protection Source environment. 'kHyperV' indicates the HyperV
                Protection Source environment. 'kSQL' indicates the SQL
                Protection Source environment. 'kView' indicates the View
                Protection Source environment. 'kPuppeteer' indicates the
                Cohesity's Remote Adapter. 'kPhysical' indicates the physical
                Protection Source environment. 'kPure' indicates the Pure
                Storage Protection Source environment. 'Nimble' indicates the
                Nimble Storage Protection Source environment. 'kAzure'
                indicates the Microsoft's Azure Protection Source environment.
                'kNetapp' indicates the Netapp Protection Source environment.
                'kAgent' indicates the Agent Protection Source environment.
                'kGenericNas' indicates the Generic Network Attached Storage
                Protection Source environment. 'kAcropolis' indicates the
                Acropolis Protection Source environment. 'kPhsicalFiles'
                indicates the Physical Files Protection Source environment.
                'kIsilon' indicates the Dell EMC's Isilon Protection Source
                environment. 'kGPFS' indicates IBM's GPFS Protection Source
                environment. 'kKVM' indicates the KVM Protection Source
                environment. 'kAWS' indicates the AWS Protection Source
                environment. 'kExchange' indicates the Exchange Protection
                Source environment. 'kHyperVVSS' indicates the HyperV VSS
                Protection Source environment. 'kOracle' indicates the Oracle
                Protection Source environment. 'kGCP' indicates the Google
                Cloud Platform Protection Source environment. 'kFlashBlade'
                indicates the Flash Blade Protection Source environment.
                'kAWSNative' indicates the AWS Native Protection Source
                environment. 'kO365' indicates the Office 365 Protection Source
                environment. 'kO365Outlook' indicates Office 365 outlook
                Protection Source environment. 'kHyperFlex' indicates the Hyper
                Flex Protection Source environment. 'kGCPNative' indicates the
                GCP Native Protection Source environment. 'kAzureNative'
                indicates the Azure Native Protection Source environment.
                'kKubernetes' indicates a Kubernetes Protection Source
                environment. 'kElastifile' indicates Elastifile Protection
                Source environment. 'kAD' indicates Active Directory Protection
                Source environment. 'kRDSSnapshotManager' indicates AWS RDS
                Protection Source environment. 'kCassandra' indicates Cassandra
                Protection Source environment. 'kMongoDB' indicates MongoDB
                Protection Source environment. 'kCouchbase' indicates Couchbase
                Protection Source environment. 'kHdfs' indicates Hdfs
                Protection Source environment. 'kHive' indicates Hive
                Protection Source environment. 'kHBase' indicates HBase
                Protection Source environment.
            last_protection_job_run_status (list of int, optional): Specifies
                the last Protection Job run status of the object. If
                specified, objects will be filtered based on last job run
                status.
            physical_server_host_types (list of PhysicalServerHostTypeEnum,
                optional): Specifies physical server host OS type. If
                specified, the physical server objects will be filtered based
                on OS type of the server. 'kLinux' indicates the Linux
                operating system. 'kWindows' indicates the Microsoft Windows
                operating system. 'kAix' indicates the IBM AIX operating
                system. 'kSolaris' indicates the Oracle Solaris operating
                system. 'kSapHana' indicates the Sap Hana database system
                developed by SAP SE. 'kOther' indicates the other types of
                operating system.
            registered_source_uuids (list of string, optional): Specifies the
                list of Registered Sources Uuids. Only items from the listed
                Registered Sources are returned.
            start_index (int, optional): Specifies an index number that can be
                used to return subsets of items in multiple requests. Break up
                the items to return into multiple requests by setting
                pageCount and using startIndex to return a subsets of items.
                For example, set startIndex to 0 to get the first set of items
                for the first request. Increment startIndex by pageCount to
                get the next set of items for a next request.
            page_count (int, optional): Specifies the number of items to
                return in the response for pagination purposes. Default the
                pageCount to MaxSearchResponseSize if this is unspecified.

        Returns:
            list of ProtectionSourceResponse: Response from the API. Success

        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('search_protection_sources called.')

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for search_protection_sources.')
            _url_path = '/public/search/protectionSources'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'office365ProtectionSourceTypes':
                office_365_protection_source_types,
                'departmentList': department_list,
                'titleList': title_list,
                'countryList': country_list,
                'searchString': search_string,
                'protectionStatus': protection_status,
                'environments': environments,
                'lastProtectionJobRunStatus': last_protection_job_run_status,
                'physicalServerHostTypes': physical_server_host_types,
                'registeredSourceUuids': registered_source_uuids,
                'startIndex': start_index,
                'pageCount': page_count
            }
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for search_protection_sources.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_nodes(self,
                  ids=None, 
                  include_marked_for_removal=None,
                  include_only_unassigned_nodes=None,
                  cluster_partition_ids=None,
                  fetch_stats=None,
                  show_system_disks=None):
        """Does a GET request to /public/nodes.

        If no parameters are specified, all Nodes currently on the Cohesity
        Cluster are
        returned.
        Specifying parameters filters the results that are returned.
        Args:
            ids (long|int, optional): IdList is the ids of nodes to be
                returned. If empty, all nodes are returned.
            include_marked_for_removal (bool, optional):
                IncludeMarkedForRemoval is used to specify whether to
                include nodes marked for removal.
            include_only_unassigned_nodes (bool, optional):
                IncludeOnlyUnassignedNodes will return nodes that are not yet
                assigned to any cluster partition. If this parameter is
                specified as true and ClusterPartitionIdList is also non-empty,
                then no nodes will be returned.
            cluster_partition_ids (long|int, optional):  ClusterPartitionIdList
                specifies the list of Ids used to filter the nodes by specified
                cluster partition.
            fetch_stats (bool, optional): FetchStats is used to specify whether
                to call Stats service to fetch the stats for the nodes.
            show_system_disks (bool, optional): ShowSystemdisks is used to
                specify whether to display system disks for the nodes.

        Returns:
            list of Node: Response from the API. Success

        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_nodes called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_nodes.')
            _url_path = '/public/nodes'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'ids': ids,
                'includeMarkedForRemoval': include_marked_for_removal,
                'includeOnlyUnassignedNodes': include_only_unassigned_nodes,
                'clusterPartitionIds': cluster_partition_ids,
                'fetchStats': fetch_stats,
                'showSystemDisks': show_system_disks
            }
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_nodes.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_entities_schema(self,
                            schema_names=None,
                            metric_names=None):
        """Does a GET request to /public/statistics/entitiesSchema.

        An entity schema specifies the meta-data associated with entity such
        as
        the list of attributes and a time series of data.
        For example for a Disk entity, the entity schema specifies the Node
        that is
        using this Disk, the type of the Disk, and Metrics about the Disk such
        as Space
        Usage, Read IOs and Write IOs. Metrics define data points (time series
        data)
        to track over a period of time for a specific interval.
        If no parameters are specified, all entity schemas found on the
        Cohesity
        Cluster are returned.
        Specifying parameters filters the results that are returned.
        In the Cohesity Dashboard, similar functionality is provided in
        Advanced
        Diagnostics.

        Args:
            schema_names (list of string, optional): Specifies the list of
                schema names to filter by such as 'kIceboxJobVaultStats' which
                corresponds to 'External Target Job Stats' in Advanced
                Diagnostics of the Cohesity Dashboard.
            metric_names (list of string, optional): Specifies the list of
                metric names to filter by such as 'kRandomIos' which
                corresponds to 'Random IOs' in Advanced Diagnostics of the
                Cohesity Dashboard.

        Returns:
            list of EntitySchema: Response from the API. Success

        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_entities_schema called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_entities_schema.')
            _url_path = '/public/statistics/entitiesSchema'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'schemaNames': schema_names,
                'metricNames': metric_names
            }
            _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
                _query_parameters, Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_entities_schema.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
    def update_upgrade_node(self, body):
        """Does a PUT request to /public/nodes/software.

        Sends a request to upgrade the software version of a Node. By default,
        the
        Node that the request is sent to is the only one upgraded, but the
        user can
        specify if they want to attempt to upgrade all free nodes on the
        network.
        Before using this, you need to upload a new package to the Node you
        want to
        upgrade by using the /public/packages endpoint.

        Args:
            body (UpgradeNodeParameters): TODO: type description here.
                Example:

        Returns:
            UpgradeNodeResult: Response from the API. Success

        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('update_upgrade_node called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for update_upgrade_node.')
            self.validate_parameters(body=body)

            # Prepare query URL
            self.logger.info('Preparing query URL for update_upgrade_node.')
            _url_path = '/public/nodes/software'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for update_upgrade_node.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_resolution_by_id(self,
                             id):
        """Does a GET request to /public/alertResolutions/{id}.

        Returns the Alert Resolution object corresponding to passed in Alert
        Resolution Id.

        Args:
            id (long|int): Unique id of the Alert Resolution to return.

        Returns:
            AlertResolution1: Response from the API. Success

        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_resolution_by_id called.')

            # Validate required parameters
            self.logger.info('Validating required parameters for get_resolution_by_id.')
            self.validate_parameters(id=id)

            # Prepare query URL
            self.logger.info('Preparing query URL for get_resolution_by_id.')
            _url_path = '/public/alertResolutions/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(_url_path, {
                'id': 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_resolution_by_id.')
            _headers = {
                'accept': 'application/json'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_resolution_by_id.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
    def create_protection_job(self, body):
        """Does a POST request to /public/protectionJobs.

        Returns the created Protection Job.

        Args:
            body (ProtectionJobRequestBody): Request to create a Protection
                Job.

        Returns:
            ProtectionJob: Response from the API. Success

        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_protection_job called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for create_protection_job.')
            self.validate_parameters(body=body)

            # Prepare query URL
            self.logger.info('Preparing query URL for create_protection_job.')
            _url_path = '/public/protectionJobs'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for create_protection_job.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def create_notification_rule(self, body=None):
        """Does a POST request to /public/alertNotificationRules.

        Creates a new notification rule with provided delivery targets such as
        email
        addresses and external apis.

        Args:
            body (NotificationRule, optional): Create Notification Rule
                argument.

        Returns:
            NotificationRule: Response from the API. Success

        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_notification_rule called.')

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for create_notification_rule.')
            _url_path = '/public/alertNotificationRules'
            _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_notification_rule.')
            _headers = {
                'accept': 'application/json',
                'content-type': 'application/json; charset=utf-8'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for create_notification_rule.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def update_protection_jobs_state(self, body=None):
        """Does a POST request to /public/protectionJobs/states.

        Note that the pause or resume actions will take effect from next
        Protection
        Run. Also, user can specify only one type of action on all the
        Protection Jobs.
        Deactivate and activate actions are independent of pause and resume
        state.
        Deactivate and activate actions are useful in case of failover
        situations.
        Returns success if the state of all the Protection Jobs state is
        changed
        successfully.

        Args:
            body (UpdateProtectionJobsStateRequestBody, optional): TODO: type
                description here. Example:

        Returns:
            UpdateProtectionJobsState: Response from the API. Success

        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('update_protection_jobs_state called.')

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for update_protection_jobs_state.')
            _url_path = '/public/protectionJobs/states'
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for update_protection_jobs_state.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def update_resolution(self, id, body):
        """Does a PUT request to /public/alertResolutions/{id}.

        Apply an existing Alert Resolution to one or more additional Alerts.
        Mark those additional Alerts as resolved.

        Args:
            id (long|int): Unique id of the Alert Resolution to return.
            body (UpdateResolutionParams): Request to apply an existing
                resolution to the specified Alerts.

        Returns:
            AlertResolution: Response from the API. Success

        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('update_resolution called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for update_resolution.')
            self.validate_parameters(id=id, body=body)

            # Prepare query URL
            self.logger.info('Preparing query URL for update_resolution.')
            _url_path = '/public/alertResolutions/{id}'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': 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 update_resolution.')
            _headers = {
                'accept': 'application/json',
                'content-type': 'application/json; charset=utf-8'
            }

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for update_resolution.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_protection_job_audit(self, id):
        """Does a GET request to /public/protectionJobs/{id}/auditTrail.

        Returns the audit of specific protection job edit history.

        Args:
            id (long|int): Specifies a unique id of the Protection Job.

        Returns:
            list of ProtectionJobAuditTrail: Response from the API. Success

        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_protection_job_audit called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for get_protection_job_audit.')
            self.validate_parameters(id=id)

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for get_protection_job_audit.')
            _url_path = '/public/protectionJobs/{id}/auditTrail'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'id': id})
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for get_protection_job_audit.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def get_alerts(self,
                   max_alerts,
                   tenant_ids=None,
                   all_under_hierarchy=None,
                   alert_id_list=None,
                   alert_type_list=None,
                   alert_category_list=None,
                   property_key=None,
                   property_value=None,
                   start_date_usecs=None,
                   end_date_usecs=None,
                   alert_state_list=None,
                   alert_severity_list=None,
                   resolution_id_list=None):
        """Does a GET request to /public/alerts.

        Returns all Alert objects found on the Cohesity Cluster that
        match the filter criteria specified using parameters.
        The Cohesity Cluster creates an Alert when a potential problem
        is found or when a threshold has been exceeded on the Cohesity
        Cluster.
        If no filter parameters are specified, all Alert objects are
        returned.
        Each object provides details about the Alert such as the Status and
        Severity.

        Args:
            max_alerts (int): Specifies the number of returned Alerts to be
                returned. The newest Alerts are returned.
            tenant_ids (list of string, optional): TenantIds contains ids of
                the tenants for which objects are to be returned.
            all_under_hierarchy (bool, optional): AllUnderHierarchy specifies
                if objects of all the tenants under the hierarchy of the
                logged in user's organization should be returned.
            alert_id_list (list of string, optional): Specifies list of Alert
                ids to filter alerts by.
            alert_type_list (list of int, optional): Specifies list of Alert
                Types to filter alerts by.
            alert_category_list (list of AlertCategoryListGetAlertsEnum,
                optional): Specifies list of Alert Categories.
            property_key (string, optional): Specifies name of the property to
                filter alerts by.
            property_value (string, optional): Specifies value of the property
                to filter alerts by.
            start_date_usecs (long|int, optional): Specifies start time Unix
                epoch time in microseconds to filter alerts by.
            end_date_usecs (long|int, optional): Specifies end time Unix epoch
                time in microseconds to filter alerts by.
            alert_state_list (list of AlertStateListEnum, optional): Specifies
                list of Alert States to filter alerts by.
            alert_severity_list (list of AlertSeverityListEnum, optional):
                Specifies list of Alert severity to filter alerts by.
            resolution_id_list (list of long|int, optional): Specifies alert
                resolution ids to filter alerts by.

        Returns:
            list of Alert: Response from the API. Success

        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_alerts called.')

            # Validate required parameters
            self.logger.info('Validating required parameters for get_alerts.')
            self.validate_parameters(max_alerts=max_alerts)

            # Prepare query URL
            self.logger.info('Preparing query URL for get_alerts.')
            _url_path = '/public/alerts'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'maxAlerts': max_alerts,
                'tenantIds': tenant_ids,
                'allUnderHierarchy': all_under_hierarchy,
                'alertIdList': alert_id_list,
                'alertTypeList': alert_type_list,
                'alertCategoryList': alert_category_list,
                'propertyKey': property_key,
                'propertyValue': property_value,
                'startDateUsecs': start_date_usecs,
                'endDateUsecs': end_date_usecs,
                'alertStateList': alert_state_list,
                'alertSeverityList': alert_severity_list,
                'resolutionIdList': resolution_id_list
            }
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_alerts.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Ejemplo n.º 25
0
    def get_privileges(self,
                       name=None):
        """Does a GET request to /public/privileges.

        If the 'name' parameter is not specified, all privileges defined
        on the Cohesity Cluster are returned.
        In addition, information about each privilege is returned such as the
        associated category, description, name,  etc.
        If an exact privilege name (such as PRINCIPAL_VIEW) is specified in
        the
        'name' parameter, only information about that single privilege is
        returned.

        Args:
            name (string, optional): Specifies the name of the privilege.

        Returns:
            list of PrivilegeInformation: Response from the API. Success

        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_privileges called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_privileges.')
            _url_path = '/public/privileges'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'name': name
            }
            _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
                _query_parameters, Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_privileges.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info = True)
            raise
Ejemplo n.º 26
0
    def update_protection_runs(self,
                               body):
        """Does a PUT request to /public/protectionRuns.

        Update the expiration date (retention period) for the specified
        Protection
        Job Runs and their snapshots.
        After an expiration time is reached, the Job Run and its snapshots are
        deleted.
        If an expiration time of 0 is specified, a Job Run and its snapshots
        are immediately deleted.

        Args:
            body (UpdateProtectionJobRunsParameters): Request to update the
                expiration time of Protection Job Runs.

        Returns:
            void: Response from the API. No Content

        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('update_protection_runs called.')
    
            # Validate required parameters
            self.logger.info('Validating required parameters for update_protection_runs.')
            self.validate_parameters(body=body)
    
            # Prepare query URL
            self.logger.info('Preparing query URL for update_protection_runs.')
            _url_path = '/public/protectionRuns'
            _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 update_protection_runs.')
            _headers = {
                'content-type': 'application/json; charset=utf-8'
            }
    
            # Prepare and execute request
            self.logger.info('Preparing and executing request for update_protection_runs.')
            _request = self.http_client.put(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))
            AuthManager.apply(_request)
            _context = self.execute_request(_request, name = 'update_protection_runs')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for update_protection_runs.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info = True)
Ejemplo n.º 27
0
    def get_groups(self,
                   tenant_ids=None,
                   all_under_hierarchy=None,
                   name=None,
                   domain=None):
        """Does a GET request to /public/groups.

        If no parameters are specified, all groups currently on the Cohesity
        Cluster
        are returned. Specifying parameters filters the results that are
        returned.

        Args:
            tenant_ids (list of string, optional): TenantIds contains ids of
                the tenants for which objects are to be returned.
            all_under_hierarchy (bool, optional): AllUnderHierarchy specifies
                if objects of all the tenants under the hierarchy of the
                logged in user's organization should be returned.
            name (string, optional): Optionally specify a group name to filter
                by.
            domain (string, optional): If no domain is specified, all groups
                on the Cohesity Cluster are searched. If a domain is
                specified, only groups on the Cohesity Cluster associated with
                that domain are searched.

        Returns:
            list of GroupDetails: Response from the API. Success

        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_groups called.')

            # Prepare query URL
            self.logger.info('Preparing query URL for get_groups.')
            _url_path = '/public/groups'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'tenantIds': tenant_ids,
                'allUnderHierarchy': all_under_hierarchy,
                'name': name,
                'domain': domain
            }
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_groups.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)

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

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
Ejemplo n.º 28
0
    def get_protection_runs(self,
                            start_time_usecs=None,
                            exclude_tasks=None,
                            source_id=None,
                            job_id=None,
                            end_time_usecs=None,
                            num_runs=None,
                            run_types=None,
                            exclude_error_runs=None,
                            exclude_non_restoreable_runs=None,
                            started_time_usecs=None):
        """Does a GET request to /public/protectionRuns.

        If no parameters are specified, Job Runs currently
        on the Cohesity Cluster are returned. Both running and completed Job
        Runs
        are reported.
        Specifying parameters filters the results that are returned.

        Args:
            start_time_usecs (long|int, optional): Filter by a start time.
                Only Job Runs that started after the specified time are
                returned. Specify the start time as a Unix epoch Timestamp (in
                microseconds).
            exclude_tasks (bool, optional): If true, the individual backup
                status for all the objects protected by the Job Run are not
                populated in the response. For example in a VMware
                environment, the status of backing up each VM associated with
                a Job is not returned.
            source_id (long|int, optional): Filter by source id. Only Job Runs
                protecting the specified source (such as a VM or View) are
                returned. The source id is assigned by the Cohesity Cluster.
            job_id (long|int, optional): Filter by a Protection Job that is
                specified by id. If not specified, all Job Runs for all
                Protection Jobs are returned.
            end_time_usecs (long|int, optional): Filter by a end time
                specified as a Unix epoch Timestamp (in microseconds). Only
                Job Runs that completed before the specified end time are
                returned.
            num_runs (long|int, optional): Specify the number of Job Runs to
                return. The newest Job Runs are returned.
            run_types (list of string, optional): Filter by run type such as
                'kFull', 'kRegular' or 'kLog'. If not specified, Job Runs of
                all types are returned.
            exclude_error_runs (bool, optional): Filter out Jobs Runs with
                errors by setting this field to 'true'. If not set or set to
                'false', Job Runs with errors are returned.
            exclude_non_restoreable_runs (bool, optional): Filter out jobs
                runs that cannot be restored by setting this field to 'true'.
                If not set or set to 'false', Runs without any successful
                object will be returned. The default value is false.
            started_time_usecs (long|int, optional): Return a specific Job Run
                by specifying a time and a jobId. Specify the time when the
                Job Run started as a Unix epoch Timestamp (in microseconds).
                If this field is specified, jobId must also be specified.

        Returns:
            list of ProtectionJobRunInstance: Response from the API. Success

        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_protection_runs called.')
    
            # Prepare query URL
            self.logger.info('Preparing query URL for get_protection_runs.')
            _url_path = '/public/protectionRuns'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'startTimeUsecs': start_time_usecs,
                'excludeTasks': exclude_tasks,
                'sourceId': source_id,
                'jobId': job_id,
                'endTimeUsecs': end_time_usecs,
                'numRuns': num_runs,
                'runTypes': run_types,
                'excludeErrorRuns': exclude_error_runs,
                'excludeNonRestoreableRuns': exclude_non_restoreable_runs,
                'startedTimeUsecs': started_time_usecs
            }
            _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
                _query_parameters, Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)
    
            # Prepare headers
            self.logger.info('Preparing headers for get_protection_runs.')
            _headers = {
                'accept': 'application/json'
            }
    
            # Prepare and execute request
            self.logger.info('Preparing and executing request for get_protection_runs.')
            _request = self.http_client.get(_query_url, headers=_headers)
            AuthManager.apply(_request)
            _context = self.execute_request(_request, name = 'get_protection_runs')

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info('Validating response for get_protection_runs.')
            if _context.response.status_code == 0:
                raise ErrorErrorException('Error', _context)
            self.validate_response(_context)
    
            # Return appropriate type
            return APIHelper.json_deserialize(_context.response.raw_body, ProtectionJobRunInstance.from_dictionary)

        except Exception as e:
            self.logger.error(e, exc_info = True)
Ejemplo n.º 29
0
    def update_app_instance_state(self, app_instance_id, body):
        """Does a PUT request to /public/appInstances/{appInstanceId}/states.

        Changes the state of the app instances.

        Args:
            app_instance_id (int): Specifies the app instance Id.
            body (UpdateAppInstanceStateParameters): Request to update app
            instance state.

        Returns:
            void: Response from the API. No Content

        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('update_app_instance_state called.')

            # Validate required parameters
            self.logger.info(
                'Validating required parameters for update_app_instance_state.'
            )
            self.validate_parameters(app_instance_id=app_instance_id,
                                     body=body)

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for update_app_instance_state.')
            _url_path = '/public/appInstances/{appInstanceId}/states'
            _url_path = APIHelper.append_url_with_template_parameters(
                _url_path, {'appInstanceId': app_instance_id})
            _query_builder = self.config.get_base_uri()
            _query_builder += _url_path
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for update_app_instance_state.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

        except Exception as e:
            self.logger.error(e, exc_info=True)
            raise
    def search_cluster_audit_logs(self,
                                  user_names=None,
                                  domains=None,
                                  entity_types=None,
                                  actions=None,
                                  search=None,
                                  start_time_usecs=None,
                                  end_time_usecs=None,
                                  start_index=None,
                                  page_count=None,
                                  output_format=None,
                                  tenant_id=None,
                                  all_under_hierarchy=None):
        """Does a GET request to /public/auditLogs/cluster.

        When actions (such as a login or a Job being paused) occur on the
        Cohesity Cluster, the Cluster generates Audit Logs.
        If no parameters are specified, all logs currently on the Cohesity
        Cluster
        are returned. Specifying parameters filters the results that are
        returned.

        Args:
            user_names (list of string, optional): Filter by user names who
                cause the actions that generate Cluster Audit Logs.
            domains (list of string, optional): Filter by domains of users who
                cause the actions that trigger Cluster audit logs.
            entity_types (list of string, optional): Filter by entity types
                involved in the actions that generate the Cluster audit logs,
                such as User, Protection Job, View, etc. For a complete list,
                see the Category drop-down in the Admin > Audit Logs page of
                the Cohesity Dashboard.
            actions (list of string, optional): Filter by the actions that
                generate Cluster audit logs such as Activate, Cancel, Clone,
                Create, etc. For a complete list, see the Actions drop-down in
                the Admin > Audit Logs page of the Cohesity Dashboard.
            search (string, optional): Filter by matching a substring in
                entity name or details of the Cluster audit log.
            start_time_usecs (long|int, optional): Filter by a start time.
                Only Cluster audit logs that were generated after the
                specified time are returned. Specify the start time as a Unix
                epoch Timestamp (in microseconds).
            end_time_usecs (long|int, optional): Filter by a end time
                specified as a Unix epoch Timestamp (in microseconds). Only
                Cluster audit logs that were generated before the specified
                end time are returned.
            start_index (long|int, optional): Specifies an index number that
                can be used to return subsets of items in multiple requests.
                Break up the items to return into multiple requests by setting
                pageCount and startIndex to return a subsets of items in the
                search result. For example, set startIndex to 0 to get the
                first set of pageCount items for the first request. Increment
                startIndex by pageCount to get the next set of pageCount items
                for a next request. Continue until all items are returned and
                therefore the total number of returned items is equal to
                totalCount. Default value is 0.
            page_count (long|int, optional): Limit the number of items to
                return in the response for pagination purposes. Default value
                is 1000.
            output_format (string, optional): Specifies the format of the
                output such as csv and json. If not specified, the json format
                is returned. If csv is specified, a comma-separated list with
                a heading row is returned.
            tenant_id (string, optional): TenantId specifies the tenant whose
                action resulted in the audit log.
            all_under_hierarchy (bool, optional): AllUnderHierarchy specifies
                if logs of all the tenants under the hierarchy of tenant with
                id TenantId should be returned.

        Returns:
            ClusterAuditLogsSearchResult: Response from the API. Success

        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('search_cluster_audit_logs called.')

            # Prepare query URL
            self.logger.info(
                'Preparing query URL for search_cluster_audit_logs.')
            _url_path = '/public/auditLogs/cluster'
            _query_builder = Configuration.get_base_uri()
            _query_builder += _url_path
            _query_parameters = {
                'userNames': user_names,
                'domains': domains,
                'entityTypes': entity_types,
                'actions': actions,
                'search': search,
                'startTimeUsecs': start_time_usecs,
                'endTimeUsecs': end_time_usecs,
                'startIndex': start_index,
                'pageCount': page_count,
                'outputFormat': output_format,
                'tenantId': tenant_id,
                'allUnderHierarchy': all_under_hierarchy
            }
            _query_builder = APIHelper.append_url_with_query_parameters(
                _query_builder, _query_parameters,
                Configuration.array_serialization)
            _query_url = APIHelper.clean_url(_query_builder)

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

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

            # Endpoint and global error handling using HTTP status codes.
            self.logger.info(
                'Validating response for search_cluster_audit_logs.')
            if _context.response.status_code == 0:
                raise RequestErrorErrorException('Error', _context)
            self.validate_response(_context)

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

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