Ejemplo n.º 1
0
class IsmGetReportInfo():

    module = AnsibleModule(argument_spec=dict(config=dict(required=True),
                                              hostname=dict(required=True)))

    def __init__(self):
        self.__present()

    def __present(self):
        try:
            self.common = IsmCommon(self.module)

            self.common.preProcess(self.module.params,
                                   usableEssential=True,
                                   NodeCheck=False)

            node_info = self.getNodeInfo()

            inventory_info = self.getInventoryInfo()

            status_info, alarm_info, node_ids = self.countNodeStatus(node_info)

            firmware_info = self.getUpdatableFirmwareInfo(node_ids)

            time_stamp = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')

            self.module.exit_json(changed=False,
                                  ism_node_count=len(
                                      node_info['IsmBody']['Nodes']),
                                  ism_node_info=node_info,
                                  ism_inventory_info=inventory_info,
                                  ism_firmware_info=firmware_info,
                                  ism_status_count=status_info,
                                  ism_alarm_status_count=alarm_info,
                                  time=time_stamp)

        except Exception as e:
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
        finally:
            # ISM logout
            self.common.ismLogout()

    """
    @Description Function to get inventory infomation
    @return      dict json_data
    """

    def getInventoryInfo(self):
        self.module.debug("***** getInventoryInfo Start *****")

        # Create query param
        dict_param = dict()
        dict_param['level'] = "All"
        dict_param['target'] = "Firmware"

        param = self.common.getQueryParam(dict_param)

        # Get REST URL
        rest_url = self.common.getRestUrl(self.common.NODES_REST_URL,
                                          "inventory" + param)

        # REST API execution
        json_data = self.common.execRest(rest_url, self.common.GET,
                                         self.common.RESPONSE_CODE_200)

        # Filter not supported values on Essential mode
        self.common.filterEssentialModeForInventoryArray(json_data)

        self.module.debug("***** getInventoryInfo End *****")

        return json_data

    """
    @Description Function to get node infomation
    @return      dict json_data
    """

    def getNodeInfo(self):
        self.module.debug("***** getNodeInfo Start *****")

        # Get REST URL
        rest_url = self.common.getRestUrl(self.common.NODES_REST_URL)

        # REST API execution
        json_data = self.common.execRest(rest_url, self.common.GET,
                                         self.common.RESPONSE_CODE_200)

        # Filter not supported values on Essential mode
        self.common.filterEssentialModeForNodeListArray(json_data)

        self.module.debug("***** getNodeInfo End *****")

        return json_data

    """
    @Description Function to count node status and correct node id
    @return      dict status_info, dict alarm_info, array node_ids
    """

    def countNodeStatus(self, node_info):
        self.module.debug("***** countNodeStatus Start *****")

        status_info = {
            'Error': 0,
            'Warning': 0,
            'Unknown': 0,
            'Updating': 0,
            'Normal': 0
        }
        alarm_info = {'Error': 0, 'Warning': 0, 'Info': 0, 'Normal': 0}

        node_ids = []

        for node in node_info['IsmBody']['Nodes']:
            # status
            if node['Status'] in status_info:
                status_info[node['Status']] += 1
            # alarm
            if node['AlarmStatus'] in alarm_info:
                alarm_info[node['AlarmStatus']] += 1

            node_ids.append("nodeid=" + str(node['NodeId']))

        self.module.debug("***** countNodeStatus End *****")

        return status_info, alarm_info, node_ids

    """
    @Description Function to get updatable firmware infomation
    @param       array node id list
    @return      dict json_data
    """

    def getUpdatableFirmwareInfo(self, node_ids):
        self.module.debug("***** getUpdatableFirmwareInfo Start *****")

        rest_url = None
        node_exist = None

        if len(node_ids) > 0:
            # nodes exist
            node_exist = True
            rest_url = self.common.getRestUrl(self.common.FIRMWARE_URL +
                                              "list?" + "&".join(node_ids))
        else:
            # node not exist
            node_exist = False
            rest_url = self.common.getRestUrl(self.common.FIRMWARE_URL +
                                              "list")

        # REST API execution
        json_data = self.common.execRest(rest_url, self.common.GET,
                                         self.common.RESPONSE_CODE_200)

        if not node_exist:
            # clear firmwarelist
            json_data["IsmBody"]["FirmwareList"] = []

        self.module.debug("***** getUpdatableFirmwareInfo End *****")

        return json_data
Ejemplo n.º 2
0
class IsmCopyProfile():

    CRYPTPASS = "******"
    # Receiving args
    module = AnsibleModule(argument_spec=dict(
        config=dict(type="str", required=True),
        ism_source_profile_name=dict(type="str", required=True),
        ism_profile_name=dict(typer="str", required=True),
        ism_profile_data=dict(type="dict", required=False)))

    def __init__(self):
        self.__present()

    def __present(self):
        # Instance of common class
        self.common = IsmCommon(self.module)

        # check for blank("") and None
        self.common.required_param_check(self.module.params["config"],
                                         "config")
        self.common.required_param_check(
            self.module.params["ism_source_profile_name"],
            "ism_source_profile_name")
        self.common.required_param_check(
            self.module.params["ism_profile_name"], "ism_profile_name")

        try:

            # Pre-process
            self.common.preProcess(self.module.params,
                                   NodeCheck=False,
                                   noHost=True)
            self.module.params['config'] = self.common.covert_unicode(
                self.module.params['config'])
            self.module.params[
                'ism_source_profile_name'] = self.common.covert_unicode(
                    self.module.params['ism_source_profile_name'])
            self.module.params[
                'ism_profile_name'] = self.common.covert_unicode(
                    self.module.params['ism_profile_name'])

            if self.module.params['ism_profile_data']:
                self.common.covertUnicodeHashDict(
                    self.module.params['ism_profile_data'])

            # Check profile
            check_profile_result = \
                self.__checkProfile(self.module.params['ism_source_profile_name'],
                                    self.module.params['ism_profile_name'])

            # Get profile
            get_profile_result = self.__getProfile(check_profile_result)

            # Copy profile
            self.__copyProfile(get_profile_result)

            self.module.exit_json(changed=True, ism_copy_profile="Success")

        except Exception as e:
            self.module.log(str(e))
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
        finally:
            self.common.ismLogout()

    def __checkProfile(self, source, dest):
        profile_id = None

        # source and dest profile name are same
        if source == dest:
            msg = "ism_source_profile_name and ism_profile_name have duplicate values: {0}".\
                  format(source)
            self.module.log(msg)
            self.module.fail_json(msg=msg)

        # Get REST URL
        rest_url = self.common.getRestUrl(self.common.PROFILE_LIST_REST_URL)

        # REST API execution
        json_data = self.common.execRest(rest_url, self.common.GET,
                                         self.common.RESPONSE_CODE_200)

        for profile in json_data['IsmBody']['ProfileList']:

            if profile['ProfileName'] == dest:
                # already copied
                self.module.exit_json(changed=False,
                                      ism_copy_profile="Success")

            elif profile['ProfileName'] == source:
                profile_id = profile['ProfileId']

        # Profile not found
        if not profile_id:
            msg = "profile not found: {0}".format(source)
            self.module.log(msg)
            self.module.fail_json(msg=msg)

        return profile_id

    def __getProfile(self, profile_id):
        # Get REST URL
        rest_url = self.common.getRestUrl(
            self.common.PROFILE_LIST_REST_URL,
            "/" + profile_id + "?passwordkey=" + self.CRYPTPASS)
        # REST API execution
        json_data = self.common.execRest(rest_url, self.common.GET,
                                         self.common.RESPONSE_CODE_200)

        source_info = json_data['IsmBody']

        # delete create profile REST-API not supported keys
        not_supported_keys = [
            'ProfileId', 'PathName', 'AssignedNodeId', 'Status',
            'InternalStatus', 'VerifyStatus', 'HistoryList', 'VerifyList',
            'TimeStampInfo'
        ]

        for not_supported_key in not_supported_keys:
            if not_supported_key in source_info:
                del source_info[not_supported_key]

        # add information
        if self.module.params['ism_profile_data']:
            dict_data = source_info['ProfileData']
            dict_set = dict(self.module.params['ism_profile_data'])
            source_info['ProfileData'] = self.common.mergeDicts(
                dict_data, dict_set)

        source_info['ProfileName'] = self.module.params['ism_profile_name']
        source_info['OneTimePasswordKey'] = self.CRYPTPASS

        all_data = {"IsmBody": source_info}
        return all_data

    def __copyProfile(self, body):
        # Get REST URL
        rest_url = self.common.getRestUrl(self.common.PROFILE_LIST_REST_URL)

        # REST API execution
        param_str = "\'" + self.common.singleEscape(json.dumps(body)) + "\'"
        self.common.execRest(rest_url, self.common.POST,
                             self.common.RESPONSE_CODE_201, param_str)