def main(): if is_console_app(): # config logging configure_logging() # add console logging root_logger = logging.getLogger() console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(logging.Formatter('%(name)-20s: %(levelname)-8s %(message)s')) root_logger.addHandler(console) # start app app = create_appcontainer() app.start() logging.info('[PRESS ENTER TO DIE]') raw_input() app.stop() else: # start as deamon app = App() daemon_runner = DaemonRunner(app) daemon_runner.daemon_context.signal_map = {SIGTERM: app.terminate} daemon_runner.daemon_context.working_directory = '.' daemon_runner.do_action()
def __init__(self, data_dir, action, files_preserve, pid_file): self.data_dir = os.path.abspath(data_dir) # attributes required by daemon runner self.stdin_path = '/dev/null' self.stdout_path = '/dev/null' self.stderr_path = '/dev/null' self.pidfile_path = pid_file self.pidfile_timeout = 5 # initialise daemon runner DaemonRunner.__init__(self, self) self.daemon_context.files_preserve = files_preserve self.action = action
def main(): if g.config.get('wstund', 'role') != 'server': g.logger.error('config role is not server') return # g.logger.debug('YMK in wstund_client main') daemon_runner = DaemonRunner(wstundServertApp()) try: daemon_runner.do_action() except (DaemonRunnerStopFailureError, LockTimeout) as e: g.logger.error(e) sys.exit(e)
def __init__(self, app): for cmd in app.EXTRA_CMDS: DaemonRunner.action_funcs[cmd] = getattr(app, cmd) self.parse_args() self._stdout_path = app.stdout_path self._stdin_path = app.stdin_path self._stderr_path = app.stderr_path with open(app.stdin_path, 'a'): pass if self.action not in self.START_CMDS: app.stdin_path = '/dev/null' app.stdout_path = '/dev/null' app.stderr_path = '/dev/null' elif self.action in self.START_CMDS: self.pidfile = make_pidlockfile(app.pidfile_path, app.pidfile_timeout) status = self._get_status() if status[0] == 1: print('app is running.') raise ValueError('app is running') self._rename_log(app.stdout_path) self._rename_log(app.stderr_path) #主微线程 self._main_let = getcurrent() def _wrap_run(func): """守护模式后,没有下面sleep, 某些(admin进程在socket.getaddrinfo)会在卡死 怀疑是gevent微线程切换问题,暂时这么处理 """ def _func(*args, **kw): sleep(0.05) return func(*args, **kw) return _func app.run = _wrap_run(app.start) DaemonRunner.__init__(self, app) self._init_signal()
def _terminate_daemon_process(self): """ Terminate the daemon process specified in the current PID file. """ if 1: DaemonRunner._terminate_daemon_process(self) else: #用app.stop import config from grpc import get_proxy_by_addr, uninit app = get_proxy_by_addr(config.admin_addr, 'app') app.stop(_no_result=True) sleep(0.5) del app uninit() timeout = 60 while timeout > 0: timeout -= 1 time.sleep(1) if not self.pidfile.is_locked(): break if timeout <= 0: sys.exit('stop error:Timeout')
def __init__(self, app): for cmd in app.EXTRA_CMDS: DaemonRunner.action_funcs[cmd] = getattr(app, cmd) self.parse_args() self._stdout_path = app.stdout_path self._stdin_path = app.stdin_path self._stderr_path = app.stderr_path if self.action not in self.START_CMDS: app.stdin_path = '/dev/null' app.stdout_path = '/dev/null' app.stderr_path = '/dev/null' elif self.action in self.START_CMDS: self.pidfile = make_pidlockfile( app.pidfile_path, app.pidfile_timeout) status = self._get_status() if status[0] == 1: print 'app is running.' raise ValueError, 'app is running' self._rename_log(app.stdout_path) self._rename_log(app.stderr_path) #主微线程 self._main_let = getcurrent() def _wrap_run(func): """守护模式后,没有下面sleep, 某些(admin进程在socket.getaddrinfo)会在卡死 怀疑是gevent微线程切换问题,暂时这么处理 """ def _func(*args, **kw): sleep(0.05) return func(*args, **kw) return _func app.run = _wrap_run(app.run) DaemonRunner.__init__(self, app) self._init_signal()
def main(): """ Call with arguments start/restart/stop """ run = DaemonRunner(DashCam()) run.do_action()
try: query = self.mc_server.query() except: return current_players = set(query.players.names) diff = current_players - self.current_players self.current_players = current_players if len(diff) > 0: for p in diff: await self.channel.send(random.choice(LOGIN_MSG).format(p)) class steve_miner_bot: def __init__(self): self.stdin_path = tempfile.mkstemp()[1] self.stdout_path = tempfile.mkstemp()[1] self.stderr_path = tempfile.mkstemp()[1] self.pidfile_path = "/tmp/steve_miner_bot.pid" self.pidfile_timeout = 15 def run(self): client = MyClient() client.run(os.environ['DISCORD_TOKEN']) bot = DaemonRunner(steve_miner_bot()) bot.do_action() # bot = steve_miner_bot() # bot.run()
@zk.ChildrenWatch(ZK_ROOT + "stop") def stop_watch(children): for job in children: logging.info("stop {}".format(job)) zk.delete(ZK_ROOT + "stop/" + job) try: pid = int(zk.get(ZK_ROOT + "pid/" + job)[0].decode()) zk.delete(ZK_ROOT + "pid/" + job) os.kill(pid, signal.SIGKILL) except NoNodeError as no_node_err: no_node_err.__traceback__ if __name__ == '__main__': try: zk.start() except KazooTimeoutError as e: e.__traceback__ exit("can't connect zookeeper") if not zk.exists(ZK_ROOT + "start"): zk.create(ZK_ROOT + "start") if not zk.exists(ZK_ROOT + "stop"): zk.create(ZK_ROOT + "stop") if not zk.exists(ZK_ROOT + "pid"): zk.create(ZK_ROOT + "pid") input() """ if __name__ == '__main__': daemon_runner = DaemonRunner(Listen_kg()) daemon_runner.do_action()
self.log.exception( "The mail sending process failed. Have in mind that is required that the web service must be online." ) finish_timestamp = datetime.today() self.stall_loop(start_timestamp, finish_timestamp) parser = argparse.ArgumentParser( description='Starts or stops the seal daemon.') parser.add_argument('command', metavar='start/stop', help='the command that should be executed on the daemon') args = parser.parse_args() logger_manager = LoggerManager() log = logger_manager.getLogger() log.info("Daemon action recived: '%s'", args.command) loop_runner = LoopRunner() daemon_runner = DaemonRunner(loop_runner) # runner.DaemonRunner(loop_runner) daemon_runner.daemon_context.files_preserve = [ logger_manager.get_file_handler().stream ] daemon_runner.do_action() if ("start".__eq__(args.command.lower())): log.info("Daemon launched.") else: log.info("Daemon stopped.")
doorbell = DoorBell() webhook = IftttWebHook(ifttt_webhook_endpoint, ifttt_webhook_key, 'button_pressed') def get_button_pressed(self, hwsrc): logging.debug('in %s::%s', self.__class__.__name__, 'get_button_pressed') logging.debug("Processing %s" % hwsrc) for button in self.buttons: if hwsrc in button['hwsrc']: logging.info('%s button pressed' % button['name']) self.webhook.send_event(options={'value1': button['name']}) # self.doorbell.chime() def get_arp_src(self, packet): logging.debug('in %s::%s', self.__class__.__name__, 'get_arp_src') hwsrc = packet[ARP].hwsrc self.get_button_pressed(hwsrc) def run(self): logging.basicConfig(filename=self.stdout_path, level=LOGLEVEL) logging.info("Starting") sniff(filter='arp', iface='en0', prn=self.get_arp_src) if __name__ == '__main__': # buttonEvent = ButtonEvent() # buttonEvent.run() buttonEventLoop = DaemonRunner(ButtonEvent()) buttonEventLoop.do_action()
from __future__ import division, print_function, unicode_literals import os import sys from daemon.runner import DaemonRunner PREFIX = os.path.abspath(os.path.dirname(__file__)) class WebUIDaemon(object): def __init__(self): self.stdin_path = os.devnull # self.stdout_path = os.devnull self.stdout_path = os.path.join(PREFIX, "/var/log/webui.log") self.stderr_path = self.stdout_path self.pidfile_path = "/var/run/webui.pid" self.pidfile_timeout = 1 def run(self): sys.path.append(PREFIX) # Flask's reloader forks using sys.argv, set it to the actual entry-point since we can't run the daemon script again sys.argv = [os.path.join(PREFIX, "webui.py")] from webui import app app.run(debug=True) if __name__ == "__main__": sys.argv[0] = os.path.abspath(sys.argv[0]) DaemonRunner(WebUIDaemon()).do_action()
for msg, ts in messages: if len(msg) > 14: continue df = pms.df(msg) if df not in [4, 5, 11]: continue line = ['%.6f' % ts, 'DF%02d' % df, msg] self.lines.append(line) if len(self.lines) > 1000: try: fcsv = open(csvfile, 'a') writer = csv.writer(fcsv) writer.writerows(self.lines) fcsv.close() except Exception, err: print err self.lines = [] if __name__ == '__main__': app = ELSClient(host=HOST, port=PORT) daemon_runner = DaemonRunner(app) daemon_runner.do_action()
{"symbol_id": self._db.get_symbol_id(symbol), what: when} for what, symbol, when in self.__update_cache ] ) self.__update_cache = [] else: symbol = context["symbol"] frequency = context["frequency"] latest_dt = context.get("to_date_time", None) self.__update_cache.append((bar.FrequencyToStr[frequency], symbol, latest_dt)) # def key_stats_updated(self, symbol): # return self.__last_updated['key_stats_updated'].get(symbol, False) # def __key_stats_updated(self, symbol): # self.__last_updated['key_stats_updated'][symbol] = True if __name__ == "__main__": um = Manager() logger = logging.getLogger("SymbolUpdateManager") logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler = logging.FileHandler("/var/log/testdaemon/testdaemon.log") handler.setFormatter(formatter) logger.addHandler(handler) runner = DaemonRunner(um) runner.daemon_context.files_preserve = [handler.stream] runner.do_action()
def run(indocker=None): docker_settings = init_config() log_location = '/var/log/dockerlaunch' run_location = '/var/run/dockerlaunch' lib_location = '/var/lib/dockerlaunch' socket_name = 'dockerlaunch.sock' log_name = 'dockerlaunch.log' pid_name = 'dockerlaunch.pid' script_name = 'docker-launch-inner.py' if not os.path.exists(lib_location): os.makedirs(lib_location) os.chmod(lib_location, 0o755) if indocker is None: indocker = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'indocker.py') script_filename = os.path.join(lib_location, script_name) with open(script_filename, 'w') as f, open(indocker, 'r') as g: # Any processing of indocker here f.write(g.read()) os.chmod(script_filename, 0o644) docker_settings['script_filename'] = script_filename # Drop privileges docker_launch_pwd = pwd.getpwnam('dockerlaunch') docker_launch_uid = docker_launch_pwd.pw_uid docker_launch_gid = docker_launch_pwd.pw_gid os.setgid(docker_launch_gid) # This pulls in the docker group (of which dockerlaunch should be a member) os.initgroups('dockerlaunch', docker_launch_gid) # http://www.gavinj.net/2012/06/building-python-daemon-process.html for location in (run_location, log_location): if not os.path.exists(location): # NOTE: while there is a mode arg, it's overridden by umask os.makedirs(location) os.chmod(location, 0o750) os.chown( location, docker_launch_uid, docker_launch_gid ) socket_filename = os.path.join(run_location, socket_name) pid_filename = os.path.join(run_location, pid_name) logger = logging.getLogger("DockerLaunchLog") logger.setLevel(logging.INFO) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) log_filename = os.path.join(log_location, log_name) if not os.path.exists(log_filename): open(log_filename, 'a').close() os.chown(log_filename, docker_launch_uid, docker_launch_gid) os.chmod(log_filename, 0o755) handler = logging.FileHandler(log_filename) handler.setFormatter(formatter) logger.addHandler(handler) docker_app = DockerLaunchApp( docker_settings, socket_filename, pid_filename, logger=logger ) runner = DaemonRunner(docker_app) runner.daemon_context.uid = docker_launch_uid runner.daemon_context.gid = docker_launch_gid runner.daemon_context.umask = 0o027 runner.daemon_context.files_preserve = [handler.stream, _find_urandom_fd()] runner.do_action()
when } for what, symbol, when in self.__update_cache]) self.__update_cache = [] else: symbol = context['symbol'] frequency = context['frequency'] latest_dt = context.get('to_date_time', None) self.__update_cache.append( (bar.FrequencyToStr[frequency], symbol, latest_dt)) #def key_stats_updated(self, symbol): #return self.__last_updated['key_stats_updated'].get(symbol, False) #def __key_stats_updated(self, symbol): #self.__last_updated['key_stats_updated'][symbol] = True if __name__ == '__main__': um = Manager() logger = logging.getLogger('SymbolUpdateManager') logger.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler = logging.FileHandler('/var/log/testdaemon/testdaemon.log') handler.setFormatter(formatter) logger.addHandler(handler) runner = DaemonRunner(um) runner.daemon_context.files_preserve = [handler.stream] runner.do_action()
def run(indocker=None): docker_settings = init_config() log_location = '/var/log/dockerlaunch' run_location = '/var/run/dockerlaunch' lib_location = '/var/lib/dockerlaunch' socket_name = 'dockerlaunch.sock' log_name = 'dockerlaunch.log' pid_name = 'dockerlaunch.pid' script_name = 'docker-launch-inner.py' if not os.path.exists(lib_location): os.makedirs(lib_location) os.chmod(lib_location, 0o755) if indocker is None: indocker = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'indocker.py') script_filename = os.path.join(lib_location, script_name) with open(script_filename, 'w') as f, open(indocker, 'r') as g: # Any processing of indocker here f.write(g.read()) os.chmod(script_filename, 0o644) docker_settings['script_filename'] = script_filename # Drop privileges docker_launch_pwd = pwd.getpwnam('dockerlaunch') docker_launch_uid = docker_launch_pwd.pw_uid docker_launch_gid = docker_launch_pwd.pw_gid os.setgid(docker_launch_gid) # This pulls in the docker group (of which dockerlaunch should be a member) os.initgroups('dockerlaunch', docker_launch_gid) # http://www.gavinj.net/2012/06/building-python-daemon-process.html for location in (run_location, log_location): if not os.path.exists(location): # NOTE: while there is a mode arg, it's overridden by umask os.makedirs(location) os.chmod(location, 0o750) os.chown(location, docker_launch_uid, docker_launch_gid) socket_filename = os.path.join(run_location, socket_name) pid_filename = os.path.join(run_location, pid_name) logger = logging.getLogger("DockerLaunchLog") logger.setLevel(logging.INFO) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") log_filename = os.path.join(log_location, log_name) if not os.path.exists(log_filename): open(log_filename, 'a').close() os.chown(log_filename, docker_launch_uid, docker_launch_gid) os.chmod(log_filename, 0o755) handler = logging.FileHandler(log_filename) handler.setFormatter(formatter) logger.addHandler(handler) docker_app = DockerLaunchApp(docker_settings, socket_filename, pid_filename, logger=logger) runner = DaemonRunner(docker_app) runner.daemon_context.uid = docker_launch_uid runner.daemon_context.gid = docker_launch_gid runner.daemon_context.umask = 0o027 runner.daemon_context.files_preserve = [handler.stream, _find_urandom_fd()] runner.do_action()
phi2 = (90.0 - lat2)*degrees_to_radians theta1 = long1*degrees_to_radians theta2 = long2*degrees_to_radians cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2)) arc = math.acos( cos ) return arc * 3960 def run(self): logging.basicConfig(format='%(asctime)s | iss_tracker | %(levelname)s | %(message)s', filename='track_iss.log',level=logging.INFO) self.log("Started Tracking ISS") try: while True: closest_distance = self.work (home_lat, home_long) time.sleep(30) except (SystemExit,KeyboardInterrupt): self.clear_alert() logging.info("Stopped Tracking ISS Closest Distance = %s",closest_distance) pass except: self.clear_alert() logging.exception("Unexpected Error: Stopped Tracking ISS") raise if __name__ == '__main__': try: run = DaemonRunner(Tracker()) run.daemon_context.working_directory=os.getcwd() run.do_action() except DaemonRunnerStopFailureError: print("iss_tracker is not running")
import os from daemon.runner import DaemonRunner import pydevd import signal from pihex import PiHex import util __author__ = 'paul' pihex = PiHex() daemon_runner = DaemonRunner(pihex) daemon_runner.daemon_context.working_directory = os.getcwd() # add our terminate method to the signal map daemon_runner.daemon_context.signal_map[signal.SIGTERM] = pihex.terminate daemon_runner.daemon_context.files_preserve = [util.file_handler.stream] daemon_runner.do_action()
def do_action(self): r = DaemonRunner(self) r.daemon_context.files_preserve = self.files_preserve r.do_action()
SCHED.add_job(func=FUNC_PID, args=('cn-north-1', ), trigger=PID_TRIGGER) SCHED.add_job(func=FUNC_PID, args=('cn-east-2', ), trigger=PID_TRIGGER) SCHED.add_job(func=FUNC_PID, args=('cn-south-1', ), trigger=PID_TRIGGER) SCHED.add_job(func=FUNC_EIP, args=('cn-north-1', ), trigger=EIP_TRIGGER) SCHED.add_job(func=FUNC_EIP, args=('cn-east-2', ), trigger=EIP_TRIGGER) SCHED.add_job(func=FUNC_EIP, args=('cn-south-1', ), trigger=EIP_TRIGGER) SCHED.start() while True: time.sleep(10) log.logging.info('service is active.') run = DaemonRunner(Tianlei()) run.do_action() #if bbb=='config': # print(bbb) #elif bbb=='service': # run = DaemonRunner(Tianlei()) # run.do_action() #else: # print('nonono')