示例#1
0
def start(daemon=True, **kwargs):
    lock = PIDLockFile(os.path.join(RAMMON_PATH, "rammon.pid"))
    if lock.is_locked():
        try:
            Process(lock.read_pid())
            print("Rammon is already running")
            sys.exit(1)
        except NoSuchProcess:
            print(
                "Rammon was stopped, however it was stopped uncleanly leaving behind a pidfile.\n"
                "Breaking pidfile lock...")
            lock.break_lock()
    if daemon:
        logger.info("Starting rammon as a daemon...")
    else:
        logger.info("Starting rammon in the foreground...")

    if daemon:
        if try_systemd_start():
            logger.info("Starting with systemd...")
            sys.exit(0)
        else:
            mon = RamMonitor()
            set_handlers(mon)
            logger.info("Starting without systemd...")
            with DaemonContext(umask=0o077,
                               pidfile=lock,
                               detach_process=daemon):
                mon.start()
    else:
        with lock:
            mon = RamMonitor()
            set_handlers(mon)
            mon.start()
示例#2
0
def do_vpn_client(walt_vpn_entrypoint):
    # setup credentials if needed
    if not PRIV_KEY_FILE.exists():
        sys.exit("Run the following command once, first: 'walt-vpn-setup-credentials <walt-server>'")

    # Create TAP
    tap, tap_name = createtap()

    # create bridge
    if not (Path('/sys/class/net') / BRIDGE_INTF).exists():
        check_call('ip link add %s type bridge' % BRIDGE_INTF, shell=True)
    check_call('ip link set up dev %s' % BRIDGE_INTF, shell=True)

    # bring it up, add it to bridge
    check_call('ip link set up dev %(intf)s' % dict(intf = tap_name), shell=True)
    check_call('ip link set master ' + BRIDGE_INTF + ' dev ' + tap_name, shell=True)

    print('added ' + tap_name + ' to bridge ' + BRIDGE_INTF)

    # start loop
    if DEBUG:
        print('Running...')
        vpn_client_loop(tap, walt_vpn_entrypoint)
    else:
        print('Going to background.')
        with daemon.DaemonContext(
                    files_preserve = [tap],
                    pidfile = PIDLockFile('/var/run/walt-vpn-client.pid')):
            vpn_client_loop(tap, walt_vpn_entrypoint)
示例#3
0
def main():
    parser = get_parser()
    opts, args = parser.parse_args()
    load_config_or_exit(opts.configfile)
    if opts.check and opts.background:
        parser.error(
            '--check --background makes no sense, how will you know the result?'
        )
    if not opts.background:
        log_to_stream(sys.stderr,
                      level=logging.DEBUG if opts.debug else logging.WARNING)
        return doit(opts)
    else:
        pidlockfile = PIDLockFile(PIDFILE)
        existing_pid = pidlockfile.read_pid()
        if existing_pid:
            if process_is_alive(existing_pid):
                sys.stderr.write(
                    'Another beaker-init process is running (pid %s)\n' %
                    existing_pid)
                return 1
            else:
                sys.stderr.write('Pid file %s exists but pid %s is dead, '
                                 'removing the pid file\n' %
                                 (PIDFILE, existing_pid))
                pidlockfile.break_lock()
        with daemon.DaemonContext(pidfile=pidlockfile, detach_process=True):
            log_to_syslog('beaker-init')
            return doit(opts)
示例#4
0
def start_daemon():
    """

    Returns
    -------
    pid: int or None
        PID of the daemon if started successfully, None otherwise.

    """
    pid = get_daemon_pid()

    if pid is None:
        print("starting daemon")
    else:
        print(f"daemon seems already running under PID={pid}")

    log_fd = open(_LOG_FILE, 'w+')
    context = daemon.DaemonContext(
        pidfile=PIDLockFile(_PID_FILE),
        working_directory=_WORKING_DIR,
        stdout=log_fd,
        stderr=log_fd,
    )

    def start():

        with context:
            logger = logging.getLogger('serial_driver_daemon')
            logger.setLevel(logging.DEBUG)
            fh = logging.FileHandler(_LOG_FILE, mode='w+')
            fh.setLevel(_LOG_LEVEL)
            logger.addHandler(fh)
            logging.basicConfig(level=_LOG_LEVEL)

            try:
                daemon_code()
            except Exception:
                logger.exception("daemon failed")
                raise

    # daemonize the current(!) process,
    # but we don't want to be it, because
    # we could not run more code then..
    p = Process(target=start, name="some_foo")
    p.start()
    p.join(1)

    if p.is_alive() or p.exitcode != 0:
        raise RuntimeError("something went wrong")

    # wait until file was created and just
    # a bit longer until it also was written
    t0 = time.time()
    while time.time() - t0 < 5:
        if os.path.exists(_PID_FILE):
            break
    time.sleep(0.1)

    return get_daemon_pid()
示例#5
0
 def start(self):
     lock_file = PIDLockFile(self._file_name)
     if lock_file.is_locked():
         print("Already run this daenon.")
     else:
         with daemon.DaemonContext(pidfile=lock_file):
             # TODO : Add code about error and exception.
             self.run(self._path)
示例#6
0
    def __init__(self, server_config, daemon_config):
        self.context = DaemonContext(working_directory=os.getcwd())

        self.context.server = SBDServer(*server_config)
        self.context.files_preserve = [self.context.server.fileno()]

        pidfile, stdout, stderr = daemon_config
        if pidfile: self.context.pidfile = PIDLockFile(pidfile)
        if stdout: self.context.stdout = open(stdout, "w+")
        if stderr: self.context.stderr = open(stderr, "w+")

        self.context.signal_map = {SIGINT: self.down}
示例#7
0
 def _start(self):
     '''
     Set the daemon context and run the application.
     '''
     pidlock = PIDLockFile(self.pidfile)
     with DaemonContext(
             pidfile=pidlock,
             working_directory=os.path.dirname(os.path.realpath(__file__)) +
             os.sep,
             stdout=self.fh.stream,
             stderr=self.fh.stream):
         return self.run()
示例#8
0
def main():
    opt_parser = OptionParser()
    opt_parser.add_option("-c","--config",action="store",type="string",
            dest="config",default="~/.articles.ini",
            help="specify the configure file [default:~/.articles.ini]")
    opt_parser.add_option("-n","--no-cgi-server",action="store_true",dest="nocgi",
            help="only generate HTML file (CGI server does not stand)")
    opt_parser.add_option("-i","--install",action="store_true",dest="install",
            help="install attachments (CGI server does not stand)")
    opt_parser.add_option("-b","--getbib",action="store_true",dest="getbib",
            help="get bib infos for .pdf files whose bibtexkey is absent in .bib file")
    opt_parser.add_option("-d","--daemonize",action="store_true",dest="daemonize",
            help="stand CGI server as a daemon process (experimental)")
    (option,args) = opt_parser.parse_args()

    config_file = os.path.expanduser(option.config)
    if not os.path.exists(config_file):
        print("configure file does not exists : " + config_file)
        sys.exit(1)

    try:
        config = configure.read(config_file)
    except UserWarning as e:
        print("\nERROR : configure file is invalid.")
        print e
        sys.exit(1)

    if option.getbib:
        bibupdate.update(config,silent=False)
        return

    bib2html.generate(config)
    if option.install:
        copy_attachment(config)
        return

    pid_filename = "/tmp/articles.pid"
    log_filename = "server.log"
    if not option.nocgi:
        if option.daemonize and not os.path.exists(pid_filename):
            from daemon import DaemonContext
            from daemon.pidfile import PIDLockFile
            dc = DaemonContext(
                    pidfile = PIDLockFile(pid_filename),
                    stderr = open(log_filename,"w+"),
                    working_directory = os.getcwd(),
                )
            with dc:
                start_CGI_server(config)
        else:
            start_CGI_server(config)
示例#9
0
    def _daemonize(self, func, config):
        from daemon import DaemonContext
        try:
            from daemon.pidfile import TimeoutPIDLockFile as PIDLockFile
        except:
            from daemon.pidlockfile import PIDLockFile

        pidlock = PIDLockFile('/var/run/fedmsg/%s.pid' % self.name)
        output = file('/var/log/fedmsg/%s.log' % self.name, 'a')
        daemon = DaemonContext(pidfile=pidlock, stdout=output, stderr=output)
        daemon.terminate = self._handle_signal

        with daemon:
            return func(**config)
示例#10
0
def status(**kwargs):
    lock = PIDLockFile(os.path.join(RAMMON_PATH, "rammon.pid"))
    if lock.is_locked():
        try:
            Process(lock.read_pid())
            print("Rammon is running" +
                  (", and auto-start is enabled" if is_enabled() else ""))
        except NoSuchProcess:
            print(
                "Rammon is stopped, however it was stopped uncleanly leaving behind a pidfile.\n"
                "Breaking pidfile lock...")
            lock.break_lock()
    else:
        print("Rammon is stopped" +
              (", but auto-start is enabled" if is_enabled() else ""))
示例#11
0
def _daemonize(func):
    from daemon import DaemonContext
    try:
        from daemon.pidfile import TimeoutPIDLockFile as PIDLockFile
    except:
        from daemon.pidlockfile import PIDLockFile

    pidlock = PIDLockFile('/var/run/mattd/mattd.pid')
    stdout = file('/var/log/mattd/mattd-stdout.log', 'a')
    stderr = file('/var/log/mattd/mattd-stderr.log', 'a')
    daemon = DaemonContext(pidfile=pidlock, stdout=stdout, stderr=stderr)
    #daemon.terminate = _handle_signal

    with daemon:
        return func()
示例#12
0
def start(args):
    port = int(args.port)
    log_path = args.logfilepath
    lock_path = args.lockfile
    data_path = utility.abspath(args.json)
    utility.check_file(data_path)
    app.config["DATA_PATH"] = data_path
    app.config["SECRET_KEY"] = "development key"
    if not op.exists(lock_path):
        dc = DaemonContext(pidfile=PIDLockFile(lock_path),
                           stderr=open(log_path, "w+"),
                           working_directory=ROOT)
        with dc:
            app.run(port=port)
    else:
        raise exception.DataProcessorError("Server already stands.")
示例#13
0
    def _daemonize(self):
        import psutil
        from daemon import DaemonContext
        try:
            from daemon.pidfile import TimeoutPIDLockFile as PIDLockFile
        except:
            from daemon.pidlockfile import PIDLockFile

        pidlock = PIDLockFile('/var/run/fedmsg/%s.pid' % self.name)

        pid = pidlock.read_pid()
        if pid and not psutil.pid_exists(pid):
            self.log.warn("PID file exists but with no proc:  coup d'etat!")
            pidlock.break_lock()

        output = file('/var/log/fedmsg/%s.log' % self.name, 'a')
        daemon = DaemonContext(pidfile=pidlock, stdout=output, stderr=output)
        daemon.terminate = self._handle_signal

        with daemon:
            return self.run()
示例#14
0
def daemon():
    def die_in_a_fire(signum, stack):
        for thread in threads:
            thread.kill()

    import signal
    from daemon import DaemonContext
    try:
        from daemon.pidfile import TimeoutPIDLockFile as PIDLockFile
    except:
        from daemon.pidlockfile import PIDLockFile

    config = appconfig("config:" + find_config_file())

    #pidlock = PIDLockFile('/var/run/fedoracommunity/worker.pid')
    #output = file('/var/log/fedoracommunity/worker.log', 'a')
    pidlock = PIDLockFile(
        config.get('cache-worker.pidfile', '/tmp/fedoracommunity-worker.pid'))
    output = file(
        config.get('cache-worker.logfile', '/tmp/fedoracommunity-worker.log'),
        'a')

    daemon = DaemonContext(pidfile=pidlock, stdout=output, stderr=output)
    daemon.terminate = die_in_a_fire

    n = int(config.get('cache-worker.threads', '8'))
    with daemon:
        log.info("Creating %i threads" % n)
        for i in range(n):
            threads.append(Thread())

        for thread in threads:
            thread.start()

        # I used to do thread.join() here, but that makes it so the
        # signal_handler never gets fired.  Crazy python...
        while any([not thread.die for thread in threads]):
            time.sleep(2)
示例#15
0
def main():
    # Check user
    if os.getuid() != _uid:
        print('daemon must be run by the libreeye user', file=sys.stderr)
        sys.exit(errno.EPERM)
    # Create DaemonContext
    context = DaemonContext(uid=_uid,
                            gid=_gid,
                            pidfile=PIDLockFile('/tmp/libreeyed.pid'))
    # Create daemon, complete DaemonContext configuration
    daemon = Daemon(context=context)
    # Check lock
    if context.pidfile.is_locked():
        try:
            os.kill(context.pidfile.read_pid(), 0)
        except OSError:
            context.pidfile.break_lock()
        else:
            print('daemon is already running!', file=sys.stderr)
            sys.exit(errno.EEXIST)
    # Start daemon
    with context:
        daemon.run()
示例#16
0
def stop(**kwargs):
    lock = PIDLockFile(os.path.join(RAMMON_PATH, "rammon.pid"))
    if try_systemd_stop():
        logger.info("Stopping rammon daemon with systemd...")
    if lock.is_locked():
        try:
            proc = Process(lock.read_pid())
            proc.terminate()
            try:
                proc.wait(1)
            except TimeoutExpired:
                print("Rammon did not stop gracefully, killing it...")
                proc.kill()
                lock.break_lock()
            logger.info("Rammon stopped successfully")
        except NoSuchProcess:
            logger.warning(
                "Rammon was already stopped, but had not stopped cleanly.\n"
                "Breaking pidfile lock...")
            lock.break_lock()
    else:
        logger.error("Rammon is already stopped")
        sys.exit(1)
示例#17
0
import time
import daemon
from daemon.pidfile import PIDLockFile
import logging
from logging import handlers

logger = logging.getLogger("mylogger")
logger.setLevel(logging.INFO)

file_handler = handlers.RotatingFileHandler("log/daemon.log",
                                            maxBytes=(1024 * 1024 * 512),
                                            backupCount=3)
logger.addHandler(file_handler)

pidLockfile = PIDLockFile('.pid')
if pidLockfile.is_locked():
    print("running already (pid: %d)" % pidLockfile.read_pid())
    exit(1)

context = daemon.DaemonContext(pidfile=pidLockfile)
logfile_fileno = file_handler.stream.fileno()
context.files_preserve = [logfile_fileno]


def main():
    while True:
        time.sleep(0.5)


with context:
示例#18
0
 def _get_daemon_context(self):
     return daemon.DaemonContext(
         working_directory='.',
         pidfile=PIDLockFile(self.pidfile)
         )
示例#19
0
文件: run.py 项目: kingsaffair/kaqpay
import os, sys
import bjoern
import daemon
# import logging
from daemon.pidfile import PIDLockFile
from kaqpay import app

if __name__ == '__main__':
    current_dir = os.getcwd()
    pidfile = PIDLockFile(app.config.get('PID_FILE'))
    if pidfile.is_locked():
        print("Running Already (pid: {})".format(pidfile.read_pid()))

    # can use logging but why make things complicated?
    stdout = open(app.config.get('STDOUT_LOG'), 'a+')
    stderr = open(app.config.get('STDERR_LOG'), 'a+')

    ctx = daemon.DaemonContext(working_directory=current_dir,
                               umask=0o002,
                               pidfile=pidfile,
                               stdout=stdout,
                               stderr=stderr)

    with ctx:
        bjoern.run(app, 'localhost', 9091)
示例#20
0
import os
import signal
import ssl
import sys

import colorama
import daemon
from daemon.pidfile import PIDLockFile

CONF_DIR = os.path.expanduser('~/.tctools/frontserver/')
REPO_DIR = os.path.expanduser('~/.tctools/repo/')
CONF_JSON_FILE = os.path.join(CONF_DIR, "config.json")
PEM_FILE = os.path.join(REPO_DIR, "frontserver", "pemfile.pem")
CWD = os.getcwd()
HTTP_PORT = 8800
PID_LOCK_FILE = PIDLockFile('/tmp/frontserver.pid')


def test(HandlerClass, ServerClass, port, protocol="HTTP/1.0"):
    server_address = ('', port)
    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)
    httpd.socket = ssl.wrap_socket(httpd.socket,
                                   server_side=True,
                                   certfile=PEM_FILE)
    httpd.serve_forever()


class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
示例#21
0
文件: dellogd.py 项目: sunghagi/HC
                    if log_type == 'dir':
                        shutil.rmtree(LogFile, ignore_errors=True)
                    logger.logger.info('%s :: Removed Log File : %s',
                                       GetCurFunc(), LogFile)
                except Exception as e:
                    logger.logger.info('%s :: Remove Log File Failure : %s',
                                       GetCurFunc(), e)
    logger.logger.info('dellog.py End   ===================')


if __name__ == "__main__":
    #   logger = DaemonLogger("dellogLog")
    logger = DaemonLogger()

    app = App()
    daemon_runner = runner.DaemonRunner(app)
    daemon_runner.daemon_context.files_preserve = [logger.hdlr.stream.fileno()]
    try:
        daemon_runner.do_action()
    except LockTimeout:
        pidLockfile = PIDLockFile(app.pidfile_path)
        if pidLockfile.is_locked():
            print "dellog running already (pid: %s)" % (pidLockfile.read_pid())
            logger.logger.info("dellog running already (pid: %s)",
                               pidLockfile.read_pid())
            logger.logger.info('sys.exit')
            sys.exit()
    except runner.DaemonRunnerStopFailureError:
        print "dellog not running !!"
        sys.exit()
示例#22
0
def main():
    try:
        import twisted
    except ImportError:
        print "Orbited requires Twisted, which is not installed. See http://twistedmatrix.com/trac/ for installation instructions."
        sys.exit(1)

    #################
    # This corrects a bug in Twisted 8.2.0 for certain Python 2.6 builds on Windows
    #   Twisted ticket: http://twistedmatrix.com/trac/ticket/3868
    #     -mario
    try:
        from twisted.python import lockfile
    except ImportError:
        from orbited import __path__ as orbited_path
        sys.path.append(os.path.join(orbited_path[0], "hotfixes", "win32api"))
        from twisted.python import lockfile
        lockfile.kill = None
    #################

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-c",
                      "--config",
                      dest="config",
                      default=None,
                      help="path to configuration file")
    parser.add_option("-v",
                      "--version",
                      dest="version",
                      action="store_true",
                      default=False,
                      help="print Orbited version")
    parser.add_option("-p",
                      "--profile",
                      dest="profile",
                      action="store_true",
                      default=False,
                      help="run Orbited with a profiler")
    parser.add_option(
        "-q",
        "--quickstart",
        dest="quickstart",
        action="store_true",
        default=False,
        help="run Orbited on port 8000 and MorbidQ on port 61613")
    parser.add_option(
        "-d",
        "--daemon",
        dest="daemon",
        action="store_true",
        default=False,
        help="run Orbited as a daemon (requires the python-daemon package)")
    parser.add_option(
        "--pid-file",
        dest="pidfile",
        default="/var/run/orbited/orbited.pid",
        help=("use PIDFILE as the orbited daemon pid file",
              "; defaults to '/var/run/orbited/orbited.pid'"),
    )

    MemoryUtil.add_options_to_parser(parser)

    (options, args) = parser.parse_args()

    if args:
        print 'the "orbited" command does not accept positional arguments. type "orbited -h" for options.'
        sys.exit(1)

    if options.version:
        print "Orbited version: %s" % (version, )
        sys.exit(0)

    global logger

    if options.quickstart:
        logging.basicConfig()
        logger = logging.getLogger(__name__)
        config.map['[listen]'].append('http://:8000')
        config.map['[listen]'].append('stomp://:61613')
        config.map['[access]'][('localhost', 61613)] = ['*']
        logger.info("Quickstarting Orbited")
    else:
        # load configuration from configuration
        # file and from command line arguments.
        config.setup(options=options)
        logging.config.fileConfig(options.config)
        logger = logging.getLogger(__name__)
        logger.info("Starting Orbited with config file %s" % options.config)

    if options.daemon:
        try:
            from daemon import DaemonContext
            from daemon.pidfile import PIDLockFile
            pidlock = PIDLockFile(options.pidfile)
            daemon = DaemonContext(pidfile=pidlock)
            logger.debug('daemonizing with pid file %r', options.pidfile)
            daemon.open()
            logger.debug('daemonized!')
        except Exception, exc:
            logger.debug(exc)
示例#23
0
    parser.add_option('-P', '--pidfile')
    parser.add_option('-U', '--user')
    parser.add_option('--queue-check-interval', type='int', default=60)
    parser.add_option('--process-delay-count', type='int', default=2)
    options, args = parser.parse_args()

    if not options.sqs_name and not args:
        parser.error("Must specify SQS queue name or rpm file args")
    if options.sqs_name and args:
        parser.error("Don't give file args when specifying an SQS queue")

    if options.daemon:
        import daemon
        daemon_args = {}
        if options.pidfile:
            try:
                # daemon 1.6+ uses pidfile module
                from daemon.pidfile import PIDLockFile
            except ImportError:
                from daemon.pidlockfile import PIDLockFile
            daemon_args['pidfile'] = PIDLockFile(options.pidfile)
        if options.user:
            import pwd
            user = pwd.getpwnam(options.user)
            daemon_args['uid'] = user.pw_uid
            daemon_args['gid'] = user.pw_gid
        with daemon.DaemonContext(**daemon_args):
            main(options, args)
    else:
        main(options, args)
示例#24
0
    os.remove(pidfile)
    sys.exit()


pidfile = '/tmp/iqutefy.pid'

# check if pidfile refers to dead process
# if so, remove it
if os.path.isfile(pidfile):
    with open(pidfile) as pf:
        pid = int(pf.readline())
    if not psutil.pid_exists(pid):
        os.remove(pidfile)

with daemon.DaemonContext(detach_process=False,
                          pidfile=PIDLockFile(pidfile),
                          signal_map={signal.SIGTERM: cleanup}):
    inotify = INotify()
    watch_flags = flags.CREATE | flags.MODIFY
    wd = inotify.add_watch(sys.argv[1], watch_flags)
    process = psutil.Process()

    # inotify iterator runs out immediately
    while True:
        for event in inotify.read():
            os.system('qutebrowser :config-source')

    # kill after qutebrowser exits
    # not reached on SIGKILL
    cleanup()
示例#25
0

def reload_program_config():
    """docstring for reload_program_config"""
    logger.warn('stop daemon')
    exit()


logger.info('start daemon')

parser = argparse.ArgumentParser(version='1.0')
parser.add_argument('-d', action="store_true", default=False,
                    help='daemonize')
args = parser.parse_args()
if args.d:
    dc = DaemonContext(
        pidfile = PIDLockFile('/tmp/lost.pid'),
        files_preserve = [logger.handlers[0].stream],
        signal_map = {
            signal.SIGTERM: reload_program_config
        }
    )
    with dc:
        while True:
            logger.info('daemon working')
            time.sleep(2)
else:
    while True:
        logger.info('daemon working')
        time.sleep(2)
示例#26
0
#!/usr/bin/python

from __future__ import with_statement
from daemon import DaemonContext
# Fedoraの場合
from daemon.pidfile import PIDLockFile
# Fedora以外の場合
from daemon.pidlockfile import PIDLockFile


dc = DaemonContext(
    pidfile=PIDLockFile('./tmp/lock'),
    stderr=open('./tmp/lock', 'w+')
)

with dc:
    print("test")
示例#27
0
import signal
import argparse

logging.config.fileConfig("logging.conf")
logger = logging.getLogger("app")


def reload_program_config():
    """docstring for reload_program_config"""
    logger.warn('stop daemon')
    exit()


logger.info('start daemon')

parser = argparse.ArgumentParser(version='1.0')
parser.add_argument('-d', action="store_true", default=False, help='daemonize')
args = parser.parse_args()
if args.d:
    dc = DaemonContext(pidfile=PIDLockFile('/tmp/lost.pid'),
                       files_preserve=[logger.handlers[0].stream],
                       signal_map={signal.SIGTERM: reload_program_config})
    with dc:
        while True:
            logger.info('daemon working')
            time.sleep(2)
else:
    while True:
        logger.info('daemon working')
        time.sleep(2)