예제 #1
0
    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()
예제 #2
0
    def __present(self):
        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["hostname"],
                                         "hostname")
        self.common.required_param_check(self.module.params["dest_dir"],
                                         "dest_dir")

        # check pexpect installed and its version
        if not HAS_PEXPECT:
            self.module.fail_json(msg=self.PEXPECT_VERSION_MSG)
        if not self.common.checkLibraryVersion(pexpect.__version__, "4.7.0"):
            self.module.fail_json(msg=self.PEXPECT_VERSION_MSG)

        try:
            self.common.preProcess(
                self.module.params,
                usableEssential=True,
                NodeCheck=False,
                paramListNotBlank=["timeout"
                                   ],  # don't convert None to blank("")
                doIsmLogin=False)
            # convert to unicode
            self.module.params['config'] = self.common.covert_unicode(
                self.module.params['config'])
            self.module.params['hostname'] = self.common.covert_unicode(
                self.module.params['hostname'])
            self.module.params['dest_dir'] = self.common.covert_unicode(
                self.module.params['dest_dir'])

            self.dest_dir = self.module.params["dest_dir"]

            self.timeout = self.module.params["timeout"]
            if not (self.timeout) or self.timeout <= 0:  # less than or equal 0
                self.timeout = None  # no timeout

            config_json = self.common.ism_config_json

            self.ism_ip = config_json["ip"]
            self.ism_user_name = config_json["credentials"]["userName"]
            self.ism_password = config_json["credentials"]["password"]

            self.ism_password = self.common.decryptIsmPassword(
                self.ism_password, self.ism_ip)

            filename = self.__backup()
            dest_file = os.path.join(self.dest_dir, filename)

            self.__download(dest_file, filename)

            self.module.exit_json(changed=True, ism_backup_file=dest_file)

        except Exception as e:
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
예제 #3
0
    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()
예제 #4
0
    def __present(self):
        try:
            self.module.log("argument_spec with config=" +
                            str(self.module.params['config']) + " hostname=" +
                            str(self.module.params['hostname']))

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

            # Pre-process
            common.preProcess(self.module.params)

            # License Check
            common.licenseCheck(license_check=False)

            # Get power status execution
            result = self.getPowerStatus(common)

            # ISM logout
            common.ismLogout()

            # Return json
            changed_result = False
            self.module.log("ism_get_power_status successful completion")
            self.module.exit_json(changed=changed_result,
                                  ism_get_power_status=result)

        except Exception as e:
            self.module.log(str(e))
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
    def __present(self):
        try:
            self.module.log("argument_spec with config=" +
                            str(self.module.params['config']) + " hostname=" +
                            str(self.module.params['hostname']) + " filter=" +
                            str(self.module.params['filter']))

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

            # Pre-process
            common.preProcess(self.module.params, NodeCheck=False)

            # License Check
            common.licenseCheck(usable_essential=True)

            # Get Download Firmware Info execution
            result = self.getDownloadFirmwareInfo(common)

            # ISM logout
            common.ismLogout()

            # Return json
            changed_result = False
            self.module.log(
                "ism_get_download_firmware_list successful completion")
            self.module.exit_json(changed=changed_result,
                                  ism_get_download_firmware_list=result)

        except Exception as e:
            self.module.log(str(e))
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
 def __present(self):
     try :
         self.module.log("argument_spec with config=" + str(self.module.params['config']) + " hostname=" + str(self.module.params['hostname']))
         
         # Instance of common class
         common = IsmCommon(self.module)
         
         # Pre-process
         common.preProcess(self.module.params)
         
         # License Check
         common.licenseCheck(license_check = False)
         
         # Refresh node info execution
         result = self.execRefreshNodeInfo(common)
         
         # ISM logout
         common.ismLogout()
         
         # return json
         changed_result = False
         args = dict(
             ism_refresh_node_info = result
         )
         
         self.module.log("ism_refresh_node_info successful completion")
         self.module.exit_json(changed=changed_result, **args)
         
     except Exception as e:
         self.module.log(str(e))
         self.module.log(traceback.format_exc())
         self.module.fail_json(msg=str(e))
    def __present(self):
        try:
            self.module.log("argument_spec with config=" + str(self.module.params['config']) + " hostname=" + str(self.module.params['hostname']) + \
                            " level=" + str(self.module.params['level']) + " target=" + str(self.module.params['target']))

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

            # Pre-process
            common.preProcess(self.module.params)

            # License Check
            common.licenseCheck(usable_essential=True)

            # Get inventory info execution
            result = self.getInventoryInfo(common)

            # ISM logout
            common.ismLogout()

            # Return json
            changed_result = False
            self.module.log("ism_get_inventory_info successful completion")
            self.module.exit_json(changed=changed_result,
                                  ism_get_inventory_info=result)

        except Exception as e:
            self.module.log(str(e))
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
    def __present(self):
        try:
            self.module.log("argument_spec with config=" +
                            str(self.module.params['config']) + " hostname=" +
                            str(self.module.params['hostname']) +
                            " download_list=" +
                            str(self.module.params['download_list']))

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

            # Parameter chack hash list
            required_keys = ["firmware_name", "firmware_version"]
            common.covert_unicode_hash_list(
                self.module.params['download_list'], required_keys)

            # Pre-process
            common.preProcess(self.module.params, NodeCheck=False)

            # License Check
            common.licenseCheck(usable_essential=True)

            # Get download firmware execution
            downloaded_list = self.DownloadedFirmwareList(common)

            # Get check firmware execution
            target_list = self.CheckFirmwareList(common, downloaded_list)

            if len(target_list) == 0:
                task_result = "Success"
                changed_result = False
            else:
                # Download Firmware
                task_result = self.DownloadFirmware(common, target_list)
                changed_result = True

            # ISM logout
            common.ismLogout()

            # Return json
            self.module.log("ism_download_firmware successful completion")
            self.module.exit_json(changed=changed_result,
                                  ism_download_firmware=task_result)

        except Exception as e:
            self.module.log(str(e))
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
예제 #9
0
 def __present(self):
     try :
         self.module.log("argument_spec with config=" + str(self.module.params['config']) + " hostname=" + str(self.module.params['hostname']) + \
                         " status=" + str(self.module.params['status']))
         
         # Instance of common class
         common = IsmCommon(self.module)
         
         # Pre-process
         common.preProcess(self.module.params)
         
         # Get profile info execution
         result = self.getProfileInfo(common)
         
         # ISM logout
         common.ismLogout()
         
         # Return json
         changed_result = False
         self.module.log("ism_get_profile_info successful completion")
         self.module.exit_json(changed=changed_result, ism_get_profile_info=result)
         
     except Exception as e:
         self.module.log(str(e))
         self.module.log(traceback.format_exc())
         self.module.fail_json(msg=str(e))
예제 #10
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
예제 #11
0
    def __present(self):
        try:
            self.module.log("argument_spec with config=" +
                            str(self.module.params['config']) + " hostname=" +
                            str(self.module.params['hostname']) +
                            " firmware_type=" +
                            str(self.module.params['firmware_type']))

            # instance of common class
            common = IsmCommon(self.module)

            # convert parameters to unicode string
            self.module.params['config'] = common.covert_unicode(
                self.module.params['config'])
            self.module.params['hostname'] = common.covert_unicode(
                self.module.params['hostname'])
            self.module.params['firmware_type'] = common.covert_unicode(
                self.module.params['firmware_type'])

            # config file open
            try:
                config_path = path.abspath(self.module.params['config'])
                f = open(config_path)
            except Exception as e:
                self.module.log("file open error: " + str(config_path) +
                                ", e=" + str(e))
                self.module.fail_json(msg="file open error: " +
                                      str(config_path))

            # config loads
            try:
                json_data = json.load(f)
            except Exception as e:
                f.close()
                self.module.log("Not json format data: " + str(config_path) +
                                ", e=" + str(e))
                self.module.fail_json(msg="It is not json format data: " +
                                      str(config_path))

            f.close()

            # ip transformation
            match = re.match(r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$',
                             self.module.params['hostname'])
            if match == None:
                try:
                    self.module.params['hostname'] = socket.gethostbyname(
                        self.module.params['hostname'])
                    self.module.debug(
                        "Host name is converted to IP address: " +
                        str(self.module.params['hostname']))
                except Exception as e:
                    self.module.log("ip transformation error: IP address=" +
                                    str(self.module.params['hostname']) +
                                    ", e=" + str(e))
                    self.module.fail_json(
                        msg="Host name could not be converted to IP address: "
                        + str(self.module.params['hostname']))

            # ISM login
            common.ismLogin(json_data)

            # License Check
            common.licenseCheck(license_check=False)

            # get node OS
            common.getNodeOS()

            # get node hard
            if common.getNodeId() == "":
                common.getNodeHard()

            # node check
            if common.getNodeId() == "":
                self.module.log("The target host name was not found.: " +
                                str(self.module.params['hostname']))
                self.module.fail_json(
                    msg="The target host name was not found.: " +
                    str(self.module.params['hostname']))
            else:
                self.module.debug("node_id: " + str(common.getNodeId()))

            # firmware list execution
            result = self.execFirmwareList(common)

            # ISM logout
            common.ismLogout()

            # return json
            changed_result = False
            self.module.log("ism_firmware_list successful completion")
            self.module.exit_json(changed=changed_result,
                                  ism_firmware_list=result)

        except Exception as e:
            self.module.log(str(e))
            self.module.fail_json(msg=str(e))
    def __present(self):
        try:
            self.module.log("argument_spec with config=" +
                            str(self.module.params['config']) + " hostname=" +
                            str(self.module.params['hostname']) + " mode=" +
                            str(self.module.params['mode']))

            # instance of common class
            common = IsmCommon(self.module)

            # convert parameters to unicode string
            self.module.params['config'] = common.covert_unicode(
                self.module.params['config'])
            self.module.params['hostname'] = common.covert_unicode(
                self.module.params['hostname'])
            self.module.params['mode'] = common.covert_unicode(
                self.module.params['mode'])

            # config file open
            try:
                config_path = path.abspath(self.module.params['config'])
                f = open(config_path)
            except Exception as e:
                self.module.log("file open error: " + str(config_path) +
                                ", e=" + str(e))
                self.module.fail_json(msg="file open error: " +
                                      str(config_path))

            # config loads
            try:
                json_data = json.load(f)
            except Exception as e:
                f.close()
                self.module.log("Not json format data: " + str(config_path) +
                                ", e=" + str(e))
                self.module.fail_json(msg="It is not json format data: " +
                                      str(config_path))

            f.close()

            # ip transformation
            match = re.match(r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$',
                             self.module.params['hostname'])
            if match == None:
                try:
                    self.module.params['hostname'] = socket.gethostbyname(
                        self.module.params['hostname'])
                    self.module.debug(
                        "Host name is converted to IP address: " +
                        str(self.module.params['hostname']))
                except Exception as e:
                    self.module.log("ip transformation error: IP address=" +
                                    str(self.module.params['hostname']) +
                                    ", e=" + str(e))
                    self.module.fail_json(
                        msg="Host name could not be converted to IP address: "
                        + str(self.module.params['hostname']))

            # ISM login
            common.ismLogin(json_data)

            # get node OS
            common.getNodeOS()

            # get node hard
            if common.getNodeId() == "":
                common.getNodeHard()

            # node check
            if common.getNodeId() == "":
                self.module.log("The target host name was not found.: " +
                                str(self.module.params['hostname']))
                self.module.fail_json(
                    msg="The target host name was not found.: " +
                    str(self.module.params['hostname']))
            else:
                self.module.debug("node_id: " + common.getNodeId())

            mode = ""
            if self.module.params['mode'] == "On":
                mode = "Maintenance"
            elif self.module.params['mode'] == "Off":
                mode = "Normal"
            else:
                self.module.log(
                    "A value other than On or Off is specified for mode parameter: "
                    + str(self.module.params['mode']))
                self.module.fail_json(
                    msg=
                    "A value other than On or Off is specified for mode parameter: "
                    + str(self.module.params['mode']))

            # check maintenance mode
            chk = self.checkMaintenanceMode(common, mode)

            # set maintenance mode
            if chk is True:
                result = self.maintenanceModeSetting(common, mode)
                changed_result = True
            else:
                result = "Success"
                changed_result = False

            # ISM logout
            common.ismLogout()

            # return json
            args = dict(ism_maintenance_mode=result)
            self.module.log("ism_maintenance_mode successful completion")
            self.module.exit_json(changed=changed_result, **args)

        except Exception as e:
            self.module.log(str(e))
            self.module.fail_json(msg=str(e))
예제 #13
0
    def __present(self):
        try:
            self.module.log("argument_spec with config=" +
                            str(self.module.params['config']) + " hostname=" +
                            str(self.module.params['hostname']) +
                            " firmware_update_list=" +
                            str(self.module.params['firmware_update_list']))

            # instance of common class
            common = IsmCommon(self.module)

            # param check
            common.param_check(self.module.params['firmware_update_list'])

            # convert parameters to unicode string
            self.module.params['config'] = common.covert_unicode(
                self.module.params['config'])
            self.module.params['hostname'] = common.covert_unicode(
                self.module.params['hostname'])

            # config file open
            try:
                config_path = path.abspath(self.module.params['config'])
                f = open(config_path)
            except Exception as e:
                self.module.log("file open error: " + str(config_path) +
                                ", e=" + str(e))
                self.module.fail_json(msg="file open error: " +
                                      str(config_path))

            # config loads
            try:
                json_data = json.load(f)
            except Exception as e:
                f.close()
                self.module.log("Not json format data: " + str(config_path) +
                                ", e=" + str(e))
                self.module.fail_json(msg="It is not json format data: " +
                                      str(config_path))

            f.close()

            # ip transformation
            match = re.match(r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$',
                             self.module.params['hostname'])
            if match == None:
                try:
                    self.module.params['hostname'] = socket.gethostbyname(
                        self.module.params['hostname'])
                    self.module.debug(
                        "Host name is converted to IP address: " +
                        str(self.module.params['hostname']))
                except Exception as e:
                    self.module.log("ip transformation error: IP address=" +
                                    str(self.module.params['hostname']) +
                                    ", e=" + str(e))
                    self.module.fail_json(
                        msg="Host name could not be converted to IP address: "
                        + str(self.module.params['hostname']))

            # ISM login
            common.ismLogin(json_data)

            # License Check
            common.licenseCheck(usable_essential=True)

            # get node OS
            common.getNodeOS()

            # get node hard
            if common.getNodeId() == "":
                common.getNodeHard()

            # node check
            if common.getNodeId() == "":
                self.module.log("The target host name was not found.: " +
                                str(self.module.params['hostname']))
                self.module.fail_json(
                    msg="The target host name was not found.: " +
                    str(self.module.params['hostname']))
            else:
                self.module.debug("node_id: " + common.getNodeId())

            # Check type and model of node are supporetd on Essential mode
            common.checkNodeSupportedOnEssential()

            # firmware update execution
            firmware_update_list = []
            for update_param_hash in self.module.params[
                    'firmware_update_list']:

                if "firmware_version" in update_param_hash:
                    self.module.debug("***** firmwareversion specified *****")

                    if update_param_hash[
                            'firmware_version'] == "" or update_param_hash[
                                'firmware_version'] == None:
                        # latest firmware version
                        latest_firmware_version = self.getFirmwareVersion(
                            common, update_param_hash['firmware_name'],
                            update_param_hash['operation_mode'])
                        update_param_hash[
                            'firmware_version'] = latest_firmware_version

                    # check firmware version
                    chk = self.checkFirmwareVersion(
                        common, update_param_hash['firmware_name'],
                        update_param_hash['firmware_version'])

                else:
                    self.module.debug(
                        "***** firmwareversion not specified *****")

                    # latest firmware version
                    latest_firmware_version = self.getFirmwareVersion(
                        common, update_param_hash['firmware_name'],
                        update_param_hash['operation_mode'])
                    update_param_hash[
                        'firmware_version'] = latest_firmware_version

                    # check firmware version
                    chk = self.checkFirmwareVersion(
                        common, update_param_hash['firmware_name'],
                        update_param_hash['firmware_version'])

                if chk is True:
                    firmware_update_list.append(update_param_hash)

            # firmware update start execution
            if len(firmware_update_list) == 0:
                result = "Success"
                changed_result = False
            else:
                result = self.firmwareUpdate(common, firmware_update_list)
                changed_result = True

            # ISM logout
            common.ismLogout()

            # return json
            args = dict(ism_firmware_update=result)
            self.module.log("ism_firmware_update successful completion")
            self.module.exit_json(changed=changed_result, **args)
        except Exception as e:
            self.module.log(str(e))
            self.module.fail_json(msg=str(e))
예제 #14
0
 def __present(self):
     try :
         self.module.log("argument_spec with config=" + str(self.module.params['config']) + " hostname=" + str(self.module.params['hostname']) + " ism_profile_name=" + str(self.module.params['ism_profile_name']) + " assign_mode=" + str(self.module.params['assign_mode']) + " advanced_kind=" + str(self.module.params['advanced_kind']) + " assign_range=" + str(self.module.params['assign_range']))
         
         # instance of common class
         common = IsmCommon(self.module)
         
         # convert parameters to unicode string
         self.module.params['config'] = common.covert_unicode(self.module.params['config'])
         self.module.params['hostname'] = common.covert_unicode(self.module.params['hostname'])
         self.module.params['ism_profile_name'] = common.covert_unicode(self.module.params['ism_profile_name'])
         self.module.params['assign_mode'] = common.covert_unicode(self.module.params['assign_mode'])
         self.module.params['advanced_kind'] = common.covert_unicode(self.module.params['advanced_kind'])
         if self.module.params['assign_range'] is not None:
             for key in self.module.params['assign_range']:
                 key = common.covert_unicode(key)
                 
         # config file open
         try :
             config_path = path.abspath(self.module.params['config'])
             f = open(config_path)
         except Exception as e:
             self.module.log("file open error: " + str(config_path) + ", e=" + str(e))
             self.module.fail_json(msg="file open error: " + str(config_path))
         
         # config loads
         try :
             json_data = json.load(f)
         except Exception as e:
             f.close()
             self.module.log("Not json format data: " + str(config_path) + ", e=" + str(e))
             self.module.fail_json(msg="It is not json format data: " + str(config_path))
             
         f.close()
         
         # ip transformation
         match = re.match(r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$', self.module.params['hostname'])
         if match is None:
             try :
                 self.module.params['hostname'] = socket.gethostbyname(self.module.params['hostname'])
                 self.module.debug("Host name is converted to IP address: " + str(self.module.params['hostname']))
             except Exception as e:
                 self.module.log("ip transformation error: IP address=" + str(self.module.params['hostname']) + ", e=" + str(e))
                 self.module.fail_json(msg="Host name could not be converted to IP address: " + str(self.module.params['hostname']))
                 
         # ISM login
         common.ismLogin(json_data)
         
         # License Check
         common.licenseCheck()
         
         # get node OS
         common.getNodeOS()
         
         # get node hard
         if common.getNodeId() == "":
             common.getNodeHard()
             
         # node check
         if common.getNodeId() == "":
             self.module.log("The target host name was not found.: " + str(self.module.params['hostname']))
             self.module.fail_json(msg="The target host name was not found.: " + str(self.module.params['hostname']))
         else:
             self.module.debug("node_id: " + common.getNodeId())
             
         # get profileId
         profile_id = self.getProfileId(common)
         
         if profile_id == "":
             self.module.log("Profile name matching the profile name of the parameter could not be found. profile name:" + self.module.params['ism_profile_name'])
             self.module.fail_json(msg="Profile name matching the profile name of the parameter could not be found. profile name:" + self.module.params['ism_profile_name'])
             
         if self.module.params['assign_mode'] == "Advanced" and self.module.params['advanced_kind'] == "ForcedAssign":
             # profile assignment execution
             result = self.profileAssignment(common, profile_id)
             changed_result = True
         else:
             # check profile assignment
             chk = self.checkProfileAssignment(common, profile_id)
             
             # profile assignment execution
             if chk is True:
                 result = self.profileAssignment(common, profile_id)
                 changed_result = True
             else:
                 result = "Success"
                 changed_result = False
             
         # ISM logout
         common.ismLogout()
         
         # return json
         args = dict(
             ism_profile_assignment = result
         )
         self.module.log("ism_profile_assignment successful completion")
         self.module.exit_json(changed=changed_result, **args)
         
     except Exception as e:
         self.module.log(str(e))
         self.module.fail_json(msg=str(e))
예제 #15
0
class IsmBackup():
    PEXPECT_VERSION = "4.7.0"
    PEXPECT_VERSION_MSG = 'The pexpect >= 4.7.0 python module is required'
    PXSSH_DEBUG = False
    PXSSH_CONNECT_TIMEOUT = 60
    PXSSH_MSG_HEADER = "SSH connection error: {0}"
    PXSSH_OPTION = {
        "ConnectTimeout": PXSSH_CONNECT_TIMEOUT,
        "StrictHostKeyChecking": "no",
        "UserKnownHostsFile": "/dev/null"
    }

    PORT_SSH = 22

    FTP_CONNECT_TIMEOUT = 60
    FTP_MSG_CONNECT_HEADER = "FTP connection error: {0}"
    FTP_MSG_OPERATION_HEADER = "FTP operation error: {0}"

    RE_CONNECT_ERROR = re.compile(r'^could not set shell prompt')
    RE_START_BACKUP = re.compile(r'^Start backup process\? \[y/n\]: ',
                                 re.MULTILINE)
    RE_ERROR = re.compile(r'^(ERROR:\d+:.+)$', re.MULTILINE)
    RE_OUTPUT_FILE = re.compile(r'^Output file: (ism.+\.gz)', re.MULTILINE)

    FTP_DIR = "/Administrator/ftp/"

    module = AnsibleModule(argument_spec=dict(
        config=dict(type="str", required=True),
        hostname=dict(type="str", required=True),
        dest_dir=dict(type="str", required=True),
        timeout=dict(type="int", default=0, required=False)))

    def __init__(self):
        self.__present()

    def __present(self):
        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["hostname"],
                                         "hostname")
        self.common.required_param_check(self.module.params["dest_dir"],
                                         "dest_dir")

        # check pexpect installed and its version
        if not HAS_PEXPECT:
            self.module.fail_json(msg=self.PEXPECT_VERSION_MSG)
        if not self.common.checkLibraryVersion(pexpect.__version__, "4.7.0"):
            self.module.fail_json(msg=self.PEXPECT_VERSION_MSG)

        try:
            self.common.preProcess(
                self.module.params,
                usableEssential=True,
                NodeCheck=False,
                paramListNotBlank=["timeout"
                                   ],  # don't convert None to blank("")
                doIsmLogin=False)
            # convert to unicode
            self.module.params['config'] = self.common.covert_unicode(
                self.module.params['config'])
            self.module.params['hostname'] = self.common.covert_unicode(
                self.module.params['hostname'])
            self.module.params['dest_dir'] = self.common.covert_unicode(
                self.module.params['dest_dir'])

            self.dest_dir = self.module.params["dest_dir"]

            self.timeout = self.module.params["timeout"]
            if not (self.timeout) or self.timeout <= 0:  # less than or equal 0
                self.timeout = None  # no timeout

            config_json = self.common.ism_config_json

            self.ism_ip = config_json["ip"]
            self.ism_user_name = config_json["credentials"]["userName"]
            self.ism_password = config_json["credentials"]["password"]

            self.ism_password = self.common.decryptIsmPassword(
                self.ism_password, self.ism_ip)

            filename = self.__backup()
            dest_file = os.path.join(self.dest_dir, filename)

            self.__download(dest_file, filename)

            self.module.exit_json(changed=True, ism_backup_file=dest_file)

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

    def __backup(self):
        ssh = None

        try:
            ssh = pxssh.pxssh(options=self.PXSSH_OPTION)

            if self.PXSSH_DEBUG:
                # pxssh stdout for debug
                ssh.logfile = sys.stdout

            try:
                ssh.login(self.ism_ip,
                          username=self.ism_user_name,
                          password=self.ism_password,
                          login_timeout=self.PXSSH_CONNECT_TIMEOUT,
                          port=self.PORT_SSH)
            except pexpect.ExceptionPexpect as e:
                msg = str(e)
                if self.RE_CONNECT_ERROR.match(msg):
                    # connection error
                    msg = self.PXSSH_MSG_HEADER.format(
                        "Failed to connect host")
                else:
                    msg = self.PXSSH_MSG_HEADER.format(msg)
                self.module.log(msg)
                self.module.log(traceback.format_exc())
                self.module.fail_json(msg=msg)

            ssh.sendline("ismadm system backup")

            # waiting backup size estimation
            index = ssh.expect(
                [self.RE_START_BACKUP, self.RE_ERROR, ssh.PROMPT],
                timeout=self.timeout)

            if index == 1:
                # error message
                msg = ssh.match.group(1).rstrip()
                self.module.log(msg)
                self.module.fail_json(msg=msg)
            elif index == 2:
                # not ISM server
                msg = "backup failed: not ISM server"
                self.module.log(msg)
                self.module.log("output={0}".format(ssh.before))
                self.module.fail_json(msg=msg)

            # start backup
            ssh.sendline("y")

            # waiting backup complete
            ssh.expect(ssh.PROMPT, timeout=self.timeout)

            output = ssh.before

            match = self.RE_ERROR.search(output)
            if match:
                # error message
                msg = match.group(1).rstrip()
                self.module.log(msg)
                self.module.fail_json(msg=msg)

            match = self.RE_OUTPUT_FILE.search(output)
            if not match:
                # Output file not found
                msg = "missing backup file info"
                self.module.log(msg)
                self.module.log("output={0}".format(output))
                self.module.fail_json(msg=msg)

            filename = match.group(1)

            return filename

        except pexpect.TIMEOUT:
            msg = "waiting for backup timeout: {0}s".format(self.timeout)
            self.module.log(msg)
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=msg)
        finally:
            # close
            if ssh:
                try:
                    ssh.close()
                except Exception:
                    # ignore error
                    self.module.log(traceback.format_exc())

    def __download(self, dest_file, ftp_file):
        ftp = None
        file_deleted = False
        try:
            try:
                ftp = FTP(self.ism_ip, self.ism_user_name, self.ism_password,
                          self.FTP_CONNECT_TIMEOUT)
            except Exception as e:
                msg = self.FTP_MSG_CONNECT_HEADER.format(e)
                self.module.log(msg)
                self.module.log(traceback.format_exc())
                self.module.fail_json(msg=msg)

            with open(dest_file, 'wb') as f:
                try:
                    ftp.retrbinary('RETR ' + self.FTP_DIR + ftp_file, f.write)
                    ftp.delete(self.FTP_DIR + ftp_file)
                    file_deleted = True
                except Exception as e:
                    msg = self.FTP_MSG_OPERATION_HEADER.format(e)
                    self.module.log(msg)
                    self.module.log(traceback.format_exc())
                    self.module.fail_json(msg=msg)

        except Exception as e:
            self.module.log(traceback.format_exc())
            self.module.fail_json(msg=str(e))
        finally:
            # FTP logout
            if ftp:
                try:
                    if not file_deleted:
                        # delete file
                        ftp.delete(self.FTP_DIR + ftp_file)
                    ftp.quit()
                except Exception:
                    # ignore error
                    self.module.log(traceback.format_exc())
예제 #16
0
 def __present(self):
     try :
         self.module.log("argument_spec with config=" + str(self.module.params['config']) + " hostname=" + str(self.module.params['hostname']))
         
         # instance of common class
         common = IsmCommon(self.module)
         
         # convert parameters to unicode string
         self.module.params['config'] = common.covert_unicode(self.module.params['config'])
         self.module.params['hostname'] = common.covert_unicode(self.module.params['hostname'])
         
         # config file open
         try :
             config_path = path.abspath(self.module.params['config'])
             f = open(config_path)
         except Exception as e:
             self.module.log("file open error: " + str(config_path) + ", e=" + str(e))
             self.module.fail_json(msg="file open error: " + str(config_path))
         
         # config loads
         try :
             json_data = json.load(f)
         except Exception as e:
             f.close()
             self.module.log("Not json format data: " + str(config_path) + ", e=" + str(e))
             self.module.fail_json(msg="It is not json format data: " + str(config_path))
             
         f.close()
         
         # ip transformation
         match = re.match(r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$', self.module.params['hostname'])
         if match is None:
             try :
                 self.module.params['hostname'] = socket.gethostbyname(self.module.params['hostname'])
                 self.module.debug("Host name is converted to IP address: " + str(self.module.params['hostname']))
             except Exception as e:
                 self.module.log("ip transformation error: IP address=" + str(self.module.params['hostname']) + ", e=" + str(e))
                 self.module.fail_json(msg="Host name could not be converted to IP address: " + str(self.module.params['hostname']))
                 
         # ISM login
         common.ismLogin(json_data)
         
          # License Check
         common.licenseCheck(usable_essential = True)
         
         # get node OS
         common.getNodeOS()
         
         # get node hard
         if common.getNodeId() == "":
             common.getNodeHard()
             
         # node check
         if common.getNodeId() == "":
             self.module.log("The target host name was not found.: " + str(self.module.params['hostname']))
             self.module.fail_json(msg="The target host name was not found.: " + str(self.module.params['hostname']))
         else:
             self.module.debug("node_id: " + common.getNodeId())
         
         # Check type and model of node are supporetd on Essential mode
         common.checkNodeSupportedOnEssential()
             
         # check powercontrol
         chk = self.checkPowerControl(common)
         
         # power on execution
         if chk is True:
             result = self.powerOn(common)
             changed_result = True
         else:
             result = "Success"
             changed_result = False
         
         # ISM logout
         common.ismLogout()
         
         # return json
         args = dict(
             ism_power_on = result
         )
         self.module.log("ism_power_on successful completion")
         self.module.exit_json(changed=changed_result, **args)
         
     except Exception as e:
         self.module.log(str(e))
         self.module.fail_json(msg=str(e))
예제 #17
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)