Exemplo n.º 1
0
    def take_action(self, opts):
        if opts.stop_daemon:
            return self.stop_daemon(opts)

        if not hasattr(opts, 'set_user'):
            # Windows case:
            opts.set_user = opts.set_group = None

        self.verbose = self.app_args.verbose_level

        # @@: Is this the right stage to set the user at?
        self.change_user_group(opts.set_user, opts.set_group)

        app_spec = opts.config_file
        if opts.args and opts.args[0] in self.possible_subcommands:
            cmd = opts.args[0]
            restvars = opts.args[1:]
        else:
            cmd = None
            restvars = opts.args[0:]

        if opts.reload:
            if os.environ.get(self._reloader_environ_key):
                if self.verbose > 1:
                    self.out('Running reloading file monitor')
                install_reloader(int(opts.reload_interval), [app_spec])
            else:
                return self.restart_with_reloader()

        if cmd not in (None, 'start', 'stop', 'restart', 'status'):
            self.out(
                'Error: must give start|stop|restart (not %s)' % cmd)
            return 2

        if cmd == 'status' or opts.show_status:
            return self.show_status(opts)

        if cmd == 'restart' or cmd == 'stop':
            result = self.stop_daemon(opts)
            if result:
                if cmd == 'restart':
                    self.out("Could not stop daemon; aborting")
                else:
                    self.out("Could not stop daemon")
                return result
            if cmd == 'stop':
                return result
            opts.daemon = True

        if cmd == 'start':
            opts.daemon = True

        app_name = opts.app_name
        parsed_vars = self.parse_vars(restvars)
        if not self._scheme_re.search(app_spec):
            app_spec = 'config:' + app_spec
        server_name = opts.server_name
        if opts.server:
            server_spec = 'egg:gearbox'
            assert server_name is None
            server_name = opts.server
        else:
            server_spec = app_spec
        base = os.getcwd()

        if getattr(opts, 'daemon', False):
            if not opts.pid_file:
                opts.pid_file = 'gearbox.pid'

        # Ensure the pid file is writeable
        if opts.pid_file:
            try:
                writeable_pid_file = open(opts.pid_file, 'a')
            except IOError as ioe:
                msg = 'Error: Unable to write to pid file: %s' % ioe
                raise ValueError(msg)
            writeable_pid_file.close()

        if getattr(opts, 'daemon', False):
            try:
                self.daemonize(opts)
            except DaemonizeException as ex:
                if self.verbose > 0:
                    self.out(str(ex))
                return 2

        if (opts.monitor_restart
            and not os.environ.get(self._monitor_environ_key)):
            return self.restart_with_monitor()

        if opts.pid_file:
            self.record_pid(opts.pid_file)

        log_fn = app_spec
        if log_fn.startswith('config:'):
            log_fn = app_spec[len('config:'):]
        elif log_fn.startswith('egg:'):
            log_fn = None

        if self.app.options.log_file:
            stdout_log = LazyWriter(self.app.options.log_file, 'a')
            sys.stdout = stdout_log
            sys.stderr = stdout_log

        try:
            server = self.loadserver(server_spec, name=server_name,
                                     relative_to=base, global_conf=parsed_vars)
            app = self.loadapp(app_spec, name=app_name,
                               relative_to=base, global_conf=parsed_vars)
        except Exception:
            self.out('Failed to load application or server', error=True)
            raise

        if log_fn:
            log_fn = os.path.join(base, log_fn)
            setup_logging(log_fn)

        if self.verbose > 0:
            if hasattr(os, 'getpid'):
                msg = 'Starting server in PID %i.' % os.getpid()
            else:
                msg = 'Starting server.'
            self.out(msg)

        def serve():
            try:
                server(app)
            except (SystemExit, KeyboardInterrupt) as e:
                if self.verbose > 1:
                    raise
                if str(e):
                    msg = ' ' + str(e)
                else:
                    msg = ''
                self.out('Exiting%s (-v to see traceback)' % msg)

        serve()
Exemplo n.º 2
0
    def take_action(self, opts):
        if opts.stop_daemon:
            return self.stop_daemon(opts)

        if not hasattr(opts, 'set_user'):
            # Windows case:
            opts.set_user = opts.set_group = None

        self.verbose = self.app_args.verbose_level

        # @@: Is this the right stage to set the user at?
        self.change_user_group(opts.set_user, opts.set_group)

        app_spec = opts.config_file
        if opts.args and opts.args[0] in self.possible_subcommands:
            cmd = opts.args[0]
            restvars = opts.args[1:]
        else:
            cmd = None
            restvars = opts.args[0:]

        if cmd not in (None, 'start', 'stop', 'restart', 'status'):
            self.out('Error: must give start|stop|restart (not %s)' % cmd)
            return 2

        if cmd == 'status' or opts.show_status:
            return self.show_status(opts)

        if opts.monitor_restart and opts.reload:
            self.out('Cannot user --monitor-restart with --reload')
            return 2

        if opts.monitor_restart and not os.environ.get(
                self._monitor_environ_key):
            # gearbox serve was started with an angel and we are not already inside the angel.
            # Switch this process to being the angel and start a new one with the real server.
            return self.restart_with_monitor()

        if opts.reload and not hupper.is_active():
            if self.verbose > 1:
                self.out('Running reloading file monitor')
            reloader = hupper.reloader.Reloader(
                worker_path='gearbox.main.main',
                reload_interval=opts.reload_interval,
                monitor_factory=hupper.reloader.find_default_monitor_factory(
                    logging.getLogger('gearbox')),
                logger=logging.getLogger('gearbox'),
            )
            reloader.run()

        if hupper.is_active():
            # Tack also config file changes
            hupper.get_reloader().watch_files([opts.config_file])

        if cmd == 'restart' or cmd == 'stop':
            result = self.stop_daemon(opts)
            if result:
                if cmd == 'restart':
                    self.out("Could not stop daemon; aborting")
                else:
                    self.out("Could not stop daemon")
                return result
            if cmd == 'stop':
                return result
            opts.daemon = True

        if cmd == 'start':
            opts.daemon = True

        app_name = opts.app_name
        parsed_vars = self.parse_vars(restvars)
        if not self._scheme_re.search(app_spec):
            app_spec = 'config:' + app_spec
        server_name = opts.server_name
        if opts.server:
            server_spec = 'egg:gearbox'
            assert server_name is None
            server_name = opts.server
        else:
            server_spec = app_spec
        base = os.getcwd()

        if getattr(opts, 'daemon', False):
            if not opts.pid_file:
                opts.pid_file = 'gearbox.pid'

        # Ensure the pid file is writeable
        if opts.pid_file:
            try:
                writeable_pid_file = open(opts.pid_file, 'a')
            except IOError as ioe:
                msg = 'Error: Unable to write to pid file: %s' % ioe
                raise ValueError(msg)
            writeable_pid_file.close()

        if getattr(opts, 'daemon', False):
            try:
                self.daemonize(opts)
            except DaemonizeException as ex:
                if self.verbose > 0:
                    self.out(str(ex))
                return 2

        if opts.pid_file:
            self.record_pid(opts.pid_file)

        log_fn = app_spec
        if log_fn.startswith('config:'):
            log_fn = app_spec[len('config:'):]
        elif log_fn.startswith('egg:'):
            log_fn = None

        if self.app.options.log_file:
            stdout_log = LazyWriter(self.app.options.log_file, 'a')
            sys.stdout = stdout_log
            sys.stderr = stdout_log

        try:
            server = self.loadserver(server_spec,
                                     name=server_name,
                                     relative_to=base,
                                     global_conf=parsed_vars)
        except Exception:
            self.out('Failed to load server', error=True)
            raise

        if log_fn:
            log_fn = os.path.join(base, log_fn)
            setup_logging(log_fn)

        try:
            app = self.loadapp(app_spec,
                               name=app_name,
                               relative_to=base,
                               global_conf=parsed_vars)
        except Exception:
            self.out('Failed to load application', error=True)
            raise

        if self.verbose > 0:
            if hasattr(os, 'getpid'):
                msg = 'Starting server in PID %i.' % os.getpid()
            else:
                msg = 'Starting server.'
            self.out(msg)

        def serve():
            try:
                server(app)
            except (SystemExit, KeyboardInterrupt) as e:
                if self.verbose > 1:
                    raise
                if str(e):
                    msg = ' ' + str(e)
                else:
                    msg = ''
                self.out('Exiting%s (-v to see traceback)' % msg)

        serve()