def test_inheritance(): load_config_file("tests/data/event_config/1.conf") configs = getEventConfigs() assert sorted(list(configs)) == sorted([ 'gui_startup', 'gui_startup{cache_ready}', 'gui_startup{installation_pending}', 'gui_startup{user_logged_in}', 'maintenance', 'net_connection', 'on_demand', 'on_demand{user_logged_in}', 'on_shutdown', 'on_shutdown{installation_pending}', 'opsiclientd_start', 'opsiclientd_start{cache_ready}', 'silent_install', 'software_on_demand', 'sync_completed', 'sync_completed{cache_ready_user_logged_in}', 'sync_completed{cache_ready}', 'timer', 'timer_silentinstall', 'user_login' ]) assert configs["on_demand"]["shutdownWarningTime"] == 3600 assert configs["on_demand{user_logged_in}"]["shutdownWarningTime"] == 36000 Config().set(section="event_default", option="shutdown_warning_time", value=12345) reconfigureEventGenerators() configs = getEventConfigs() assert configs["on_demand"]["shutdownWarningTime"] == 12345 assert configs["on_demand{user_logged_in}"]["shutdownWarningTime"] == 36000 assert configs["gui_startup"]["shutdownWarningTime"] == 12345 assert configs["gui_startup{cache_ready}"]["shutdownWarningTime"] == 12345 assert configs["gui_startup{installation_pending}"][ "shutdownWarningTime"] == 12345
""" Event configuration utilities. """ import copy as pycopy import pprint from opsicommon.logging import logger from OPSI.Types import forceBool, forceList, forceUnicodeLower from opsiclientd.Config import Config from opsiclientd.Localization import getLanguage __all__ = ['getEventConfigs'] config = Config() def getEventConfigs(): # pylint: disable=too-many-locals,too-many-branches,too-many-statements preconditions = {} for (section, options) in config.getDict().items(): section = section.lower() if section.startswith('precondition_'): preconditionId = section.split('_', 1)[1] preconditions[preconditionId] = {} try: for key in options.keys(): if forceBool(options[key]): # Only check if value in precondition is true # false means: do not check state preconditions[preconditionId][key] = True logger.info("Precondition '%s' created: %s", preconditionId, preconditions[preconditionId])
def load_config_file(config_file): config = Config() config.set("global", "config_file", config_file) config.readConfigFile()
def opsiclientd_auth(): config = Config() return (config.get("global", "host_id"), config.get("global", "opsi_host_key"))
def main(): # pylint: disable=too-many-statements,too-many-branches startup_log("windows.main") log_dir = os.path.join(System.getSystemDrive() + "\\opsi.org\\log") parent = psutil.Process(os.getpid()).parent() parent_name = parent.name() if parent else None # https://stackoverflow.com/questions/25770873/python-windows-service-pyinstaller-executables-error-1053 startup_log(f"argv={sys.argv} parent_name={parent_name}") if len(sys.argv) == 1 and parent_name == "services.exe": startup_log("import start service") from opsiclientd.windows.service import start_service # pylint: disable=import-outside-toplevel startup_log("init logging") init_logging(stderr_level=LOG_NONE, log_dir=log_dir) startup_log("start service") start_service() return if any(arg in sys.argv[1:] for arg in ("install", "update", "remove", "start", "stop", "restart")): from opsiclientd.windows.service import handle_commandline # pylint: disable=import-outside-toplevel handle_commandline() return if any(arg in sys.argv[1:] for arg in ("setup", "--version", "--help")): options = parser.parse_args() if options.config_file: Config().set("global", "config_file", options.config_file) if options.action == "setup": oc_init_logging(stderr_level=options.logLevel, stderr_format=DEFAULT_STDERR_LOG_FORMAT) setup(full=True, options=options) return try: if "--elevated" not in sys.argv and parent_name != "python.exe": executable = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + ".exe" args = " ".join(sys.argv[1:]) command = executable + " " + args + " --elevated" try: run_as_system(command) except Exception as err: # pylint: disable=broad-except print(f"Failed to run {command} as system: {err}", file=sys.stderr) raise return integrity_level = get_integrity_level() if int(integrity_level.split("-")[-1]) < 12288: raise RuntimeError( f"opsiclientd.exe must be run as service or from an elevated cmd.exe (integrity_level={integrity_level})" ) if "--elevated" in sys.argv: sys.argv.remove("--elevated") options = parser.parse_args() if options.config_file: Config().set("global", "config_file", options.config_file) init_logging(log_dir=log_dir, stderr_level=options.logLevel, log_filter=options.logFilter) with opsicommon.logging.log_context({'instance', 'opsiclientd'}): logger.notice("Running as user: %s", win32api.GetUserName()) if parent: logger.notice("Parent process: %s (%s)", parent.name(), parent.pid) logger.debug(os.environ) from .opsiclientd import opsiclientd_factory # pylint: disable=import-outside-toplevel opsiclientd = opsiclientd_factory() try: opsiclientd.start() while True: time.sleep(1) except KeyboardInterrupt: logger.essential("KeyboardInterrupt #1 -> stop") opsiclientd.stop() try: opsiclientd.join(15) except KeyboardInterrupt: logger.essential("KeyboardInterrupt #2 -> kill process") psutil.Process(os.getpid()).kill() except Exception as err: # pylint: disable=broad-except logger.error(err, exc_info=True) time.sleep(3) sys.exit(1)
import os from twisted.internet import defer from OPSI.Exceptions import OpsiAuthenticationError from OPSI.Service.Worker import WorkerOpsiJsonRpc from OPSI.Service.Resource import ResourceOpsi from opsicommon.logging import logger, log_context from opsiclientd.OpsiService import ServiceConnection from opsiclientd.Config import Config from opsiclientd.Events.SwOnDemand import SwOnDemandEventGenerator from opsiclientd.Events.Utilities.Generators import getEventGenerators config = Config() # pylint: disable=invalid-name service_connection = ServiceConnection() # pylint: disable=invalid-name class WorkerKioskJsonRpc(WorkerOpsiJsonRpc): # pylint: disable=too-few-public-methods _allowedMethods = [ "getClientId", "fireEvent_software_on_demand", "processActionRequests", "getConfigDataFromOpsiclientd", "backend_setOptions", "configState_getObjects", "getDepotId", "getGeneralConfigValue", "getKioskProductInfosForClient", "hostControlSafe_fireEvent", "objectToGroup_getObjects", "product_getObjects", "productDependency_getObjects", "productOnClient_getObjects", "productOnDepot_getObjects", "setProductActionRequestWithDependencies" ] def __init__(self, service, request, resource):
def main(): global opsiclientd # pylint: disable=global-statement,invalid-name log_dir = "/var/log/opsi-client-agent" parser.add_argument( "--no-signal-handlers", "-t", dest="signalHandlers", action="store_false", default=True, help="Do not register signal handlers." ) parser.add_argument( "--daemon", "-D", dest="daemon", action="store_true", default=False, help="Daemonize process." ) parser.add_argument( "--pid-file", dest="pidFile", default=None, help="Write the PID into this file." ) options = parser.parse_args() if options.config_file: Config().set("global", "config_file", options.config_file) if options.action == "setup": oc_init_logging(stderr_level=options.logLevel, stderr_format=DEFAULT_STDERR_LOG_FORMAT) setup(full=True, options=options) return init_logging(log_dir=log_dir, stderr_level=options.logLevel, log_filter=options.logFilter) with opsicommon.logging.log_context({'instance', 'opsiclientd'}): if options.signalHandlers: logger.debug("Registering signal handlers") signal.signal(SIGHUP, signal.SIG_IGN) # ignore SIGHUP signal.signal(SIGTERM, signal_handler) signal.signal(SIGINT, signal_handler) # aka. KeyboardInterrupt else: logger.notice("Not registering any signal handlers!") if options.daemon: logging_config(stderr_level=LOG_NONE) daemonize() write_pid_file(options.pidFile) logger.debug("Starting opsiclientd") opsiclientd = OpsiclientdPosix() opsiclientd.start() try: while opsiclientd.is_alive(): time.sleep(1) logger.debug("Stopping opsiclientd") opsiclientd.join(60) logger.debug("Stopped") except Exception as err: # pylint: disable=broad-except logger.error(err, exc_info=True) finally: if options.pidFile: logger.debug("Removing PID file") try: os.remove(options.pidFile) logger.debug("PID file removed") except OSError as oserr: logger.debug("Removing pid file failed: %s", oserr)