Esempio n. 1
0
 def itoolkit_run_rtv_command(self, command, args_dict):
     '''IBM i XMLSERVICE call *CMD with REXX'''
     itool = iToolKit(iparm=0, iret=0, ids=1, irow=0)
     itransport = DatabaseTransport(self.conn)
     args = ' '
     for (k, v) in args_dict.items():
         parm = '(?) '
         if v == 'number':
             parm = '(?N) '
         args = args + k + parm
     itool.add(iCmd('rtv_command', command + args))
     itool.call(itransport)
     rtv_command = itool.dict_out('rtv_command')
     ibmi_util.log_debug("rtv_command " + str(rtv_command), sys._getframe().f_code.co_name)
     if 'error' in rtv_command:
         rc = ibmi_util.IBMi_COMMAND_RC_ERROR
         out_dict = dict()
         error = str(rtv_command)
     else:
         # remove the key 'success' and its value, just left the result
         del rtv_command['success']
         rc = ibmi_util.IBMi_COMMAND_RC_SUCCESS
         out_dict = rtv_command
         error = ''
     return rc, out_dict, error
Esempio n. 2
0
    def itoolkit_run_command5250(self, command):
        '''IBM i XMLSERVICE call 5250 *CMD returning *OUTPUT'''
        itool = iToolKit()
        itransport = DatabaseTransport(self.conn)
        if command:
            command = command.upper().replace('OUTPUT(*)', '')
        itool.add(iCmd5250('command', command))
        itool.call(itransport)
        command_output = itool.dict_out('command')
        ibmi_util.log_debug("command_output " + str(command_output), sys._getframe().f_code.co_name)

        out = ''
        err = ''

        if 'error' in command_output:
            rc = ibmi_util.IBMi_COMMAND_RC_ERROR
            err = str(command_output)
        else:
            rc = ibmi_util.IBMi_COMMAND_RC_SUCCESS
            out = str(command_output['command'])
        return rc, out, err
Esempio n. 3
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            operation=dict(type='str', choices=['display'], default='display'),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )
    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    rc = SUCCESS
    ethernet_ports = []
    result = ''
    try:
        ibmi_module = imodule.IBMiModule(
            become_user_name=become_user,
            become_user_password=become_user_password)
    except Exception as inst:
        message = 'Exception occurred: {0}'.format(str(inst))
        module.fail_json(rc=999, msg=message)

    rc, ethernet_ports, result = list_ethernet_ports_info(ibmi_module)
    ibmi_util.log_debug(
        "list_ethernet_ports_info result is: {0}".format(result), module._name)
    ibmi_util.log_debug(
        "list_ethernet_ports_info resources information are: {0}".format(
            ethernet_ports), module._name)

    if rc:
        module.fail_json(
            rc=rc,
            msg="Error when getting ethernet ports information: {0}".format(
                result))

    module.exit_json(rc=SUCCESS,
                     msg="Success to get ethernet ports information",
                     ethernet_ports=ethernet_ports)
Esempio n. 4
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            object_names=dict(type='str', default='*ALL'),
            object_lib=dict(type='str', required=True),
            object_types=dict(type='str', default='*ALL'),
            savefile_name=dict(type='str', required=True),
            savefile_lib=dict(type='str', required=True),
            format=dict(type='str', default='*SAVF', choices=['*SAVF']),
            force_save=dict(type='bool', default=False),
            target_release=dict(type='str', default='*CURRENT'),
            joblog=dict(type='bool', default=False),
            asp_group=dict(type='str', default='*SYSBAS'),
            parameters=dict(type='str', default=' '),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )
    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    try:
        object_names = module.params['object_names']
        object_lib = module.params['object_lib']
        object_types = module.params['object_types']
        savefile_name = module.params['savefile_name']
        savefile_lib = module.params['savefile_lib']
        format = module.params['format']
        force_save = module.params['force_save']
        target_release = module.params['target_release']
        joblog = module.params['joblog']
        asp_group = module.params['asp_group'].strip().upper()
        parameters = module.params['parameters']
        become_user = module.params['become_user']
        become_user_password = module.params['become_user_password']

        startd = datetime.datetime.now()

        try:
            ibmi_module = imodule.IBMiModule(
                db_name=asp_group, become_user_name=become_user, become_user_password=become_user_password)
        except Exception as inst:
            message = 'Exception occurred: {0}'.format(str(inst))
            module.fail_json(rc=999, msg=message)

        # crtsavf
        command = 'QSYS/CRTSAVF FILE({p_savefile_lib}/{p_savefile_name})'.format(
            p_savefile_lib=savefile_lib,
            p_savefile_name=savefile_name)
        rc, out, error = ibmi_module.itoolkit_run_command(command)
        job_log = ibmi_module.itoolkit_get_job_log(startd)
        ibmi_util.log_debug("CRTSAVF: " + command, module._name)
        if rc == ibmi_util.IBMi_COMMAND_RC_SUCCESS:
            # SAVOBJ
            command = 'QSYS/SAVOBJ OBJ({p_object_names}) LIB({p_object_lib}) DEV({p_format}) OBJTYPE({p_object_types}) \
                SAVF({p_savefile_lib}/{p_savefile_name}) TGTRLS({p_target_release}) {p_parameters}'.format(
                p_object_names=object_names,
                p_object_lib=object_lib,
                p_format=format,
                p_object_types=object_types,
                p_savefile_lib=savefile_lib,
                p_savefile_name=savefile_name,
                p_target_release=target_release,
                p_parameters=parameters)
            rc, out, error = ibmi_module.itoolkit_run_command(' '.join(command.split()))
        else:
            if 'CPF5813' in str(job_log):
                ibmi_util.log_debug("SAVF " + savefile_name + " already exists", module._name)
                if force_save is True:
                    # CLRSAVF
                    command = 'QSYS/CLRSAVF FILE({p_savefile_lib}/{p_savefile_name})'.format(
                        p_savefile_lib=savefile_lib,
                        p_savefile_name=savefile_name)
                    rc, out, error = ibmi_module.itoolkit_run_command(command)
                    ibmi_util.log_debug("CLRSAVF: " + command, module._name)
                    if rc == ibmi_util.IBMi_COMMAND_RC_SUCCESS:
                        command = 'QSYS/SAVOBJ OBJ({p_object_names}) LIB({p_object_lib}) DEV({p_format}) OBJTYPE({p_object_types}) \
                            SAVF({p_savefile_lib}/{p_savefile_name}) TGTRLS({p_target_release}) {p_parameters}'.format(
                            p_object_names=object_names,
                            p_object_lib=object_lib,
                            p_format=format,
                            p_object_types=object_types,
                            p_savefile_lib=savefile_lib,
                            p_savefile_name=savefile_name,
                            p_target_release=target_release,
                            p_parameters=parameters)
                        rc, out, error = ibmi_module.itoolkit_run_command(' '.join(command.split()))
                else:
                    out = 'File {p_savefile_name} in library {p_savefile_lib} already exists. Set force_save to force save.'.format(
                        p_savefile_name=savefile_name,
                        p_savefile_lib=savefile_lib)

        endd = datetime.datetime.now()
        delta = endd - startd
        job_log = ibmi_module.itoolkit_get_job_log(startd)
        result = dict(
            object_names=object_names,
            object_lib=object_lib,
            object_types=object_types,
            savefile_name=savefile_name,
            savefile_lib=savefile_lib,
            joblog=joblog,
            format=format,
            force_save=force_save,
            target_release=target_release,
            command=' '.join(command.split()),
            job_log=job_log if joblog or rc else [],
            stdout=out,
            stderr=error,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
        )

        if rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS:
            module.fail_json(msg='non-zero return code', **result)

        module.exit_json(**result)
    except Exception as e:
        module.fail_json(rc=ibmi_util.IBMi_COMMAND_RC_UNEXPECTED, msg=str(e))
def main():
    module = AnsibleModule(
        argument_spec=dict(
            src=dict(type='path', required=True),
            asp_group=dict(type='str', default='*SYSBAS'),
            severity_level=dict(type='int', default=10),
            type=dict(type='str', required=True, choices=['CL', 'SQL']),
            parameters=dict(type='str', default=' '),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )
    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    result = dict(
        stdout='',
        stderr='',
        rc=0,
        delta='',
        job_log=[]
    )

    try:
        src = module.params['src']
        type = module.params['type']
        severity_level = module.params['severity_level']
        asp_group = module.params['asp_group'].strip().upper()
        parameters = module.params['parameters']
        become_user = module.params['become_user']
        become_user_password = module.params['become_user_password']

        startd = datetime.datetime.now()

        try:
            ibmi_module = imodule.IBMiModule(
                db_name=asp_group, become_user_name=become_user, become_user_password=become_user_password)
        except Exception as inst:
            message = 'Exception occurred: {0}'.format(str(inst))
            module.fail_json(rc=999, msg=message)

        src = os.path.realpath(src)
        if not os.path.isfile(src):
            return_error(module, ibmi_module, "src {p_src} doesn't exist.".format(p_src=src), '', startd, result)

        f = open(src, "r")
        if not f:
            return_error(module, ibmi_module, "Can't open src {p_src}.".format(p_src=src), '', startd, result)

        command = ''
        if type == 'CL':
            for line in f:
                line_command = line.strip()
                if line_command != '':
                    if not line_command.endswith(":"):
                        command = command + line_command + ' '
                    else:
                        if line_command.endswith(":"):
                            command = command + line_command[:-1]
                        else:
                            command = command + line_command
                        rc, out, error = ibmi_module.itoolkit_run_command(command)
                        if rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS:
                            break
                        command = ''
                elif command != '':
                    rc, out, error = ibmi_module.itoolkit_run_command(command)
                    if rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS:
                        break
                    command = ''
            if command != '':
                rc, out, error = ibmi_module.itoolkit_run_command(command)
                ibmi_util.log_debug("run command: " + command, module._name)
        else:
            command = "QSYS/RUNSQLSTM SRCSTMF('{p_src}') ERRLVL({p_severity_level}) {p_parameters}".format(
                p_src=src,
                p_severity_level=severity_level,
                p_parameters=parameters)
            rc, out, error = ibmi_module.itoolkit_run_command(command)
            ibmi_util.log_debug("RUNSQLSTM: " + command, module._name)
            if rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS:
                return_error(module, ibmi_module, "Execute sql statement file {p_command} failed. err: \n {p_err}".format(
                    p_command=command,
                    p_err=error),
                    out,
                    startd,
                    result)

        endd = datetime.datetime.now()
        delta = endd - startd
        if rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS:
            return_error(module, ibmi_module, "Execute command {p_command} failed. err: {p_err}".format(
                p_command=command,
                p_err=error),
                out,
                startd,
                result)
        result['stdout'] = "Successfully execute script file."
        result.update({'rc': rc, 'delta': str(delta)})
        module.exit_json(**result)

    except Exception as e:
        result.update({'rc': ibmi_util.IBMi_COMMAND_RC_ERROR,
                      'stderr': "Unexpected exception happens. error: {p_to_text}. Use -vvv for more information.".format(
                          p_to_text=to_text(e))})
        module.fail_json(**result)
Esempio n. 6
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            cmd=dict(type='str', required=True),
            time_out=dict(type='str', default='1m'),
            status=dict(type='list', default=["*NONE"], elements='str'),
            check_interval=dict(type='str', default='1m'),
            parameters=dict(type='str', default=''),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )

    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)

    command = module.params['cmd']
    time_out = module.params['time_out']
    check_interval = module.params['check_interval']
    wait_for_job_status = module.params['status']
    parameters = module.params['parameters']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    ibmi_module = imodule.IBMiModule(become_user_name=become_user,
                                     become_user_password=become_user_password)

    cl_sbmjob = "QSYS/SBMJOB CMD(" + command + ") " + parameters

    if set(wait_for_job_status) < set(IBMi_JOB_STATUS_LIST):
        # this is expected
        pass
    else:
        rc = IBMi_PARAM_NOT_VALID
        result_failed_parameter_check = dict(
            # size=input_size,
            # age=input_age,
            # age_stamp=input_age_stamp,
            stderr="Parameter passed is not valid. ",
            rc=rc,
            sbmjob_cmd=cl_sbmjob,
            # changed=True,
        )
        module.fail_json(
            msg=
            'Value specified for status option is not valid. Valid values are '
            '*NONE, *ACTIVE, *COMPLETE, *JOBQ, *OUTQ',
            **result_failed_parameter_check)

    startd = datetime.datetime.now()

    # args = ['system', cl_sbmjob]
    # rc, out, err = module.run_command(args, use_unsafe_shell=False)
    rc, out, err = ibmi_module.itoolkit_run_command(cl_sbmjob)

    current_job_log = ibmi_module.itoolkit_get_job_log(startd)
    message_description = ''
    for i in current_job_log:
        if i["MESSAGE_ID"] == "CPC1221":
            message_description = i["MESSAGE_TEXT"]
            break

    if rc != IBMi_COMMAND_RC_SUCCESS:
        result_failed = dict(
            # size=input_size,
            # age=input_age,
            # age_stamp=input_age_stamp,
            stderr=err,
            rc=rc,
            sbmjob_cmd=cl_sbmjob,
            # changed=True,
        )
        module.fail_json(msg='Submit job failed. ', **result_failed)
    elif '*NONE' in wait_for_job_status:
        submitted_job = re.search(
            r'\d{6}/[A-Za-z0-9#_]{1,10}/[A-Za-z0-9#_]{1,10}',
            message_description)
        job_submitted = submitted_job.group()

        result_success = dict(
            rc=rc,
            job_submitted=job_submitted,
            sbmjob_cmd=cl_sbmjob,
            # changed=True,
        )
        module.exit_json(**result_success)

    submitted_job = re.search(r'\d{6}/[A-Za-z0-9#_]{1,10}/[A-Za-z0-9#_]{1,10}',
                              message_description)
    job_submitted = submitted_job.group()
    ibmi_util.log_debug("job_submitted: " + job_submitted, module._name)
    sql_get_job_info = "SELECT V_JOB_STATUS as \"job_status\", " \
                       "V_ACTIVE_JOB_STATUS as \"active_job_status\", " \
                       "V_RUN_PRIORITY as \"run_priority\", " \
                       "V_SBS_NAME as \"sbs_name\", " \
                       "V_CLIENT_IP_ADDRESS as \"ip_address\"" \
                       " FROM TABLE(QSYS2.GET_JOB_INFO('" + job_submitted + "')) A"
    rc, out, err_msg = ibmi_module.itoolkit_run_sql(sql_get_job_info)

    time_out_in_seconds = convert_wait_time_to_seconds(time_out)
    returned_job_status = ''
    if isinstance(out, list) and len(out) == 1:
        returned_job_status = out[0]['job_status'].strip()
    ibmi_util.log_debug("job_status: " + returned_job_status, module._name)

    while returned_job_status not in wait_for_job_status:
        rc, out, err_msg = ibmi_module.itoolkit_run_sql(sql_get_job_info)
        returned_job_status = ''
        if isinstance(out, list) and len(out) == 1:
            returned_job_status = out[0]['job_status'].strip()
        ibmi_util.log_debug("job_status: " + returned_job_status, module._name)
        wait_for_certain_time(check_interval)
        current_time = datetime.datetime.now()
        running_time = (current_time - startd).seconds
        if running_time > time_out_in_seconds:
            break

    ibmi_util.log_debug("job_status: " + returned_job_status, module._name)
    if returned_job_status not in wait_for_job_status:
        rc = IBMi_JOB_STATUS_NOT_EXPECTED

    endd = datetime.datetime.now()
    delta = endd - startd
    rc_msg = interpret_return_code(rc)

    if rc != IBMi_COMMAND_RC_SUCCESS:
        result_failed = dict(
            # size=input_size,
            # age=input_age,
            # age_stamp=input_age_stamp,
            job_info=out,
            stderr=err,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            job_submitted=job_submitted,
            sbmjob_cmd=cl_sbmjob,
            # changed=True,
        )
        module.fail_json(msg='non-zero return code: ' + rc_msg,
                         **result_failed)
    else:
        result_success = dict(
            job_info=out,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            job_submitted=job_submitted,
            sbmjob_cmd=cl_sbmjob,
            # changed=True,
        )
        module.exit_json(**result_success)
Esempio n. 7
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            operation=dict(type='str', choices=[
                           'add', 'remove'], required=True),
            nrg_name=dict(type='str', choices=['*MIRROR', 'MIRROR_DATABASE', 'MIRROR_ENGINE',
                                               'MIRROR_IFS', 'MIRROR_OTHER', 'MIRROR_RESYNC'], default='*MIRROR'),
            source_address=dict(type='str', required=True),
            target_address=dict(type='str'),
            link_priority=dict(type='str'),
            change_load_balance_link_count=dict(type='bool', default=True),
            line_description=dict(type='str', default=''),
            virtual_lan_id=dict(type='str', default=''),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
        required_if=[
            ['operation', 'add', ['target_address', 'link_priority']],
        ],
    )
    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    operation = module.params['operation']
    nrg_name = module.params['nrg_name']
    source_address = module.params['source_address']
    target_address = module.params['target_address']
    link_priority = module.params['link_priority']
    change_load_balance_link_count = module.params['change_load_balance_link_count']
    line_description = module.params['line_description']
    virtual_lan_id = module.params['virtual_lan_id']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if change_load_balance_link_count:
        change_load_balance_link_count_str = 'YES'
    else:
        change_load_balance_link_count_str = 'NO'

    try:
        ibmi_module = imodule.IBMiModule(
            become_user_name=become_user, become_user_password=become_user_password)
    except Exception as inst:
        message = 'Exception occurred: {0}'.format(str(inst))
        module.fail_json(rc=999, msg=message)

    if operation == 'add':
        try:
            link_priority_int = int(link_priority)
            if link_priority_int < 1 or link_priority_int > 16:
                module.fail_json(
                    rc=255, msg="The value of argument link_priority is {0} which out of range from 1 to 16".format(link_priority_int))
        except (TypeError, ValueError):
            module.fail_json(
                rc=255, msg="The value of argument link_priority is {0} which can't be converted to int".format(link_priority))
        if source_address == '*ALL':
            module.fail_json(
                rc=255, msg="The value of argument source_address can not be '*ALL' when the operation is 'add'")

        sql = "CALL QSYS2.ADD_NRG_LINK(NRG_NAME => '{p_name}', SOURCE_ADDRESS => '{s_addr}', TARGET_ADDRESS => '{t_addr}', \
            LINK_PRIORITY => {p_linkp}, INCREMENT_LOAD_BALANCE_LINK_COUNT => '{p_load}'".format(
            p_name=nrg_name, s_addr=source_address, t_addr=target_address,
            p_linkp=link_priority_int, p_load=change_load_balance_link_count_str)
        if line_description:
            sql = sql + \
                ", LINE_DESCRIPTION => '{p_lined}'".format(
                    p_lined=line_description)
        if virtual_lan_id:
            sql = sql + \
                ", VIRTUAL_LAN_ID => '{p_vlan_id}'".format(
                    p_vlan_id=virtual_lan_id)
        sql = sql + ")"

        ibmi_util.log_info("Run sql statement: " + sql, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_sql_callproc_once(sql)
        ibmi_util.log_debug("out={0}, err={1} ".format(str(out), str(err)), module._name)
        if rc:
            if (rc == ibmi_util.IBMi_PACKAGES_NOT_FOUND) or (rc == ibmi_util.IBMi_DB_CONNECTION_ERROR):
                msg = "Error occurred when add NRG link: {0}".format(err)
            else:
                msg = "Error occurred when add NRG link, see job log for detail"
            module.fail_json(
                rc=rc, msg=msg, job_log=job_log)

        sql = "CALL QSYS2.CHANGE_NRG(NRG_NAME => '{p_name}', NRG_DESCRIPTION => 'DB2MIRROR GROUP')".format(p_name=nrg_name)
        ibmi_util.log_info("Run sql statement: " + sql, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_sql_callproc_once(sql)
        ibmi_util.log_debug("out={0}, err={1} ".format(str(out), str(err)), module._name)
        if rc:
            module.fail_json(
                rc=rc, msg="Error occurred when change NRG deescription, see job log for detail", job_log=job_log)

        module.exit_json(
            rc=0, msg="Success to add NRG link")
    else:
        sql = "CALL QSYS2.REMOVE_NRG_LINK(NRG_NAME => '{p_name}', SOURCE_ADDRESS => '{s_addr}', \
            DECREMENT_LOAD_BALANCE_LINK_COUNT => '{p_load}'".format(
            p_name=nrg_name, s_addr=source_address, p_load=change_load_balance_link_count_str)
        if line_description:
            sql = sql + \
                ", LINE_DESCRIPTION => '{p_lined}'".format(
                    p_lined=line_description)
        if virtual_lan_id:
            sql = sql + \
                ", VIRTUAL_LAN_ID => '{p_vlan_id}'".format(
                    p_vlan_id=virtual_lan_id)
        sql = sql + ")"

        ibmi_util.log_info("Run sql statement: " + sql, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_sql_callproc_once(sql)
        ibmi_util.log_debug("out={0}, err={1} ".format(str(out), str(err)), module._name)
        if rc:
            module.fail_json(
                rc=rc, msg="Error occurred when remove NRG link, see job log for detail", job_log=job_log)
        module.exit_json(
            rc=0, msg="Success to remove NRG link")
Esempio n. 8
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            product=dict(type='str', default='*ONLY'),
            ptf=dict(type='str', required=True),
            release=dict(type='str', default='*ALL'),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )

    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)

    product = module.params['product'].strip().upper()
    ptf = module.params['ptf'].strip().upper()
    release = module.params['release'].strip().upper()
    if release:
        release = release.strip().upper()
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if len(product) > 7:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of product exceeds 7 characters")
    if len(ptf) > 7:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of ptf exceeds 7 characters")
    if (release != '*ALL') and (not (len(release) == 6)):
        module.fail_json(
            rc=ibmi_util.IBMi_PARAM_NOT_VALID,
            msg="Value of release is not a correct format(VxRyMz or vvrrmm")

    result = dict(rc=0,
                  ptf_info=[],
                  requisite_ptf_info=[],
                  job_log=[],
                  stderr='')
    try:
        ibmi_module = imodule.IBMiModule(
            become_user_name=become_user,
            become_user_password=become_user_password)
    except Exception as inst:
        message = 'Exception occurred: {0}'.format(str(inst))
        module.fail_json(rc=999, msg=message)

    sql = "SELECT * FROM QSYS2.PTF_INFO WHERE PTF_IDENTIFIER = '{0}' ".format(
        ptf)
    if product != '*ONLY':
        sql = sql + "and PTF_PRODUCT_ID = '{0}' ".format(product)
    if release != '*ALL':
        sql = sql + "and PTF_PRODUCT_RELEASE_LEVEL = '{0}' ".format(release)
    ibmi_util.log_debug("SQL to run: {0}".format(sql), module._name)

    rc, out, err, job_log = ibmi_module.itoolkit_run_sql_once(sql)

    result.update({'job_log': job_log})

    if rc:
        result.update({'rc': rc})
        result.update({'stderr': err})
        message = 'non-zero return code when get PTF information:{rc}'.format(
            rc=rc)
        module.fail_json(msg=message, **result)

    result.update({'ptf_info': out})

    if len(out) > 0:
        if product == '*ONLY':
            product = out[0]['PTF_PRODUCT_ID']
        if release == '*ALL':
            release = out[0]['PTF_RELEASE_LEVEL']
        ibmi_util.log_debug(
            "PTF release level: {0}, product id: {1}, ptf id: {2}".format(
                release, product, ptf), module._name)
        rc, pre_req_list, api_result = get_ptf_info(ibmi_module, ptf, product,
                                                    release)
        ibmi_util.log_debug("Requisite PTFs info: " + str(pre_req_list),
                            module._name)
        if rc:
            result.update({'rc': rc})
            result.update({'stderr': str(api_result)})
            message = 'non-zero return code when get requisite PTFs infomation:{rc}'.format(
                rc=rc)
            module.fail_json(msg=message, **result)
        result.update({'requisite_ptf_info': pre_req_list})
    else:
        ibmi_util.log_info("No PTF information returned", module._name)
        message = 'No PTF information returned, check if the inputs are correct or if the PTF is loaded status'
        result.update({'rc': ibmi_util.IBMi_PTF_NOT_FOUND})
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})
    module.exit_json(**result)
Esempio n. 9
0
def get_ptf_info(imodule, ptf_id, product_id, release_level):
    conn = imodule.get_connection()
    itransport = DatabaseTransport(conn)
    itool = iToolKit()
    system_release_info, err = imodule.get_ibmi_release()
    ibmi_util.log_debug(
        "get_ibmi_release() return release_info: " + str(system_release_info),
        sys._getframe().f_code.co_name)
    ibmi_util.log_debug("get_ibmi_release() return err: " + str(err),
                        sys._getframe().f_code.co_name)
    # Example output for system_release_info: {'version': 7, 'release': 2, 'version_release': 7.2}
    # Note, version_release is float but not string
    if system_release_info['version_release'] == 7.2:
        itool.add(
            iPgm('qpzrtvfx', 'QPZRTVFX').addParm(
                iDS('PTFR0300_t', {
                    'len': 'rhrlen'
                }).addData(iData('rhrRet', '10i0', '')).addData(
                    iData('rhrAvl', '10i0', '')).addData(
                        iData('rhrOftAddIn', '10i0', '')).addData(
                            iData('rhrPid', '7A', '')).addData(
                                iData('rhrPtfId', '7A', '')).addData(
                                    iData('rhrRlsLvl', '6A', '')).addData(
                                        iData('rhrPrdOpt', '4A', '')).addData(
                                            iData('rhrLodId', '4A', '')).
                addData(iData('rhrLdSts', '1A', '')).addData(
                    iData('rhrCvrLtrSts', '1A',
                          '')).addData(iData('rhrOnOrdSts', '1A', '')).addData(
                              iData('rhrSavfSts', '1A', '')).addData(
                                  iData('rhrFilNam', '10A', '')).addData(
                                      iData('rhrFilLibNam', '10A',
                                            '')).addData(
                                                iData('rhrPtfTyp', '1A',
                                                      '')).addData(
                                                          iData(
                                                              'rhrIplAct',
                                                              '1A', '')).
                addData(iData(
                    'rhrActPnd', '1A',
                    '')).addData(iData(
                        'rhrActReq', '1A',
                        '')).addData(iData('rhrPtfRls', '1A', '')).addData(
                            iData('rhrTgtRls', '6A', '')).addData(
                                iData('rhrSpsPtf', '7A', '')).addData(
                                    iData('rhrIplSid', '1A', '')).addData(
                                        iData('rhrMinLvl', '2A', '')).addData(
                                            iData('rhrMaxLvl', '2A', '')).
                addData(iData('rhrFmtInfAvl', '1A', '')).addData(
                    iData('rhrStsDtaTim', '13A',
                          '')).addData(iData('rhrLicGrp', '7A', '')).addData(
                              iData('rhrSpsByPtf', '7A', '')).addData(
                                  iData('rhrSvrIplSrc', '1A', '')).addData(
                                      iData('rhrSvrIplRad', '1A', '')).addData(
                                          iData('rhrCrtDtaTim', '13A',
                                                '')).addData(
                                                    iData(
                                                        'rhrTecRfsPtf', '1A',
                                                        ''))
                # .addData(iData('rhrTmpApyDtaTim', '13A', '')) # V7R2M0 does not has this field
                .addData(iData('rhrOftPreReqRec', '10i0', '')).addData(
                    iData('rhrNbrPreReq', '10i0', '',
                          {'enddo': 'mycnt'})).addData(
                              iData('rhrLenPreReq', '10i0', '')).
                addData(
                    iDS('rhrReqs', {
                        'dim': '999',
                        'dou': 'mycnt'
                    }).addData(iData(
                        'REQUISITE_PRODUCT_ID',
                        '7A',
                        '')).addData(iData(
                            'REQUISITE_PTF_ID',
                            '7A',
                            '')).addData(
                                iData('RELEASE_OF_REQUISITE', '6A',
                                      '')).addData(
                                          iData('REQUISITE_MIN_LEVLE', '2A',
                                                '')).
                    addData(iData('REQUISITE_MAX_LEVLE', '2A', '')).addData(
                        iData('TYPE_OF_REQUISITE', '1A', '')).addData(
                            iData(
                                'REQUISITE_IS_CONDITIONAL', '1A', '')).addData(
                                    iData('REQUISITE_IS_REQUIRED', '1A',
                                          '')).addData(
                                              iData(
                                                  'REQUISITE_OPTION', '4A',
                                                  '')).addData(
                                                      iData(
                                                          'REQUISITE_LOAD_ID',
                                                          '4A', '')))).
            addParm(iData('rcvlen', '10i0', '', {
                'setlen': 'rhrlen'
            })).addParm(
                iDS('Qpz_Rtv_PTF_Info_t').addData(iData(
                    'PTF_ID', '7A',
                    ptf_id)).addData(iData(
                        'PID', '7A', product_id)).addData(
                            iData('Rls_Lvl', '6A', release_level)).addData(
                                iData('CCSID', '10i0', '')).addData(
                                    iData('Close_Files', '1A', '')).addData(
                                        iData('Reserved', '25A', ''))
            ).addParm(iData('fmtnam', '8A', 'PTFR0300')).addParm(
                iDS('ERRC0100_t', {
                    'len': 'errlen'
                }).addData(iData('errRet', '10i0', '')).addData(
                    iData('errAvl', '10i0', '')).addData(
                        iData('errExp', '7A', '',
                              {'setlen': 'errlen'})).addData(
                                  iData('errRsv', '1A', ''))))
    else:
        itool.add(
            iPgm('qpzrtvfx', 'QPZRTVFX').addParm(
                iDS('PTFR0300_t', {
                    'len': 'rhrlen'
                }).addData(iData('rhrRet', '10i0', '')).addData(
                    iData('rhrAvl', '10i0', '')).addData(
                        iData('rhrOftAddIn', '10i0', '')).addData(
                            iData('rhrPid', '7A', '')).addData(
                                iData('rhrPtfId', '7A', '')).addData(
                                    iData('rhrRlsLvl', '6A', '')).addData(
                                        iData('rhrPrdOpt', '4A', '')).addData(
                                            iData('rhrLodId', '4A', '')).
                addData(iData('rhrLdSts', '1A', '')).addData(
                    iData('rhrCvrLtrSts', '1A',
                          '')).addData(iData('rhrOnOrdSts', '1A', '')).addData(
                              iData('rhrSavfSts', '1A', '')).addData(
                                  iData('rhrFilNam', '10A', '')).addData(
                                      iData('rhrFilLibNam', '10A',
                                            '')).addData(
                                                iData('rhrPtfTyp', '1A',
                                                      '')).addData(
                                                          iData(
                                                              'rhrIplAct',
                                                              '1A', '')).
                addData(iData(
                    'rhrActPnd', '1A',
                    '')).addData(iData(
                        'rhrActReq', '1A',
                        '')).addData(iData('rhrPtfRls', '1A', '')).addData(
                            iData('rhrTgtRls', '6A', '')).addData(
                                iData('rhrSpsPtf', '7A', '')).addData(
                                    iData('rhrIplSid', '1A', '')).addData(
                                        iData('rhrMinLvl', '2A', '')).addData(
                                            iData('rhrMaxLvl', '2A', '')).
                addData(iData('rhrFmtInfAvl', '1A', '')).addData(
                    iData('rhrStsDtaTim', '13A',
                          '')).addData(iData('rhrLicGrp', '7A', '')).addData(
                              iData('rhrSpsByPtf', '7A', '')).addData(
                                  iData('rhrSvrIplSrc', '1A', '')).addData(
                                      iData('rhrSvrIplRad', '1A', '')).addData(
                                          iData('rhrCrtDtaTim', '13A', '')).
                addData(iData(
                    'rhrTecRfsPtf', '1A',
                    '')).addData(iData(
                        'rhrTmpApyDtaTim',
                        '13A', '')).addData(
                            iData('rhrOftPreReqRec', '10i0',
                                  '')).addData(
                                      iData('rhrNbrPreReq', '10i0', '',
                                            {'enddo': 'mycnt'})).addData(
                                                iData('rhrLenPreReq', '10i0',
                                                      '')).
                addData(
                    iDS('rhrReqs', {
                        'dim': '999',
                        'dou': 'mycnt'
                    }).addData(iData(
                        'REQUISITE_PRODUCT_ID',
                        '7A',
                        '')).addData(iData(
                            'REQUISITE_PTF_ID',
                            '7A',
                            '')).addData(
                                iData('RELEASE_OF_REQUISITE', '6A',
                                      '')).addData(
                                          iData('REQUISITE_MIN_LEVLE', '2A',
                                                '')).addData(
                                                    iData(
                                                        'REQUISITE_MAX_LEVLE',
                                                        '2A', '')).
                    addData(iData(
                        'TYPE_OF_REQUISITE',
                        '1A',
                        '')).addData(
                            iData(
                                'REQUISITE_IS_CONDITIONAL', '1A', '')).addData(
                                    iData('REQUISITE_IS_REQUIRED', '1A',
                                          '')).addData(
                                              iData(
                                                  'REQUISITE_OPTION', '4A',
                                                  '')).addData(
                                                      iData(
                                                          'REQUISITE_LOAD_ID',
                                                          '4A', '')))).
            addParm(iData('rcvlen', '10i0', '', {
                'setlen': 'rhrlen'
            })).addParm(
                iDS('Qpz_Rtv_PTF_Info_t').addData(iData(
                    'PTF_ID', '7A',
                    ptf_id)).addData(iData(
                        'PID', '7A', product_id)).addData(
                            iData('Rls_Lvl', '6A', release_level)).addData(
                                iData('CCSID', '10i0', '')).addData(
                                    iData('Close_Files', '1A', '')).addData(
                                        iData('Reserved', '25A', ''))
            ).addParm(iData('fmtnam', '8A', 'PTFR0300')).addParm(
                iDS('ERRC0100_t', {
                    'len': 'errlen'
                }).addData(iData('errRet', '10i0', '')).addData(
                    iData('errAvl', '10i0', '')).addData(
                        iData('errExp', '7A', '',
                              {'setlen': 'errlen'})).addData(
                                  iData('errRsv', '1A', ''))))
    itool.call(itransport)
    qpzrtvfx = itool.dict_out('qpzrtvfx')
    ibmi_util.log_debug(str(qpzrtvfx), sys._getframe().f_code.co_name)
    res_list = []
    if 'success' in qpzrtvfx:
        ptfr0300_t = qpzrtvfx['PTFR0300_t']
        ibmi_util.log_debug(str(ptfr0300_t), sys._getframe().f_code.co_name)
        if int(ptfr0300_t['rhrNbrPreReq']) > 0:
            res = ptfr0300_t['rhrReqs']
            if isinstance(res, dict):
                res_list.append(res)
            elif isinstance(res, list):
                res_list = res
            ibmi_util.log_debug(str(res_list), sys._getframe().f_code.co_name)
        return 0, res_list, qpzrtvfx['success']
    else:
        return -1, res_list, qpzrtvfx['error']
Esempio n. 10
0
def list_ethernet_ports_info(imodule):
    conn = imodule.get_connection()
    itransport = DatabaseTransport(conn)
    itool = iToolKit()
    itool.add(
        iSrvPgm('qgyrhr', 'QGYRHR', 'QgyRtvHdwRscList').addParm(
            iDS('RHRL0100_t', {
                'len': 'rhrlen'
            }).addData(iData('rhrRet', '10i0', '')).addData(
                iData('rhrAvl', '10i0', '')).addData(
                    iData('rhrNbr', '10i0', '', {'enddo': 'mycnt'})).addData(
                        iData('rhrLen', '10i0', '')).addData(
                            iDS('res_t', {
                                'dim': '999',
                                'dou': 'mycnt'
                            }).addData(iData('resCat', '10i0', '')).addData(
                                iData('resLvl', '10i0', '')).addData(
                                    iData('resLin', '10i0', '')).addData(
                                        iData('resNam', '10a', '')).addData(
                                            iData('resTyp', '4a', '')).addData(
                                                iData('resMod', '3a', '')).
                            addData(iData('resSts', '1a', '')).addData(
                                iData('resSys', '8a', '')).addData(
                                    iData('resAdp', '12a', '')).addData(
                                        iData('resDsc', '50h', '')).addData(
                                            iData('resKnd', '24b', '')))).
        addParm(iData(
            'rcvlen',
            '10i0', '',
            {'setlen': 'rhrlen'})).addParm(iData(
                'fmtnam', '10a',
                'RHRL0100')).addParm(iData('rescat', '10i0', '2')).addParm(
                    iDS('ERRC0100_t', {
                        'len': 'errlen'
                    }).addData(iData(
                        'errRet', '10i0',
                        '')).addData(iData(
                            'errAvl', '10i0', '')).addData(
                                iData('errExp', '7A', '',
                                      {'setlen': 'errlen'})).addData(
                                          iData('errRsv', '1A', ''))))
    itool.call(itransport)
    qgyrhr = itool.dict_out('qgyrhr')
    ibmi_util.log_debug("qgyrhr output: " + str(qgyrhr),
                        sys._getframe().f_code.co_name)
    res_list = []
    if 'success' in qgyrhr:
        rhrl0100_t = qgyrhr['RHRL0100_t']
        if int(rhrl0100_t['rhrNbr']) > 0:
            res_t = rhrl0100_t['res_t']
            res_info = dict()
            for rec in res_t:
                if rec['resKnd'] == kKindVirtEthernet or rec[
                        'resKnd'] == kKindPhysEthernet:
                    ibmi_util.log_debug("resource name is " + rec['resNam'],
                                        sys._getframe().f_code.co_name)
                    rc, res_info, result = get_info_from_resource_name(
                        imodule, rec['resNam'])
                    ibmi_util.log_debug("resource info is " + str(res_info),
                                        sys._getframe().f_code.co_name)
                    ibmi_util.log_debug(
                        "get resource info result is " + result,
                        sys._getframe().f_code.co_name)
                    if rc == SUCCESS:
                        res_list.append(res_info)
        return SUCCESS, res_list, qgyrhr['success']
    else:
        return ERROR, res_list, qgyrhr['error']
Esempio n. 11
0
def get_info_from_resource_name(imodule, resource_name):
    conn = imodule.get_connection()
    itransport = DatabaseTransport(conn)
    itool = iToolKit()
    itool.add(
        iSrvPgm('qgyrhr', 'QGYRHR', 'QgyRtvHdwRscInfo').addParm(
            iDS('RHRI0100_t', {
                'len': 'rhrlen'
            }).addData(iData('rhrRet', '10i0', '')).addData(
                iData('rhrAvl', '10i0',
                      '')).addData(iData('sysBusNum', '10i0', '')).addData(
                          iData('sysBdNum', '10i0', '')).addData(
                              iData('sysCdNum', '10i0', '')).addData(
                                  iData('IOBusAdd', '10i0', '')).addData(
                                      iData('AdaptAdd', '10i0', '')).addData(
                                          iData('PortNum', '10i0', '')).
            addData(iData('srNum', '10a', '')).addData(
                iData('partNum', '12a',
                      '')).addData(iData('frmID', '4a', '')).addData(
                          iData('cdPst', '5a', '')).addData(
                              iData('locCd', '79a', '')).addData(
                                  iData('expSrNum', '15a', '')).addData(
                                      iData('LANSpeed', '8a', '',
                                            {'hex': 'on'})).addData(
                                                iData('LinkAgg', '1a', '',
                                                      {'hex': 'on'})).addData(
                                                          iData(
                                                              'MAC', '6a', '',
                                                              {'hex': 'on'}))).
        addParm(iData('rcvlen', '10i0', '', {'setlen': 'rhrlen'})).addParm(
            iData('fmtnam', '8a', 'RHRI0100')).addParm(
                iData('resnam', '10a', resource_name)).addParm(
                    iDS('ERRC0100_t', {
                        'len': 'errlen'
                    }).addData(iData('errRet', '10i0', '')).addData(
                        iData('errAvl', '10i0', '')).addData(
                            iData('errExp', '7A', '',
                                  {'setlen': 'errlen'})).addData(
                                      iData('errRsv', '1A', ''))))

    resoure_info = dict()
    itool.call(itransport)
    qgyrhr = itool.dict_out('qgyrhr')
    ibmi_util.log_debug("qgyrhr output: " + str(qgyrhr),
                        sys._getframe().f_code.co_name)
    if 'success' in qgyrhr:
        rhri0100_t = qgyrhr['RHRI0100_t']
        if int(rhri0100_t['rhrAvl']) > 0:
            resoure_info = {
                "RESOURCE_NAME": resource_name,
                "SYSTEM_BUS_NUMBER": rhri0100_t['sysBusNum'],
                "SYSTEM_BOARD_NUMBER": rhri0100_t['sysCdNum'],
                "SYSTEM_CARD_NUMBER": rhri0100_t['sysCdNum'],
                "IO_BUS_ADDRESS": rhri0100_t['IOBusAdd'],
                "ADAPTER_ADDRESS": rhri0100_t['AdaptAdd'],
                "PORT_NUMBER": rhri0100_t['PortNum'],
                "SERIAL_NUMBER": rhri0100_t['srNum'],
                "PART_NUMBER": rhri0100_t['partNum'],
                "FRAME_ID": rhri0100_t['frmID'],
                "CARD_POSITION": rhri0100_t['cdPst'],
                "LOCATION_CODE": rhri0100_t['locCd'],
                "EXPANDED_SERIAL_NUMBER": rhri0100_t['expSrNum'],
                "LAN_SPEED": rhri0100_t['LANSpeed'],
                "SUPPORTS_LINK_AGGREGATION": rhri0100_t['LinkAgg'],
                "DEFAULT_MAC_ADDRESS": rhri0100_t['MAC'],
            }
        return SUCCESS, resoure_info, qgyrhr['success']
    else:
        return ERROR, resoure_info, qgyrhr['error']
Esempio n. 12
0
def main():
    module = AnsibleModule(
        argument_spec=dict(src=dict(type='str', required=True),
                           dest=dict(type='str', default=''),
                           remote_user=dict(type='str', required=True),
                           remote_host=dict(type='str', required=True),
                           private_key=dict(type='path',
                                            default='~/.ssh/id_rsa')),
        supports_check_mode=True,
    )
    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    result = dict(
        stdout='',
        stderr='',
        rc=0,
        delta='',
    )

    try:
        if HAS_PARAMIKO is False:
            module.fail_json(msg="paramiko package is required",
                             rc=ibmi_util.IBMi_COMMAND_RC_ERROR)

        src = module.params['src']
        dest = module.params['dest']
        remote_user = module.params['remote_user']
        remote_host = module.params['remote_host']
        private_key = module.params['private_key']

        startd = datetime.datetime.now()
        if os.path.splitext(os.path.basename(src))[-1].upper() != '.FILE':
            return_error(
                module,
                "src {p_src} is not a save file. src must be end with '.FILE'."
                .format(p_src=src), result)
        if src[0:9].upper() != '/QSYS.LIB':
            return_error(
                module,
                "src {p_src} path should be absolute, start with /QSYS.LIB.".
                format(p_src=src), result)

        if dest == '':
            dest = src
        if dest[0:9].upper() != '/QSYS.LIB':
            return_error(
                module,
                "dest {p_dest} path should be absolute, start with /QSYS.LIB.".
                format(p_dest=dest), result)

        # Check if the savefile exists
        if not os.path.isfile(src):
            return_error(module,
                         "src doesn't exist. {p_src}".format(p_src=src),
                         result)

        ibmi_util.log_debug("mkdir " + ifs_dir, module._name)
        rc, out, err = module.run_command(['mkdir', ifs_dir],
                                          use_unsafe_shell=False)
        if rc == 0 or 'File exists' in err:
            ibmi_util.log_debug("cp " + src + " " + ifs_dir, module._name)
            rc, out, err = module.run_command(['cp', src, ifs_dir],
                                              use_unsafe_shell=False)
            if rc == 0:
                src_basename = os.path.basename(src)
                ifs_name = ifs_dir + src_basename
                private_key = to_bytes(private_key,
                                       errors='surrogate_or_strict')
                p_key = paramiko.RSAKey.from_private_key_file(private_key)
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(hostname=remote_host,
                            port=22,
                            username=remote_user,
                            pkey=p_key)

                transport = paramiko.Transport((remote_host, 22))
                transport.connect(username=remote_user, pkey=p_key)
                sftp = paramiko.SFTPClient.from_transport(transport)
                stdin, stdout, stderr = ssh.exec_command(
                    'mkdir {p_ifs_dir}'.format(p_ifs_dir=ifs_dir))
                line = stderr.readlines()
                if line != [] and 'File exists' not in "".join(line):
                    return_error(
                        module,
                        "Failed to mkdir on remote host, dir = {p_ifs_dir}. {p_line}"
                        .format(p_ifs_dir=ifs_dir, p_line=line), result)
                try:
                    ibmi_util.log_debug(
                        "sftp: put " + ifs_name + " " + ifs_name, module._name)
                    sftp.put(ifs_name, ifs_name)
                except Exception as e:
                    return_error(
                        module,
                        "Put {p_to_text} to remote host exception. Use -vvv for more information."
                        .format(p_to_text=to_text(e)), result)

                ibmi_util.log_debug("mv " + ifs_name + " " + dest,
                                    module._name)
                stdin, stdout, stderr = ssh.exec_command(
                    'mv {p_ifs_name} {p_dest}'.format(p_ifs_name=ifs_name,
                                                      p_dest=dest))
                line = stderr.readlines()
                if line != []:
                    return_error(
                        module,
                        "Failed to mv file to qsys. qsys dir = {p_dest}. {p_line}"
                        .format(p_dest=dest, p_line=line), result)
            else:
                return_error(
                    module,
                    "Copy file to current host tmp dir failed. cp {p_src} {p_ifs_dir}. {p_err}"
                    .format(p_src=src, p_ifs_dir=ifs_dir, p_err=err), result)
        else:
            return_error(
                module,
                "mkdir on current host failed. dir = {p_ifs_dir}. {p_err}".
                format(p_ifs_dir=ifs_dir, p_err=err), result)

        endd = datetime.datetime.now()
        delta = endd - startd
        result[
            'stdout'] = "Successfully synchronize file {p_src} to remote host {p_remote_host}:{p_dest}".format(
                p_src=src, p_remote_host=remote_host, p_dest=dest)
        result.update({'stderr': err, 'rc': rc, 'delta': str(delta)})
        module.exit_json(**result)

    except Exception as e:
        return_error(
            module,
            "Unexpected exception happens. error: {p_to_text}. Use -vvv for more information."
            .format(p_to_text=to_text(e)), result)
    finally:
        if 'ssh' in vars():
            ssh.close()
        if 'sftp' in vars():
            sftp.close()
Esempio n. 13
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            ptf_id=dict(type='str', required=True),
            product=dict(type='str', default='*ONLYPRD'),
            release=dict(type='str', default='*ONLYRLS'),
            delivery_format=dict(type='str',
                                 default='*SAVF',
                                 choices=['*SAVF', '*IMAGE']),
            order=dict(type='str',
                       default='*REQUIRED',
                       choices=['*REQUIRED', '*PTFID']),
            reorder=dict(type='str', default='*YES', choices=['*NO', '*YES']),
            check_PTF=dict(type='str', default='*NO', choices=['*NO', '*YES']),
            image_directory=dict(type='str', default='*DFT'),
            joblog=dict(type='bool', default=False),
            parameters=dict(type='str', default=' '),
            time_out=dict(type='str', default='15m'),
            wait=dict(type='bool', default=True),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )

    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)

    ptf_id = module.params['ptf_id']
    product = module.params['product']
    release = module.params['release']
    delivery_format = module.params['delivery_format']
    order = module.params['order']
    reorder = module.params['reorder']
    check_PTF = module.params['check_PTF']
    image_directory = module.params['image_directory']
    joblog = module.params['joblog']
    parameters = module.params['parameters']
    time_out = module.params['time_out']
    wait = module.params['wait']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    result = dict(stdout='',
                  stderr='',
                  rc=0,
                  delta='',
                  command='',
                  download_list=[],
                  job_log=[],
                  msg='',
                  order_id=0,
                  job_info='')
    error = ''
    out = ''
    returned_job_status = ''
    job_log = []
    download_list = []
    time_up = False
    success = False
    job_submitted = ''
    job_submitted_split = ''
    order_id = 0
    order_start_time = 0
    order_end_time = 0
    file_path = ''

    try:
        ibmi_module = imodule.IBMiModule(
            become_user_name=become_user,
            become_user_password=become_user_password)
    except Exception as inst:
        message = 'Exception occurred: {0}'.format(str(inst))
        module.fail_json(rc=999, msg=message)

    conn = ibmi_module.get_connection()

    if image_directory != "*DFT":
        image_directory = "'{p_image_directory}'".format(
            p_image_directory=image_directory)

    command = 'SNDPTFORD PTFID(({p_ptf_id} {p_product} {p_release})) DLVRYFMT({p_delivery_format}) ORDER({p_order}) \
    REORDER({p_reorder}) CHKPTF({p_check_PTF}) IMGDIR({p_image_directory}) {p_parameters}'.format(
        p_ptf_id=ptf_id,
        p_product=product,
        p_release=release,
        p_delivery_format=delivery_format,
        p_order=order,
        p_reorder=reorder,
        p_check_PTF=check_PTF,
        p_image_directory=image_directory,
        p_parameters=parameters)

    cl_sbmjob = "QSYS/SBMJOB CMD(" + ' '.join(command.split(
    )) + ") " + 'LOG(4 *JOBD *SECLVL) ' + 'LOGOUTPUT(*PND) ' + parameters
    startd = datetime.datetime.now()
    message_description = ''
    rc, out, error = ibmi_module.itoolkit_run_command(cl_sbmjob)

    current_job_log = ibmi_module.itoolkit_get_job_log(startd)
    for i in current_job_log:
        if i["MESSAGE_ID"] == "CPC1221":
            message_description = i["MESSAGE_TEXT"]
            break

    if rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS:
        return_error(module, conn, message_description, out,
                     'Submit job failed.', current_job_log,
                     ibmi_util.IBMi_COMMAND_RC_ERROR, job_submitted_split,
                     wait, delivery_format, result)

    submitted_job = re.search(r'\d{6}/[A-Za-z0-9#_]{1,10}/[A-Za-z0-9#_]{1,10}',
                              message_description)
    job_submitted = submitted_job.group()
    job_submitted_split = job_submitted.split("/")
    sql_get_job_info = "SELECT V_JOB_STATUS as \"job_status\", " \
                       "V_ACTIVE_JOB_STATUS as \"active_job_status\"" \
                       " FROM TABLE(QSYS2.GET_JOB_INFO('" + job_submitted + "')) A"
    try:
        time_out_in_seconds = convert_wait_time_to_seconds(time_out)
        if wait or delivery_format == '*IMAGE':
            rc, out, error = ibmi_module.itoolkit_run_sql(sql_get_job_info)
            if isinstance(out, list) and len(out) == 1:
                returned_job_status = out[0]['job_status'].strip()

            while returned_job_status != '*UNKNOWN' and returned_job_status != '*OUTQ':
                wait_for_certain_time('1s')
                current_time = datetime.datetime.now()
                running_time = (current_time - startd).seconds
                if running_time > time_out_in_seconds:
                    time_up = True
                    break
                rc, out, error = ibmi_module.itoolkit_run_sql(sql_get_job_info)
                returned_job_status = ''
                if isinstance(out, list) and len(out) == 1:
                    returned_job_status = out[0]['job_status'].strip()
                ibmi_util.log_debug("job_status: " + returned_job_status,
                                    module._name)

        if rc == ibmi_util.IBMi_COMMAND_RC_SUCCESS:
            job_log = db2i_tools.get_job_log(conn, job_submitted, startd)
        else:
            return_error(module, conn, error, out, 'itoolkit_run_sql failed',
                         [], ibmi_util.IBMi_COMMAND_RC_ERROR,
                         job_submitted_split, wait, delivery_format, result)

        if time_up is True:
            return_error(module, conn, error, '',
                         'Time up when waiting for SNDPTFORD complete.',
                         job_log, ibmi_util.IBMi_COMMAND_RC_ERROR,
                         job_submitted_split, wait, delivery_format, result)

        if delivery_format == '*SAVF':
            j = 0
            while order_id == 0:
                for i in range(len(job_log) - 1, -1, -1):
                    if job_log[i]['MESSAGE_ID'] == 'CPF8C07':
                        return_error(module, conn, '', '',
                                     job_log[i]['MESSAGE_TEXT'], job_log,
                                     ibmi_util.IBMi_COMMAND_RC_ERROR,
                                     job_submitted_split, wait,
                                     delivery_format, result)
                    elif job_log[i]['MESSAGE_ID'] == 'CPZ8C38':
                        order_id = job_log[i]['MESSAGE_TEXT'][18:28]
                        order_start_time = job_log[i]['MESSAGE_TIMESTAMP']
                    elif job_log[i]['MESSAGE_ID'] == 'CPZ8C12':
                        download_list.append({})
                        download_list[j]['product'] = (
                            job_log[i]['MESSAGE_TEXT'])[4:11]
                        download_list[j]['ptf_id'] = job_log[i][
                            'MESSAGE_TEXT'][12:19]
                        download_list[j]['release'] = job_log[i][
                            'MESSAGE_TEXT'][20:26]
                        download_list[j]['download_time'] = job_log[i][
                            'MESSAGE_TIMESTAMP']
                        download_list[j][
                            'file_name'] = 'Q' + download_list[j]['ptf_id']
                        download_list[j][
                            'file_path'] = '/qsys.lib/qgpl.lib/' + download_list[
                                j]['file_name'] + '.FILE'
                        download_list[j]['order_id'] = order_id
                        j = j + 1
                        success = True
                    elif job_log[i]['MESSAGE_ID'] == 'CPF1164':
                        order_end_time = job_log[i]['MESSAGE_TIMESTAMP']
                    elif job_log[i]['MESSAGE_ID'] == 'CPI8C02':
                        return_error(module, conn, '', '',
                                     job_log[i]['MESSAGE_TEXT'], job_log,
                                     ibmi_util.IBMi_COMMAND_RC_ERROR,
                                     job_submitted_split, wait,
                                     delivery_format, result)
                    elif job_log[i]['MESSAGE_ID'] == 'CPF8C32':
                        return_error(
                            module, conn, '', '',
                            'PTF order cannot be processed. See joblog',
                            job_log, ibmi_util.IBMi_COMMAND_RC_ERROR,
                            job_submitted_split, wait, delivery_format, result)
                job_log = db2i_tools.get_job_log(conn, job_submitted, startd)
        elif delivery_format == '*IMAGE':
            if job_log:
                for i in range(len(job_log)):
                    if job_log[i]['MESSAGE_ID'] == 'CPZ8C38':
                        order_id = job_log[i]['MESSAGE_TEXT'][18:28]
                        order_start_time = job_log[i]['MESSAGE_TIMESTAMP']
                        success = True
                    elif job_log[i]['MESSAGE_ID'] == 'CPF8C32':
                        return_error(
                            module, conn, '', '',
                            'PTF order cannot be processed. See joblog',
                            job_log, ibmi_util.IBMi_COMMAND_RC_ERROR,
                            job_submitted_split, wait, delivery_format, result)
            else:
                return_error(module, conn, error, out, 'No joblog returned.',
                             job_log, ibmi_util.IBMi_COMMAND_RC_ERROR,
                             job_submitted_split, wait, delivery_format,
                             result)

        if wait is True or delivery_format == '*IMAGE':
            ret, message = remove_pending_joblog(conn, job_submitted_split[2],
                                                 job_submitted_split[1],
                                                 job_submitted_split[0])
            if ret != 0:
                error = error + '/n remove pending joblog fail.' + message

        endd = datetime.datetime.now()
        delta = endd - startd

        if delivery_format == '*IMAGE':
            if image_directory == '*DFT':
                file_path = '/QIBM/UserData/OS/Service/ECS/PTF/' + str(
                    order_id)
            else:
                file_path = image_directory.strip("'")

        result.update({
            'job_log':
            job_log if joblog or rc or success is False else [],
            'stdout':
            '',
            'stderr':
            error,
            'download_list':
            download_list,
            'rc':
            rc,
            'delta':
            str(delta),
            'order_id':
            order_id,
            'msg':
            'SNDPTFORD successfully ended.',
            'job_info':
            job_submitted,
            'command':
            cl_sbmjob,
            'order_start_time':
            order_start_time,
            'order_end_time':
            order_end_time,
            'file_path':
            file_path
        })

        module.exit_json(**result)

    except ImportError as e_import:
        return_error(module, conn, str(e_import), '', '', '',
                     ibmi_util.IBMi_PACKAGES_NOT_FOUND, job_submitted_split,
                     wait, delivery_format, result)
    except Exception as e_db_connect:
        return_error(module, conn, str(e_db_connect), '', '', '',
                     ibmi_util.IBMi_DB_CONNECTION_ERROR, job_submitted_split,
                     wait, delivery_format, result)
Esempio n. 14
0
def get_system_value(imodule, sysvaluename, expect=None, check='equal'):
    sysvalue = dict()
    sysvalue['name'] = sysvaluename.strip().upper()
    for value in sysval_array:
        for key in value['key']:
            if (sysvalue['name'] == key):
                sysvalue['type'] = value['type']
                if expect is not None:
                    sysvalue['expect'] = expect
                    if not check:
                        check = 'equal'
                    sysvalue['check'] = check
                break

    if sysvalue.get('type') is None:
        return -1, sysvalue, 'Unknown System Value Name'

    conn = imodule.get_connection()
    itransport = DatabaseTransport(conn)
    itool = iToolKit()
    itool.add(
        iPgm('qwcrsval', 'QWCRSVAL', {
            'lib': 'QSYS'
        }).addParm(
            iDS('QWCRSVAL_t', {
                'len': 'qwcrslen',
                'io': 'out'
            })
            # Number of system values returned
            .addData(iData('count', '10i0', ''))
            # Offset to system value information table
            .addData(iData('offset', '10i0',
                           '')).addData(iData('sysvalue', '10A',
                                              ''))  # System value
            # Type of data(C--character / B--binary / blank--not available.)
            .addData(iData('dataType', '1A', ''))
            # Information status(blank--The information was available.)
            .addData(iData('infoStatus', '1A',
                           '')).addData(iData('length', '10i0',
                                              ''))  # Length of data
            # Returned system value data
            .addData(iData('data', sysvalue['type'], ''))).addParm(
                iData('rcvlen', '10i0', '', {'setlen': 'qwcrslen'})).addParm(
                    iData('count', '10i0', '1')).addParm(
                        iData('valueName', '10A', sysvalue['name'])).addParm(
                            iDS('ERRC0100_t', {
                                'len': 'errlen'
                            }).addData(
                                iData('bytesProvided', '10i0', '',
                                      {'setlen': 'errlen'})).addData(
                                          iData('bytesAvailable', '10i0',
                                                '')).addData(
                                                    iData(
                                                        'messageID', '7A',
                                                        '')).addData(
                                                            iData(
                                                                'reserved',
                                                                '1A', ''))))
    itool.call(itransport)

    qwcrsval = itool.dict_out('qwcrsval')
    ibmi_util.log_debug(str(qwcrsval), sys._getframe().f_code.co_name)

    if 'success' in qwcrsval:
        qwcrsval_t = qwcrsval['QWCRSVAL_t']
        ibmi_util.log_debug(str(qwcrsval_t), sys._getframe().f_code.co_name)
        if int(qwcrsval_t['count']) > 0:
            sysvalue['value'] = qwcrsval_t['data']
            if 'expect' in sysvalue:
                sysvalue['compliant'] = chk_system_value(
                    sysvalue['value'], sysvalue['expect'], check)
            ibmi_util.log_debug(str(sysvalue), sys._getframe().f_code.co_name)
        return 0, sysvalue, qwcrsval['success']
    return -1, sysvalue, qwcrsval['error']
Esempio n. 15
0
def main():
    module = AnsibleModule(
        argument_spec=dict(src_list=dict(type='list',
                                         required=True,
                                         elements='dict'),
                           dest=dict(type='str', default=''),
                           remote_user=dict(type='str', required=True),
                           remote_host=dict(type='str', required=True),
                           private_key=dict(type='path',
                                            default='~/.ssh/id_rsa')),
        supports_check_mode=True,
    )
    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    result = dict(stdout='',
                  stderr='',
                  rc=0,
                  delta='',
                  success_list=[],
                  fail_list=[],
                  msg='')

    try:
        if HAS_PARAMIKO is False:
            module.fail_json(msg="paramiko package is required",
                             rc=ibmi_util.IBMi_COMMAND_RC_ERROR)

        src_list = module.params['src_list']
        dest = module.params['dest']
        remote_user = module.params['remote_user']
        remote_host = module.params['remote_host']
        private_key = module.params['private_key']
        delete_list = []
        success_list = []
        fail_list = []
        delete = False
        startd = datetime.datetime.now()
        ibmi_util.log_debug("mkdir " + ifs_dir, module._name)
        rc, out, err = module.run_command(['mkdir', ifs_dir],
                                          use_unsafe_shell=False)
        if rc != 0 and 'File exists' not in err:
            return_error(
                module,
                "mkdir on current host failed. dir = {p_ifs_dir}. {p_err}".
                format(p_ifs_dir=ifs_dir, p_err=err), result)

        private_key = to_bytes(private_key, errors='surrogate_or_strict')
        p_key = paramiko.RSAKey.from_private_key_file(private_key)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=remote_host,
                    port=22,
                    username=remote_user,
                    pkey=p_key)
        transport = paramiko.Transport((remote_host, 22))
        transport.connect(username=remote_user, pkey=p_key)
        sftp = paramiko.SFTPClient.from_transport(transport)

        if dest:
            try:
                sftp.stat(dest)
            except Exception as e:
                if 'No such file' in to_text(e):
                    return_error(
                        module, "dest: {p_dest} is not a directory.".format(
                            p_dest=dest), result)
                return_error(
                    module,
                    "Exception. {p_to_text}. Use -vvv for more information.".
                    format(p_to_text=to_text(e)), result)

        for i in range(len(src_list)):
            final_dest = dest
            if not os.path.isfile(src_list[i]['src']):
                src_list[i][
                    'fail_reason'] = "src {p_src} doesn't exist.".format(
                        p_src=src_list[i]['src'])
                fail_list.append(src_list[i])
                continue
            src_basename = os.path.basename(src_list[i]['src'])
            if final_dest == '':
                if 'dest' in src_list[i]:
                    final_dest = src_list[i]['dest']
            if final_dest == '':
                final_dest = os.path.dirname(
                    os.path.realpath(src_list[i]['src']))

            if final_dest[0:9].upper() == '/QSYS.LIB':
                final_dest = (final_dest + '/' +
                              os.path.splitext(src_basename)[0] +
                              '.FILE').replace("//", "/")
            else:
                final_dest = (final_dest + '/' + src_basename).replace(
                    "//", "/")

            if src_list[i]['src'][0:9].upper() == '/QSYS.LIB':
                ibmi_util.log_debug("cp " + src_list[i]['src'] + " " + ifs_dir,
                                    module._name)
                rc, out, err = module.run_command(
                    ['cp', src_list[i]['src'], ifs_dir],
                    use_unsafe_shell=False)
                if rc == 0:
                    final_src = ifs_dir + src_basename
                    delete = True
                    delete_list.append(final_src)
                else:
                    src_list[i][
                        'fail_reason'] = "Copy file to current host tmp dir failed. cp {p_src} {p_ifs_dir}. {p_err}".format(
                            p_src=src_list[i]['src'],
                            p_ifs_dir=ifs_dir,
                            p_err=err)
                    fail_list.append(src_list[i])
                    continue
            else:
                final_src = src_list[i]['src']

            try:
                ibmi_util.log_debug(
                    "sftp: put " + final_src + " " + final_dest, module._name)
                sftp.put(final_src, final_dest)
                success_list.append(src_list[i])
            except Exception as e:
                if 'size mismatch' in to_text(e):
                    src_list[i][
                        'fail_reason'] = "Can't sync file to /QSYS.LIB. Put {p_final_src} to remote host fail.".format(
                            p_final_src=final_src)
                else:
                    src_list[i][
                        'fail_reason'] = "{p_to_text}. Put {p_final_src} to remote host exception.".format(
                            p_to_text=to_text(e), p_final_src=final_src)
                fail_list.append(src_list[i])

        endd = datetime.datetime.now()
        delta = endd - startd
        if success_list != []:
            result[
                'msg'] = "Complete synchronize file list to remote host {p_remote_host}".format(
                    p_remote_host=remote_host)
            result.update({
                'stderr': '',
                'rc': 0,
                'delta': str(delta),
                'success_list': success_list,
                'fail_list': fail_list
            })
            module.exit_json(**result)
        else:
            result['msg'] = "No files were successfully transferred."
            result.update({
                'stderr': '',
                'rc': 255,
                'delta': str(delta),
                'success_list': success_list,
                'fail_list': fail_list
            })
            module.fail_json(**result)

    except Exception as e:
        return_error(
            module,
            "Exception. {p_to_text}. Use -vvv for more information.".format(
                p_to_text=to_text(e)), result)
    finally:
        if 'ssh' in vars():
            ssh.close()
        if 'sftp' in vars():
            sftp.close()
        if delete is True:
            for i in range(len(delete_list)):
                rc, out, err = module.run_command(['rm', delete_list[i]],
                                                  use_unsafe_shell=False)