def start(self): self.end = time.time() + self.ttl context = daemon.DaemonContext(working_directory=os.getcwd(), umask=0o002, pidfile=PIDLockFile(self.pid_file)) with context: self.run_http_server()
def make_pidlockfile(path): """ Make a LockFile instance with the given filesystem path. """ if not isinstance(path, basestring): raise ValueError("Not a filesystem path: %(path)r" % vars()) if not os.path.isabs(path): raise ValueError("Not an absolute path: %(path)r" % vars()) return PIDLockFile(path)
def execute(self, *args, **options): if options["daemon"]: pid_file = options["pid-file"] if os.path.exists(pid_file + ".lock") or os.path.exists(pid_file): try: pid = int(open(pid_file).read()) os.kill(pid, 0) except (ValueError, OSError, IOError): # Not running, delete stale PID file sys.stderr.write("Removing stale PID file\n") import errno try: os.remove(pid_file) except OSError as e: if e.errno != errno.ENOENT: raise e try: os.remove(pid_file + ".lock") except OSError as e: if e.errno != errno.ENOENT: raise e else: # Running, we should refuse to run raise RuntimeError("Daemon is already running (PID %s)" % pid) with DaemonContext(pidfile=PIDLockFile(pid_file)): self._execute_inner(*args, **options) else: self._execute_inner(*args, **options)
def __init__(self, pidfile): """ Create exclusive app lock """ if pidfile.startswith("/"): piddir = os.path.dirname(pidfile) pidpath = pidfile # use explicit path else: piddir = "/var/lib/zabbixsrv/" pidpath = "{dir}{file}".format(dir=piddir, file=pidfile) # Check lockdir exists if not os.path.exists(piddir): raise PidlockConflict("directory {0} is missing or insufficient permission".format( piddir ) ) # Check for orphaned pids if os.path.isfile(pidpath): with open(pidpath) as f: conflictpid = f.read() raise PidlockConflict("process {0} has lock in {1}".format( conflictpid.strip(), pidpath ) ) # Acquire lock self.pidfile = PIDLockFile(pidpath) self.locked = False if not self.pidfile.is_locked(): self.pidfile.acquire() self.locked = True
def pidfile(tmpdir): try: from daemon.pidlockfile import PIDLockFile except ImportError: from daemon.pidfile import PIDLockFile # Create a tmpdir for the pidfile and overwrite # the current util.PID_FILE constant util.PID = PIDLockFile(tmpdir.join('plight.pid').strpath) return util.PID
class Command(BaseCommand): requires_model_validation = False help = """Run a single ChromaService in a new plugin.""" option_list = BaseCommand.option_list + ( make_option( '--gevent', action='store_true', dest='gevent', default=False), make_option('--lightweight-rpc', action='store_true', dest='lightweight_rpc', default=False), make_option( '--verbose', action='store_true', dest='verbose', default=False), make_option( '--console', action='store_true', dest='console', default=False), make_option('--name', dest='name', default='chroma_service'), make_option( '--daemon', dest='daemon', action='store_true', default=None), make_option('--trace', dest='trace', action='store_true', default=None), make_option('--pid-file', dest='pid-file', default=None), ) def execute(self, *args, **options): if options['daemon']: pid_file = options['pid-file'] if os.path.exists(pid_file + ".lock") or os.path.exists(pid_file): try: pid = int(open(pid_file).read()) os.kill(pid, 0) except (ValueError, OSError, IOError): # Not running, delete stale PID file sys.stderr.write("Removing stale PID file\n") import errno try: os.remove(pid_file) except OSError, e: if e.errno != errno.ENOENT: raise e try: os.remove(pid_file + ".lock") except OSError, e: if e.errno != errno.ENOENT: raise e else: # Running, we should refuse to run raise RuntimeError("Daemon is already running (PID %s)" % pid) with DaemonContext(pidfile=PIDLockFile(pid_file)): self._execute_inner(*args, **options)
def acquire_pidlock(pidfile): """Get the :class:`daemon.pidlockfile.PIDLockFile` handler for ``pidfile``. If the ``pidfile`` already exists, but the process is not running the ``pidfile`` will be removed, a ``"stale pidfile"`` message is emitted and execution continues as normally. However, if the process is still running the program will exit complaning that the program is already running in the background somewhere. """ from daemon.pidlockfile import PIDLockFile import errno pidlock = PIDLockFile(pidfile) if not pidlock.is_locked(): return pidlock pid = pidlock.read_pid() try: os.kill(pid, 0) except os.error, exc: if exc.errno == errno.ESRCH: sys.stderr.write("Stale pidfile exists. Removing it.\n") os.unlink(pidfile) return PIDLockFile(pidfile)
def main(): """Daemonize and handle unexpected exceptions""" parser = argparse.ArgumentParser( description="Intel® Manager for Lustre* software Agent") parser.add_argument("--foreground", action="store_true") parser.add_argument("--publish-zconf", action="store_true") parser.add_argument("--pid-file", default="/var/run/chroma-agent.pid") args = parser.parse_args() # FIXME: at startup, if there is a PID file hanging around, find any # processes which are children of that old PID, and kill them: prevent # orphaned processes from an old agent run hanging around where they # could cause trouble (think of a 2 hour mkfs) if not args.foreground: if os.path.exists(args.pid_file): pid = None try: pid = int(open(args.pid_file).read()) os.kill(pid, 0) except (ValueError, OSError, IOError): # Not running, delete stale PID file sys.stderr.write("Removing stale PID file\n") try: os.remove(args.pid_file) os.remove(args.pid_file + ".lock") except OSError, e: import errno if e.errno != errno.ENOENT: raise e if pid is not None: kill_orphans_of(pid) else: # Running, we should refuse to run raise RuntimeError("Daemon is already running (PID %s)" % pid) else: if os.path.exists(args.pid_file + ".lock"): sys.stderr.write("Removing stale lock file\n") os.remove(args.pid_file + ".lock") signal.signal(signal.SIGHUP, signal.SIG_IGN) context = DaemonContext(pidfile=PIDLockFile(args.pid_file)) context.open() daemon_log_setup() console_log_setup() daemon_log.info("Starting in the background")
class AcquireRunLock(object): """ Establishes a lockfile to avoid duplicate runs for same config. """ def __init__(self, pidfile): """ Create exclusive app lock """ if pidfile.startswith("/"): piddir = os.path.dirname(pidfile) pidpath = pidfile # use explicit path else: piddir = "/var/lib/zabbixsrv/" pidpath = "{dir}{file}".format(dir=piddir, file=pidfile) # Check lockdir exists if not os.path.exists(piddir): raise PidlockConflict("directory {0} is missing or insufficient permission".format( piddir ) ) # Check for orphaned pids if os.path.isfile(pidpath): with open(pidpath) as f: conflictpid = f.read() raise PidlockConflict("process {0} has lock in {1}".format( conflictpid.strip(), pidpath ) ) # Acquire lock self.pidfile = PIDLockFile(pidpath) self.locked = False if not self.pidfile.is_locked(): self.pidfile.acquire() self.locked = True def release(self): """ Releases exclusive lock """ if self.pidfile.is_locked(): self.locked = False return self.pidfile.release() def islocked(self): """ Return true if exclusively locked """ return self.pidfile.is_locked()
def start(args): if not os.path.exists(args.out_dir): os.makedirs(args.out_dir) if os.path.exists(get_pid_path(args)): if args.ignore_stale_pid: os.remove(get_pid_path(args)) else: print >> sys.stderr, '{0}: File exists. Already running?'.format( get_pid_path(args)) sys.exit(1) pid_file = PIDLockFile(get_pid_path(args)) log_file = open(get_log_path(args), 'a') if not args.foreground: with daemon.DaemonContext(pidfile=pid_file, stdout=log_file, stderr=log_file): do_dsm(args.port) else: do_dsm(args.port)
def __init__(self, lockfile, timeout, **kwargs): PIDLockFile.__init__(self, lockfile, **kwargs) self.timeout = timeout
def start_service(self, host, port, logfile, pidfile, server): log = open(logfile, 'a') pid = PIDLockFile(pidfile) with daemon.DaemonContext(stderr=log, pidfile=pid): run(host=host, port=port, server=server)
else: logger.error("no vm found with mac %s", mac) return True def run(self): try: self.serve_forever() except Exception, e: logger.info(e) if __name__ == '__main__': logger.setLevel(logging.INFO) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler = logging.FileHandler("/var/lib/jenkins/wolproxy.log") handler.setFormatter(formatter) logger.addHandler(handler) listen = ('0.0.0.0', 8000) logger.info("wolproxy server listening on %s:%s", listen[0], listen[1]) with daemon.DaemonContext( detach_process=True, files_preserve=[handler.stream], pidfile=PIDLockFile('/var/lib/jenkins/wolproxy.pid')): server = WolproxyServer(listen) server.run()
print "west toggle" west.toggle() print "waiting..." #チャタリングと長押し対策 time.sleep(0.5) continue if int(open("/sys/class/gpio/gpio110/value", "r").read().split("\n")[0]) == 0: #右ボタンが押された時の処理 print "heater toggle" heater.toggle() print "waiting..." #チャタリングと長押し対策 time.sleep(0.5) continue print "nothing loop" time.sleep(0.2) #スクリプトとして動作された場合、ここから実行される if __name__ == '__main__': #daemonとして動作する場合の処理 #pidファイルは/etc/init.d/wemo内の指定と同じファイルにする with daemon.DaemonContext(pidfile=PIDLockFile('/var/run/wemo.pid')): #daemonとして起動した際に、networking側の処理が追いつかずにネットワークが確立していない場合がある。 #その場合Environment()などでexceptionを吐いて終了してしまう。 #対応として、exceptで全部のexceptionを受け止めてもう一度wemo_main()をやり直すようにした。 while True: try: wemo_main() except: time.sleep(3)
import signal try: import BaseHTTPServer except ImportError: import http.server as BaseHTTPServer from daemon import DaemonContext try: from daemon.pidlockfile import PIDLockFile except ImportError: from daemon.pidfile import PIDLockFile import logging from logging.handlers import RotatingFileHandler import plight import plight.config as plconfig PID = PIDLockFile(plconfig.PID_FILE) def start_server(config): os.umask(0o022) weblogger = logging.getLogger('plight_httpd') weblogger.setLevel(config['web_log_level']) if weblogger.handlers == []: weblogging_handler = RotatingFileHandler(config['web_log_file'], mode='a', maxBytes=config[ 'web_log_filesize'], backupCount=config[ 'web_log_rotation_count']) weblogger.addHandler(weblogging_handler)