Ejemplo n.º 1
0
    def start(self):
        if self.ui_args is None:
            # Started directly by deluge-console script so must find the UI args manually
            options, remaining = BaseArgParser(common_help=False).parse_known_args()
            self.ui_args = remaining

        i = self.console_parser.find_subcommand(args=self.ui_args)
        self.console_parser.subcommand = False
        self.parser.subcommand = False if i == -1 else True

        super(Console, self).start(self.console_parser)
        from deluge.ui.console.main import ConsoleUI  # import here because (see top)

        def run(options):
            try:
                c = ConsoleUI(self.options, self.console_cmds, self.parser.log_stream)
                return c.start_ui()
            except Exception as ex:
                log.exception(ex)
                raise

        return deluge.common.run_profiled(
            run,
            self.options,
            output_file=self.options.profile,
            do_profile=self.options.profile,
        )
Ejemplo n.º 2
0
Archivo: ui.py Proyecto: th841/deluge
 def __init__(self, name, **kwargs):
     self.__name = name
     self.ui_args = kwargs.pop('ui_args', None)
     setup_translations()
     self.__parser = BaseArgParser(**kwargs)
Ejemplo n.º 3
0
def start_ui():
    """Entry point for ui script"""
    setup_translations()

    # Get the registered UI entry points
    ui_entrypoints = {}
    for entrypoint in pkg_resources.iter_entry_points('deluge.ui'):
        try:
            ui_entrypoints[entrypoint.name] = entrypoint.load()
        except ImportError:
            # Unable to load entrypoint so skip adding it.
            pass

    ui_titles = sorted(ui_entrypoints)

    def add_ui_options_group(_parser):
        """Function to enable reuse of UI Options group"""
        group = _parser.add_argument_group(_('UI Options'))
        group.add_argument(
            '-s',
            '--set-default-ui',
            dest='default_ui',
            choices=ui_titles,
            help=_('Set the default UI to be run, when no UI is specified'),
        )
        return _parser

    # Setup parser with Common Options and add UI Options group.
    parser = add_ui_options_group(BaseArgParser())

    # Parse and handle common/process group options
    options = parser.parse_known_ui_args(sys.argv, withhold=AMBIGUOUS_CMD_ARGS)

    config = deluge.configmanager.ConfigManager('ui.conf', DEFAULT_PREFS)
    log = logging.getLogger(__name__)
    log.info('Deluge ui %s', deluge.common.get_version())

    if options.default_ui:
        config['default_ui'] = options.default_ui
        config.save()
        log.info('The default UI has been changed to %s', options.default_ui)
        sys.exit(0)

    default_ui = config['default_ui']
    config.save()  # Save in case config didn't already exist.
    del config

    # We have parsed and got the config dir needed to get the default UI
    # Now create a parser for choosing the UI. We reuse the ui option group for
    # parsing to succeed and the text displayed to user, but result is not used.
    parser = add_ui_options_group(BaseArgParser(common_help=True))

    # Create subparser for each registered UI. Empty title is used to remove unwanted positional text.
    subparsers = parser.add_subparsers(
        dest='selected_ui',
        metavar='{%s} [UI args]' % ','.join(ui_titles),
        title=None,
        help=
        _('Alternative UI to launch, with optional ui args \n  (default UI: *)'
          ),
    )
    for ui in ui_titles:
        parser_ui = subparsers.add_parser(
            ui,
            common_help=False,
            help=getattr(ui_entrypoints[ui], 'cmd_description', ''),
        )
        parser_ui.add_argument('ui_args', nargs=argparse.REMAINDER)
        # If the UI is set as default, indicate this in help by prefixing with a star.
        subactions = subparsers._get_subactions()
        prefix = '*' if ui == default_ui else ' '
        subactions[-1].metavar = '%s %s' % (prefix, ui)

    # Insert a default UI subcommand unless one of the ambiguous_args are specified
    parser.set_default_subparser(default_ui, abort_opts=AMBIGUOUS_CMD_ARGS)

    # Only parse known arguments to leave the UIs to show a help message if parsing fails.
    options, remaining = parser.parse_known_args()
    selected_ui = options.selected_ui
    ui_args = remaining + options.ui_args

    # Remove the UI argument before launching the UI.
    sys.argv.remove(selected_ui)

    try:
        ui = ui_entrypoints[selected_ui](
            prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui),
            ui_args=ui_args)
    except KeyError as ex:
        log.error(
            'Unable to find chosen UI: "%s". Please choose a different UI '
            'or use "--set-default-ui" to change default UI.',
            selected_ui,
        )
    except ImportError as ex:
        import traceback

        error_type, error_value, tb = sys.exc_info()
        stack = traceback.extract_tb(tb)
        last_frame = stack[-1]
        if last_frame[0] == __file__:
            log.error(
                'Unable to find chosen UI: "%s". Please choose a different UI '
                'or use "--set-default-ui" to change default UI.',
                selected_ui,
            )
        else:
            log.exception(ex)
            log.error('Encountered an error launching the request UI: %s',
                      selected_ui)
        sys.exit(1)
    else:
        ui.start()
Ejemplo n.º 4
0
def start_daemon(skip_start=False):
    """
    Entry point for daemon script

    Args:
        skip_start (bool): If starting daemon should be skipped.

    Returns:
        deluge.core.daemon.Daemon: A new daemon object

    """
    set_dummy_trans(warn_msg=True)

    # Setup the argument parser
    parser = BaseArgParser()
    add_daemon_options(parser)

    options = parser.parse_args()

    # Check for any daemons running with this same config
    from deluge.core.daemon import is_daemon_running
    pid_file = get_config_dir('deluged.pid')
    if is_daemon_running(pid_file):
        print('Cannot run multiple daemons with same config directory.\n'
              'If you believe this is an error, force starting by deleting: %s' % pid_file)
        sys.exit(1)

    log = getLogger(__name__)

    # If no logfile specified add logging to default location (as well as stdout)
    if not options.logfile:
        options.logfile = get_config_dir('deluged.log')
        file_handler = FileHandler(options.logfile)
        log.addHandler(file_handler)

    def run_daemon(options):
        try:
            from deluge.core.daemon import Daemon
            daemon = Daemon(listen_interface=options.listen_interface,
                            interface=options.ui_interface,
                            port=options.port,
                            read_only_config_keys=options.read_only_config_keys.split(','))
            if skip_start:
                return daemon
            else:
                daemon.start()
        except CannotListenError as ex:
            log.error('Cannot start deluged, listen port in use.\n'
                      ' Check for other running daemons or services using this port: %s:%s',
                      ex.interface, ex.port)
            sys.exit(1)
        except Exception as ex:
            log.error('Unable to start deluged: %s', ex)
            if log.isEnabledFor(DEBUG):
                log.exception(ex)
            sys.exit(1)
        finally:
            log.info('Exiting...')
            if options.pidfile:
                os.remove(options.pidfile)

    return run_profiled(run_daemon, options, output_file=options.profile, do_profile=options.profile)