Esempio n. 1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c",
                        "--config",
                        required=True,
                        help="Path to yaml config file.")
    parser.add_argument("-d",
                        "--debuglog",
                        help="Enable debug log. "
                        "Specifies file to write log to.")
    parser.add_argument("--foreground",
                        action='store_true',
                        help="Run in the foreground.")
    parser.add_argument("-p",
                        "--pidfile",
                        default="/var/run/jenkins-log-pusher/"
                        "jenkins-log-gearman-client.pid",
                        help="PID file to lock during daemonization.")
    args = parser.parse_args()

    with open(args.config, 'r') as config_stream:
        config = yaml.load(config_stream)
    server = Server(config, args.debuglog)

    if args.foreground:
        server.setup_logging()
        server.main()
    else:
        pidfile = pidfile_mod.TimeoutPIDLockFile(args.pidfile, 10)
        with daemon.DaemonContext(pidfile=pidfile):
            server.setup_logging()
            server.main()
Esempio n. 2
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("--port",
                        type=int,
                        default=0,
                        help="listening port for switch")
    parser.add_argument(
        "--statusfile",
        help="file to record status; useful for communications")
    parser.add_argument("--pidfile",
                        help="file to record pid; useful for communciations")
    args = parser.parse_args()

    pidFileName = os.path.expanduser(os.path.expandvars(args.pidfile))
    statusFileName = os.path.expanduser(os.path.expandvars(args.statusfile))
    pidFileDir = os.path.dirname(pidFileName)

    with daemon.DaemonContext(
            working_directory=pidFileDir,
            umask=0o002,
            pidfile=pidfile.TimeoutPIDLockFile(pidFileName),
    ) as context:

        runSwitch(args.port, statusFileName)
Esempio n. 3
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("--private",
                        action="store_true",
                        help="Only accept local connections.")
    parser.add_argument("--port",
                        type=int,
                        default=0,
                        help="listening port for switch")
    parser.add_argument(
        "--statusfile",
        help="file to record status; useful for communications")
    parser.add_argument("--pidfile",
                        help="file to record pid; useful for communciations")
    args = parser.parse_args()

    pidFileName = os.path.expanduser(os.path.expandvars(args.pidfile))
    statusFileName = os.path.expanduser(os.path.expandvars(args.statusfile))
    pidFileDir = os.path.dirname(pidFileName)
    host = None
    if args.private: host = "127.0.0.1"

    with daemon.DaemonContext(
            working_directory=pidFileDir,
            umask=0o002,
            pidfile=pidfile.TimeoutPIDLockFile(pidFileName),
    ) as context:

        runSwitch(host, args.port, statusFileName)
Esempio n. 4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--working-dir", default=os.getcwd(), help="working directory for the switch process")
    parser.add_argument("--private", action="store_true", help="Only accept local connections.")
    parser.add_argument("--port", type=int, default=0, help="listening port for switch")
    parser.add_argument("--statusfile", help="file to record status; useful for communications")
    parser.add_argument("--pidfile", help="file to record pid; useful for communciations")
    parser.add_argument("--unreliable", action="store_true", default=False, help="Introduce errors on the wire")
    parser.add_argument("--no-daemon", action="store_true", default=False, help="do not launch switch in a daemon; remain in foreground")
    args = parser.parse_args()
    
    workingDir = os.path.expanduser(os.path.expandvars(args.working_dir))
    pidFileName = os.path.expanduser(os.path.expandvars(args.pidfile))
    statusFileName = os.path.expanduser(os.path.expandvars(args.statusfile))
    pidFileDir = os.path.dirname(pidFileName)
    host = None
    if args.private: host = "127.0.0.1"

    switch_type = "reliable"
    if args.unreliable:
        switch_type = "unreliable"
    
    if args.no_daemon:
        runSwitch(switch_type, host, args.port, statusFileName)    
    else:
        with daemon.DaemonContext(
            working_directory=workingDir,
            umask=0o002,
            pidfile=pidfile.TimeoutPIDLockFile(pidFileName),
            ) as context:
            
            runSwitch(switch_type, host, args.port, statusFileName)
Esempio n. 5
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("vnic_address", help="Playground address of the VNIC")
    parser.add_argument("switch_address",
                        help="IP address of the Playground Switch")
    parser.add_argument("switch_port",
                        type=int,
                        help="TCP port of the Playground Switch")
    parser.add_argument("--port",
                        type=int,
                        default=0,
                        help="TCP port for serving VNIC connections")
    parser.add_argument(
        "--statusfile",
        help="file to record status; useful for communications")
    parser.add_argument("--pidfile",
                        help="file to record pid; useful for communciations")
    args = parser.parse_args()

    pidFileName = os.path.expanduser(os.path.expandvars(args.pidfile))
    statusFileName = os.path.expanduser(os.path.expandvars(args.statusfile))
    pidFileDir = os.path.dirname(pidFileName)

    with daemon.DaemonContext(
            working_directory=pidFileDir,
            umask=0o002,
            pidfile=pidfile.TimeoutPIDLockFile(pidFileName),
    ) as context:

        runVnic(args.vnic_address, args.port, statusFileName,
                args.switch_address, args.switch_port)
Esempio n. 6
0
    def setUp(self):
        """ Set up test fixtures. """
        self.mock_tracker = scaffold.MockTracker()

        pidlockfile_scenarios = make_pidlockfile_scenarios()
        self.pidlockfile_scenario = pidlockfile_scenarios['simple']
        pidfile_path = self.pidlockfile_scenario['path']

        scaffold.mock(
            "pidlockfile.PIDLockFile.__init__",
            tracker=self.mock_tracker)
        scaffold.mock(
            "pidlockfile.PIDLockFile.acquire",
            tracker=self.mock_tracker)

        self.scenario = {
            'pidfile_path': self.pidlockfile_scenario['path'],
            'acquire_timeout': object(),
            }

        self.test_kwargs = dict(
            path=self.scenario['pidfile_path'],
            acquire_timeout=self.scenario['acquire_timeout'],
            )
        self.test_instance = pidlockfile.TimeoutPIDLockFile(**self.test_kwargs)
Esempio n. 7
0
def serve(name, main):
    argv = FLAGS(sys.argv)

    if not FLAGS.pidfile:
        FLAGS.pidfile = '%s.pid' % name

    logging.debug("Full set of FLAGS: \n\n\n")
    for flag in FLAGS:
        logging.debug("%s : %s" % (flag, FLAGS.get(flag, None)))

    action = 'start'
    if len(argv) > 1:
        action = argv.pop()

    if action == 'stop':
        stop(FLAGS.pidfile)
        sys.exit()
    elif action == 'restart':
        stop(FLAGS.pidfile)
    elif action == 'start':
        pass
    else:
        print 'usage: %s [options] [start|stop|restart]' % argv[0]
        sys.exit(1)

    logging.getLogger('amqplib').setLevel(logging.WARN)
    if FLAGS.daemonize:
        logger = logging.getLogger()
        formatter = logging.Formatter(name +
                                      '(%(name)s): %(levelname)s %(message)s')
        if FLAGS.use_syslog and not FLAGS.logfile:
            syslog = logging.handlers.SysLogHandler(address='/dev/log')
            syslog.setFormatter(formatter)
            logger.addHandler(syslog)
        else:
            if not FLAGS.logfile:
                FLAGS.logfile = '%s.log' % name
            logfile = logging.handlers.FileHandler(FLAGS.logfile)
            logfile.setFormatter(formatter)
            logger.addHandler(logfile)
        stdin, stdout, stderr = None, None, None
    else:
        stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr

    if FLAGS.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.WARNING)

    with daemon.DaemonContext(detach_process=FLAGS.daemonize,
                              working_directory=FLAGS.working_directory,
                              pidfile=pidlockfile.TimeoutPIDLockFile(
                                  FLAGS.pidfile,
                                  acquire_timeout=1,
                                  threaded=False),
                              stdin=stdin,
                              stdout=stdout,
                              stderr=stderr):
        main(argv)
Esempio n. 8
0
def make_pidlockfile(path, acquire_timeout):
    """ Make a PIDLockFile instance with the given filesystem path. """
    if not isinstance(path, basestring):
        error = ValueError("Not a filesystem path: %(path)r" % vars())
        raise error
    if not os.path.isabs(path):
        error = ValueError("Not an absolute path: %(path)r" % vars())
        raise error
    lockfile = pidlockfile.TimeoutPIDLockFile(path, acquire_timeout)

    return lockfile
Esempio n. 9
0
def main():
    parser = argparse.ArgumentParser(description='PTG bot.')
    parser.add_argument('configfile', help='specify the config file')
    parser.add_argument('-d', dest='nodaemon', action='store_true',
                        help='do not run as a daemon')
    args = parser.parse_args()

    if not args.nodaemon:
        pid = pid_file_module.TimeoutPIDLockFile(
            "/var/run/ptgbot/ptgbot.pid", 10)
        with daemon.DaemonContext(pidfile=pid):
            start(args.configfile)
    start(args.configfile)
Esempio n. 10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("vnic_address", help="Playground address of the VNIC")
    parser.add_argument("switch_address",
                        help="IP address of the Playground Switch")
    parser.add_argument("switch_port",
                        type=int,
                        help="TCP port of the Playground Switch")
    parser.add_argument("--working-directory",
                        default=os.getcwd(),
                        help="working directory for vnic process")
    parser.add_argument("--port",
                        type=int,
                        default=0,
                        help="TCP port for serving VNIC connections")
    parser.add_argument(
        "--statusfile",
        help="file to record status; useful for communications")
    parser.add_argument("--pidfile",
                        help="file to record pid; useful for communciations")
    parser.add_argument(
        "--no-daemon",
        action="store_true",
        default=False,
        help="do not launch VNIC in a daemon; remain in foreground")
    args = parser.parse_args()

    workingDir = os.path.expanduser(os.path.expandvars(args.working_directory))
    pidFileName = os.path.expanduser(os.path.expandvars(args.pidfile))
    statusFileName = os.path.expanduser(os.path.expandvars(args.statusfile))
    pidFileDir = os.path.dirname(pidFileName)

    if args.no_daemon:
        runVnic(args.vnic_address, args.port, statusFileName,
                args.switch_address, args.switch_port, False)

    else:
        with daemon.DaemonContext(
                working_directory=workingDir,
                umask=0o002,
                pidfile=pidfile.TimeoutPIDLockFile(pidFileName),
        ) as context:

            runVnic(args.vnic_address, args.port, statusFileName,
                    args.switch_address, args.switch_port, True)
Esempio n. 11
0
            if app_data is None:
                print("Failed to mine amznMusic.appConfig", file=sys.stderr)
                logger.error("Failed to mine amznMusic.appConfig")
                sys.exit(1)

            logger.info(
                "Startup good, polling for new purchases every %d seconds." %
                pollInterval)
            if opts.daemonize:
                dcontext = daemon.DaemonContext()
                dcontext.files_preserve = [handler.stream]
                dcontext.umask = configuration['umask']
                pidfile = configuration['daemonPidfile'].replace(
                    '{username}',
                    pwd.getpwuid(os.geteuid()).pw_name)
                dcontext.pidfile = pidlockfile.TimeoutPIDLockFile(pidfile)
                logger.info("Daemonizing...")

                try:
                    with dcontext:
                        functions.main_dl_loop(configuration, app_data, opts,
                                               session, pollInterval, logger)
                except pidlockfile.LockFailed as ex:
                    # good chance we're detached from a tty at this point, but maybe print to stderr too anyway?
                    logger.error("Could not acquire pidfile lock: " +
                                 ex.message)
                    logger.error(
                        "Check that you have permission to create and write to the pidfile, and that another instance is not already running."
                    )
                    sys.exit(1)
                except Exception as ex:
Esempio n. 12
0
    def execute(self, *args, **options):
        """
        Takes the options and starts a daemon context from them.

        Example::

            python manage.py linkconsumer --pidfile=/var/run/cb_link.pid
                --stdout=/var/log/cb/links.out --stderr=/var/log/cb/links.err

        """
        # print 20130610, 'execute', __file__

        #~ print options

        if daemon is not None:

            context = daemon.DaemonContext()

            context.chroot_directory = self.get_option_value(
                options, 'chroot_directory')
            context.working_directory = self.get_option_value(
                options, 'working_directory', '/')
            context.umask = self.get_option_value(options, 'umask', 0)
            context.detach_process = self.get_option_value(
                options, 'detach_process')
            context.prevent_core = self.get_option_value(
                options, 'prevent_core', True)
            if self.preserve_loggers:
                context.files_preserve = get_logger_files(
                    self.preserve_loggers)

            # Get file objects
            # stdin =  self.get_option_value(options, 'stdin')
            stdin = options.pop('stdin', None)
            if stdin is not None:
                options['stdin'] = context.stdin = open(stdin, "r")

            # stdout = self.get_option_value(options, 'stdout')
            stdout = options.pop('stdout', None)
            if stdout is not None:
                options['stdout'] = context.stdout = open(stdout, "a+")

            # stderr = self.get_option_value(options, 'stderr')
            stderr = options.pop('stderr', None)
            if stderr is not None:
                self.stderr = options['stderr'] = context.stderr = open(
                    stderr, "a+")
            # self.stderr is needed in case there is an exception during execute.
            # Django then would try to write to sys.stderr which is None because
            # we are a daemon

            # Make pid lock file
            pidfile = self.get_option_value(options, 'pidfile')
            if pidfile is not None:
                #~ context.pidfile=pidlockfile.PIDLockFile(pidfile)
                context.pidfile = pidlockfile.TimeoutPIDLockFile(pidfile, 0)

            uid = self.get_option_value(options, 'uid')
            if uid is not None:
                context.uid = int(uid)

            gid = self.get_option_value(options, 'gid')
            if gid is not None:
                context.gid = int(gid)

            context.open()

        # Django 1.5.1 needs them:
        # for k in ('stdout','stderr'):
        #     options[k] = getattr(context,k,None)

        # self.handle_daemon(*args, **options)
        BaseCommand.execute(self, *args, **options)