def main(): config = configparser.ConfigParser() # does not throw an error, just returns the empty set if the file doesn't exist config.read(CONFIG.BASEPATH + '/config/iGrill_config.ini') loglevel = config.get("Logging", "LogLevel", fallback="Error") logfile = config.get("Logging", "LogFile", fallback="") parser = argparse.ArgumentParser( description='Runs a thread to control the buzzer') parser.add_argument('-l', '--log-level', action='store', dest='log_level', default=loglevel, help='Set log level, default: \'' + loglevel + '\'') parser.add_argument('-d', '--log-destination', action='store', dest='log_destination', default=logfile, help='Set log destination (file), default: \'' + logfile + '\'') options = parser.parse_args() SetupLog(options.log_level, options.log_destination) daemon = Daemon(host=BUZZ.DAEMON.PYRO_HOST, port=BUZZ.DAEMON.PYRO_PORT) buzzObj = Buzzer(daemon) uri = daemon.register(buzzObj, objectId=BUZZ.DAEMON.PYRO_OBJECT_ID) logging.debug(uri) daemon.requestLoop() logging.debug('exited requestLoop') daemon.shutdown() daemon.close() logging.debug('daemon closed') sys.exit(buzzObj.ExitCode())
def run_maestral_daemon(config_name="maestral", run=True, log_to_stdout=False): """ Wraps :class:`maestral.main.Maestral` as Pyro daemon object, creates a new instance and start Pyro's event loop to listen for requests on a unix domain socket. This call will block until the event loop shuts down. This command will return silently if the daemon is already running. :param str config_name: The name of the Maestral configuration to use. :param bool run: If ``True``, start syncing automatically. Defaults to ``True``. :param bool log_to_stdout: If ``True``, write logs to stdout. Defaults to ``False``. """ from maestral.main import Maestral sock_name = sockpath_for_config(config_name) pid_name = pidpath_for_config(config_name) lockfile = PIDLockFile(pid_name) # acquire PID lock file try: lockfile.acquire(timeout=1) except AlreadyLocked: if is_pidfile_stale(lockfile): lockfile.break_lock() else: logger.debug(f"Maestral already running") return logger.debug(f"Starting Maestral daemon on socket '{sock_name}'") try: # clean up old socket, create new one try: os.remove(sock_name) except FileNotFoundError: pass daemon = Daemon(unixsocket=sock_name) # start Maestral as Pyro server ExposedMaestral = expose(Maestral) # mark stop_sync and shutdown_daemon as oneway methods # so that they don't block on call ExposedMaestral.stop_sync = oneway(ExposedMaestral.stop_sync) ExposedMaestral.shutdown_pyro_daemon = oneway( ExposedMaestral.shutdown_pyro_daemon) m = ExposedMaestral(config_name, run=run, log_to_stdout=log_to_stdout) daemon.register(m, f"maestral.{config_name}") daemon.requestLoop(loopCondition=m._loop_condition) daemon.close() except Exception: traceback.print_exc() finally: # remove PID lock lockfile.release()
import time from Pyro5.api import expose, locate_ns, Daemon, config @expose class TimeoutServer(object): def delay(self, amount): print("sleeping %d" % amount) time.sleep(amount) print("done.") return "slept %d seconds" % amount config.COMMTIMEOUT = 0 # the server won't be using timeouts ns = locate_ns() daemon = Daemon() daemon2 = Daemon() obj = TimeoutServer() obj2 = TimeoutServer() uri = daemon.register(obj) uri2 = daemon2.register(obj2) ns.register("example.timeout", uri) ns.register("example.timeout.frozendaemon", uri2) print("Server ready.") # Note that we're only starting one of the 2 daemons. # daemon2 is not started, to simulate connection timeouts. daemon.requestLoop()
def run_maestral_daemon(config_name='maestral', run=True, log_to_stdout=False): """ Wraps :class:`maestral.main.Maestral` as Pyro daemon object, creates a new instance and start Pyro's event loop to listen for requests on a unix domain socket. This call will block until the event loop shuts down. This command will return silently if the daemon is already running. :param str config_name: The name of the Maestral configuration to use. :param bool run: If ``True``, start syncing automatically. Defaults to ``True``. :param bool log_to_stdout: If ``True``, write logs to stdout. Defaults to ``False``. """ import threading from maestral.main import Maestral sock_name = sockpath_for_config(config_name) pid_name = pidpath_for_config(config_name) lockfile = PIDLockFile(pid_name) if threading.current_thread() is threading.main_thread(): signal.signal(signal.SIGTERM, _sigterm_handler) # acquire PID lock file try: lockfile.acquire(timeout=1) except (AlreadyLocked, LockTimeout): if is_pidfile_stale(lockfile): lockfile.break_lock() else: logger.debug(f'Maestral already running') return # Nice ourselves give other processes priority. We will likely only # have significant CPU usage in case of many concurrent downloads. os.nice(10) logger.debug(f'Starting Maestral daemon on socket "{sock_name}"') try: # clean up old socket try: os.remove(sock_name) except FileNotFoundError: pass daemon = Daemon(unixsocket=sock_name) # start Maestral as Pyro server ExposedMaestral = expose(Maestral) # mark stop_sync and shutdown_daemon as one way # methods so that they don't block on call ExposedMaestral.stop_sync = oneway(ExposedMaestral.stop_sync) ExposedMaestral.pause_sync = oneway(ExposedMaestral.pause_sync) ExposedMaestral.shutdown_pyro_daemon = oneway( ExposedMaestral.shutdown_pyro_daemon) m = ExposedMaestral(config_name, run=run, log_to_stdout=log_to_stdout) daemon.register(m, f'maestral.{config_name}') daemon.requestLoop(loopCondition=m._loop_condition) daemon.close() except Exception: traceback.print_exc() except (KeyboardInterrupt, SystemExit): logger.info('Received system exit') sys.exit(0) finally: lockfile.release()
def main(log_to_file=True): import pkg_resources version = pkg_resources.require('humidifier-controller')[0].version print('Starting Humidifier Controller Server, version: ' + version) config.SERVERTYPE = 'multiplex' daemon = Daemon() def start_client_logger(): from threading import Thread t = Thread(target=Logger, kwargs={'log_to_file': log_to_file}, daemon=True) t.start() return t def signal_handler(signo, frame): if daemon != None: daemon.transportServer.shutting_down = True print(f'Shutting down gracefully exit code: {signo}') daemon.shutdown() from threading import enumerate logger_threads = [ thread for thread in enumerate() if isinstance(thread, Logger) ] for logger_thread in logger_threads: print("Stopping {}.".format(logger_thread)) logger_thread.stop() sys.exit(1) import signal for sig in ('TERM', 'HUP', 'INT'): signal.signal(getattr(signal, 'SIG' + sig), signal_handler) nameserverDaemon = None try: nameserverUri, nameserverDaemon, broadcastServer = start_ns() assert broadcastServer is not None, "expect a broadcast server to be created" print("got a Nameserver, uri=%s" % nameserverUri) except OSError: print('Pyro nameserver already running. No idea who started it.') if (nameserverDaemon == None): with locate_ns() as ns: try: ns.lookup('serial_server.serial_connection') print("Serial server is already registered. Aborting.") return 0 except: pass serial_connection = SerialConnection(baudrate='9600') serial_connection.set_settings(serial_connection.read_settings()) serial_connection.post_message('\0') serial_uri = daemon.register(serial_connection) if (nameserverDaemon == None): with locate_ns() as ns: ns.register('serial_server.serial_connection', serial_uri) else: nameserverDaemon.nameserver.register('serial_server.serial_connection', serial_uri) daemon.combine(nameserverDaemon) daemon.combine(broadcastServer) print('Serial connection registered.') start_client_logger() daemon.requestLoop()
def run(self): daemon = Daemon() obj = MessagePrinter(self.gui) self.uri = daemon.register(obj, "pyrogui.message2") self.started.set() daemon.requestLoop()