def run(): global args logger = None args = parse_args() if args.stop: stop_daemon(args) sys.exit(0) if args.respawn: stop_daemon(args) time.sleep(3) # daemonize logs exceptions to its logger (which defaults to the syslog) # and does not make them appear on stdout/stderr. If we're in foreground # mode, override that logger with our own. if args.foreground: logger = logging.getLogger('run-daemon') if args.verbose: logger.setLevel(logging.DEBUG) install_example_config_file() os.makedirs(args.run_dir, exist_ok=True) daemon = Daemonize(app="openrazer-daemon", pid=os.path.join(args.run_dir, "openrazer-daemon.pid"), action=run_daemon, foreground=args.foreground, verbose=args.verbose, chdir=args.run_dir, logger=logger) daemon.start()
def main(): parser = argparse.ArgumentParser(description='Router pinger') parser.add_argument('host', help='Host to ping') parser.add_argument('-i', '--interval', default=DEFAULT_INTERVAL, help='Interval of pinging') parser.add_argument('-f', '--log-file', dest='logfile', help='Log file to log into') parser.add_argument('-d', '--daemon', action="store_true", help='Fork into background as a daemon') parser.add_argument('-p', '--pid-file', dest='pidfile', default=DEFAULT_PID_FILE, help='Pidfile of the process') parser.add_argument( '-t', '--mail-to', dest='mailto', help='On midnight rotation, send the old log to this email address.') args = parser.parse_args() if args.host: rtt = ping(args.host) if rtt is not None: print("Test ping %s is up, RTT %f" % (args.host, rtt)) else: print("Test ping %s is down" % (args.host, )) else: parser.print_help(sys.stderr) exit(1) if not args.logfile: parser.print_help(sys.stderr) exit(1) # Sanity check interval args.interval = int(args.interval) if args.interval <= 0: parser.print_help(sys.stderr) exit(1) if args.daemon: # Go daemon! daemon = Daemonize( app="router_ping.py", pid=args.pidfile, action=lambda: log_pings(args.host, args.logfile, args.interval, args.mailto), foreground=False) daemon.start() # Never reached # Go foreground. log_pings(args.host, args.logfile, args.interval, args.mailto)
def setup(): parser = argparse.ArgumentParser() parser.add_argument("directory") parser.add_argument("-p", "--port", dest="port", type=int, default=8080) parser.add_argument('-P', "--pid-file", dest="pid", default="web.pid") args = parser.parse_args() # Get absolute path to directory to serve, as daemonize changes to '/' os.chdir(args.directory) dr = os.getcwd() httpd = BaseHTTPServer.HTTPServer(('', args.port), SimpleHTTPRequestHandlerWithPOST) def run(): os.chdir(dr) httpd.serve_forever() daemon = Daemonize( app="synapse-webclient", pid=args.pid, action=run, auto_close_fds=False, ) daemon.start()
def prepare_repack(self): self.stop_replay() signal.signal(signal.SIGINT, self.__terminate_prepare) if self.args.debug: self.logger.args["log_dest"] = "console" self.__prepare_repack() else: if self.config["logging"]["log_dest"] == 'console': foreground = True else: foreground = False print("Prepare repack process started.") keep_fds = [ self.logger.file_logger_fds, self.logger.cons_logger_fds, ] self.logger.log_message( 'Starting the repack process for configurantion %s.' % (self.args.config, ), 'info') prepare_daemon = Daemonize(app="repack_tables", pid=self.prepare_pid, action=self.__prepare_repack, foreground=foreground, keep_fds=keep_fds) prepare_daemon.start()
def watch(): """ Watches for figures. """ daemon = Daemonize(app='inkscape-figures', pid='/tmp/inkscape-figures.pid', action=watch_daemon) daemon.start() print("Watching figures.")
def run_maintenance(self): """ The method runs a maintenance process on the target postgresql database specified in the given source. """ maintenance_pid = os.path.expanduser('%s/%s_maintenance.pid' % (self.config["pid_dir"],self.args.source)) if self.args.source == "*": print("You must specify a source name with the argument --source") else: if self.args.debug: self.pg_engine.run_maintenance() else: if self.config["log_dest"] == 'stdout': foreground = True else: self.logger.info("Starting the maintenance on the source %s" % (self.args.source, )) foreground = False print("Starting the maintenance process for source %s" % (self.args.source)) keep_fds = [self.logger_fds] app_name = "%s_maintenance" % self.args.source maintenance_daemon = Daemonize(app=app_name, pid=maintenance_pid, action=self.pg_engine.run_maintenance, foreground=foreground , keep_fds=keep_fds) try: maintenance_daemon.start() except: print("The maintenance process is already started. Aborting the command.")
def __init__(self, app, pid, action, keep_fds=None, foreground=False): Daemonize.__init__( self, app, pid, action, keep_fds=keep_fds, foreground=foreground) signal.signal(signal.SIGINT, self.sigterm) signal.signal(signal.SIGTERM, self.sigterm)
def sigterm(self, signum, frame): now = datetime.now().strftime('%Y.%m.%d %H:%M') if signum == 15: logger.debug("{} - SIGTERM, завершение работы".format(now)) if signum == 2: logger.debug("{} - SIGINT, завершение работы".format(now)) Daemonize.sigterm(self, signum, frame)
def main(): """Execute entry function.""" args = parser.parse_args() args_dict = vars(args) root_dir = args_dict['root'] if 'root' in args else None # If a root directory is specified, get the absolute path and # check if it exists. Abort if it doesn't exist! if root_dir: root_dir = os.path.abspath(root_dir) if not os.path.exists(root_dir): print("The specified directory doesn't exist!") sys.exit(1) # Default to home directory if no root is specified else: root_dir = os.path.expanduser('~') if args.stopdaemon: print_command_factory('STOPDAEMON')(vars(args), root_dir) elif args.nodaemon: daemon_factory(root_dir)() elif args.daemon: config_dir = os.path.join(root_dir, '.config/pueue') os.makedirs(config_dir, exist_ok=True) daemon = Daemonize(app='pueue', pid=os.path.join(config_dir, 'pueue.pid'), action=daemon_factory(root_dir), chdir=root_dir) daemon.start() elif hasattr(args, 'func'): try: args.func(args_dict, root_dir) except EOFError: print('Apparently the daemon just died. Sorry for that :/') else: print('Invalid Command. Please check -h')
def start_daemon(config_path, pid=DEFAULT_PID, verbose=False, logfile=None): from oshino.config import load from oshino.core.heart import start_loop keep_fds = [] if logfile: level = DEBUG if verbose else INFO fh = FileHandler(logfile, level=level) logger.handlers.append(fh) fh.push_application() keep_fds.append(fh.stream.fileno()) def wrapped(): cfg = load(config_path) return start_loop(cfg) daemon = Daemonize(app='oshino', pid=pid, action=wrapped, verbose=verbose, keep_fds=keep_fds, logger=logger, chdir=os.getcwd()) daemon.start() return daemon
def main(): parser = argparse.ArgumentParser(description='cstar_perf_notifications') parser.add_argument('-F', '--foreground', dest='foreground', action='store_true', help='Run in the foreground instead of daemonizing') parser.add_argument('--pid', default="/tmp/cstar_perf_notifications.pid", help='PID file for daemon', dest='pid') parser.add_argument('-l', '--log', default='/tmp/cstar_perf_notifications.log', help='File to log to', dest='logfile') parser.add_argument('-v', '--verbose', action='store_true', help='Print log messages', dest='verbose') args = parser.parse_args() log.setLevel(logging.DEBUG) log.propagate = False fh = logging.FileHandler(args.logfile, "a") formatter = logging.Formatter("%(levelname)s:%(funcName)s:%(asctime) -8s %(message)s") fh.setFormatter(formatter) fh.setLevel(logging.DEBUG) log.addHandler(fh) if args.verbose: sh = logging.StreamHandler() sh.setFormatter(formatter) sh.setLevel(logging.DEBUG) log.addHandler(sh) keep_fds = [fh.stream.fileno()] if args.foreground: multi_service() else: daemon = Daemonize(app="notifications", pid=args.pid, action=multi_service, keep_fds=keep_fds) daemon.start()
def setup(): parser = argparse.ArgumentParser() parser.add_argument("directory") parser.add_argument("-p", "--port", dest="port", type=int, default=8080) parser.add_argument('-P', "--pid-file", dest="pid", default="web.pid") args = parser.parse_args() # Get absolute path to directory to serve, as daemonize changes to '/' os.chdir(args.directory) dr = os.getcwd() httpd = BaseHTTPServer.HTTPServer( ('', args.port), SimpleHTTPRequestHandlerWithPOST ) def run(): os.chdir(dr) httpd.serve_forever() daemon = Daemonize( app="synapse-webclient", pid=args.pid, action=run, auto_close_fds=False, ) daemon.start()
def main(): # pragma: no cover args = parser.parse_args() ctx.load_args(args) from spruned import settings from spruned.application.tools import create_directory create_directory(ctx, settings.STORAGE_ADDRESS) from daemonize import Daemonize from spruned.main import main_task def start(): # pragma: no cover from spruned.application.logging_factory import Logger Logger.root.debug('Arguments: %s', args) main_loop = asyncio.get_event_loop() main_loop.create_task(main_task(main_loop)) main_loop.run_forever() if args.daemonize: from spruned.application.logging_factory import Logger pid = ctx.datadir + '/spruned.pid' Logger.root.debug('Running spruned daemon') daemon = Daemonize(app="spruned", pid=pid, action=start, logger=Logger.root, auto_close_fds=False) daemon.start() else: start()
def daemon(pidfile, url, role, secret, channel, position, username, password, dev, foreground): '''Chat daemon, to get notifications when messages are received''' click.secho(f'Kill me with kill -9 `cat {pidfile}`', fg='cyan') if dev: url = DEFAULT_LOCAL_URL handler = functools.partial( main, url=url, role=role, secret=secret, channel=channel, position=position, username=username, password=password, ) # Use foreground mode for testing d = Daemonize(app="test_app", pid=pidfile, action=handler, foreground=foreground) d.start()
def __init_pgsql_replica(self): """ The method initialise a replica for a given postgresql source within the specified configuration. The method is called by the public method init_replica. """ if self.args.debug: self.pgsql_source.init_replica() else: if self.config["log_dest"] == 'stdout': foreground = True else: foreground = False print("Init replica process for source %s started." % (self.args.source)) keep_fds = [self.logger_fds] init_pid = os.path.expanduser( '%s/%s.pid' % (self.config["pid_dir"], self.args.source)) self.logger.info("Initialising the replica for source %s" % self.args.source) init_daemon = Daemonize(app="init_replica", pid=init_pid, action=self.pgsql_source.init_replica, foreground=foreground, keep_fds=keep_fds) init_daemon.start()
def main(self): # Command line parser if len(sys.argv) == 2 and (sys.argv[1] == '--list'): self.check_cache() print json.dumps(self.inventory, indent=4) elif len(sys.argv) == 2 and (sys.argv[1] == '--host'): self.check_cache() print json.dumps(self.inventory["hosts"][sys.argv[2]], indent=4) elif len(sys.argv) == 2 and (sys.argv[1] == '--debug'): self.check_cache() print "debug=", self.debug print "Groups" for group in self.inventory: print " _ " + group #print json.dumps(self.inventory["hosts"][sys.argv[2]], indent=4) else: print "Usage: %s --list or --host <hostname>" % sys.argv[0] sys.exit(1) sys.stdout.flush() sys.stderr.flush() # Update cache if we are using smart cache if self.cache_enable and self.cache_smart and not os.path.exists( self.pid_file): daemon = Daemonize(app="joyent_inv", pid=self.pid_file, action=self.build_inv_from_api) daemon.start() sys.exit(0)
def sync_tables(self): """ The method reload the data from a source only for specified tables. Is compulsory to specify a source name and at least one table name when running this method. Multiple tables are allowed if comma separated. """ if self.args.source == "*": print("You must specify a source name using the argument --source") elif self.args.tables == "*": print( "You must specify one or more tables, in the form schema.table, separated by comma using the argument --tables" ) else: self.__stop_replica() if self.args.debug: self.mysql_source.sync_tables() else: if self.config["log_dest"] == 'stdout': foreground = True else: foreground = False print("Sync tables process for source %s started." % (self.args.source)) keep_fds = [self.logger_fds] init_pid = os.path.expanduser( '%s/%s.pid' % (self.config["pid_dir"], self.args.source)) self.logger.info( "The tables %s within source %s will be synced." % (self.args.tables, self.args.source)) sync_daemon = Daemonize(app="sync_tables", pid=init_pid, action=self.mysql_source.sync_tables, foreground=foreground, keep_fds=keep_fds) sync_daemon.start()
def setup(): config = HomeServerConfig.load_config( "Synapse Homeserver", sys.argv[1:], generate_section="Homeserver" ) config.setup_logging() logger.info("Server hostname: %s", config.server_name) if re.search(":[0-9]+$", config.server_name): domain_with_port = config.server_name else: domain_with_port = "%s:%s" % (config.server_name, config.bind_port) tls_context_factory = context_factory.ServerContextFactory(config) hs = SynapseHomeServer( config.server_name, domain_with_port=domain_with_port, upload_dir=os.path.abspath("uploads"), db_name=config.database_path, tls_context_factory=tls_context_factory, config=config, content_addr=config.content_addr, ) hs.register_servlets() hs.create_resource_tree( web_client=config.webclient, redirect_root_to_web_client=True, ) hs.start_listening(config.bind_port, config.unsecure_port) hs.get_db_pool() if config.manhole: f = twisted.manhole.telnet.ShellFactory() f.username = "******" f.password = "******" f.namespace['hs'] = hs reactor.listenTCP(config.manhole, f, interface='127.0.0.1') if config.daemonize: print config.pid_file daemon = Daemonize( app="synapse-homeserver", pid=config.pid_file, action=run, auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: run()
def start(config_options): try: config = HomeServerConfig.load_config("Synapse synchrotron", config_options) except ConfigError as e: sys.stderr.write("\n" + e.message + "\n") sys.exit(1) assert config.worker_app == "synapse.app.synchrotron" setup_logging(config, use_worker_options=True) synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts database_engine = create_engine(config.database_config) ss = SynchrotronServer( config.server_name, db_config=config.database_config, config=config, version_string="Synapse/" + get_version_string(synapse), database_engine=database_engine, application_service_handler=SynchrotronApplicationService(), ) ss.setup() ss.start_listening(config.worker_listeners) def run(): # make sure that we run the reactor with the sentinel log context, # otherwise other PreserveLoggingContext instances will get confused # and complain when they see the logcontext arbitrarily swapping # between the sentinel and `run` logcontexts. with PreserveLoggingContext(): logger.info("Running") change_resource_limit(config.soft_file_limit) if config.gc_thresholds: gc.set_threshold(*config.gc_thresholds) reactor.run() def start(): ss.get_datastore().start_profiling() ss.replicate() ss.get_state_handler().start_caching() reactor.callWhenRunning(start) if config.worker_daemonize: daemon = Daemonize( app="synapse-synchrotron", pid=config.worker_pid_file, action=run, auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: run()
def start_replica(self): """ The method starts a new replica process. Is compulsory to specify a source name when running this method. """ replica_pid = os.path.expanduser( '%s/%s.pid' % (self.config["pid_dir"], self.args.source)) if self.args.source == "*": print("You must specify a source name using the argument --source") else: self.pg_engine.connect_db() self.logger.info( "Checking if the replica for source %s is stopped " % (self.args.source)) replica_status = self.pg_engine.get_replica_status() if replica_status in ['syncing', 'running', 'initialising']: print( "The replica process is already started or is syncing. Aborting the command." ) elif replica_status == 'error': print("The replica process is in error state.") print( "You may need to check the replica status first. To enable it run the following command." ) print("chameleon.py enable_replica --config %s --source %s " % (self.args.config, self.args.source)) else: self.logger.info( "Cleaning not processed batches for source %s" % (self.args.source)) self.pg_engine.clean_not_processed_batches() self.pg_engine.disconnect_db() if self.args.debug: self.run_replica() else: if self.config["log_dest"] == 'stdout': foreground = True else: self.logger = self.__init_logger() foreground = False print("Starting the replica process for source %s" % (self.args.source)) keep_fds = [self.logger_fds] app_name = "%s_replica" % self.args.source replica_daemon = Daemonize(app=app_name, pid=replica_pid, action=self.run_replica, foreground=foreground, keep_fds=keep_fds) try: replica_daemon.start() except: print( "The replica process is already started. Aborting the command." )
def start_reactor( appname, soft_file_limit, gc_thresholds, pid_file, daemonize, print_pidfile, logger, run_command=reactor.run, ): """ Run the reactor in the main process Daemonizes if necessary, and then configures some resources, before starting the reactor Args: appname (str): application name which will be sent to syslog soft_file_limit (int): gc_thresholds: pid_file (str): name of pid file to write to if daemonize is True daemonize (bool): true to run the reactor in a background process print_pidfile (bool): whether to print the pid file, if daemonize is True logger (logging.Logger): logger instance to pass to Daemonize run_command (Callable[]): callable that actually runs the reactor """ install_dns_limiter(reactor) def run(): logger.info("Running") change_resource_limit(soft_file_limit) if gc_thresholds: gc.set_threshold(*gc_thresholds) run_command() # make sure that we run the reactor with the sentinel log context, # otherwise other PreserveLoggingContext instances will get confused # and complain when they see the logcontext arbitrarily swapping # between the sentinel and `run` logcontexts. # # We also need to drop the logcontext before forking if we're daemonizing, # otherwise the cputime metrics get confused about the per-thread resource usage # appearing to go backwards. with PreserveLoggingContext(): if daemonize: if print_pidfile: print(pid_file) daemon = Daemonize( app=appname, pid=pid_file, action=run, auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: run()
def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-d', '--daemon', dest='daemon', action='store_true', default=False, required=False) arg_parser.add_argument('-f', '--foreground', dest='foreground', action='store_true', default=False, required=False) arg_parser.add_argument('-p', '--pidfile', dest='pidfile', default='/var/run/sensors-asus-ec.pid', required=False) arg_parser.add_argument('-P', '--port', dest='port', default=2787, required=False) args = arg_parser.parse_args() if args.daemon: reader = Reader(daemonize=True) server = Server(args.port, reader) daemon = Daemonize(app='sensors-asus-ec', pid=args.pidfile, foreground=args.foreground, action=server.run) daemon.start() else: data = None try: s = socket.socket() s.connect(('127.0.0.1', args.port)) data = s.recv(1024).decode() data = json.loads(data) except: pass if not data: try: reader = Reader() data = reader.get() except: print("Unable to read data.") sys.exit(1) for k, v in data.items(): print('{:20}: {}'.format(k, v))
def main(): parser = optparse.OptionParser() aws_group = optparse.OptionGroup(parser, 'AWS Options') aws_group.add_option('--region', default='us-east-1', help='AWS region to manage Spot Instances in') parser.add_option_group(aws_group) parser.add_option('--verbose', action='store_true', default=False, help='Enable verbose logging') parser.add_option('--daemon', action='store_false', dest='foreground', default=True, help='Start awsspotd in the background') parser.add_option('--pidfile', default=PIDFILE, help='Location of PID file') polling_group = optparse.OptionGroup(parser, 'Polling Options') polling_group.add_option( '--polling-interval', '-p', type='int', default=SPOT_INSTANCE_POLLING_INTERVAL, metavar='<value>', help='Polling interval in seconds (default: %default)') parser.add_option_group(polling_group) options_, args_ = parser.parse_args() result_ = [ region for region in boto.ec2.regions() if region.name == options_.region ] if not result_: sys.stderr.write('Error: Invalid EC2 region [{0}] specified\n'.format( options_.region)) sys.exit(1) cls = AWSSpotdAppClass(options_, args_) daemon = Daemonize(app='awsspotd', pid=options_.pidfile, action=cls.run, verbose=options_.verbose, foreground=options_.foreground) daemon.start()
def start_reactor( appname, soft_file_limit, gc_thresholds, pid_file, daemonize, cpu_affinity, logger, ): """ Run the reactor in the main process Daemonizes if necessary, and then configures some resources, before starting the reactor Args: appname (str): application name which will be sent to syslog soft_file_limit (int): gc_thresholds: pid_file (str): name of pid file to write to if daemonize is True daemonize (bool): true to run the reactor in a background process cpu_affinity (int|None): cpu affinity mask logger (logging.Logger): logger instance to pass to Daemonize """ def run(): # make sure that we run the reactor with the sentinel log context, # otherwise other PreserveLoggingContext instances will get confused # and complain when they see the logcontext arbitrarily swapping # between the sentinel and `run` logcontexts. with PreserveLoggingContext(): logger.info("Running") if cpu_affinity is not None: if not affinity: quit_with_error( "Missing package 'affinity' required for cpu_affinity\n" "option\n\n" "Install by running:\n\n" " pip install affinity\n\n" ) logger.info("Setting CPU affinity to %s" % cpu_affinity) affinity.set_process_affinity_mask(0, cpu_affinity) change_resource_limit(soft_file_limit) if gc_thresholds: gc.set_threshold(*gc_thresholds) reactor.run() if daemonize: daemon = Daemonize( app=appname, pid=pid_file, action=run, auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: run()
def main(): '''Wrapper main(), just enough to decide to daemonize or not''' global args descr = 'load ACARS logs into a mongodb instance' parser = argparse.ArgumentParser( description=descr, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-b', '--bind', dest='bind', type=str, metavar='IP', default='localhost', help='hostname or IP address to listen on') parser.add_argument('-p', '--port', dest='port', type=int, metavar='PORT', default=5555, help='port to listen on') parser.add_argument('-f', '--file', dest='file', type=str, metavar='FILE', default=None, help='Read file instead of doing network I/O') parser.add_argument('-m', '--mongodb', dest='db', metavar='MONGO', default=None, help='MongoDB server url') parser.add_argument('-v', '--verbose', dest='verbose', action='count', default=0, help='increase verbosity') parser.add_argument('-d', '--daemon', dest='daemon', action='store_true', default=False, help='detach from controlling terminal') args = parser.parse_args() if args.daemon: procname = 'skyshark_acars_loader' pidfile = '/tmp/{}.pid'.format(procname) daemon = Daemonize(app=procname, pid=pidfile, action=skyshark_acars_loader) daemon.start() else: skyshark_acars_loader()
def start(config_options): try: config = HomeServerConfig.load_config("Synapse client reader", config_options) except ConfigError as e: sys.stderr.write("\n" + e.message + "\n") sys.exit(1) assert config.worker_app == "synapse.app.client_reader" setup_logging(config.worker_log_config, config.worker_log_file) events.USE_FROZEN_DICTS = config.use_frozen_dicts database_engine = create_engine(config.database_config) tls_server_context_factory = context_factory.ServerContextFactory(config) ss = ClientReaderServer( config.server_name, db_config=config.database_config, tls_server_context_factory=tls_server_context_factory, config=config, version_string="Synapse/" + get_version_string(synapse), database_engine=database_engine, ) ss.setup() ss.get_handlers() ss.start_listening(config.worker_listeners) def run(): with LoggingContext("run"): logger.info("Running") change_resource_limit(config.soft_file_limit) if config.gc_thresholds: gc.set_threshold(*config.gc_thresholds) reactor.run() def start(): ss.get_state_handler().start_caching() ss.get_datastore().start_profiling() ss.replicate() reactor.callWhenRunning(start) if config.worker_daemonize: daemon = Daemonize( app="synapse-client-reader", pid=config.worker_pid_file, action=run, auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: run()
def start(config_options): try: config = HomeServerConfig.load_config( "Synapse federation reader", config_options ) except ConfigError as e: sys.stderr.write("\n" + e.message + "\n") sys.exit(1) assert config.worker_app == "synapse.app.federation_reader" setup_logging(config.worker_log_config, config.worker_log_file) database_engine = create_engine(config.database_config) tls_server_context_factory = context_factory.ServerContextFactory(config) ss = FederationReaderServer( config.server_name, db_config=config.database_config, tls_server_context_factory=tls_server_context_factory, config=config, version_string="Synapse/" + get_version_string(synapse), database_engine=database_engine, ) ss.setup() ss.get_handlers() ss.start_listening(config.worker_listeners) def run(): with LoggingContext("run"): logger.info("Running") change_resource_limit(config.soft_file_limit) if config.gc_thresholds: gc.set_threshold(*config.gc_thresholds) reactor.run() def start(): ss.get_state_handler().start_caching() ss.get_datastore().start_profiling() ss.replicate() reactor.callWhenRunning(start) if config.worker_daemonize: daemon = Daemonize( app="synapse-federation-reader", pid=config.worker_pid_file, action=run, auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: run()
def start_daemon(processor, logger, file_descriptors): daemon = Daemonize(app=processor.SYSLOG_NAME, pid=processor.pid_path, action=processor.start, keep_fds=file_descriptors, logger=logger, foreground=True) daemon.start()
def main(): import argparse import logging import os import setproctitle import traceback from daemonize import Daemonize from kolejka.common.settings import OBSERVER_SOCKET from kolejka.observer import KolejkaObserverServer parser = argparse.ArgumentParser(description='KOLEJKA observer') parser.add_argument("-s", "--socket", type=str, default=OBSERVER_SOCKET, help='listen on socket') parser.add_argument("-v", "--verbose", action="store_true", default=False, help='show more info') parser.add_argument("-d", "--debug", action="store_true", default=False, help='show debug info') parser.add_argument("--detach", action="store_true", default=False, help='run in background') parser.add_argument("--pid-file", type=str, default=OBSERVER_PID_FILE, help='pid file') args = parser.parse_args() level = logging.WARNING if args.verbose: level = logging.INFO if args.debug: level = logging.DEBUG logging.basicConfig(level=level) setproctitle.setproctitle('kolejka-observer') with KolejkaObserverServer(args.socket) as server: def action(): return server.serve_forever() if args.detach: daemon = Daemonize(app='kolejka-observer', pid=args.pid_file, action=action, verbose=(args.debug or args.verbose)) daemon.start() else: action()
def daemonize(pidfile): try: import traceback from daemonize import Daemonize daemon = Daemonize(app='pynab', pid=pidfile, action=main) daemon.start() except SystemExit: raise except: log.critical(traceback.format_exc())
def main(): f = Monitor() if len(sys.argv) > 1 and sys.argv[1] == '-d': pid = '/tmp/watchman.pid' daemon = Daemonize(app='monitoring', pid=pid, action=f.run) daemon.start() else: f.run()
def start(): logger.info('Starting TPyNode in Daemon Mode') pidfile = config['TPyNode'].get('pidfile') def runner(): run_tpynode(config, modules) daemon = Daemonize(app="tpynode", pid=pidfile, action=runner) daemon.start()
def run(background=False): if background == True: pid = os.fork() if pid: p = basename(sys.argv[0]) myname, file_extension = os.path.splitext(p) pidfile = '/tmp/%s.pid' % myname daemon = Daemonize(app=myname, pid=pidfile, action=runAgent) daemon.start() else: runAgent()
def start(self): self.initLog() pidfile = self.prefix + ".pid" daemon = Daemonize(app=self.prefix, pid=pidfile, action=self.loopRun, auto_close_fds=False, chdir=".", foreground=False, logger=self.slogger) daemon.start()
def start(configfile): _load_config(configfile) os.environ["UPD89_DATADIR"] = _config.getDataDir() newpid = os.fork() if newpid == 0: import websrv websrv.start(_config) else: daemon = Daemonize(app="test_app", pid=_pid, action=main, keep_fds=_log.getKeepfds()) daemon.start()
def main(): parser, opts = parseopt() if path.exists(opts.socket): print("+ socket file {} already exists".format(opts.socket)) exit(1) if opts.daemonize: print("+ daemonizing - pid file {}".format(opts.pidfile)) daemon = Daemonize(app="module_launcher", pid=opts.pidfile, action=lambda: _main(opts)) daemon.start() else: _main(opts)
def main(argv=None): logger.setLevel(CONF.log_level) formatter = logging.Formatter(CONF.log_format) handler = logging.FileHandler(CONF.log_file) handler.setFormatter(formatter) logger.addHandler(handler) daemon = Daemonize(app="Downtimer", pid=CONF.pid_file, action=downtimer_starter, logger=logger, keep_fds=[handler.stream.fileno()]) daemon.start()
def startApp(ourWsgiApp): global runWsgiApp runWsgiApp = ourWsgiApp if runInForeGround: runApp() return ourPidfile = runningConfig.server.pidfile ourDaemon = Daemonize(app = 'wsgiApp', pid = ourPidfile, action = runApp, verbose = True) ourDaemon.start()
def daemonize(pidfile): try: import traceback from daemonize import Daemonize fds = [] if log_descriptor: fds = [log_descriptor] daemon = Daemonize(app='pynab', pid=pidfile, action=main, keep_fds=fds) daemon.start() except SystemExit: raise except: log.critical(traceback.format_exc())
def run_server(): parser = ArgumentParser() parser.add_argument('command', choices=['START', 'STOP', 'RESTART']) parser.add_argument('--port', type=int, default=default_port, help='the port the server will use (default: {0})'.format(default_port)) parser.add_argument('--taskqueue', type=str, default=default_taskqueue, help='hostname of the taskqueue (default: {0})'.format(default_taskqueue)) parser.add_argument('--triplestore', type=str, default=default_triplestore, help='hostname of the triplestore (default: {0})'.format(default_triplestore)) parser.add_argument('--background', action="store_true", help='when provided, the server will run in the background') arguments = parser.parse_args() def args_run(): run(arguments.port, arguments.taskqueue, arguments.triplestore) pidfile = '/var/run/sos-server.pid' command = arguments.command.upper() if command != 'START': from os import kill from signal import SIGTERM from errno import EPERM # stop the server pid = int(open(pidfile).read()) try: kill(pid, SIGTERM) print('The SPARQL over SMS server has been stopped.') except OSError as e: if e.errno == EPERM: exit(1) if command == 'STOP': exit(0) if arguments.background: from daemonize import Daemonize daemon = Daemonize(app="sos-server", pid=pidfile, action=args_run) daemon.start() else: args_run()
def nodes(start_port, cores, daemonize): """start multiple nodes""" cpus = multiprocessing.cpu_count() if cores > 0: cores = min(cpus, cores) else: cores = max(1, cpus - cores) click.echo('starting {} nodes'.format(cores)) if daemonize: def action(): start_nodes(start_port, cores) daemon = Daemonize(app='syd', pid='/tmp/syd.pid', action=action) daemon.start() else: start_nodes(start_port, cores)
def start_daemon(self): for sender in self.senders: ev, unit = sender.schedule_ev, sender.schedule_unit def r(): providers = [f.fetch() for f in self.fetchers] sender.send(providers) self.schedule(r, ev, unit) def main_loop(): while True: schedule.run_pending() time.sleep(1) pidfile = '/tmp/issues-reminder.pid' daemon = Daemonize(app='issues-reminder', pid=pidfile, action=main_loop) daemon.start()
def daemon(args): print "Daemon" def main(): print "Running Main" context = zmq.Context() socket = context.socket(zmq.REP) socket.bind('tcp://127.0.0.1:5555') while True: msg = socket.recv() socket.send("Hello World!") # Actually Daemonize if args.foreground: main() else: daemon = Daemonize(app="test_app", pid=args.pidfile, action=main) daemon.start()
def run(hs): PROFILE_SYNAPSE = False if PROFILE_SYNAPSE: def profile(func): from cProfile import Profile from threading import current_thread def profiled(*args, **kargs): profile = Profile() profile.enable() func(*args, **kargs) profile.disable() ident = current_thread().ident profile.dump_stats("/tmp/%s.%s.%i.pstat" % ( hs.hostname, func.__name__, ident )) return profiled from twisted.python.threadpool import ThreadPool ThreadPool._worker = profile(ThreadPool._worker) reactor.run = profile(reactor.run) def in_thread(): with LoggingContext("run"): change_resource_limit(hs.config.soft_file_limit) reactor.run() if hs.config.daemonize: if hs.config.print_pidfile: print hs.config.pid_file daemon = Daemonize( app="synapse-homeserver", pid=hs.config.pid_file, action=lambda: in_thread(), auto_close_fds=False, verbose=True, logger=logger, ) daemon.start() else: in_thread()
def __init_mysql_replica(self): """ The method initialise a replica for a given mysql source within the specified configuration. The method is called by the public method init_replica. """ if self.args.debug: self.mysql_source.init_replica() else: if self.config["log_dest"] == 'stdout': foreground = True else: foreground = False print("Init replica process for source %s started." % (self.args.source)) keep_fds = [self.logger_fds] init_pid = os.path.expanduser('%s/%s.pid' % (self.config["pid_dir"],self.args.source)) self.logger.info("Initialising the replica for source %s" % self.args.source) init_daemon = Daemonize(app="init_replica", pid=init_pid, action=self.mysql_source.init_replica, foreground=foreground , keep_fds=keep_fds) init_daemon.start()
def daemonize(fetcher, args, config): logger = logging.getLogger('daemon') pid = config.daemon['pid'] if 'pid' in config.daemon else '/tmp/fetcherd.pid' user = config.daemon['user'] if 'user' in config.daemon else None group = config.daemon['group'] if 'group' in config.daemon else None daemon = Daemonize("fetcherd", pid, daemon_setup, privileged_action=lambda: [fetcher, args, config], user=user, group=group, ) try: logger.info("Forked") daemon.start() except Exception as e: logger.critical("Error during daemonize: {}".format(e))
def main(argv=None): if argv is None: argv = sys.argv mod_docstring = sys.modules[__name__].__doc__ arg_parser = ArgumentParser( description=mod_docstring, formatter_class=RawDescriptionHelpFormatter, ) PulsarConfigBuilder.populate_options(arg_parser) args = arg_parser.parse_args(argv) pid_file = args.pid_file log.setLevel(logging.DEBUG) log.propagate = False if args.daemonize: if Daemonize is None: raise ImportError(REQUIRES_DAEMONIZE_MESSAGE) keep_fds = [] if args.daemon_log_file: fh = logging.FileHandler(args.daemon_log_file, "w") fh.setLevel(logging.DEBUG) log.addHandler(fh) keep_fds.append(fh.stream.fileno()) else: fh = logging.StreamHandler(sys.stderr) fh.setLevel(logging.DEBUG) log.addHandler(fh) daemon = Daemonize( app="pulsar", pid=pid_file, action=functools.partial(app_loop, args, log), verbose=DEFAULT_VERBOSE, logger=log, keep_fds=keep_fds, ) daemon.start() else: app_loop(args, log)
def handle(self, verbosity, *args, **options): log_handler = None log_file = options.get('log_file') if log_file is not None: log_handler = logging.FileHandler(log_file) if verbosity >= 3: configure_logging(level=logging.DEBUG, handler=log_handler) configure_logging(level=logging.DEBUG, logger='ExchangeSession', handler=log_handler) elif verbosity >= 2 or log_handler is not None: configure_logging(handler=log_handler) pid_file = options.get('pid_file') if options['daemonize']: if not pid_file: self.stderr.write(self.style.ERROR("--daemonize requires also the --pid-file argument")) exit(1) kwargs = {} if log_handler: kwargs['keep_fds'] = [log_handler.stream.fileno()] listener = None def run_listener(): atexit.register(stop_listener) listener = NotificationListener(sync_after_start=True) listener.start() def stop_listener(): logger.info("Stopping listener") listener.close() daemon = Daemonize(app='respa_exchange_listen', pid=pid_file, action=run_listener, logger=logger, **kwargs) daemon.start() else: pid_file = options.get('pid_file') if pid_file: pid = str(os.getpid()) with open(pid_file, 'w') as f: f.write(pid) with closing(NotificationListener()) as listener: listener.start()
def launch_daemon(): worker = get_available_worker_name() pid = "/tmp/%s.pid" % worker logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.propagate = False fh = logging.FileHandler("/tmp/%s.log" % worker, "w") fh.setLevel(logging.DEBUG) logger.addHandler(fh) keep_fds = [fh.stream.fileno()] daemon = Daemonize( app="dune", pid=pid, action=launch_worker, keep_fds=keep_fds ) daemon.start()
def start_replica(self): """ The method starts a new replica process. Is compulsory to specify a source name when running this method. """ replica_pid = os.path.expanduser('%s/%s.pid' % (self.config["pid_dir"],self.args.source)) if self.args.source == "*": print("You must specify a source name using the argument --source") else: self.pg_engine.connect_db() self.logger.info("Checking if the replica for source %s is stopped " % (self.args.source)) replica_status = self.pg_engine.get_replica_status() if replica_status in ['syncing', 'running', 'initialising']: print("The replica process is already started or is syncing. Aborting the command.") elif replica_status == 'error': print("The replica process is in error state.") print("You may need to check the replica status first. To enable it run the following command.") print("chameleon.py enable_replica --config %s --source %s " % (self.args.config, self.args.source)) else: self.logger.info("Cleaning not processed batches for source %s" % (self.args.source)) self.pg_engine.clean_not_processed_batches() self.pg_engine.disconnect_db() if self.args.debug: self.__run_replica() else: if self.config["log_dest"] == 'stdout': foreground = True else: foreground = False print("Starting the replica process for source %s" % (self.args.source)) keep_fds = [self.logger_fds] app_name = "%s_replica" % self.args.source replica_daemon = Daemonize(app=app_name, pid=replica_pid, action=self.__run_replica, foreground=foreground , keep_fds=keep_fds) try: replica_daemon.start() except: print("The replica process is already started. Aborting the command.")
def run(): global args logger = None args = parse_args() if args.stop: stop_daemon(args) sys.exit(0) if os.getuid() == 0: if args.as_root: print("The daemon is being run as root.") else: print("The daemon should not be run as root. If you have a good reason to do so, use the --as-root flag.") sys.exit(1) if args.respawn: stop_daemon(args) time.sleep(3) # daemonize logs exceptions to its logger (which defaults to the syslog) # and does not make them appear on stdout/stderr. If we're in foreground # mode, override that logger with our own. if args.foreground: logger = logging.getLogger('run-daemon') if args.verbose: logger.setLevel(logging.DEBUG) install_example_config_file(args.config) os.makedirs(args.run_dir, exist_ok=True) daemon = Daemonize(app="openrazer-daemon", pid=os.path.join(args.run_dir, "openrazer-daemon.pid"), action=run_daemon, foreground=args.foreground, verbose=args.verbose, chdir=args.run_dir, logger=logger) daemon.start()
def daemonize(command, name, pidfile, logger): """Daemonizes the `command` function. Uses `name` for syslogging, `pidfile` for the pid file, and logs messages to `logger` or a child logger of logger as appropriate. """ # This is the only function that requires daemonize. # Bail if we don't have it. if not HAS_DAEMONIZE: raise Exception("Need `daemonize` to run as daemon") _using_pidfile(pidfile, logger) daemon = Daemonize( app=name, pid=pidfile, action=command, logger=logging.getLogger(logger.name + ".daemon") ) # Daemonize.start() calls sys.exit() for parent thread, so nothing # after this will execute. daemon.start()
def main(): arg_parser = ArgumentParser(description=DESCRIPTION) GalaxyConfigBuilder.populate_options(arg_parser) args = arg_parser.parse_args() if args.log_file: os.environ["GALAXY_CONFIG_LOG_DESTINATION"] = os.path.abspath(args.log_file) if args.server_name: os.environ["GALAXY_CONFIG_SERVER_NAME"] = args.server_name pid_file = args.pid_file log.setLevel(logging.DEBUG) log.propagate = False if args.daemonize: if Daemonize is None: raise ImportError(REQUIRES_DAEMONIZE_MESSAGE) keep_fds = [] if args.daemon_log_file: fh = logging.FileHandler(args.daemon_log_file, "w") fh.setLevel(logging.DEBUG) log.addHandler(fh) keep_fds.append(fh.stream.fileno()) else: fh = logging.StreamHandler(sys.stderr) fh.setLevel(logging.DEBUG) log.addHandler(fh) daemon = Daemonize( app="galaxy", pid=pid_file, action=functools.partial(app_loop, args, log), verbose=DEFAULT_VERBOSE, logger=log, keep_fds=keep_fds, ) daemon.start() else: app_loop(args, log)
def run(app): """Setup some reasonable defaults (even if running as dummy), run application""" if 'servertype' not in app: app['servertype'] = 'auto' if not app.get('data_dir'): app['data_dir'] = resource_filename(__name__, '') if not app.get('db_dir'): app['db_dir'] = '/tmp' root.static_dir = app['data_dir'] + '/static/' bottle.TEMPLATE_PATH = [app['data_dir'] + '/views/'] if app['debug']: bottle.debug(True) if not app['nofork']: pidfile_path = app['db_dir'] + '/go-runner.pid' print pidfile_path daemon = Daemonize(app='go', pid=pidfile_path, action=lambda: startServing(app)) daemon.start() else: startServing(app)
def main(): if Daemonize is None: raise ImportError("Attempted to use LWR in daemon mode, but daemonize is unavailable.") arg_parser = ArgumentParser(description=DESCRIPTION) LwrConfigBuilder.populate_options(arg_parser) args = arg_parser.parse_args() log.setLevel(logging.DEBUG) log.propagate = False fh = logging.FileHandler("daemon.log", "w") fh.setLevel(logging.DEBUG) log.addHandler(fh) keep_fds = [fh.stream.fileno()] daemon = Daemonize( app="lwr", pid=DEFAULT_PID, action=functools.partial(app_loop, args), verbose=DEFAULT_VERBOSE, keep_fds=keep_fds, ) daemon.start()