Exemple #1
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            cmd=dict(type='str', required=True),
            char_vars=dict(type='list', elements='str'),
            number_vars=dict(type='list', elements='str'),
            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)

    command = module.params['cmd'].strip().upper()
    char_vars = module.params['char_vars']
    args_dict = dict()
    if char_vars:
        char_vars = [item.strip().upper() for item in char_vars]
        for item in char_vars:
            args_dict.update({item: 'chars'})
    number_vars = module.params['number_vars']
    if number_vars:
        number_vars = [item.strip().upper() for item in number_vars]
        for item in number_vars:
            args_dict.update({item: 'number'})
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    out = dict()
    if (not char_vars) and (not number_vars):
        module.fail_json(msg='At least one of the option char_vars or number_vars must contain value')
    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)

    job_log = []
    rc, out, err, job_log = ibmi_module.itoolkit_run_rtv_command_once(command, args_dict)

    result = dict(
        rc=rc,
        output=out,
        args_dict=args_dict,
        job_log=job_log
    )

    if rc:
        message = 'non-zero return code:{rc}, error: {err}'.format(rc=rc, err=err)
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(msg='Success', **result)
Exemple #2
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            subsystem=dict(type='str', required=True),
            library=dict(type='str', default='*LIBL'),
            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)

    subsystem = module.params['subsystem'].strip().upper()
    library = module.params['library'].strip().upper()
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if len(subsystem) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of subsystem exceeds 10 characters")
    if len(library) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of library exceeds 10 characters")
    command = 'QSYS/STRSBS SBSD({library}/{subsystem})'.format(
        library=library, subsystem=subsystem)

    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, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

    result = dict(
        command=command,
        stdout=out,
        stderr=err,
        rc=rc,
        job_log=job_log,
        changed=True,
    )

    if rc != 0:
        message = 'non-zero return code:{rc}'.format(rc=rc)
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
Exemple #3
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            sysvalue=dict(type='list', elements='dict', required=True),
            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)

    sysvalue = module.params['sysvalue']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if len(sysvalue) == 0:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Not found input system value name")

    result = dict(sysval=[], rc=0, message='')
    rc = 0

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

    for value in sysvalue:
        rc, sysval, message = get_system_value(ibmi_module, value.get('name'),
                                               value.get('expect'),
                                               value.get('check'))
        result['sysval'].append(sysval)

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

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})
    else:
        result.update({'job_log': message})

    module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            sql=dict(type='str', required=True),
            database=dict(type='str', default='*SYSBAS'),
            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)

    sql = module.params['sql'].strip().upper()
    database = module.params['database'].strip().upper()
    joblog = module.params['joblog']
    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=database, 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, out, err, job_log = ibmi_module.itoolkit_sql_callproc_once(sql)

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

    result = dict(
        sql=sql,
        stdout=out,
        stderr=err,
        rc=rc,
        start=str(startd),
        end=str(endd),
        delta=str(delta),
        job_log=job_log,
    )

    if rc:
        message = 'non-zero return code:{rc}'.format(rc=rc)
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
Exemple #5
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            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)
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()

    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)

    disk_list, job_log = getNonconfigureDisk(ibmi_module, startd)
    if not disk_list:
        rc_msg = "Here is no un-configure disk."
        rc = 0
    else:
        rc_msg = "Success to get all un-configure disks."
        rc = 0
    endd = datetime.datetime.now()
    delta = endd - startd

    result = dict(
        disks=disk_list,
        rc=rc,
        out=rc_msg,
        start=str(startd),
        job_log=job_log,
        end=str(endd),
        delta=str(delta),
    )

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

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
Exemple #6
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)
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)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name_list=dict(type='list', elements='str', required=True),
            state=dict(type='str',
                       choices=['started', 'stopped'],
                       required=True),
            extra_parameters=dict(type='str', default=' '),
            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)
    name_list = module.params['name_list']
    state = module.params['state']
    extra_parameters = module.params['extra_parameters']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()
    if state == 'started':
        command = IBMi_STRSVR + " SERVER(" + " ".join(
            i for i in name_list) + ") " + extra_parameters
    if state == 'stopped':
        command = IBMi_ENDSVR + " SERVER(" + " ".join(
            i for i in name_list) + ") " + extra_parameters

    if set(name_list) < set(IBMi_TCP_SERVER_LIST):
        # this is expected
        pass
    else:
        rc = ibmi_util.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,
            command=command,
            # changed=True,
        )
        module.fail_json(
            msg='Value specified for name_list is not valid. Valid values are '
            + ", ".join(i for i in IBMi_TCP_SERVER_LIST),
            **result_failed_parameter_check)
    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)
    job_log = []
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

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

    result = dict(
        cmd=command,
        job_log=job_log,
        stdout=out,
        stderr=err,
        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)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            subsystem=dict(type='str', default='*ALL'),
            user=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)

    subsystem = module.params['subsystem'].strip().upper()
    user = module.params['user'].strip().upper()
    joblog = module.params['joblog']
    if len(subsystem) > 10:
        module.fail_json(rc=256, msg="Value of subsystem exceeds 10 characters")
    if len(user) > 10:
        module.fail_json(rc=256, msg="Value of user exceeds 10 characters")
    if subsystem == '*JOBQ' or subsystem == '*OUTQ':
        module.fail_json(rc=256, msg="Value of option subsystem can not be {subsystem_pattern}".format(subsystem_pattern=subsystem))
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    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)

    job_log = []
    if subsystem == '*ALL':
        command = 'QSYS/WRKSBS'
        rc, out, err, job_log = ibmi_module.itoolkit_run_command5250_once(command)

        if rc:
            result_failed = dict(
                stdout=out,
                stderr=err,
                job_log=job_log,
                rc=rc,
            )
            message = 'non-zero return code:{rc}'.format(
                rc=rc)
            module.fail_json(msg=message, **result_failed)
        else:
            result_success = dict(
                subsystems=out.splitlines(),
                job_log=job_log,
                rc=rc,
            )
            if not joblog:
                empty_list = []
                result_success.update({'job_log': empty_list})
            module.exit_json(**result_success)
    else:
        sql = "SELECT J.SUBSYSTEM FROM TABLE (QSYS2.ACTIVE_JOB_INFO()) J WHERE JOB_TYPE = 'SBS'"
        ibmi_util.log_info("Command to run: " + sql, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_run_sql_once(sql)

        if rc:
            result_failed = dict(
                stdout=out,
                stderr=err,
                job_log=job_log,
                rc=rc,
            )
            message = 'Failed to retrieve subsystem {subsystem_pattern} status, non-zero return code:{rc}'.format(
                subsystem_pattern=subsystem, rc=rc)
            module.fail_json(msg=message, **result_failed)
        else:
            is_active = False
            for items in out:
                if subsystem == items['SUBSYSTEM']:
                    is_active = True
            if not is_active:
                module.fail_json(rc=ibmi_util.IBMi_SUBSYSTEM_NOT_ACTIVE, msg="Subsystem {0} is not active".format(subsystem))

            if user == '*ALL':
                sql = "SELECT J.* FROM TABLE (QSYS2.ACTIVE_JOB_INFO(SUBSYSTEM_LIST_FILTER => '{subsystem_pattern}')) J \
                  WHERE JOB_TYPE NOT IN ('SBS', 'SYS')".format(subsystem_pattern=subsystem)
            else:
                sql = "SELECT J.* FROM TABLE (QSYS2.ACTIVE_JOB_INFO(\
                    SUBSYSTEM_LIST_FILTER => '{subsystem_pattern}', \
                    CURRENT_USER_LIST_FILTER => '{user_pattern}')) J WHERE JOB_TYPE NOT IN ('SBS', 'SYS')".format(
                    subsystem_pattern=subsystem, user_pattern=user)
            ibmi_util.log_info("Command to run: " + sql, module._name)
            rc, out, err, job_log = ibmi_module.itoolkit_run_sql_once(sql)
            if rc:
                result_failed = dict(
                    stdout=out,
                    stderr=err,
                    job_log=job_log,
                    rc=rc,
                )
                message = 'non-zero return code:{rc}'.format(
                    rc=rc)
                module.fail_json(msg=message, **result_failed)
            else:
                result_success = dict(
                    active_jobs=out,
                    job_log=job_log,
                    rc=rc,
                )
                if not joblog:
                    empty_list = []
                    result_success.update({'job_log': empty_list})
                module.exit_json(**result_success)
Exemple #10
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            job_name=dict(type='str', required=True),
            cmd=dict(type='str', required=True),
            frequency=dict(type='str',
                           required=True,
                           choices=['*ONCE', '*WEEKLY', '*MONTHLY']),
            scddate=dict(type='str', default='*CURRENT'),
            scdday=dict(type='list', elements='str', default='*NONE'),
            schtime=dict(type='str', default='*CURRENT'),
            text=dict(type='str', default='*BLANK'),
            parameters=dict(type='str', default=''),
            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)

    job_name = module.params['job_name']
    cmd = module.params['cmd']
    frequency = module.params['frequency']
    scddate = module.params['scddate']
    scdday = module.params['scdday']
    schtime = module.params['schtime']
    text = module.params['text']
    parameters = module.params['parameters']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if scddate not in ["*CURRENT", "*MONTHSTR", "*MONTHEND", "*NONE"]:
        scddate = "'{p_scddate}'".format(p_scddate=scddate)
    if schtime != "*CURRENT":
        schtime = "'{p_schtime}'".format(p_schtime=schtime)
    if text != "*BLANK":
        text = "'{p_text}'".format(p_text=text)
    result = dict(command='',
                  stdout='',
                  stderr='',
                  rc='',
                  delta='',
                  msg='',
                  job_log=[])

    if set(scdday) < set(scdday_list):
        pass
    else:
        result.update({
            'msg':
            'Value specified for scdday is not valid. Valid values are {p_scdday_list}'
            .format(p_scdday_list=", ".join(scdday_list)),
            'stderr':
            'Parameter passed is not valid.',
            'rc':
            ibmi_util.IBMi_PARAM_NOT_VALID
        })
        module.fail_json(**result)

    scdday = " ".join(scdday)
    if scddate != '*NONE' and scdday != '*NONE':
        result['msg'] = 'Either scddate or scdday need to be *NONE.'

    if scddate == '*NONE' and scdday == '*NONE':
        result['msg'] = 'scddate and scdday cannot be *NONE at the sametime.'

    if result.get('msg'):
        module.fail_json(**result)

    startd = datetime.datetime.now()
    command = 'QSYS/ADDJOBSCDE JOB({p_job_name}) CMD({p_cmd}) FRQ({p_frequency}) SCDDATE({p_scddate}) SCDDAY({p_scdday}) \
        SCDTIME({p_schtime}) TEXT({p_text}) {p_parameters}'.format(
        p_job_name=job_name,
        p_cmd=cmd,
        p_frequency=frequency,
        p_scddate=scddate,
        p_scdday=scdday,
        p_schtime=schtime,
        p_text=text,
        p_parameters=parameters)

    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, out, error, job_log = ibmi_module.itoolkit_run_command_once(command)
    endd = datetime.datetime.now()
    delta = endd - startd

    if rc:
        result.update({
            'msg':
            'Failed to add Job schedule entry {p_job_name}. Please double check the input.'
            .format(p_job_name=job_name),
            'command':
            ' '.join(command.split()),
            'stdout':
            out,
            'stderr':
            error,
            'rc':
            rc,
            'delta':
            str(delta),
            'job_log':
            job_log
        })
        module.fail_json(**result)
    elif joblog:
        result.update({
            'msg':
            'Job schedule entry {p_job_name} is successfully added.'.format(
                p_job_name=job_name),
            'command':
            ' '.join(command.split()),
            'stdout':
            out,
            'stderr':
            error,
            'rc':
            rc,
            'delta':
            str(delta),
            'job_log':
            job_log
        })
        module.exit_json(**result)
    else:
        result.update({
            'msg':
            'Job schedule entry {p_job_name} is successfully added.'.format(
                p_job_name=job_name),
            'command':
            ' '.join(command.split()),
            'stdout':
            out,
            'stderr':
            error,
            'rc':
            rc,
            'delta':
            str(delta)
        })
        module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            operation=dict(type='str',
                           choices=[
                               'grant', 'revoke', 'display', 'grant_autl',
                               'revoke_autl', 'grant_ref'
                           ],
                           required=True),
            object_name=dict(type='str', required=True),
            object_library=dict(type='str', default='*LIBL'),
            object_type=dict(
                type='str',
                choices=[
                    '*ALL', '*ALRTBL', '*BNDDIR', '*CFGL', '*CHTFMT', '*CLD',
                    '*CLS', '*CMD', '*CNNL', '*COSD', '*CRG', '*CRQD', '*CSI',
                    '*CSPMAP', '*CSPTBL', '*CTLD', '*DEVD', '*DTAARA',
                    '*DTADCT', '*DTAQ', '*EDTD', '*FCT', '*FILE', '*FNTRSC',
                    '*FNTTBL', '*FORMDF', '*FTR', '*GSS', '*IGCDCT', '*IGCSRT',
                    '*IGCTBL', '*IMGCLG', '*IPXD', '*JOBD', '*JOBQ', '*JOBSCD',
                    '*JRN', '*JRNRCV', '*LIB', '*LIND', '*LOCALE', '*M36',
                    '*M36CFG', '*MEDDFN', '*MENU', '*MGTCOL', '*MODD',
                    '*MODULE', '*MSGF', '*MSGQ', '*NODGRP', '*NODL', '*NTBD',
                    '*NWID', '*NWSCFG', '*NWSD', '*OUTQ', '*OVL', '*PAGDFN',
                    '*PAGSEG', '*PDFMAP', '*PDG', '*PGM', '*PNLGRP', '*PRDAVL',
                    '*PRDDFN', '*PRDLOD', '*PSFCFG', '*QMFORM', '*QMQRY',
                    '*QRYDFN', '*RCT', '*S36', '*SBSD', '*SCHIDX', '*SPADCT',
                    '*SQLPKG', '*SQLUDT', '*SQLXSR', '*SRVPGM', '*SSND',
                    '*SVRSTG', '*TBL', '*TIMZON', '*USRIDX', '*USRPRF',
                    '*USRQ', '*USRSPC', '*VLDL', '*WSCST'
                ],
                required=True),
            asp_device=dict(type='str', default='*'),
            user=dict(type='list', default=[''], elements='str'),
            authority=dict(type='list',
                           default=['*CHANGE'],
                           choices=[
                               '*CHANGE', '*ALL', '*USE', '*EXCLUDE', '*AUTL',
                               '*OBJALTER', '*OBJEXIST', '*OBJMGT', '*OBJOPR',
                               '*OBJREF', '*ADD', '*DLT', '*READ', '*UPD',
                               '*EXECUTE'
                           ],
                           elements='str'),
            replace_authority=dict(type='bool', default=False),
            authorization_list=dict(type='str', default=''),
            ref_object_name=dict(type='str', default=''),
            ref_object_library=dict(type='str', default='*LIBL'),
            ref_object_type=dict(
                type='str',
                choices=[
                    '*OBJTYPE', '*ALRTBL', '*AUTL', '*BNDDIR', '*CFGL',
                    '*CHTFMT', '*CLD', '*CLS', '*CMD',
                    '*CNNL', '*COSD', '*CRG', '*CRQD', '*CSI', '*CSPMAP',
                    '*CSPTBL', '*CTLD', '*DEVD', '*DTAARA', '*DTADCT', '*DTAQ',
                    '*EDTD', '*FCT', '*FILE', '*FNTRSC', '*FNTTBL', '*FORMDF',
                    '*FTR', '*GSS', '*IGCDCT', '*IGCSRT', '*IGCTBL', '*IMGCLG',
                    '*IPXD', '*JOBD', '*JOBQ', '*JOBSCD', '*JRN', '*JRNRCV',
                    '*LIB', '*LIND', '*LOCALE', '*M36', '*M36CFG', '*MEDDFN',
                    '*MENU', '*MGTCOL', '*MODD', '*MODULE', '*MSGF', '*MSGQ',
                    '*NODGRP', '*NODL', '*NTBD', '*NWID', '*NWSCFG', '*NWSD',
                    '*OUTQ', '*OVL', '*PAGDFN', '*PAGSEG', '*PDFMAP', '*PDG',
                    '*PGM', '*PNLGRP', '*PRDDFN', '*PRDLOD', '*PSFCFG',
                    '*QMFORM', '*QMQRY', '*QRYDFN', '*RCT', '*S36', '*SBSD',
                    '*SCHIDX', '*SPADCT', '*SQLPKG', '*SQLUDT', '*SQLXSR',
                    '*SRVPGM', '*SSND', '*SVRSTG', '*TBL', '*TIMZON',
                    '*USRIDX', '*USRPRF', '*USRQ', '*USRSPC', '*VLDL', '*WSCST'
                ],
                default='*OBJTYPE'),
            ref_asp_device=dict(type='str', default='*'),
            asp_group=dict(type='str', default='*SYSBAS'),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        required_if=[
            ['operation', 'grant', ['object_name', 'user', 'authority']],
            ['operation', 'revoke', ['object_name', 'user', 'authority']],
            ['operation', 'display', ['object_name']],
            ['operation', 'grant_autl', ['object_name', 'authorization_list']],
            [
                'operation', 'revoke_autl',
                ['object_name', 'authorization_list']
            ], ['operation', 'grant_ref', ['object_name', 'ref_object_name']]
        ],
        supports_check_mode=True,
    )

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

    operation = module.params['operation'].strip().upper()
    object_name = module.params['object_name'].strip().upper()
    if len(object_name) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of object_name exceeds 10 characters")
    object_library = module.params['object_library'].strip().upper()
    if len(object_library) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of object_library exceeds 10 characters")
    object_type = module.params['object_type'].strip().upper()
    asp_device = module.params['asp_device'].strip().upper()
    if len(asp_device) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of asp_device exceeds 10 characters")
    user = module.params['user']
    user = [item.strip().upper() for item in user]
    for item in user:
        if len(item) > 10:
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="Value of {p_item} in option user exceeds 10 characters".
                format(p_item=item))
    authority = module.params['authority']
    authority = [item.strip().upper() for item in authority]
    for item in authority:
        if len(item) > 10:
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="Value of {p_item} in option authority exceeds 10 characters"
                .format(p_item=item))
    replace_authority = module.params['replace_authority']
    authorization_list = module.params['authorization_list'].strip().upper()
    if len(authorization_list) > 10:
        module.fail_json(
            rc=ibmi_util.IBMi_PARAM_NOT_VALID,
            msg="Value of authorization_list exceeds 10 characters")
    ref_object_name = module.params['ref_object_name'].strip().upper()
    if len(ref_object_name) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of ref_object_name exceeds 10 characters")
    ref_object_library = module.params['ref_object_library'].strip().upper()
    if len(ref_object_library) > 10:
        module.fail_json(
            rc=ibmi_util.IBMi_PARAM_NOT_VALID,
            msg="Value of ref_object_library exceeds 10 characters")
    ref_object_type = module.params['ref_object_type'].strip().upper()
    ref_asp_device = module.params['ref_asp_device'].strip().upper()
    if len(ref_asp_device) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of ref_asp_device exceeds 10 characters")
    asp_group = module.params['asp_group'].strip().upper()
    if len(asp_group) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of asp_group exceeds 10 characters")
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if operation == 'GRANT' or operation == 'REVOKE':
        # handle single value for user
        if isinstance(user, list) and len(user) > 1 and ('*PUBLIC' in user
                                                         or '*ALL' in user):
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="*PUBLIC or *ALL must be only value for parameter user")

        # handle single value or other values for authority
        if isinstance(authority, list) and len(authority) > 1:
            single_value = ['*CHANGE', '*ALL', '*USE', '*EXCLUDE', '*AUTL']
            for item in single_value:
                if item in authority:
                    module.fail_json(
                        rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                        msg="{p_item} must be only value for parameter authority"
                        .format(p_item=item))

        # handle the relateionship of *PUBLIC and *AUTL
        if isinstance(authority, list) and len(authority) == 1 and authority[
                0] == '*AUTL' and user[0] != '*PUBLIC':
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="Authority of *AUTL is allowed only with user *PUBLIC")

        # handle the REPLACE option
        replace = '*NO'
        if replace_authority:
            replace = '*YES'

        # handle parameter user
        users = ''
        for item in user:
            users = users + ' ' + item
        if users.strip() == '':
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="Specify user when the operation is grant or revoke")

        # handle parameter authority
        authorities = ''
        for item in authority:
            authorities = authorities + ' ' + item

    if operation == 'GRANT_REF' and ref_object_type == '*OBJTYPE' and object_type == '*ALL':
        module.fail_json(
            rc=ibmi_util.IBMi_PARAM_NOT_VALID,
            msg=
            "ref_object_type(*OBJTYPE) and object_type(*ALL) cannot be used together"
        )

    if operation == 'GRANT_REF' and ref_object_name == '':
        module.fail_json(
            rc=ibmi_util.IBMi_PARAM_NOT_VALID,
            msg="Specify ref_object_name when the operation is grant_ref")

    if (operation == 'GRANT_AUTL'
            or operation == 'REVOKE_AUTL') and authorization_list == '':
        module.fail_json(
            rc=ibmi_util.IBMi_PARAM_NOT_VALID,
            msg=
            "Specify authorization_list when the operation is grant_autl or revoke_autl"
        )

    if operation == 'GRANT':
        command = 'QSYS/GRTOBJAUT OBJ({p_lib}/{p_obj}) \
            OBJTYPE({p_type}) ASPDEV({p_asp}) USER({p_user}) \
            AUT({p_aut}) REPLACE({p_rep})'.format(p_lib=object_library,
                                                  p_obj=object_name,
                                                  p_type=object_type,
                                                  p_asp=asp_device,
                                                  p_user=users,
                                                  p_aut=authorities,
                                                  p_rep=replace)
    elif operation == 'REVOKE':
        command = 'QSYS/RVKOBJAUT OBJ({p_lib}/{p_obj}) \
            OBJTYPE({p_type}) ASPDEV({p_asp}) USER({p_user}) \
            AUT({p_aut})'.format(p_lib=object_library,
                                 p_obj=object_name,
                                 p_type=object_type,
                                 p_asp=asp_device,
                                 p_user=users,
                                 p_aut=authorities)
    elif operation == 'GRANT_AUTL':
        command = 'QSYS/GRTOBJAUT OBJ({p_lib}/{p_obj}) \
            OBJTYPE({p_type}) ASPDEV({p_asp}) \
            AUTL({p_autl})'.format(p_lib=object_library,
                                   p_obj=object_name,
                                   p_type=object_type,
                                   p_asp=asp_device,
                                   p_autl=authorization_list)
    elif operation == 'REVOKE_AUTL':
        command = 'QSYS/RVKOBJAUT OBJ({p_lib}/{p_obj}) \
            OBJTYPE({p_type}) ASPDEV({p_asp}) \
            AUTL({p_autl})'.format(p_lib=object_library,
                                   p_obj=object_name,
                                   p_type=object_type,
                                   p_asp=asp_device,
                                   p_autl=authorization_list)
    elif operation == 'GRANT_REF':
        command = 'QSYS/GRTOBJAUT OBJ({p_lib}/{p_obj}) \
            OBJTYPE({p_type}) ASPDEV({p_asp}) \
            REFOBJ({p_ref_lib}/{p_ref_obj}) REFOBJTYPE({p_ref_type}) \
            REFASPDEV({p_ref_asp})'.format(p_lib=object_library,
                                           p_obj=object_name,
                                           p_type=object_type,
                                           p_asp=asp_device,
                                           p_ref_lib=ref_object_library,
                                           p_ref_obj=ref_object_name,
                                           p_ref_type=ref_object_type,
                                           p_ref_asp=ref_asp_device)
    else:
        command = "SELECT * FROM QSYS2.OBJECT_PRIVILEGES WHERE SYSTEM_OBJECT_NAME = '{p_obj}'".format(
            p_obj=object_name)
        if (object_library != '') and (not object_library.startswith('*')):
            command = command + ' ' + "AND SYSTEM_OBJECT_SCHEMA = '{p_lib}'".format(
                p_lib=object_library)
        if object_type != '*ALL':
            command = command + ' ' + "AND OBJECT_TYPE = '{p_type}'".format(
                p_type=object_type)

    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)

    if asp_group or operation == 'DISPLAY':
        if operation != 'DISPLAY':
            command = ' '.join(command.split(
            ))  # keep only one space between adjacent strings
            rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(
                command)
        else:
            command = ' '.join(command.split(
            ))  # keep only one space between adjacent strings
            rc, out, err, job_log = ibmi_module.itoolkit_run_sql_once(command)
    else:
        rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

    if operation == 'DISPLAY':
        if rc:
            result_failed = dict(
                stdout=out,
                stderr=err,
                command=command,
                job_log=job_log,
                rc=rc,
            )
            message = 'non-zero return code:{rc}'.format(rc=rc)
            module.fail_json(msg=message, **result_failed)
        else:
            result_success = dict(
                object_authority_list=out,
                command=command,
                job_log=job_log,
                rc=rc,
            )
            if not joblog:
                empty_list = []
                result_success.update({'job_log': empty_list})
            module.exit_json(**result_success)
    else:
        if rc:
            result_failed = dict(
                command=command,
                stderr=err,
                job_log=job_log,
                rc=rc,
            )
            message = 'non-zero return code:{rc}'.format(rc=rc)
            module.fail_json(msg=message, **result_failed)
        else:
            result_success = dict(
                command=command,
                stdout=out,
                rc=rc,
                job_log=job_log,
                changed=True,
            )
            if not joblog:
                empty_list = []
                result_success.update({'job_log': empty_list})
            module.exit_json(**result_success)
Exemple #12
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            product=dict(type='str', required=True),
            option=dict(type='str', default='*ALL'),
            release=dict(type='str', default='*ONLY'),
            language=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'].upper()
    option = module.params['option'].upper()
    release = module.params['release'].upper()
    language = module.params['language'].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(option) > 4:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID, msg="Value of option exceeds 4 characters")
    if len(release) > 6:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID, msg="Value of release exceeds 6 characters")
    if len(language) > 4:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID, msg="Value of language exceeds 4 characters")

    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)

    command = 'QSYS/DLTLICPGM LICPGM({pattern_product}) \
      OPTION({pattern_option}) RLS({pattern_release}) LNG({pattern_language})'.format(
        pattern_product=product,
        pattern_option=option,
        pattern_release=release,
        pattern_language=language)

    command = ' '.join(command.split())  # keep only one space between adjacent strings
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

    result = dict(
        command=command,
        stdout=out,
        stderr=err,
        rc=rc,
        job_log=job_log,
        changed=True,
    )

    if rc != 0:
        message = 'non-zero return code:{rc}'.format(rc=rc)
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            message_key=dict(type='str', required=True),
            message_queue=dict(type='str', required=True),
            message_lib=dict(type='str', default='*LIB'),
            reply=dict(type='str', default='*DFT'),
            remove_message=dict(type='str', choices=['*YES', '*NO'], default='*YES'),
            reject_default_reply=dict(type='str', choices=['*NOALWRJT', '*ALWRJT'], default='*NOALWRJT'),
            ccsid=dict(type='str', default='*JOB'),
            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)
    message_key = module.params['message_key']
    message_queue = module.params['message_queue']
    message_lib = module.params['message_lib']
    reply = module.params['reply']
    remove_message = module.params['remove_message']
    reject_default_reply = module.params['reject_default_reply']
    ccsid = module.params['ccsid']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    # handle the message key which more than 4 characters
    if len(message_key) > 4:
        message_key = "x'{0}'".format(message_key)

    command = "QSYS/SNDRPY MSGKEY({p_message_key}) MSGQ({p_message_lib}/{p_message_queue}) \
        RPY({p_reply}) RMV({p_remove_message}) RJTDFTRPY({p_reject_default_reply}) CCSID({p_ccsid})".format(
        p_message_key=message_key,
        p_message_queue=message_queue,
        p_message_lib=message_lib,
        p_reply=reply,
        p_remove_message=remove_message,
        p_reject_default_reply=reject_default_reply,
        p_ccsid=ccsid)

    startd = datetime.datetime.now()

    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)

    job_log = []
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

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

    result = dict(
        cmd=command,
        job_log=job_log,
        stdout=out,
        stderr=err,
        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)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
Exemple #14
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(type='str', required=True),
            operation=dict(
                type='str',
                required=True,
                choices=['create', 'add_disks', 'delete', 'display']),
            disks=dict(type='list', elements='str'),
            asp_type=dict(type='str',
                          default="*PRIMARY",
                          choices=['*PRIMARY', '*SECONDARY', '*UDFS']),
            primary_asp=dict(type='str'),
            extra_parameters=dict(type='str', default=' '),
            synchronous=dict(type='bool', default=True),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        required_if=[["operation", "create", ["disks", "asp_type"]],
                     ["operation", "add_disks", ["disks"]],
                     ["asp_type", "*SECONDARY", ["primary_asp"]]],
        supports_check_mode=True,
    )

    ibmi_util.log_info("version: " + __ibmi_module_version__, module._name)
    name = module.params['name']
    operation = module.params['operation']
    disks = module.params['disks']
    asp_type = module.params['asp_type']
    primary_asp = module.params['primary_asp']
    extra_parameters = module.params['extra_parameters']
    synchronous = module.params['synchronous']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()
    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)

    command = ''
    rc = ''
    rc_msg = ''
    out = ''
    state = ''
    asp_number = '000'
    asp_info = ''
    job_log = []
    sql = "SELECT * FROM QSYS2.ASP_INFO WHERE RESOURCE_NAME = '" + name.upper(
    ) + "'"
    rc, asp_info, error, job_log = ibmi_module.itoolkit_run_sql_once(sql)
    if asp_info:
        state = asp_info[0]['ASP_STATE']
        asp_number = asp_info[0]['ASP_NUMBER']
    error = ''
    if operation == "create":
        if not state:
            command = "QSYS/CFGDEVASP ASPDEV(" + name + ") ACTION(*CREATE) TYPE(" + asp_type + ") "
            if asp_type == "*SECONDARY":
                command = command + "PRIASPDEV(" + primary_asp + ") "
            command = command + "UNITS(" + " ".join(
                disks) + ") CONFIRM(*NO) " + extra_parameters
        else:
            rc = ibmi_util.IBMi_COMMAND_RC_ERROR
            out = "ASP " + name + " already exsit."
            error = out
    elif operation == "add_disks":
        if not state:
            rc = ibmi_util.IBMi_COMMAND_RC_ERROR
            out = "ASP " + name + " does not exsit"
            error = out
        else:
            command = "CALL PGM(QSYS/QAENGADDDU) PARM('{p_name}' '{p_asp_number}' '0' ".format(
                p_name=ibmi_util.fmtTo10(name), p_asp_number=asp_number)
            for disk in disks:
                command = command + "'" + ibmi_util.fmtTo10(disk) + "' "
            command = command + ")"
    elif operation == "delete":
        if state:
            command = "QSYS/CFGDEVASP ASPDEV(" + name + ") ACTION(*DELETE) CONFIRM(*NO)"
        else:
            rc = ibmi_util.IBMi_COMMAND_RC_ERROR
            out = "ASP " + name + " already deleted."
    elif operation == 'display':
        if state:
            rc = ibmi_util.IBMi_COMMAND_RC_SUCCESS
            out = rc_msg
        else:
            rc = ibmi_util.IBMi_COMMAND_RC_ERROR
            out = "ASP " + name + " does not exsit."
            error = out
    if command:
        if not synchronous:
            command = "SBMJOB CMD(" + command + ")"
        rc, out, error, job_log = ibmi_module.itoolkit_run_command_once(
            command)

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

    result = dict(
        cmd=command,
        stdout=out,
        stderr=error,
        asp_info=asp_info,
        rc=rc,
        start=str(startd),
        end=str(endd),
        delta=str(delta),
        job_log=job_log,
    )

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

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
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)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            age=dict(default=None, type='str'),
            age_stamp=dict(default="ctime", choices=['ctime'], type='str'),
            object_type_list=dict(type='str', default='*ALL'),
            lib_name=dict(type='str', default='*ALLUSR'),
            object_name=dict(type='str', default='*ALL'),
            size=dict(default=None, type='str'),
            iasp_name=dict(type='str', default='*SYSBAS'),
            use_regex=dict(default=False, type='bool'),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )

    input_age = module.params['age']
    input_age_stamp = module.params['age_stamp']
    input_object_type = module.params['object_type_list']
    input_iasp_name = module.params['iasp_name']
    input_size = module.params['size']
    input_lib = module.params['lib_name']
    input_obj_name = module.params['object_name']
    input_use_regex = module.params['use_regex']
    joblog = module.params['joblog']
    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=input_iasp_name,
            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)

    db_conn = ibmi_module.get_connection()

    # generate age where stmt
    if input_age is None:
        # age = None
        sql_where_stmt_age = ''
    else:
        sql_where_stmt_age = age_where_stmt(input_age, input_age_stamp)
        if sql_where_stmt_age is None:
            module.fail_json(msg="failed to process age: " + input_age)

    # generate size where stmt
    if input_size is None:
        sql_where_stmt_size = ''
    else:
        sql_where_stmt_size = size_where_stmt(input_size)
        if sql_where_stmt_size is None:
            module.fail_json(msg="failed to process size: " + input_size)

    # get the version and release info
    release_info, err = db2i_tools.get_ibmi_release(db_conn)

    if release_info["version_release"] < 7.4:
        lib_name_label = "(SELECT SYSTEM_SCHEMA_NAME FROM QSYS2.SYSSCHEMAS WHERE SCHEMA_NAME = OBJLONGSCHEMA)"
    else:
        lib_name_label = "OBJLIB"

    if input_use_regex:
        obj_stats_expression = " SELECT OBJNAME, OBJTYPE, OBJOWNER, OBJDEFINER, OBJCREATED," \
                               " TEXT, " + lib_name_label + " AS OBJLIB, IASP_NUMBER, LAST_USED_TIMESTAMP, " \
                               " LAST_RESET_TIMESTAMP," \
                               " BIGINT(OBJSIZE) AS OBJSIZE, OBJATTRIBUTE, OBJLONGSCHEMA " \
                               " FROM TABLE (QSYS2.OBJECT_STATISTICS('" + input_lib + "','" + \
                               input_object_type + "','*ALL')) X "
        sql_where_stmt_regex = " AND REGEXP_LIKE(A.OBJNAME, '" + input_obj_name + "') "
    else:
        obj_stats_expression = " SELECT OBJNAME, OBJTYPE, OBJOWNER, OBJDEFINER, OBJCREATED," \
                               " TEXT, " + lib_name_label + " AS OBJLIB, IASP_NUMBER, LAST_USED_TIMESTAMP, " \
                               " LAST_RESET_TIMESTAMP," \
                               " BIGINT(OBJSIZE) AS OBJSIZE, OBJATTRIBUTE, OBJLONGSCHEMA " \
                               " FROM TABLE (QSYS2.OBJECT_STATISTICS('" + input_lib + "','" + \
                               input_object_type + "','" + input_obj_name + "')) X "
        sql_where_stmt_regex = ""

    sql = "select * from (" + obj_stats_expression + ") A WHERE 1 = 1 " + \
          sql_where_stmt_age + \
          sql_where_stmt_size + \
          sql_where_stmt_regex

    rc, out_result_set, err = ibmi_module.itoolkit_run_sql(sql)

    if joblog or (rc != IBMi_COMMAND_RC_SUCCESS):
        job_log = ibmi_module.itoolkit_get_job_log(startd)
    else:
        job_log = []

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

    if rc != IBMi_COMMAND_RC_SUCCESS:
        result_failed = dict(
            sql=sql,
            # size=input_size,
            # age=input_age,
            job_log=job_log,
            stderr=err,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            # changed=True,
        )
        module.fail_json(msg='Non-zero return code. ', **result_failed)
    else:
        # out = []
        # for result in out_result_set:
        #     result_map = {"OBJNAME": result[0], "OBJTYPE": result[1],
        #                   "OBJOWNER": result[2], "OBJDEFINER": result[3],
        #                   "OBJCREATED": result[4], "TEXT": result[5],
        #                   "OBJLIB": result[6], "IASP_NUMBER": result[7],
        #                   "LAST_USED_TIMESTAMP": result[8], "LAST_RESET_TIMESTAMP": result[9],
        #                   "OBJSIZE": result[10], "OBJATTRIBUTE": result[11], "OBJLONGSCHEMA": result[12]
        #                   }
        #     out.append(result_map)

        result_success = dict(
            sql=sql,
            object_list=out_result_set,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            job_log=job_log,
        )
        module.exit_json(**result_success)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            internet_address=dict(type='str', required=False),
            line_description=dict(type='str', required=False),
            vlan_id=dict(type='str', required=False),
            subnet_mask=dict(type='str', required=False),
            alias_name=dict(type='str', required=False),
            associated_local_interface=dict(type='str', required=False),
            type_of_service=dict(type='str',
                                 required=False,
                                 choices=[
                                     "*NORMAL", "*MINDELAY", "*MAXTHRPUT",
                                     "*MAXRLB", "*MINCOST"
                                 ]),
            max_transmission_unit=dict(type='str', required=False),
            auto_start=dict(type='str',
                            required=False,
                            choices=["*YES", "*NO"]),
            preferred_interface=dict(type='list',
                                     elements='str',
                                     required=False),
            text_description=dict(type='str', required=False),
            sec_to_wait=dict(type='int', default=0),
            extra_params=dict(type='str', required=False),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
            state=dict(type='str',
                       default='present',
                       choices=["present", "absent", "inactive", "active"])),
        required_one_of=[["internet_address", "alias_name"]],
        supports_check_mode=True,
    )

    internet_address = module.params['internet_address']
    line_description = module.params['line_description']
    vlan_id = module.params['vlan_id']
    subnet_mask = module.params['subnet_mask']
    alias_name = module.params['alias_name']
    associated_local_interface = module.params['associated_local_interface']
    type_of_service = module.params['type_of_service']
    max_transmission_unit = module.params['max_transmission_unit']
    auto_start = module.params['auto_start']
    preferred_interface = module.params['preferred_interface']
    text_description = module.params['text_description']
    state = module.params['state']
    extra_params = module.params['extra_params']
    sec_to_wait = module.params['sec_to_wait']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()

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

    connection_id = ibmi_module.get_connection()

    only_query = False
    cl_command = ""

    if state == "present":
        # check options
        opt_vlan_id = "" if vlan_id is None else vlan_id
        opt_line_description = "" if line_description is None else "LIND(" + line_description + " " + opt_vlan_id + ") "
        opt_subnet_mask = "" if subnet_mask is None else "SUBNETMASK('" + subnet_mask + "') "
        opt_alias_name = "" if alias_name is None else "ALIASNAME(" + alias_name + ") "
        opt_associate = "" if associated_local_interface is None else "LCLIFC(" + associated_local_interface + ") "
        opt_type_of_service = "" if type_of_service is None else "TOS(" + type_of_service + ") "
        opt_max_transmission_unit = "" if max_transmission_unit is None else "MTU(" + max_transmission_unit + ") "
        opt_auto_start = "" if auto_start is None else "AUTOSTART(" + auto_start + ") "
        opt_preferred_ifc = "" if preferred_interface is None else "PREFIFC('" + "' '".join(
            preferred_interface) + "') "
        opt_text_desc = "" if text_description is None else "TEXT('" + text_description + "') "

        # options_without_alias_name = opt_line_description + opt_subnet_mask + \
        #                              opt_associate + opt_type_of_service + \
        #                              opt_max_transmission_unit + opt_auto_start + opt_preferred_ifc + opt_text_desc
        options_without_alias_name = "{0}{1}{2}{3}{4}{5}{6}{7}".format(
            opt_line_description, opt_subnet_mask, opt_associate,
            opt_type_of_service, opt_max_transmission_unit, opt_auto_start,
            opt_preferred_ifc, opt_text_desc)

        options = options_without_alias_name + opt_alias_name

        if (internet_address is not None) and (options == ""):
            # nothing to add or change means to query
            only_query = True
        elif (opt_alias_name is not None) and (internet_address is None) and (
                options_without_alias_name == ""):
            only_query = True
        else:
            if internet_address is None:
                module.fail_json(
                    msg="Parameter internet_address is not specified.")

            # see if the ip address exists for present
            rs, query_err = return_interface_information(
                connection_id, internet_address, alias_name)
            present_operation = "QSYS/ADDTCPIFC" if len(
                rs) == 0 else "QSYS/CHGTCPIFC"

            cl_command = present_operation + " INTNETADR('" + internet_address + "') " + options

    elif state in ["absent", "active", "inactive"]:
        interface_action_map = {
            "absent": "QSYS/RMVTCPIFC",
            "active": "QSYS/STRTCPIFC",
            "inactive": "QSYS/ENDTCPIFC"
        }
        if internet_address is not None:
            cl_command = interface_action_map[
                state] + " INTNETADR('" + internet_address + "')"
        elif (alias_name is not None) and (alias_name != '*NONE'):
            cl_command = interface_action_map[
                state] + " ALIASNAME(" + alias_name + ")"
        else:
            module.fail_json(
                msg=
                "internet_address or alias_name must be specified when state is"
                " absent, active or inactive.")

        check_rs, query_err = return_interface_information(
            connection_id, internet_address, alias_name)
        if len(check_rs) == 0:
            if state == "absent":
                # we are trying to remove a non-existing interface
                only_query = True
        else:
            interface_status = check_rs[0]["INTERFACE_STATUS"]
            if interface_status == state.upper():
                # This means that the interface status is already what we want, skip the cl execution
                only_query = True
    else:
        module.fail_json(msg="Value for option state is not valid.")

    if extra_params is not None:
        cl_command = cl_command + extra_params

    is_changed = False
    if only_query:
        cl_command = ""
        out = None
        err = None
        rc = IBMi_COMMAND_RC_SUCCESS
    else:
        rc, out, err = ibmi_module.itoolkit_run_command(cl_command)
        if (rc == IBMi_COMMAND_RC_SUCCESS) and (state in ["present", "absent"
                                                          ]):
            is_changed = True

    if sec_to_wait > 0:
        time.sleep(sec_to_wait)

    rs, query_err = return_interface_information(connection_id,
                                                 internet_address, alias_name)

    if query_err is not None:
        rc = IBMi_COMMAND_RC_ERROR
        err = query_err

    if joblog or (rc != IBMi_COMMAND_RC_SUCCESS):
        job_log = ibmi_module.itoolkit_get_job_log(startd)
    else:
        job_log = []

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

    if rc != IBMi_COMMAND_RC_SUCCESS:
        result_failed = dict(
            job_log=job_log,
            changed=is_changed,
            stderr=err,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            stdout=out,
            cl_command=cl_command,
        )
        module.fail_json(msg='Non zero return code.', **result_failed)
    else:
        result_success = dict(
            changed=is_changed,
            stdout=out,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            interface_info=rs,
            cl_command=cl_command,
            job_log=job_log,
        )
        module.exit_json(**result_success)
Exemple #18
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            saved_lib=dict(type='str', required=True),
            savefile_name=dict(type='str', required=True),
            savefile_lib=dict(type='str', required=True),
            format=dict(type='str', default='*SAVF', choices=['*SAVF']),
            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)

    saved_lib = module.params['saved_lib']
    savefile_name = module.params['savefile_name']
    savefile_lib = module.params['savefile_lib']
    format = module.params['format']
    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()
    # RSTLIB
    command = 'QSYS/RSTLIB SAVLIB({p_saved_lib}) DEV({p_format}) SAVF({p_savefile_lib}/{p_savefile_name}) \
        {p_parameters}'.format(p_saved_lib=saved_lib,
                               p_format=format,
                               p_savefile_lib=savefile_lib,
                               p_savefile_name=savefile_name,
                               p_parameters=parameters)

    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)

    rc, out, error, job_log = ibmi_module.itoolkit_run_command_once(' '.join(
        command.split()))
    endd = datetime.datetime.now()
    delta = endd - startd

    result = dict(
        saved_lib=saved_lib,
        savefile_name=savefile_name,
        savefile_lib=savefile_lib,
        format=format,
        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)
Exemple #19
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            product_id=dict(type='str'),
            fix_list=dict(type='list', elements='str', default=['*ALL']),
            fix_omit_list=dict(type='list', elements='str'),
            save_file_object=dict(type='str'),
            save_file_lib=dict(type='str', default='QGPL'),
            delayed_option=dict(type='str', default='*NO', choices=['*YES', '*NO', '*IMMDLY']),
            temp_or_perm=dict(type='str', default='*TEMP', choices=['*TEMP', '*PERM']),
            joblog=dict(type='bool', default=False),
            operation=dict(type='str', default='load_and_apply', choices=['load_and_apply',
                                                                          'load_only', 'apply_only',
                                                                          'remove',
                                                                          'query']),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        required_if=[
            ["operation", "apply_only", ["product_id"]],
            ["operation", "remove", ["product_id"]],
            ["operation", "load_and_apply", ["product_id", "save_file_object"]],
            ["operation", "load_only", ["product_id", "save_file_object"]]
        ],
        supports_check_mode=True,
    )

    product_id = module.params['product_id']
    ptf_list_to_select = module.params['fix_list']
    ptf_list_to_omit = module.params['fix_omit_list']
    save_file_object = module.params['save_file_object']
    save_file_lib = module.params['save_file_lib']
    delayed_option = module.params['delayed_option']
    temp_or_perm = module.params['temp_or_perm']
    operation = module.params['operation']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    if operation in ['load_and_apply', 'load_only', 'remove']:
        if product_id == '*ALL':
            module.fail_json(msg="product_id cannot be *ALL when operation is remove, load_and_apply and load_only.")

    startd = datetime.datetime.now()
    out = ''
    ibmi_module = imodule.IBMiModule(become_user_name=become_user,
                                     become_user_password=become_user_password)

    db_conn = ibmi_module.get_connection()

    if operation in ['load_and_apply', 'load_only', 'apply_only']:
        operation_bool_map = {'load_and_apply': [False, False], 'load_only': [True, False], 'apply_only': [False, True]}
        # install single or a list of PTFs

        savf_obj = "" if operation == 'apply_only' else (save_file_lib + "/" + save_file_object)

        rc, out, err = install_ptf(ibmi_module, module, product_id, ptf_list_to_select,
                                   ptf_list_to_omit, "*SAVF", savf_obj, delayed_option, temp_or_perm,
                                   operation_bool_map[operation][0], operation_bool_map[operation][1])

    elif operation in ['remove']:
        rc, out, err = remove_ptf(ibmi_module, module, product_id, ptf_list_to_select, ptf_list_to_omit,
                                  temp_or_perm=temp_or_perm, delayed_option=delayed_option)

    # return the status of the ptf
    if ptf_list_to_select is not None:
        ptf_list, query_err = return_fix_information(db_conn, product_id, ptf_list_to_select)
    else:
        module.fail_json(msg="PTF list contains no PTF.")

    if operation == "query":
        if query_err is not None:
            rc = IBMi_COMMAND_RC_ERROR
            err = query_err
        else:
            rc = IBMi_COMMAND_RC_SUCCESS

    if joblog or (rc != IBMi_COMMAND_RC_SUCCESS):
        job_log = ibmi_module.itoolkit_get_job_log(startd)
    else:
        job_log = []

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

    if rc > 0:
        result_failed = dict(
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            stdout=out,
            stderr=err,
            rc=rc,
            job_log=job_log,
            # changed=True,
        )
        module.fail_json(msg='non-zero return code', **result_failed)
    else:
        result_success = dict(
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            ptf_list=ptf_list,
            rc=rc,
            job_log=job_log,
            # changed=True,
        )
        module.exit_json(**result_success)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            users=dict(type='list', elements='str', required=True),
            fields=dict(type='list', elements='dict', required=True),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )
    # get input value
    users = module.params['users']
    fields = module.params['fields']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']
    # initialize variables
    check_special_authorities = False
    check_user_action_audit_level = False
    check_user_option = False
    check_supplemental_group_list = False
    check_locale_job_attributes = False
    check_home_directory = False
    out1 = []
    out2 = []
    # check input value
    for field in fields:
        if field.get('name') is None:
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="There is no element 'name' in the dictionary 'field'.")
        if field.get('expect') is None:
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg="There is no element 'expect' in the dictionary 'field'.")
        if not isinstance(field['name'], str):
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg=
                "The type of element 'name' of dictionary 'field' must be string."
            )
        if isinstance(field['expect'], list):
            for expect_value in field['expect']:
                if not isinstance(expect_value, str):
                    module.fail_json(
                        rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                        msg=
                        "The type of element 'expect' of dictionary 'field' must be a list comprised by string."
                    )
        else:
            module.fail_json(
                rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                msg=
                "The type of element 'expect' of dictionary 'field' must be a list comprised by string."
            )
        if (field['name'].upper() not in parmname_array):
            module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                             msg="Input attribute name is not available")
        if field['name'].upper() == 'SPECIAL_AUTHORITIES':
            check_special_authorities = True
            special_authorities_expect = list(filter(None, field['expect']))
        elif field['name'].upper() == 'USER_ACTION_AUDIT_LEVEL':
            check_user_action_audit_level = True
            user_action_audit_level_expect = list(filter(
                None, field['expect']))
        elif field['name'].upper() == 'USER_OPTIONS':
            check_user_option = True
            user_option_expect = list(filter(None, field['expect']))
        elif field['name'].upper() == 'SUPPLEMENTAL_GROUP_LIST':
            check_supplemental_group_list = True
            supplemental_group_list_expect = list(filter(
                None, field['expect']))
        elif field['name'].upper() == 'LOCALE_JOB_ATTRIBUTES':
            check_locale_job_attributes = True
            locale_job_attributes_expect = list(filter(None, field['expect']))
        elif field['name'].upper() == 'HOME_DIRECTORY':
            check_home_directory = True
            home_directory_expect = list(filter(None, field['expect']))
        elif (field['name'].upper() == 'SIGN_ON_ATTEMPTS_NOT_VALID'
              or field['name'].upper() == 'PASSWORD_EXPIRATION_INTERVAL'
              or field['name'].upper() == 'DAYS_UNTIL_PASSWORD_EXPIRES'
              or field['name'].upper() == 'SUPPLEMENTAL_GROUP_COUNT'
              or field['name'].upper() == 'MAXIMUM_ALLOWED_STORAGE'
              or field['name'].upper() == 'STORAGE_USED'
              or field['name'].upper() == 'MESSAGE_QUEUE_SEVERITY'
              or field['name'].upper() == 'USER_ID_NUMBER'
              or field['name'].upper() == 'GROUP_ID_NUMBER'
              or field['name'].upper() == 'USER_EXPIRATION_INTERVAL'
              or field['name'].upper() == 'DAYS_USED_COUNT'
              or field['name'].upper() == 'SIZE'):
            if len(field['expect']) > 1:
                module.fail_json(
                    rc=256,
                    msg="Field {p_name} should be only one value".format(
                        p_name=field['name'].upper()))
            if field['expect'][0].strip() != '' and not is_number(
                    field['expect'][0]):
                module.fail_json(
                    rc=256,
                    msg="Field {p_name} should be numerical".format(
                        p_name=field['name'].upper()))

    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)

    # Check to see if the user exists
    User_not_existed = []
    for user in users:
        chkobj_cmd = 'QSYS/CHKOBJ OBJ(QSYS/{p_user}) OBJTYPE(*USRPRF)'.format(
            p_user=user)
        ibmi_util.log_info("Command to run: " + chkobj_cmd, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(
            chkobj_cmd)
        if rc != 0:
            User_not_existed.append(user)

    sql1, sql2 = build_sql(fields, users)
    if sql1 != "":
        startd = datetime.datetime.now()
        rc, out1, err = ibmi_module.itoolkit_run_sql(sql1)
        if joblog or (rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS):
            job_log = ibmi_module.itoolkit_get_job_log(startd)
        else:
            job_log = []

        if rc:
            result_failed = dict(
                stderr=err,
                sql1=sql1,
                sql2=sql2,
                rc=rc,
                job_log=job_log,
            )
            message = 'non-zero return code:{rc}'.format(rc=rc)
            module.fail_json(msg=message, **result_failed)

    if sql2 != "":
        # fetch records of all users information specified by user
        startd = datetime.datetime.now()
        rc, out2, err = ibmi_module.itoolkit_run_sql(sql2)
        if joblog or (rc != ibmi_util.IBMi_COMMAND_RC_SUCCESS):
            job_log = ibmi_module.itoolkit_get_job_log(startd)
        else:
            job_log = []

        if rc:
            result_failed = dict(
                stderr=err,
                sql1=sql1,
                sql2=sql2,
                rc=rc,
                job_log=job_log,
            )
            message = 'non-zero return code:{rc}'.format(rc=rc)
            module.fail_json(msg=message, **result_failed)

        if out2:
            real_out2 = []
            for item in out2:
                # compare the column SPECIAL_AUTHORITIES
                if check_special_authorities:
                    special_authorities_list = item[
                        'SPECIAL_AUTHORITIES'].split()
                    not_expected_value = False
                    if (len(special_authorities_list) == len(
                            special_authorities_expect)):
                        for special_authorities_value in special_authorities_list:
                            if special_authorities_value not in special_authorities_expect:
                                not_expected_value = True
                                break
                    else:
                        not_expected_value = True

                    if not_expected_value:
                        real_out2.append(item)
                        continue

                # compare the column USER_ACTION_AUDIT_LEVEL
                if check_user_action_audit_level:
                    user_action_audit_level_list = item[
                        'USER_ACTION_AUDIT_LEVEL'].split()
                    not_expected_value = False
                    if (len(user_action_audit_level_list) == len(
                            user_action_audit_level_expect)):
                        for user_action_audit_level_value in user_action_audit_level_list:
                            if user_action_audit_level_value not in user_action_audit_level_expect:
                                not_expected_value = True
                                break
                    else:
                        not_expected_value = True

                    if not_expected_value:
                        real_out2.append(item)
                        continue

                # compare the column USER_OPTIONS
                if check_user_option:
                    user_option_list = item['USER_OPTIONS'].split()
                    not_expected_value = False
                    if (len(user_option_list) == len(user_option_expect)):
                        for user_option_value in user_option_list:
                            if user_option_value not in user_option_expect:
                                not_expected_value = True
                                break
                    else:
                        not_expected_value = True

                    if not_expected_value:
                        real_out2.append(item)
                        continue

                # compare the column SUPPLEMENTAL_GROUP_LIST
                if check_supplemental_group_list:
                    supplemental_group_list = item[
                        'SUPPLEMENTAL_GROUP_LIST'].split()
                    not_expected_value = False
                    if (len(supplemental_group_list) == len(
                            supplemental_group_list_expect)):
                        for supplemeental_group_value in supplemental_group_list:
                            if supplemeental_group_value not in supplemental_group_list_expect:
                                not_expected_value = True
                                break
                    else:
                        not_expected_value = True

                    if not_expected_value:
                        real_out2.append(item)
                        continue

                # compare the column LOCALE_JOB_ATTRIBUTES
                if check_locale_job_attributes:
                    locale_job_attributes_list = item[
                        'LOCALE_JOB_ATTRIBUTES'].split()
                    not_expected_value = False
                    if (len(locale_job_attributes_list) == len(
                            locale_job_attributes_expect)):
                        for locale_job_attributes_value in locale_job_attributes_list:
                            if locale_job_attributes_value not in locale_job_attributes_expect:
                                not_expected_value = True
                                break
                    else:
                        not_expected_value = True

                    if not_expected_value:
                        real_out2.append(item)
                        continue

                if check_home_directory:
                    home_directory = item['HOME_DIRECTORY']
                    if len(home_directory_expect) == 0:
                        if home_directory.strip() != '':
                            real_out2.append(item)
                            continue
                    else:
                        if home_directory_expect[0].upper(
                        ) != home_directory.upper():
                            real_out2.append(item)
                            continue
            if out1:
                out1_name_list = []
                for item in out1:
                    out1_name_list.append(item['AUTHORIZATION_NAME'].upper())
                out = out1
                for item in real_out2:
                    if item['AUTHORIZATION_NAME'].upper(
                    ) not in out1_name_list:
                        out.append(item)
            else:
                out = real_out2
        else:
            out = out1
    else:
        out = out1

    if len(User_not_existed) == 0:
        result_success = dict(
            result_set=out,
            sql1=sql1,
            sql2=sql2,
            rc=rc,
            job_log=job_log,
        )
    else:
        result_success = dict(
            result_set=out,
            user_not_existed=User_not_existed,
            sql1=sql1,
            sql2=sql2,
            rc=rc,
            job_log=job_log,
        )
    module.exit_json(**result_success)
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")
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)
Exemple #23
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            operation=dict(type='str', choices=["find"], required=True),
            message_type=dict(type='str',
                              choices=[
                                  "INFORMATIONAL", "COMPLETION", "DIAGNOSTIC",
                                  "ESCAPE", "INQUIRY", "REPLY", "NOTIFY",
                                  "REQUEST", "SENDER", "NO_REPLY"
                              ],
                              required=True),
            message_lib=dict(type='str', required=True),
            message_queue=dict(type='list', elements='str'),
            message_id=dict(type='list', elements='str'),
            message_text=dict(type='str'),
            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)
    operation = module.params['operation']
    message_type = module.params['message_type'].upper()
    message_queue = module.params['message_queue']
    message_lib = module.params['message_lib'].upper()
    message_id = module.params['message_id']
    message_text = module.params['message_text']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()
    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 == "find":
        sql = "SELECT MESSAGE_QUEUE_LIBRARY, MESSAGE_QUEUE_NAME, MESSAGE_ID, MESSAGE_TYPE, " + \
              "MESSAGE_SUBTYPE, MESSAGE_TEXT, SEVERITY, MESSAGE_TIMESTAMP, MESSAGE_KEY, ASSOCIATED_MESSAGE_KEY, " + \
              "FROM_USER, FROM_JOB, FROM_PROGRAM, MESSAGE_FILE_LIBRARY, MESSAGE_FILE_NAME, MESSAGE_SECOND_LEVEL_TEXT " + \
              "FROM QSYS2.MESSAGE_QUEUE_INFO WHERE MESSAGE_QUEUE_LIBRARY = '" + message_lib + "' AND "
        sql = handle_list_to_sql(sql, message_queue, "MESSAGE_QUEUE_NAME")
        sql = handle_list_to_sql(sql, message_id, "MESSAGE_ID")
        if message_text:
            sql = sql + "(MESSAGE_TEXT LIKE UPPER('%" + message_text + "%') " + \
                "OR MESSAGE_TEXT LIKE LOWER('%" + message_text + "%') " + \
                "OR MESSAGE_SECOND_LEVEL_TEXT LIKE UPPER('%" + message_text + "%') " + \
                "OR MESSAGE_SECOND_LEVEL_TEXT LIKE LOWER('%" + message_text + "%')) AND "
        if message_type == "NO_REPLY":
            sql = sql + "MESSAGE_TYPE = 'INQUIRY' AND MESSAGE_KEY NOT IN " + \
                        "(SELECT ASSOCIATED_MESSAGE_KEY FROM QSYS2.MESSAGE_QUEUE_INFO WHERE MESSAGE_TYPE = 'REPLY' " + \
                        "AND MESSAGE_QUEUE_LIBRARY = '" + message_lib + "')"
        else:
            sql = sql + "MESSAGE_TYPE = '" + message_type + "'"

    hex_convert_columns = ['MESSAGE_KEY', 'ASSOCIATED_MESSAGE_KEY']
    rc, out, error, job_log = ibmi_module.itoolkit_run_sql_once(
        sql, hex_convert_columns)
    endd = datetime.datetime.now()
    delta = endd - startd

    result = dict(
        sql=sql,
        stderr=error,
        message_info=out,
        rc=rc,
        job_log=job_log,
        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)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            product=dict(type='str', required=True),
            option=dict(type='str', default='*BASE'),
            object_type=dict(type='str',
                             default='*ALL',
                             choices=['*ALL', '*PGM', '*LNG']),
            language=dict(type='str', default='*PRIMARY'),
            release=dict(type='str', default='*ONLY'),
            target_release=dict(type='str', default='*CURRENT'),
            savf_name=dict(type='str', required=True),
            savf_library=dict(type='str', required=True),
            check_signature=dict(type='str',
                                 default='*SIGNED',
                                 choices=['*SIGNED', '*ALL', '*NONE']),
            joblog=dict(type='bool', default=False),
            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)

    product = module.params['product'].upper()
    option = module.params['option'].upper()
    object_type = module.params['object_type'].upper()
    language = module.params['language'].upper()
    release = module.params['release'].upper()
    target_release = module.params['target_release'].upper()
    savf_name = module.params['savf_name'].upper()
    savf_library = module.params['savf_library'].upper()
    parameters = module.params['parameters'].upper()
    check_signature = module.params['check_signature'].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(option) > 5:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of option exceeds 5 characters")
    if len(release) > 6:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of release exceeds 6 characters")
    if len(target_release) > 8:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of target_release exceeds 8 characters")
    if len(language) > 8:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of language exceeds 8 characters")
    if len(savf_name) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of savf_name exceeds 10 characters")
    if len(savf_library) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of savf_library exceeds 10 characters")

    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)

    # Check if the library of savf is existed
    command = 'QSYS/CHKOBJ OBJ(QSYS/{pattern_savf_library}) OBJTYPE(*LIB)'.format(
        pattern_savf_library=savf_library.strip())
    ibmi_util.log_info("Command to run: " + command, module._name)
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)
    if rc != 0:  # library not exist, create it
        command = "QSYS/CRTLIB LIB({pattern_savf_library}) TEXT('Create by Ansible')".format(
            pattern_savf_library=savf_library.strip())
        ibmi_util.log_info("Command to run: " + command, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)
        if rc != 0:  # fail to create library
            result = dict(
                command=command,
                stdout=out,
                stderr=err,
                rc=rc,
                job_log=job_log,
            )
            module.fail_json(
                msg="Fail to create library: {pattern_savf_library}".format(
                    pattern_savf_library=savf_library.strip()),
                **result)

    # library exist, now check if the savf is existed
    command = 'QSYS/CHKOBJ OBJ({pattern_savf_library}/{pattern_savf_name}) OBJTYPE(*FILE)'.format(
        pattern_savf_name=savf_name.strip(),
        pattern_savf_library=savf_library.strip())
    # Check if the savf is existed
    ibmi_util.log_info("Command to run: " + command, module._name)
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)
    if rc != 0:  # savf not existed
        command = "QSYS/CRTSAVF FILE({pattern_savf_library}/{pattern_savf_name}) TEXT('Create by Ansible')".format(
            pattern_savf_name=savf_name.strip(),
            pattern_savf_library=savf_library.strip())
        ibmi_util.log_info("Command to run: " + command, module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)
        if rc != 0:  # fail to create savf
            result = dict(
                command=command,
                stdout=out,
                stderr=err,
                rc=rc,
                job_log=job_log,
            )
            module.fail_json(
                msg=
                "Fail to create savf {pattern_savf_name} in library {pattern_savf_library}"
                .format(pattern_savf_name=savf_name.strip(),
                        pattern_savf_library=savf_library.strip()),
                **result)

    # run the SAVLICPGM command to save the product objects to the savf
    command = 'QSYS/SAVLICPGM LICPGM({pattern_product}) DEV(*SAVF) OPTION({pattern_option}) RLS({pattern_release}) \
        LNG({pattern_language})  OBJTYPE({pattern_object_type}) SAVF({pattern_savf_library}/{pattern_savf_name}) \
        TGTRLS({pattern_target_release}) CHKSIG({pattern_check_signature}) CLEAR(*ALL) {pattern_parameters}'.format(
        pattern_product=product,
        pattern_option=option,
        pattern_release=release,
        pattern_language=language,
        pattern_object_type=object_type,
        pattern_savf_library=savf_library.strip(),
        pattern_savf_name=savf_name.strip(),
        pattern_check_signature=check_signature,
        pattern_target_release=target_release,
        pattern_parameters=parameters)

    command = ' '.join(
        command.split())  # keep only one space between adjacent strings
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

    result = dict(
        command=command,
        stdout=out,
        stderr=err,
        rc=rc,
        job_log=job_log,
        changed=True,
    )

    if rc != 0:
        result = dict(
            command=command,
            stderr=err,
            job_log=job_log,
            rc=rc,
        )
        message = 'non-zero return code:{rc}'.format(rc=rc)
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            job_number=dict(type='str', required=True),
            job_name=dict(type='str', required=True),
            job_user=dict(type='str', required=True),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )

    job_number = module.params['job_number']
    job_name = module.params['job_name']
    job_user = module.params['job_user']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    sql = "SELECT ORDINAL_POSITION, MESSAGE_ID, MESSAGE_TYPE, MESSAGE_SUBTYPE, SEVERITY, \
        MESSAGE_TIMESTAMP, FROM_LIBRARY, FROM_PROGRAM, FROM_MODULE, FROM_PROCEDURE, FROM_INSTRUCTION, \
        TO_LIBRARY, TO_PROGRAM, TO_MODULE, TO_PROCEDURE, TO_INSTRUCTION, FROM_USER, MESSAGE_FILE, \
        MESSAGE_LIBRARY, MESSAGE_TEXT, MESSAGE_SECOND_LEVEL_TEXT \
        FROM TABLE(QSYS2.JOBLOG_INFO('{p_job_number}/{p_job_user}/{p_job_name}')) A".format(
        p_job_number=job_number, p_job_user=job_user, p_job_name=job_name)

    startd = datetime.datetime.now()
    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)
    job_log = []
    rc, out, err, job_log = ibmi_module.itoolkit_run_sql_once(sql)

    endd = datetime.datetime.now()
    delta = endd - startd
    if rc:
        result_failed = dict(
            sql=sql,
            job_log=job_log,
            stderr=err,
            stdout=out,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
        )
        message = 'non-zero return code {rc}'.format(rc=rc)
        module.fail_json(msg=message, **result_failed)

    result = dict(
        sql=sql,
        job_log=out,
        stderr=err,
        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)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            product=dict(type='str', required=True),
            option=dict(type='str', default='*BASE'),
            object_type=dict(type='str',
                             default='*ALL',
                             choices=['*ALL', '*PGM', '*LNG']),
            language=dict(type='str', default='*PRIMARY'),
            release=dict(type='str', default='*FIRST'),
            replace_release=dict(type='str', default='*ONLY'),
            savf_name=dict(type='str', required=True),
            savf_library=dict(type='str', required=True),
            parameters=dict(type='str', default=' '),
            acceptance_cmd=dict(type='str', default=' '),
            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'].upper()
    option = module.params['option'].upper()
    object_type = module.params['object_type'].upper()
    language = module.params['language'].upper()
    release = module.params['release'].upper()
    replace_release = module.params['replace_release'].upper()
    savf_name = module.params['savf_name'].upper()
    savf_library = module.params['savf_library'].upper()
    parameters = module.params['parameters'].upper()
    acceptance_cmd = module.params['acceptance_cmd'].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(option) > 5:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of option exceeds 5 characters")
    if len(release) > 6:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of release exceeds 6 characters")
    if len(replace_release) > 6:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of replace_release exceeds 6 characters")
    if len(language) > 8:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of language exceeds 8 characters")
    if len(savf_name) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of savf_name exceeds 10 characters")
    if len(savf_library) > 10:
        module.fail_json(rc=ibmi_util.IBMi_PARAM_NOT_VALID,
                         msg="Value of savf_library exceeds 10 characters")

    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)

    command = 'QSYS/CHKOBJ OBJ({pattern_savf_library}/{pattern_savf_name}) OBJTYPE(*FILE)'.format(
        pattern_savf_name=savf_name.strip(),
        pattern_savf_library=savf_library.strip())
    # Check to see if the savf is existed
    ibmi_util.log_info("Command to run: " + command, module._name)
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)
    if rc != 0:
        result = dict(
            command=command,
            stderr=err,
            rc=rc,
            job_log=job_log,
        )
        module.fail_json(
            msg=
            "File {pattern_savf_name} in library {pattern_savf_library} not found"
            .format(pattern_savf_name=savf_name.strip(),
                    pattern_savf_library=savf_library.strip()),
            **result)

    # Call the The Accept Software Agreement command
    if acceptance_cmd.strip():
        command = acceptance_cmd.strip()
        ibmi_util.log_info("Acceptance command to run: " + command,
                           module._name)
        rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)
        if rc != 0:
            result = dict(
                command=command,
                stderr=err,
                rc=rc,
                job_log=job_log,
            )
            module.fail_json(
                msg=
                "The Accept Software Agreement command {acceptance_cmd} failed"
                .format(acceptance_cmd=acceptance_cmd),
                **result)

    # run the RSTLICPGM command to install the product
    command = 'QSYS/RSTLICPGM LICPGM({pattern_product}) DEV(*SAVF) OPTION({pattern_option}) RSTOBJ({pattern_object_type}) \
        LNG({pattern_language}) RLS({pattern_release}) REPLACERLS({pattern_replace_release}) \
        SAVF({pattern_savf_library}/{pattern_savf_name}) {pattern_parameters}'.format(
        pattern_product=product,
        pattern_option=option,
        pattern_object_type=object_type,
        pattern_language=language,
        pattern_release=release,
        pattern_replace_release=replace_release,
        pattern_savf_library=savf_library.strip(),
        pattern_savf_name=savf_name.strip(),
        pattern_parameters=parameters)

    command = ' '.join(
        command.split())  # keep only one space between adjacent strings
    rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

    if rc:
        result = dict(
            command=command,
            stderr=err,
            rc=rc,
            job_log=job_log,
        )
        message = 'non-zero return code:{rc}'.format(rc=rc)
        module.fail_json(msg=message, **result)

    result = dict(
        command=command,
        stdout=out,
        rc=rc,
        job_log=job_log,
        changed=True,
    )

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
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)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            cmd=dict(type='str', required=True),
            asp_group=dict(type='str', default='*SYSBAS'),
            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)

    command = module.params['cmd'].strip().upper()
    asp_group = module.params['asp_group'].strip().upper()
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()

    is_cmd5250 = False
    if command.startswith('DSP'):
        is_cmd5250 = True
    if command.startswith('QSYS/DSP'):
        is_cmd5250 = True
    if command.startswith('WRK'):
        is_cmd5250 = True
    if command.startswith('QSYS/WRK'):
        is_cmd5250 = True
    if 'OUTPUT(*)' in command:
        is_cmd5250 = True

    if is_cmd5250:
        ibmi_util.log_info(
            "Command {0} starts with 'WRK' or 'DSP' or contains 'OUTPUT' keyword, call system utility to run"
            .format(command), module._name)
        # rc, out, err, job_log = ibmi_module.itoolkit_run_command5250_once(command)
        args = ['system', command]
        rc, out, err = module.run_command(args, use_unsafe_shell=False)
        job_log = []
    else:
        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)
        rc, out, err, job_log = ibmi_module.itoolkit_run_command_once(command)

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

    result = dict(
        cmd=command,
        joblog=joblog,
        rc=rc,
        stdout=out,
        stderr=err,
        job_log=job_log,
        start=str(startd),
        end=str(endd),
        delta=str(delta),
    )

    if rc:
        message = 'non-zero return code:{rc}'.format(rc=rc)
        module.fail_json(msg=message, **result)

    if not joblog:
        empty_list = []
        result.update({'job_log': empty_list})

    module.exit_json(**result)
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))
Exemple #30
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(type='str', required=False),
            status=dict(type='str',
                        default='*ALL',
                        choices=["*ALL", "*ACTIVE", "*JOBQ", "*OUTQ"]),
            type=dict(type='str',
                      default="*ALL",
                      choices=["*ALL", "*BATCH", "*INTERACT"]),
            subsystem=dict(type='str', default='*ALL'),
            user=dict(type='str', default='*ALL'),
            submitter=dict(type='str',
                           default='*ALL',
                           choices=["*ALL", "*JOB", "*USER", "*WRKSTN"]),
            joblog=dict(type='bool', default=False),
            become_user=dict(type='str'),
            become_user_password=dict(type='str', no_log=True),
        ),
        supports_check_mode=True,
    )

    job_name = module.params['name']
    job_status = module.params['status']
    job_type = module.params['type']
    job_subsystem = module.params['subsystem']
    job_user = module.params['user']
    job_submitter = module.params['submitter']
    joblog = module.params['joblog']
    become_user = module.params['become_user']
    become_user_password = module.params['become_user_password']

    startd = datetime.datetime.now()

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

    # connection_id = ibmi_module.get_connection()

    sql_job_columns = "SELECT JOB_NAME, JOB_INFORMATION, JOB_STATUS, JOB_TYPE, JOB_TYPE_ENHANCED, JOB_SUBSYSTEM, " \
                      " JOB_DATE, JOB_DESCRIPTION_LIBRARY, JOB_DESCRIPTION, JOB_ACCOUNTING_CODE, SUBMITTER_JOB_NAME, " \
                      " SUBMITTER_MESSAGE_QUEUE_LIBRARY, SUBMITTER_MESSAGE_QUEUE, JOB_ENTERED_SYSTEM_TIME, " \
                      " JOB_SCHEDULED_TIME, JOB_ACTIVE_TIME, JOB_END_TIME, JOB_END_SEVERITY, COMPLETION_STATUS, " \
                      " JOB_END_REASON, JOB_QUEUE_LIBRARY, JOB_QUEUE_NAME, JOB_QUEUE_STATUS, JOB_QUEUE_PRIORITY, " \
                      " CCSID "

    if (job_name is None) or (job_name == ""):
        sql_where = ""
    else:
        sql_where = " AND UPPER(JOB_NAME) = '" + job_name.upper() + "'"
        job_status = "*ALL"
        job_type = "*ALL"
        job_subsystem = "*ALL"
        job_user = "******"
        job_submitter = "*ALL"

    sql_job_status_filter = " JOB_STATUS_FILTER => '" + job_status + "', "
    sql_job_type_filter = " JOB_TYPE_FILTER => '" + job_type + "', "
    sql_job_subsystem_filter = " JOB_SUBSYSTEM_FILTER => '" + job_subsystem.upper(
    ) + "', "
    sql_job_user_filter = " JOB_USER_FILTER => '" + job_user.upper() + "', "
    sql_job_submitter_filter = " JOB_SUBMITTER_FILTER => '" + job_submitter + "' "

    sql_from = " FROM TABLE(QSYS2.JOB_INFO(" + sql_job_status_filter + sql_job_type_filter + \
               sql_job_subsystem_filter + \
               sql_job_user_filter + sql_job_submitter_filter + ")) X WHERE 1 = 1 "

    sql_to_run = sql_job_columns + sql_from + sql_where

    rc, out, err_msg, job_log = ibmi_module.itoolkit_run_sql_once(sql_to_run)
    rt_job_log = []
    if joblog or (rc != IBMi_COMMAND_RC_SUCCESS):
        rt_job_log = job_log

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

    if rc != IBMi_COMMAND_RC_SUCCESS:
        result_failed = dict(
            stderr=err_msg,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            job_log=rt_job_log,
        )
        module.fail_json(msg='Non-zero return code.', **result_failed)
    else:
        result_success = dict(
            job_info=out,
            rc=rc,
            start=str(startd),
            end=str(endd),
            delta=str(delta),
            job_log=rt_job_log,
        )
        module.exit_json(**result_success)