def Set()

in Providers/Scripts/2.4x-2.5x/Scripts/nxOMSAuditdPlugin.py [0:0]


def Set(WorkspaceId, Ensure):
    LogStatus("Set_Start", "Start", False)
    if not IsValidWorkspaceId(WorkspaceId):
        LogStatus("Set_End", "Invalid workspace id", False)
        return [1]

    if IsSudoScriptOutOfDate():
        LG().Log(LOG_INFO, "Updating sudo script")
        try:
            WriteFile(SUDO_SCRIPT, ReadFile(RESOURCE_SUDO_SCRIPT))
        except:
            LogStatus("Set_End", "Failed to update " + SUDO_SCRIPT, True)
            return [1]

    auoms_version = GetPackageVersion("auoms")
    if auoms_version is None:
        LogStatus("Set_End", "Failed to determine auoms version", True)
        # Failed to get auoms version, return fake success
        return [1]

    (error_msg, audit_version, auoms_state, actual_audit_rules, actual_conf, actual_collect_conf,
     actual_outconf, actual_plugin_conf, loaded_audit_rules, audit_state) = GetState(WorkspaceId)
    if error_msg is not None:
        LogStatus("Set_End", error_msg, True)
        return [1]

    (error_msg, desired_auoms_state, desired_rules, desired_conf, desired_collect_conf, desired_outconf,
     desired_plugin_conf) = GetDesiredState(WorkspaceId, Ensure, audit_version, auoms_state, auoms_version)
    if error_msg is not None:
        LogStatus("Set_End", error_msg, True)
        return [1]

    run_script = False
    if auoms_state != desired_auoms_state:
        run_script = True
        LG().Log(LOG_INFO, "Actual auoms state differs from desired auoms state")

    audit_enabled = GetEnabledFromAuditState(audit_state)

    arg1 = ""
    agent_restart_ignore_error = False
    if IsTextDifferent(actual_plugin_conf, desired_plugin_conf):
        run_script = True
        LG().Log(LOG_INFO, "Actual Plugin conf differs from Desired plugin conf, so omsagent will be restarted")
        arg1 = WorkspaceId
        if desired_plugin_conf is None:
            RemoveFile(GetOMSAgentConfPath(WorkspaceId))
        else:
            agent_restart_ignore_error = True
            WriteFile(GetOMSAgentConfPath(WorkspaceId), desired_plugin_conf)

    if AreFilesDifferent(PLUGIN_LIB_RB, RESOURCE_PLUGIN_LIB_RB) or AreFilesDifferent(PLUGIN_FILTER_RB, RESOURCE_PLUGIN_FILTER_RB):
        run_script = True
        LG().Log(LOG_INFO, "Actual Plugin RB files differ from Desired plugin RB files, so omsagent will be restarted")
        arg1 = WorkspaceId
        try:
            shutil.copyfile(RESOURCE_PLUGIN_LIB_RB, PLUGIN_LIB_RB)
        except:
            LogStatus("Set_End", "Failed to copy " + src + " to " + dest + ": " + str(sys.exc_info()[1]), True)
            return [1]
        try:
            shutil.copyfile(RESOURCE_PLUGIN_FILTER_RB, PLUGIN_FILTER_RB)
        except:
            LogStatus("Set_End", "Failed to copy " + src + " to " + dest + ": " + str(sys.exc_info()[1]), True)
            return [1]

    if arg1 == "" and OmsAgentNeedsRestart(WorkspaceId):
        run_script = True
        LG().Log(LOG_INFO, "Plugin conf or RB files have changed since omsagent start, omsagent will be restarted")
        arg1 = WorkspaceId

    rules_file_path = ""
    if IsTextDifferent(actual_audit_rules, desired_rules):
        run_script = True
        if desired_rules is None:
            LG().Log(LOG_INFO, "Auditd rules will be removed")
            rules_file_path = "remove"
        else:
            LG().Log(LOG_INFO, "Actual auditd rules differ from desired auditd rules")
            rules_file_path = GetTmpAuditRulesPath(WorkspaceId)
            WriteFile(rules_file_path, desired_rules)

    conf_path = ""
    if IsTextDifferent(actual_conf, desired_conf):
        if desired_conf is not None:
            run_script = True
            LG().Log(LOG_INFO, "Actual auoms conf differs from desired conf")
            conf_path = GetTmpAuomsConfPath(WorkspaceId)
            WriteFile(conf_path, desired_conf)

    collect_conf_path = ""
    if IsTextDifferent(actual_collect_conf, desired_collect_conf):
        if desired_collect_conf is not None:
            run_script = True
            LG().Log(LOG_INFO, "Actual auomscollect conf differs from desired conf")
            collect_conf_path = GetTmpAuomscollectConfPath(WorkspaceId)
            WriteFile(collect_conf_path, desired_collect_conf)

    outconf_name = ""
    outconf_path = ""
    if IsTextDifferent(actual_outconf, desired_outconf):
        run_script = True
        outconf_name = WorkspaceId + ".conf"
        if desired_outconf is None:
            LG().Log(LOG_INFO, "auoms output conf will be removed")
            outconf_path = "remove"
        else:
            LG().Log(LOG_INFO, "Actual auoms output conf differs from desired output conf")
            outconf_path = GetTmpAuomsOutputConfPath(WorkspaceId)
            WriteFile(outconf_path, desired_outconf)

    rules_diff = ""
    rules_diff_path = ""
    # Only do loaded rules check if auoms version < 2.0
    if CompareVersion(auoms_version, '2.0') < 0:
        # On some systems the auditd reload will cause rule load as well
        # So, to prevent trying to load rules twice (and getting an error as a result)
        # Only check loaded rules if rules file already contains the rules
        # This may cause a 15 minute delay between when plugin is enabled
        # and when rules are actually loaded
        if actual_audit_rules is not None:
            rules_diff = DiffAuditRules(desired_rules, loaded_audit_rules)
            if rules_diff is not None and audit_enabled != "2":
                run_script = True
                LG().Log(LOG_INFO, "Not all desired auditd rules are loaded")
                LG().Log(LOG_INFO, "Missing rules are: \n" + rules_diff)
                rules_diff_path = GetTmpAuditLoadedRulesPath(WorkspaceId)
                WriteFile(rules_diff_path, rules_diff)

    script_failed = False
    is_fatal = False
    status_message = "Success"
    exit_code = 0
    if run_script:
        # Run script that will restart omsagent and enable+start/disable+stop auoms
        args = []
        args.append("/usr/bin/sudo")
        args.append(SUDO_SCRIPT)
        args.append("set")
        args.append(arg1)
        if auoms_state != desired_auoms_state:
            args.append(desired_auoms_state)
        else:
            args.append("")
        args.append(rules_file_path)
        args.append(outconf_name)
        args.append(outconf_path)
        args.append(rules_diff_path)
        args.append(conf_path)
        args.append(collect_conf_path)
        (out_txt, err_txt, exit_code) = RunCommand(args)
        if exit_code != 0:
            script_failed = True
            is_fatal = True
            LG().Log(LOG_ERROR, "Command failed: '" + "' '".join(args) + "'")
            LG().Log(LOG_INFO, "stdout: " + out_txt)
            LG().Log(LOG_INFO, "stderr: " + err_txt)
            if exit_code == 2:
                status_message = "Failed to restart omsagent"
                if agent_restart_ignore_error:
                    is_fatal = False
            elif exit_code == 3:
                if desired_auoms_state == "running":
                    status_message = "Failed to enable OMS Auditd Plugin"
                else:
                    status_message = "Failed to disable OMS Auditd Plugin"
            elif exit_code == 4:
                status_message = "Failed to change OMS audit rules"
            elif exit_code == 5:
                status_message = "Failed to change auoms output config"
            elif exit_code == 6:
                if desired_auoms_state == "running":
                    status_message = "OMS Auditd Plugin failed to start"
                else:
                    status_message = "OMS Auditd Plugin failed to stop"
            elif exit_code == 7:
                status_message = "Failed to change loaded OMS audit rules"
            elif exit_code == 8:
                status_message = "Failed to trigger auditd service reload"
            elif exit_code == 9:
                status_message = "Failed to change auoms config"
            elif exit_code == 10:
                status_message = "Failed to change auomscollect config"
            elif exit_code == 11:
                status_message = "Failed to trigger auoms restart"
            elif exit_code == 12:
                status_message = "Audit rules immutable (-e 2): reboot required so that desired rules can be loaded"
            elif exit_code == 13:
                status_message = "Failed to enable auoms service"
            else:
                status_message = "Unknown error while trying to apply desired OMS Auditd Plugin changes: " + err_txt

        RemoveFile(GetTmpAuomsConfPath(WorkspaceId))
        RemoveFile(GetTmpAuomsOutputConfPath(WorkspaceId))
        RemoveFile(GetTmpAuditRulesPath(WorkspaceId))
        RemoveFile(GetTmpAuditLoadedRulesPath(WorkspaceId))

    if not script_failed and Ensure == "Present":
        # Only report running state errors if script did not fail
        # If script failed, we don't want to last LOG_FATAL message to get overridden by running state error
        if os.path.isfile(AUOMSCTL_BIN):
            if os.path.isfile(AUDITD_BIN):
                if GetAuditdPid() <= 0:
                    LogStatus("Set_End", "Auditd service needs to be started", True)
                    return [0]
                if GetAuomsCollectPid() <= 0:
                    LogStatus("Set_End", "Auditd service is running, but auomscollect is not running", True)
                    return [0]
            else:
                if GetAuomsCollectPid() <= 0:
                    LogStatus("Set_End", "Auoms service is running, but auomscollect is not running", True)
                    return [0]
        else:
            if not GetAuditdPid() <= 0:
                LogStatus("Set_End", "Auditd service needs to be started", True)
                return [0]
            if not GetAuomsPid() <= 0:
                LogStatus("Set_End", "Auditd service is running, but auoms is not running", True)
                return [0]
        if rules_diff is not None and audit_enabled == "2":
            LogStatus("Set_End", "Audit rules immutable (-e 2): reboot required so that desired rules can be loaded", True)
            return [0]
 
    LogStatus("Set_End", status_message, is_fatal)

    return [exit_code]