예제 #1
0
    def _applySystemSpecificConfiguration(self):
        defaultToApply = self.WINDOWS_DEFAULT_PATHS.copy()
        if RUNNING_ON_LINUX:
            defaultToApply = self.LINUX_DEFAULT_PATHS.copy()
        elif RUNNING_ON_DARWIN:
            defaultToApply = self.MACOS_DEFAULT_PATHS.copy()

        baseDir = self._config["global"]["base_dir"]

        for key in list(self._config):
            if key in defaultToApply:
                self._config[key].update(defaultToApply[key])

        self._config['cache_service']['extension_config_dir'] = os.path.join(
            baseDir, 'opsiclientd', 'extend.d')

        if RUNNING_ON_WINDOWS:
            systemDrive = System.getSystemDrive()
            logger.debug(
                "Running on windows: adapting paths to use system drive (%s)",
                systemDrive)
            systemDrive += "\\"
            self._config['cache_service']['storage_dir'] = os.path.join(
                systemDrive, 'opsi.org', 'cache')
            self._config['global']['config_file'] = os.path.join(
                baseDir, 'opsiclientd', 'opsiclientd.conf')
            self._config['global']['log_dir'] = os.path.join(
                systemDrive, 'opsi.org', 'log')
            self._config['global']['state_file'] = os.path.join(
                systemDrive, 'opsi.org', 'opsiclientd', 'state.json')
            self._config['global']['server_cert_dir'] = os.path.join(
                systemDrive, 'opsi.org', 'tls')
            self._config['global']['timeline_db'] = os.path.join(
                systemDrive, 'opsi.org', 'opsiclientd', 'timeline.sqlite')
            self._config['system'][
                'program_files_dir'] = System.getProgramFilesDir()

            if sys.getwindowsversion()[0] == 5:  # pylint: disable=no-member
                self._config['action_processor']['run_as_user'] = '******'
        else:
            sslCertDir = os.path.join('/etc', 'opsi-client-agent')

            for certPath in ('ssl_server_key_file', 'ssl_server_cert_file'):
                if sslCertDir not in self._config['control_server'][certPath]:
                    self._config['control_server'][certPath] = os.path.join(
                        sslCertDir, self._config['control_server'][certPath])
예제 #2
0
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)