Пример #1
0
    def get(self, alert_name):
        """Returns a alert object of the specified alert name.

            Args:
                alert_name (str) - name of the alert

            Returns:
                object - instance of the Alert class for the given alert name

            Raises:
                SDKException:
                    if type of the alert name argument is not string
                    if no alert exists with the given name
        """
        if not isinstance(alert_name, str):
            raise SDKException('Alert', '103')
        else:
            alert_name = str(alert_name).lower()
            all_alerts = self._alerts

            if all_alerts and alert_name in all_alerts:
                return Alert(self._commcell_object, alert_name,
                             all_alerts[alert_name]['id'],
                             all_alerts[alert_name]['alert_category'])

            raise SDKException(
                'Alert', '104',
                'No Alert exists with name: {0}'.format(alert_name))
Пример #2
0
    def _get_clients(self):
        """Gets all the clients associated with the commcell

            Returns:
                dict - consists of all clients in the commcell
                    {
                         "client1_name": client1_id,
                         "client2_name": client2_id
                    }

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request('GET', self._CLIENTS)

        if flag:
            if response.json():
                clients_dict = {}

                for dictionary in response.json()['clientProperties']:
                    temp_name = str(dictionary['client']['clientEntity']['clientName']).lower()
                    temp_id = str(dictionary['client']['clientEntity']['clientId']).lower()
                    clients_dict[temp_name] = temp_id

                return clients_dict
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(response.text)
            raise SDKException('Response', '101', response_string)
Пример #3
0
    def get(self, backupset_name):
        """Returns a backupset object of the specified backupset name.

            Args:
                backupset_name (str) - name of the backupset

            Returns:
                object - instance of the Backupset class for the given backupset name

            Raises:
                SDKException:
                    if type of the backupset name argument is not string
                    if no backupset exists with the given name
        """
        if not isinstance(backupset_name, str):
            raise SDKException('Backupset', '101')
        else:
            backupset_name = str(backupset_name).lower()
            all_backupsets = self._backupsets

            if all_backupsets and backupset_name in all_backupsets:
                return Backupset(self._agent_object,
                                 backupset_name,
                                 all_backupsets[backupset_name],
                                 self._instance_id)

            raise SDKException('Backupset',
                               '102',
                               'No backupset exists with name: "{0}"'.format(backupset_name))
Пример #4
0
    def get(self, client_name):
        """Returns a client object of the specified client name.

            Args:
                client_name (str) - name of the client

            Returns:
                object - instance of the Client class for the given client name

            Raises:
                SDKException:
                    if type of the client name argument is not string
                    if no client exists with the given name
        """
        if not isinstance(client_name, str):
            raise SDKException('Client', '103')
        else:
            client_name = str(client_name).lower()
            all_clients = self._clients

            if all_clients and client_name in all_clients:
                return Client(self._commcell_object, client_name, all_clients[client_name])

            raise SDKException('Client',
                               '104',
                               'No client exists with name: {0}'.format(client_name))
Пример #5
0
    def get(self, user_group_name):
        """Returns a user group object of the specified user group name.

            Args:
                user_group_name (str) - name of the user group

            Returns:
                object - instance of the UserGroup class for the given user group name

            Raises:
                SDKException:
                    if type of the user group name argument is not string
                    if no user group exists with the given name
        """
        if not isinstance(user_group_name, str):
            raise SDKException('UserGroup', '103')
        else:
            user_group_name = str(user_group_name).lower()
            all_usergroups = self._user_groups

            if all_usergroups and user_group_name in all_usergroups:
                return UserGroup(self._commcell_object,
                                 user_group_name,
                                 all_usergroups[user_group_name])

            raise SDKException('UserGroup',
                               '104',
                               'No user group exists with name: {0}'.format(user_group_name))
Пример #6
0
    def _get_agents(self):
        """Gets all the agents associated to the client specified with this client object.

            Returns:
                dict - consists of all agents in the client
                    {
                         "agent1_name": agent1_id,
                         "agent2_name": agent2_id
                    }

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._client_object._commcell_object._cvpysdk_object.make_request(
            'GET', self._ALL_AGENTS)

        if flag:
            if response.json():
                agent_dict = {}
                for dictionary in response.json()['agentProperties']:
                    temp_name = str(dictionary['idaEntity']['appName']).lower()
                    temp_id = str(
                        dictionary['idaEntity']['applicationId']).lower()
                    agent_dict[temp_name] = temp_id

                return agent_dict
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #7
0
    def _get_user_groups(self):
        """Gets all the user groups associated with the commcell

            Returns:
                dict - consists of all user group in the commcell
                    {
                         "user_group1_name": user_group1_id,
                         "user_group2_name": user_group2_id
                    }

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request('GET',
                                                                            self._USER_GROUPS)

        if flag:
            if response.json():
                user_groups_dict = {}

                if 'userGroups' in response.json():
                    response_value = response.json()['userGroups']

                    for temp in response_value:
                        temp_name = str(temp['userGroupEntity']['userGroupName']).lower()
                        temp_id = str(temp['userGroupEntity']['userGroupId']).lower()
                        user_groups_dict[temp_name] = temp_id

                return user_groups_dict
            else:
                raise SDKException('Response', '102')
        else:
            raise SDKException('Response', '101', response.text)
Пример #8
0
    def get_job_summary(self):
        """Gets the properties of this job.

            Returns:
                dict - dict that contains the summary of this job

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'GET', self._JOB)

        if flag:
            if response.json():
                if response.json()['totalRecordsWithoutPaging'] == 0:
                    return False
                if 'jobs' in response.json().keys():
                    for job in response.json()['jobs']:
                        return job['jobSummary']
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #9
0
    def disable(self):
        """Disable an alert.

            Returns:
                None

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        disable_request = self._commcell_object._services.DISABLE_ALERT % (
            self.alert_id)

        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'POST', disable_request)

        if flag:
            if response.json():
                print str(response.json()['errorMessage'])
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object.__update_response__(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #10
0
    def get(self, agent_name):
        """Returns a agent object of the specified client.

            Args:
                agent_name (str) - name of the agent

            Returns:
                object - instance of the Agent class for the given agent name

            Raises:
                SDKException:
                    if type of the agent name argument is not string
                    if no agent exists with the given name
        """
        if not isinstance(agent_name, str):
            raise SDKException('Agent', '101')
        else:
            agent_name = str(agent_name).lower()
            all_agents = self._agents

            if all_agents and agent_name in all_agents:
                return Agent(self._client_object, agent_name,
                             all_agents[agent_name])

            raise SDKException(
                'Agent', '102',
                'No agent exists with name: {0}'.format(agent_name))
Пример #11
0
    def get(self, subclient_name):
        """Returns a subclient object of the specified backupset name.

            Args:
                subclient_name (str) - name of the subclient

            Returns:
                object - instance of the Subclient class for the given subclient name

            Raises:
                SDKException:
                    if type of the subclient name argument is not string
                    if no subclient exists with the given name
        """
        if not isinstance(subclient_name, str):
            raise SDKException('Subclient', '101')
        else:
            subclient_name = str(subclient_name).lower()
            all_subclients = self._subclients

            if all_subclients and subclient_name in all_subclients:
                return Subclient(self._backupset_object, subclient_name,
                                 all_subclients[subclient_name])

            raise SDKException(
                'Subclient', '102',
                'No subclient exists with name: {0}'.format(subclient_name))
Пример #12
0
    def delete(self, alert_name):
        """Deletes the alert from the commcell.

            Args:
                alert_name (str) - name of the alert

            Returns:
                None

            Raises:
                SDKException:
                    if type of the alert name argument is not string
                    if failed to delete the alert
                    if no alert exists with the given name
        """
        if not isinstance(alert_name, str):
            raise SDKException('Alert', '103')
        else:
            alert_name = str(alert_name).lower()
            all_alerts = self._alerts

            if all_alerts and alert_name in all_alerts:
                alert_id = all_alerts[alert_name]
                alert = self._commcell_object._services.ALERT % (alert_id)

                flag, response = self._commcell_object._cvpysdk_object.make_request(
                    'DELETE', alert)

                if flag:
                    if response.json():
                        if 'errorCode' in response.json():
                            if response.json()['errorCode'] == 0:
                                o_str = 'Alert: "{0}" deleted successfully'
                                print o_str.format(alert_name)
                                self._alerts = self._get_alerts()
                            else:
                                print response.json()['errorMessage']
                    else:
                        raise SDKException('Response', '102')
                else:
                    exception_message = 'Failed to delete the Alert: {0}'.format(
                        alert_name)
                    response_string = self._commcell_object.__update_response__(
                        response.text)
                    exception_message += "\n" + response_string

                    raise SDKException('Alert', '104', exception_message)
            else:
                raise SDKException(
                    'Alert', '104',
                    'No alert exists with name: {0}'.format(alert_name))
Пример #13
0
    def _get_alerts(self):
        """Gets all the alerts associated with the commcell

            Returns:
                dict - consists of all alerts of the commcell
                    {
                         "alert1_name": {
                             "id": alert1_id,
                             "category": alert1_category
                         },
                         "alert2_name": {
                             "id": alert2_id,
                             "category": alert2_category
                         }
                    }

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'GET', self._ALERTS)

        if flag:
            if response.json():
                alerts_dict = {}
                alert_dict = {}

                for dictionary in response.json()['alertList']:
                    temp_name = str(dictionary['alert']['name']).lower()
                    temp_id = str(dictionary['alert']['id']).lower()
                    temp_description = str(dictionary['description']).lower()
                    temp_category = str(
                        dictionary['alertCategory']['name']).lower()

                    alert_dict['id'] = temp_id
                    alert_dict['description'] = temp_description
                    alert_dict['category'] = temp_category
                    alerts_dict[temp_name] = alert_dict

                return alerts_dict
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object.__update_response__(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #14
0
    def kill(self):
        """Kill the job.

            Returns:
                None

            Raises:
                SDKException:
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'POST', self._KILL)

        if flag:
            if response.json() and 'errors' in response.json():
                error_list = response.json()['errors'][0]['errList'][0]
                error_message = str(error_list['errLogMessage']).strip()
                error_code = str(error_list['errorCode']).strip()

                print 'Job kill failed with error message: "%s", and error code: "%s"' % \
                    (error_message, error_code)
            else:
                self.status = str(self.get_job_summary()['status'])
                self.finished = True
                print 'Job killed successfully'
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #15
0
    def disable_notification_type(self, alert_notification_type):
        """Disable the notification type.

            Args:
                alert_notification_type (str) - alert notification to disable

            Returns:
                None

            Raises:
                SDKException:
                    if type of alert notification argument is not string
                    if response is empty
                    if response is not success
                    if no notification type exists with the name provided
        """
        if not isinstance(alert_notification_type, str):
            raise SDKException('Alert', '103')

        if alert_notification_type.lower() in self._all_notification_types:
            alert_notification_type_id = self._all_notification_types[
                alert_notification_type.lower()]

            disable_request = self._commcell_object._services.ENABLE_ALERT_NOTIFICATION % (
                self.alert_id, alert_notification_type_id)

            flag, response = self._commcell_object._cvpysdk_object.make_request(
                'POST', disable_request)

            if flag:
                if response.json():
                    error_code = str(response.json()['errorCode'])
                    if error_code is '0':
                        print "Notification Type disabled successfully"
                    else:
                        print str(response.json()['errorMessage'])
                else:
                    raise SDKException('Response', '102')
            else:
                response_string = self._commcell_object.__update_response__(
                    response.text)
                raise SDKException('Response', '101', response_string)
        else:
            raise SDKException(
                'Alert', '104',
                'No notification type with name {0} exists'.format(
                    alert_notification_type))
Пример #16
0
    def _get_backupset_properties(self):
        """Gets the properties of this backupset.

            Returns:
                dict - properties of the backupset
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request('GET',
                                                                            self._BACKUPSET)

        if flag:
            if response.json():
                return response.json()
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(response.text)
            raise SDKException('Response', '101', response_string)
Пример #17
0
    def _login_(self):
        """Posts a login request to the server

            Returns:
                tuple - (token, user_GUID), when response is success

            Raises:
                SDKException:
                    if login failed
                    if response is empty
                    if response is not success
                Error returned by the requests package
        """
        try:
            json_login_request = {
                "mode": 4,
                "username": self._commcell_object._user,
                "password": self._commcell_object._password
            }

            flag, response = self.make_request(
                'POST', self._commcell_object._services.LOGIN,
                json_login_request)

            if flag:
                if response.json():
                    if "userName" in response.json(
                    ) and "token" in response.json():
                        print 'Login Successful'
                        return str(response.json()['token']), str(
                            response.json()['userGUID'])
                    else:
                        error_message = response.json(
                        )['errList'][0]['errLogMessage']
                        error_code = response.json()['errList'][0]['errorCode']
                        err_msg = 'Login Failed with error message: "%s" and error code: "%s"' % \
                            (error_message, error_code)
                        raise SDKException('CVPySDK', '101', err_msg)
                else:
                    raise SDKException('Response', '102')
            else:
                raise SDKException('CVPySDK', '101')

        except requests.exceptions.ConnectionError as con_err:
            raise con_err.message
Пример #18
0
    def console_alerts(self, page_number=1, page_count=1):
        """Prints the console alerts from page_number to the number of pages asked for page_count

            Args:
                page_number (int) - page number to get the alerts from
                page_count  (int) - number of pages to get the alerts of

            Raises:
                SDKException:
                    if type of the page number and page count argument is not int
                    if response is empty
                    if response is not success
        """
        if not (isinstance(page_number, int) and isinstance(page_count, int)):
            raise SDKException('Alert', '103')

        console_alerts = self._commcell_object._services.GET_ALL_CONSOLE_ALERTS % (
            page_number, page_count)

        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'GET', console_alerts)

        if flag:
            if response.json() and 'totalNoOfAlerts' in response.json():
                print "Total Console Alerts found: {0}".format(
                    response.json()['totalNoOfAlerts'])

                for dictionary in response.json()['feedsList']:
                    print "Alert Name: {0}".format(dictionary['alertName'])
                    print "Alert Type: {0}".format(dictionary['alertType'])
                    print "Alert Criteria: {0}".format(
                        dictionary['alertcriteria'])

                    if 'clientName' in dictionary['client']:
                        print "Client Name: {0}".format(
                            str(dictionary['client']['clientName']))
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object.__update_response__(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #19
0
    def _get_usergroup_properties(self):
        """Gets the user group properties of this user group.

            Returns:
                dict - dictionary consisting of the properties of this user group

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request('GET', self._USERGROUP)

        if flag:
            if response.json():
                return response.json()
            else:
                raise SDKException('Response', '102')
        else:
            raise SDKException('Response', '101', response.text)
Пример #20
0
    def __init__(self, commcell_object, job_id):
        """Initialise the Job class instance.

            Args:
                commcell_object (object) - instance of the Commcell class
                job_id (str / int) - id of the job

            Returns:
                object - instance of the Job class

            Raises:
                SDKException:
                    if job id is not of type int
                    if job is not a valid job, i.e., does not exist in the Commcell
        """
        try:
            int(job_id)
        except ValueError:
            raise SDKException('Job', '101')

        self._commcell_object = commcell_object
        self._job_id = str(job_id)

        self._JOB = self._commcell_object._services.JOB % (self.job_id)
        if not self._is_valid_job():
            raise SDKException('Job', '102')

        self._JOB_DETAILS = self._commcell_object._services.JOB_DETAILS
        self._SUSPEND = self._commcell_object._services.SUSPEND_JOB % (
            self.job_id)
        self._RESUME = self._commcell_object._services.RESUME_JOB % (
            self.job_id)
        self._KILL = self._commcell_object._services.KILL_JOB % (self.job_id)

        self.finished = self._is_finished()
        self.status = str(self.get_job_summary()['status'])

        self._initialize_job_properties()

        thread = threading.Thread(target=self._check_finished)
        thread.start()
Пример #21
0
    def _get_subclients(self):
        """Gets all the subclients associated to the client specified by the backupset object.

            Returns:
                dict - consists of all subclients in the backupset
                    {
                         "subclient1_name": subclient1_id,
                         "subclient2_name": subclient2_id
                    }

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'GET', self._ALL_SUBCLIENTS)

        if flag:
            if response.json() and 'subClientProperties' in response.json(
            ).keys():
                return_dict = {}

                for dictionary in response.json()['subClientProperties']:
                    backupset = str(dictionary['subClientEntity']
                                    ['backupsetName']).lower()

                    if self._backupset_object.backupset_name in backupset:
                        temp_name = str(dictionary['subClientEntity']
                                        ['subclientName']).lower()
                        temp_id = str(dictionary['subClientEntity']
                                      ['subclientId']).lower()
                        return_dict[temp_name] = temp_id

                return return_dict
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #22
0
    def _get_backupsets(self):
        """Gets all the backupsets associated to the agent specified by agent_object.

            Returns:
                dict - consists of all backupsets of the agent
                    {
                         "backupset1_name": backupset1_id,
                         "backupset2_name": backupset2_id
                    }

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request('GET',
                                                                            self._ALL_BACKUPSETS)

        if flag:
            if response.json() and 'backupsetProperties' in response.json().keys():
                return_dict = {}

                for dictionary in response.json()['backupsetProperties']:
                    if not self._instance_name:
                        self._instance_name = str(dictionary['backupSetEntity']['instanceName'])
                        self._instance_id = str(dictionary['backupSetEntity']['instanceId'])

                    agent = str(dictionary['backupSetEntity']['appName']).lower()

                    if self._agent_object.agent_name in agent:
                        temp_name = str(dictionary['backupSetEntity']['backupsetName']).lower()
                        temp_id = str(dictionary['backupSetEntity']['backupsetId']).lower()
                        return_dict[temp_name] = temp_id

                return return_dict
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(response.text)
            raise SDKException('Response', '101', response_string)
Пример #23
0
    def _get_subclient_properties(self):
        """Gets the subclient properties of this subclient.

            Returns:
                dict - dictionary consisting of the properties of this subclient

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'GET', self._SUBCLIENT)

        if flag:
            if response.json():
                return response.json()
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #24
0
    def _get_alert_properties(self):
        """Gets the alert properties of this alert.

            Returns:
                dict - dictionary consisting of the properties of this alert

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'GET', self._ALERT)

        if flag:
            if response.json() and 'alertDetail' in response.json().keys():
                return response.json()['alertDetail']
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object.__update_response__(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #25
0
    def _get_client_properties(self):
        """Gets the client properties of this client.

            Returns:
                dict - dictionary consisting of the properties of this client

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        flag, response = self._commcell_object._cvpysdk_object.make_request('GET',
                                                                            self._CLIENT)

        if flag:
            if response.json() and 'clientProperties' in response.json().keys():
                if isinstance(response.json()['clientProperties'][0], dict):
                    return response.json()['clientProperties'][0]
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(response.text)
            raise SDKException('Response', '101', response_string)
Пример #26
0
    def get_job_details(self):
        """Gets the detailed properties of this job.

            Returns:
                dict - dict consisting of the detailed properties of the job

            Raises:
                SDKException:
                    if response is empty
                    if response is not success
        """
        payload = {"jobId": int(self.job_id)}
        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'POST', self._JOB_DETAILS, payload)

        if flag:
            if response.json() and 'job' in response.json().keys():
                return response.json()['job']
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #27
0
    def __init__(self, class_object):
        """Initialise the Schedules class instance.

            Args:
                class_object (object) - instance of the client/agent/backupset/subclient class

            Returns:
                object - instance of the Schedules class

            Raises:
                SDKException:
                    if class object does not belong to any of the Client or Agent or Backupset or
                        Subclient class
        """
        # imports inside the __init__ method definition to avoid cyclic imports
        from client import Client
        from agent import Agent
        from backupset import Backupset
        from subclient import Subclient

        self._commcell_object = class_object._commcell_object

        if isinstance(class_object, Client):
            self._SCHEDULES = self._commcell_object._services.CLIENT_SCHEDULES % (
                class_object.client_id)
        elif isinstance(class_object, Agent):
            self._SCHEDULES = self._commcell_object._services.AGENT_SCHEDULES % (
                class_object._client_object.client_id, class_object.agent_id)
        elif isinstance(class_object, Backupset):
            self._SCHEDULES = self._commcell_object._services.BACKUPSET_SCHEDULES % (
                class_object._agent_object._client_object.client_id,
                class_object._agent_object.agent_id, class_object.backupset_id)
        elif isinstance(class_object, Subclient):
            self._SCHEDULES = self._commcell_object._services.SUBCLIENT_SCHEDULES % (
                class_object._backupset_object._agent_object._client_object.
                client_id,
                class_object._backupset_object._agent_object.agent_id,
                class_object._backupset_object.backupset_id,
                class_object.subclient_id)
        else:
            raise SDKException('Schedules', '101')

        self.schedules = self._get_schedules()
Пример #28
0
    def __init__(self, agent_object, backupset_name, backupset_id=None, instance_id=1):
        """Initialise the backupset object.

            Args:
                agent_object (object) - instance of the Agent class
                backupset_name (str) - name of the backupset
                backupset_id (str) - id of the backupset
                    default: None
                instance_id (str) - id of the instance associated with the backupset
                    default: 1, for File System iDA

            Returns:
                object - instance of the Backupset class
        """
        self._agent_object = agent_object
        self._backupset_name = str(backupset_name).lower()
        self._commcell_object = self._agent_object._commcell_object
        self._instance_id = instance_id

        if backupset_id:
            # Use the backupset id provided in the arguments
            self._backupset_id = str(backupset_id)
        else:
            # Get the id associated with this backupset
            self._backupset_id = self._get_backupset_id()

        if not self.backupset_id:
            raise SDKException('Backupset',
                               '102',
                               'No backupset exists with name: "{0}"'.format(backupset_name))

        self._BACKUPSET = self._commcell_object._services.BACKUPSET % (self.backupset_id)

        self.properties = self._get_backupset_properties()

        self.subclients = Subclients(self)
        self.schedules = Schedules(self).schedules
Пример #29
0
    def restore_out_of_place(self,
                             client,
                             destination_path,
                             paths,
                             overwrite=True,
                             restore_deleted_files=True,
                             restore_data_and_acl=True):
        """Restores the files/folders specified in the input paths list to the input client,
            at the specified destionation location.

            Args:
                client (str/object) - either the name of the client or instance of the Client
                destination_path (str) - full path of the location on client to restore to
                paths (list) - list of full paths of files/folders to restore
                overwrite (bool) - unconditional overwrite files during restore
                    default: True
                restore_deleted_files (bool) - restore files that have been deleted on media
                    default: True
                restore_data_and_acl (bool) - restore data and ACL files
                    default: True

            Returns:
                object - instance of the Job class for this restore job

            Raises:
                SDKException:
                    if client is not a string or Client instance
                    if destination_path is not a string
                    if paths is not a list
                    if response is empty
                    if response is not success
        """
        from client import Client

        if not ((isinstance(client, str) or isinstance(client, Client)) and
                isinstance(destination_path, str) and isinstance(paths, list)):
            raise SDKException('Subclient', '101')

        if isinstance(client, Client):
            client = client
        elif isinstance(client, str):
            client = Client(self._commcell_object, client)
        else:
            raise SDKException('Subclient', '105')

        for index, path in enumerate(paths):
            if int(self._backupset_object._agent_object.agent_id) == 33:
                path = path.strip('\\').strip('/')
                if path:
                    path = path.replace('/', '\\')
                else:
                    path = '\\'
            elif int(self._backupset_object._agent_object.agent_id) == 29:
                path = path.strip('\\').strip('/')
                if path:
                    path = path.replace('\\', '/')
                else:
                    path = '\\'
            paths[index] = path

        request_json = {
            "mode": 2,
            "serviceType": 1,
            "userInfo": {
                "userGuid": self._commcell_object._Commcell__user_guid
            },
            "advanced": {
                "restoreDataAndACL": restore_data_and_acl,
                "restoreDeletedFiles": restore_deleted_files,
                "unconditionalOverwrite": overwrite
            },
            "header": {
                "destination": {
                    "clientId": int(client.client_id),
                    "clientName": client.client_name,
                    "inPlace": False,
                    "destPath": [destination_path]
                },
                "filePaths": paths,
                "srcContent": {
                    "subclientId":
                    int(self.subclient_id),
                    "clientId":
                    int(self._backupset_object._agent_object._client_object.
                        client_id),
                    "instanceId":
                    int(self._backupset_object._instance_id),
                    "backupSetId":
                    int(self._backupset_object.backupset_id),
                    "appTypeId":
                    int(self._backupset_object._agent_object.agent_id)
                }
            }
        }

        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'POST', self._RESTORE, request_json)

        if flag:
            if response.json():
                if "jobId" in response.json():
                    print 'Restore job started for subclient: "{0}" with job id: "{1}"'.format(
                        self.subclient_name,
                        response.json()['jobId'])

                    time.sleep(1)
                    return Job(self._commcell_object, response.json()['jobId'])
                elif "errorList" in response.json():
                    error_code = response.json()['errorList'][0]['errorCode']
                    error_message = response.json(
                    )['errorList'][0]['errLogMessage']

                    print "Restore job failed with error code: %s" % (
                        error_code)
                    print "Error message: %s" % (error_message)
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)
Пример #30
0
    def browse_in_time(self,
                       path,
                       show_deleted_files=True,
                       restore_index=True,
                       from_date=None,
                       to_date=None):
        """Gets the content of the backup for this subclient
            at the path specified in the time range specified.

            Args:
                path (str) - folder path to get the contents of
                show_deleted_files (bool) - include deleted files in the content or not
                    default: True
                restore_index (bool) - restore index if it is not cached
                    default: True
                from_date (str) - date to get the contents after
                        format: dd/MM/YYYY
                    gets contents from 01/01/1970 if not specified
                    default: None
                to_date (str) - date to get the contents before
                        format: dd/MM/YYYY
                    gets contents till current day if not specified
                    default: None

            Returns:
                list - list of all folders or files with their full paths inside the input path
                dict - path alogn with the details like name, file/folder, size, modification time

            Raises:
                SDKException:
                    if from date value is incorrect
                    if to date value is incorrect
                    if to date is less than from date
                    if response is empty
                    if response is not success
        """
        if from_date and (from_date != '01/01/1970'
                          and from_date != '1/1/1970'):
            temp = from_date.split('/')
            if (len(temp) == 3 and 0 < int(temp[0]) < 32
                    and 0 < int(temp[1]) < 13 and int(temp[2]) > 1969
                    and (re.search(r'\d\d/\d\d/\d\d\d\d', from_date)
                         or re.search(r'\d/\d/\d\d\d\d', from_date))):
                from_date = int(
                    time.mktime(time.strptime(from_date, '%d/%m/%Y')))
            else:
                raise SDKException('Subclient', '106')
        else:
            from_date = 0

        if to_date and (to_date != '01/01/1970' and to_date != '1/1/1970'):
            temp = to_date.split('/')
            if (len(temp) == 3 and 0 < int(temp[0]) < 32
                    and 0 < int(temp[1]) < 13 and int(temp[2]) > 1969
                    and (re.search(r'\d\d/\d\d/\d\d\d\d', to_date)
                         or re.search(r'\d/\d/\d\d\d\d', to_date))):
                today = time.strftime('%d/%m/%Y')
                if today == to_date:
                    to_date = int(time.time())
                else:
                    to_date = int(
                        time.mktime(time.strptime(to_date, '%d/%m/%Y')))
            else:
                raise SDKException('Subclient', '106')
        else:
            to_date = int(time.time())

        if to_date < from_date:
            raise SDKException('Subclient', '107')

        if int(self._backupset_object._agent_object.agent_id) == 33:
            path = path.strip('\\').strip('/')
            if path:
                path = path.replace('/', '\\')
            else:
                path = '\\'
        elif int(self._backupset_object._agent_object.agent_id) == 29:
            path = path.strip('\\').strip('/')
            if path:
                path = path.replace('\\', '/')
            else:
                path = '\\'

        request_json = {
            "opType":
            0,
            "queries": [{
                "type": 0,
                "queryId": "dataQuery",
                "dataParam": {
                    "sortParam": {
                        "ascending": False,
                        "sortBy": [0]
                    }
                }
            }],
            "mode": {
                "mode": 2
            },
            "paths": [{
                "path": path
            }],
            "options": {
                "showDeletedFiles": show_deleted_files,
                "restoreIndex": restore_index
            },
            "entity": {
                "subclientId":
                int(self.subclient_id),
                "applicationId":
                int(self._backupset_object._agent_object.agent_id),
                "clientName":
                self._backupset_object._agent_object._client_object.
                client_name,
                "backupsetId":
                int(self._backupset_object.backupset_id),
                "instanceId":
                int(self._backupset_object._instance_id),
                "clientId":
                int(self._backupset_object._agent_object._client_object.
                    client_id)
            },
            "timeRange": {
                "fromTime": from_date,
                "toTime": to_date
            }
        }

        flag, response = self._commcell_object._cvpysdk_object.make_request(
            'POST', self._BROWSE, request_json)

        if flag:
            if response.json() and 'browseResponses' in response.json():
                if 'browseResult' in response.json()['browseResponses'][0]:
                    browse_result = response.json(
                    )['browseResponses'][0]['browseResult']

                    if 'dataResultSet' in browse_result:
                        result_set = browse_result['dataResultSet']
                        full_result = []
                        paths = []

                        for result in result_set:
                            name = str(result['displayName'])
                            path = str(result['path'])
                            mod_time = time.localtime(
                                result['modificationTime'])
                            mod_time = time.strftime('%d/%m/%Y %H:%M:%S',
                                                     mod_time)

                            if 'file' in result['flags']:
                                file_or_folder = 'File'
                            else:
                                file_or_folder = 'Folder'

                            # convert bits to bytes and then pass to convert_size
                            size = self._convert_size(
                                float(result['size']) / 8.0)

                            temp = {
                                path: [name, file_or_folder, size, mod_time]
                            }

                            paths.append(path)
                            full_result.append(temp)

                        return paths, full_result
                    else:
                        print 'No data found at the path specified.'
                elif 'messages' in response.json()['browseResponses'][0]:
                    message = response.json(
                    )['browseResponses'][0]['messages'][0]
                    error_code = message['errorCode']
                    error_message = message['errorMessage']

                    print "Failed to browse for subclient backup content with error code: %s" % (
                        error_code)
                    print "Error message: %s" % (error_message)
                else:
                    print 'No data found at the path specified.'
            else:
                raise SDKException('Response', '102')
        else:
            response_string = self._commcell_object._update_response_(
                response.text)
            raise SDKException('Response', '101', response_string)