def Set_Marshall()

in Providers/Scripts/3.x/Scripts/nxOMSAutomationWorker.py [0:0]


def Set_Marshall(ResourceSettings):
    try:
        settings = read_settings_from_mof_json(ResourceSettings)
        settings.workspace_id = settings.workspace_id.decode() if isinstance(settings.workspace_id, bytes) else settings.workspace_id
        if not is_oms_primary_workspace(settings.workspace_id):
            # not primary workspace
            # return unconditional [0] for a NOOP on non-primary workspace
            log(DEBUG, "Set_Marshall skipped: non primary workspace. Set marshall returned [0]")
            return [0]

        if not nxautomation_user_exists():
            log(ERROR, "Set_Marshall skipped: please update omsagent to the latest version")
            return [0]

        # compatibility from 1.4 remove state.conf file
        if os.path.isfile(STATE_CONF_FILE_PATH):
            os.remove(STATE_CONF_FILE_PATH)

        # if an update is required from 1.4
        # major changes were made in 1.5.0.0 that are incompatible with the 1.4 way of doing things
        if is_any_1_4_process_running(get_nxautomation_ps_output(), settings.workspace_id):
            log(DEBUG, "Hybrid worker 1.4 detected, attempting to kill")
            kill_process_by_pattern_string(settings.workspace_id)

        try:
            kill_any_worker_running_as_omsagent(
                worker_pgrep_pattern="/opt/microsoft/omsconfig/modules/nxOMSAutomationWorker/DSCResources/MSFT_nxOMSAutomationWorkerResource/automationworker/3.x/worker/main.py")
        except:
            log(INFO, "Unable to kill old omsagent worker")
            pass

        # Kill worker managers that might already be running
        log(DEBUG, "Killing the instance of worker manager already running")
        kill_worker_manager(settings.workspace_id)

        # Kill all stray processes
        for ws_id in get_stray_worker_and_manager_wsids(get_nxautomation_ps_output(), settings.workspace_id):
            log(DEBUG, "Workspace id %s has worker and manager processes running in improper context. Terminating."
                % ws_id)
            kill_process_by_pattern_string(WORKSPACE_ID_PREFIX + ws_id)

        # Set up conf and working directories if it doesn't exit
        if not os.path.isdir(WORKER_STATE_DIR):
            os.makedirs(WORKER_STATE_DIR, PERMISSION_LEVEL_0770)
        if not os.path.isdir(WORKING_DIRECTORY_PATH):
            os.makedirs(WORKING_DIRECTORY_PATH, PERMISSION_LEVEL_0770)

        # if the directory does not have permision level 770, reset the permission level
        if os.stat(WORKER_STATE_DIR).st_mode & PERMISSION_LEVEL_0777 != PERMISSION_LEVEL_0770:
            # bitwise AND with PERMISSION_LEVEL_0777 will give true permission level
            os.chmod(WORKER_STATE_DIR, PERMISSION_LEVEL_0770)

        # set cert permissions
        proc = subprocess.Popen(["sudo", "-u", AUTOMATION_USER, "python3", OMS_UTIL_FILE_PATH, "--initialize"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = proc.communicate()
        stdout = stdout.decode('utf-8')
        stderr = stderr.decode('utf-8')
        if proc.returncode != 0:
            raise Exception("call to omsutil.py --initialize failed. %s, %s" % (stdout, stderr))

    except Exception:
        log(ERROR, "Set_Marshall returned [-1] with following error: %s" % traceback.format_exc())
        return [-1]

    try:
        # Create the configuration object
        write_omsconf_file(settings.workspace_id, settings.auto_register_enabled, settings.diy_enabled)
        os.chmod(OMS_CONF_FILE_PATH, PERMISSION_LEVEL_0770)
        log(DEBUG, "oms.conf file was written")
    except Exception:
        log(ERROR, "Set_Marshall returned [-1] with following error: %s" % traceback.format_exc())
        return [-1]

    try:
        # register the auto worker if required
        if settings.auto_register_enabled:
            # Write worker.conf file
            oms_workspace_id, agent_id = get_workspaceid_agentid_from_oms_config()
            # If both proxy files exist use the new one
            # If neither exist use the new path, path will have no file in it, but no file means no proxy set up
            # If one of them exists, use that
            proxy_conf_path = PROXY_CONF_PATH_NEW
            if not os.path.isfile(PROXY_CONF_PATH_NEW) and os.path.isfile(PROXY_CONF_PATH_LEGACY):
                proxy_conf_path = PROXY_CONF_PATH_LEGACY

            workspace_id = settings.workspace_id.decode() if isinstance(settings.workspace_id, bytes) else settings.workspace_id
            
            agent_service_zone = settings.azure_dns_agent_svc_zone
            azure_dns_agent_svc_zone = agent_service_zone.decode() if isinstance(agent_service_zone, bytes) else agent_service_zone
            
            args = ["python3", REGISTRATION_FILE_PATH, "--register", "-w", workspace_id, "-a", agent_id,
                    "-c", OMS_CERTIFICATE_PATH, "-k", OMS_CERT_KEY_PATH, "-f", WORKING_DIRECTORY_PATH, "-s",
                    WORKER_STATE_DIR, "-e", azure_dns_agent_svc_zone, "-p", proxy_conf_path, "-g",
                    KEYRING_PATH]

            diy_account_id = get_diy_account_id()
            if diy_account_id:
                args.append("-y")
                args.append(diy_account_id)

            asset_tag, is_azure_vm, vm_id = get_optional_metadata()
            args.append("-i")
            args.append(vm_id)

            if is_azure_vm:
                args.append("-z")

            azure_resource_id = get_azure_resource_id_from_oms_config()
            if azure_resource_id:
                args.append("-v")
                args.append(azure_resource_id)

            proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            # log(DEBUG, "Trying to register Linux hybrid worker with args: %s" % str(args))
            if proc.returncode == -5:
                log(ERROR, "Linux Hybrid Worker registration failed: DIY and auto-register account ids do not match")
                log(INFO, "Worker manager with be started without auto registered worker")
            elif proc.returncode != 0:
                raise Exception("Linux Hybrid Worker registration failed: Return code %s :" % str(proc.returncode)
                                + stderr.decode() + "\n" + stdout.decode())

            elif not os.path.isfile(AUTO_REGISTERED_WORKER_CONF_PATH):
                raise Exception("Linux Hybrid Worker registration file could not be created")
            else:
                os.chmod(AUTO_REGISTERED_WORKER_CONF_PATH, PERMISSION_LEVEL_0770)

        if settings.diy_enabled:
            move_diy_settings_to_new_location()

    except Exception:
        log(ERROR, "Set_Marshall returned [-1] with following error: %s" % traceback.format_exc())
        return [-1]

    try:
        # start the worker manager proc
        if (settings.auto_register_enabled or settings.diy_enabled) and start_worker_manager_process(
                settings.workspace_id) < 0:
            log(ERROR, "Worker manager process could not be started. Set_Marshall returned [-1]")
            return [-1]
        elif not settings.auto_register_enabled and not settings.diy_enabled:
            log(DEBUG,
                "No solutions requiring linux hybrid worker are enabled. Terminating the hybrid worker processes")
            # Kill all workers and managers
            kill_process_by_pattern_string(WORKSPACE_ID_PREFIX + settings.workspace_id)
            if is_hybrid_worker_or_manager_running(settings.workspace_id):
                raise Exception("Could not kill worker and manager processes")
        log(INFO, "Set_Marshall returned [0]. Exited successfully")
        return [0]

    except Exception:
        log(ERROR, "Set_Marshall returned [-1] with following error: %s" % traceback.format_exc())
        return [-1]