Example #1
0
    def start(self):
        (self.__options, self.__args) = self.__parser.parse_args()

        if self.__options.quiet:
            self.__options.loglevel = "none"

        if self.__options.loglevel:
            self.__options.loglevel = self.__options.loglevel.lower()

        # Setup the logger
        deluge.log.setupLogger(level=self.__options.loglevel,
                               filename=self.__options.logfile)
        log = deluge.log.LOG

        if self.__options.config:
            if not deluge.configmanager.set_config_dir(self.__options.config):
                log.error(
                    "There was an error setting the config dir! Exiting..")
                sys.exit(1)

        setproctitle("deluge-%s" % self.__name)

        log.info("Deluge ui %s", deluge.common.get_version())
        log.debug("options: %s", self.__options)
        log.debug("args: %s", self.__args)
        log.info("Starting %s ui..", self.__name)
Example #2
0
File: ui.py Project: Ashod/Deluge
    def start(self):
        # Make sure all arguments are unicode
        argv = deluge.common.unicode_argv()[1:]
        (self.__options, self.__args) = self.__parser.parse_args(argv)

        if self.__options.quiet:
            self.__options.loglevel = "none"

        logfile_mode = 'w'
        if self.__options.rotate_logs:
            logfile_mode = 'a'

        if self.__options.loglevel:
            self.__options.loglevel = self.__options.loglevel.lower()

        # Setup the logger
        deluge.log.setupLogger(level=self.__options.loglevel,
                               filename=self.__options.logfile,
                               filemode=logfile_mode)

        log = logging.getLogger(__name__)

        if self.__options.config:
            if not deluge.configmanager.set_config_dir(self.__options.config):
                log.error("There was an error setting the config dir! Exiting..")
                sys.exit(1)

        setproctitle("deluge-%s" % self.__name)

        log.info("Deluge ui %s", deluge.common.get_version())
        log.debug("options: %s", self.__options)
        log.debug("args: %s", self.__args)
        log.info("Starting %s ui..", self.__name)
Example #3
0
    def start(self):
        (self.__options, self.__args) = self.__parser.parse_args()

        if self.__options.quiet:
            self.__options.loglevel = "none"

        logfile_mode = 'w'
        if self.__options.rotate_logs:
            logfile_mode = 'a'

        # Setup the logger
        # Setup the logger
        deluge.log.setupLogger(level=self.__options.loglevel,
                               filename=self.__options.logfile,
                               filemode=logfile_mode)

        log = logging.getLogger(__name__)

        if self.__options.config:
            if not deluge.configmanager.set_config_dir(self.__options.config):
                log.error("There was an error setting the config dir! Exiting..")
                sys.exit(1)

        log.info("Deluge ui %s", deluge.common.get_version())
        log.debug("options: %s", self.__options)
        log.debug("args: %s", self.__args)
        log.info("Starting ui..")
Example #4
0
    def start(self):
        if deluge.common.windows_check():
            (self.__options, self.__args) = self.__parser.parse_args(deluge.common.win32_unicode_argv()[1:])
        else:
            (self.__options, self.__args) = self.__parser.parse_args()

        if self.__options.quiet:
            self.__options.loglevel = "none"

        if self.__options.loglevel:
            self.__options.loglevel = self.__options.loglevel.lower()

        # Setup the logger
        deluge.log.setupLogger(level=self.__options.loglevel, filename=self.__options.logfile)
        log = deluge.log.LOG

        if self.__options.config:
            if not deluge.configmanager.set_config_dir(self.__options.config):
                log.error("There was an error setting the config dir! Exiting..")
                sys.exit(1)

        setproctitle("deluge-%s" % self.__name)

        log.info("Deluge ui %s", deluge.common.get_version())
        log.debug("options: %s", self.__options)
        log.debug("args: %s", self.__args)
        log.info("Starting %s ui..", self.__name)
Example #5
0
    def start(self):
        # Make sure all arguments are unicode
        argv = deluge.common.unicode_argv()[1:]
        (self.__options, self.__args) = self.__parser.parse_args(argv)

        if self.__options.quiet:
            self.__options.loglevel = "none"

        logfile_mode = 'w'
        if self.__options.rotate_logs:
            logfile_mode = 'a'

        if self.__options.loglevel:
            self.__options.loglevel = self.__options.loglevel.lower()

        # Setup the logger
        deluge.log.setupLogger(level=self.__options.loglevel,
                               filename=self.__options.logfile,
                               filemode=logfile_mode)

        log = logging.getLogger(__name__)

        if self.__options.config:
            if not deluge.configmanager.set_config_dir(self.__options.config):
                log.error(
                    "There was an error setting the config dir! Exiting..")
                sys.exit(1)

        setproctitle("deluge-%s" % self.__name)

        log.info("Deluge ui %s", deluge.common.get_version())
        log.debug("options: %s", self.__options)
        log.debug("args: %s", self.__args)
        log.info("Starting %s ui..", self.__name)
Example #6
0
File: ui.py Project: orther/Deluge
    def start(self):
        (self.__options, self.__args) = self.__parser.parse_args()

        if self.__options.quiet:
            self.__options.loglevel = "none"

        logfile_mode = 'w'
        if self.__options.rotate_logs:
            logfile_mode = 'a'

        # Setup the logger
        # Setup the logger
        deluge.log.setupLogger(level=self.__options.loglevel,
                               filename=self.__options.logfile,
                               filemode=logfile_mode)

        deluge.common.setup_translations()

        log = logging.getLogger(__name__)

        if self.__options.config:
            if not deluge.configmanager.set_config_dir(self.__options.config):
                log.error(
                    "There was an error setting the config dir! Exiting..")
                sys.exit(1)

        log.info("Deluge ui %s", deluge.common.get_version())
        log.debug("options: %s", self.__options)
        log.debug("args: %s", self.__args)
        log.info("Starting ui..")
Example #7
0
def start_ui():
    """Entry point for ui script"""
    import deluge.common

    # Setup the argument parser
    parser = OptionParser(usage="%prog [options] [actions]")
    parser.add_option("-v", "--version", action="callback", callback=version_callback,
        help="Show program's version number and exit")
    parser.add_option("-u", "--ui", dest="ui",
        help="""The UI that you wish to launch.  The UI choices are:\n
        \t gtk -- A GTK-based graphical user interface (default)\n
        \t web -- A web-based interface (http://localhost:8112)\n
        \t console -- A console or command-line interface""", action="store", type="str")
    parser.add_option("-s", "--set-default-ui", dest="default_ui",
        help="Sets the default UI to be run when no UI is specified", action="store", type="str")
    parser.add_option("-a", "--args", dest="args",
        help="Arguments to pass to UI, -a '--option args'", action="store", type="str")
    parser.add_option("-c", "--config", dest="config",
        help="Set the config folder location", action="store", type="str")
    parser.add_option("-l", "--logfile", dest="logfile",
        help="Output to designated logfile instead of stdout", action="store", type="str")
    parser.add_option("-L", "--loglevel", dest="loglevel",
        help="Set the log level: none, info, warning, error, critical, debug", action="store", type="str")
    parser.add_option("-q", "--quiet", dest="quiet",
        help="Sets the log level to 'none', this is the same as `-L none`", action="store_true", default=False)

    # Get the options and args from the OptionParser
    if deluge.common.windows_check():
        (options, args) = parser.parse_args(deluge.common.win32_unicode_argv()[1:])
    else:
        (options, args) = parser.parse_args()

    # Setup the logger
    if options.quiet:
        options.loglevel = "none"
    if options.loglevel:
        options.loglevel = options.loglevel.lower()
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile)
    from deluge.log import LOG as log

    if options.config:
        if not os.path.exists(options.config):
            # Try to create the config folder if it doesn't exist
            try:
                os.makedirs(options.config)
            except Exception, e:
                pass
        elif not os.path.isdir(options.config):
            log.error("Config option needs to be a directory!")
            sys.exit(1)
Example #8
0
def start_ui():
    """Entry point for ui script"""
    import deluge.common

    # Setup the argument parser
    parser = OptionParser(usage="%prog [options] [actions]")
    parser.add_option("-v", "--version", action="callback", callback=version_callback,
        help="Show program's version number and exit")
    parser.add_option("-u", "--ui", dest="ui",
        help="""The UI that you wish to launch.  The UI choices are:\n
        \t gtk -- A GTK-based graphical user interface (default)\n
        \t web -- A web-based interface (http://localhost:8112)\n
        \t console -- A console or command-line interface""", action="store", type="str")
    parser.add_option("-s", "--set-default-ui", dest="default_ui",
        help="Sets the default UI to be run when no UI is specified", action="store", type="str")
    parser.add_option("-a", "--args", dest="args",
        help="Arguments to pass to UI, -a '--option args'", action="store", type="str")
    parser.add_option("-c", "--config", dest="config",
        help="Set the config folder location", action="store", type="str")
    parser.add_option("-l", "--logfile", dest="logfile",
        help="Output to designated logfile instead of stdout", action="store", type="str")
    parser.add_option("-L", "--loglevel", dest="loglevel",
        help="Set the log level: none, info, warning, error, critical, debug", action="store", type="str")
    parser.add_option("-q", "--quiet", dest="quiet",
        help="Sets the log level to 'none', this is the same as `-L none`", action="store_true", default=False)

    # Get the options and args from the OptionParser
    if deluge.common.windows_check():
        (options, args) = parser.parse_args(deluge.common.win32_unicode_argv()[1:])
    else:
        (options, args) = parser.parse_args()

    # Setup the logger
    if options.quiet:
        options.loglevel = "none"
    if options.loglevel:
        options.loglevel = options.loglevel.lower()
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile)
    from deluge.log import LOG as log

    if options.config:
        if not os.path.exists(options.config):
            # Try to create the config folder if it doesn't exist
            try:
                os.makedirs(options.config)
            except Exception, e:
                pass
        elif not os.path.isdir(options.config):
            log.error("Config option needs to be a directory!")
            sys.exit(1)
Example #9
0
    def set_config_dir(self, directory):
        """
        Sets the config directory.

        :param directory: str, the directory where the config info should be

        :returns bool: True if successfully changed directory, False if not
        """

        if not directory:
            return False

        # Ensure absolute dirpath
        directory = os.path.abspath(directory)

        log.info('Setting config directory to: %s', directory)
        if not os.path.exists(directory):
            # Try to create the config folder if it doesn't exist
            try:
                os.makedirs(directory)
            except OSError as ex:
                log.error('Unable to make config directory: %s', ex)
                return False
        elif not os.path.isdir(directory):
            log.error('Config directory needs to be a directory!')
            return False

        self.__config_directory = directory

        # Reset the config_files so we don't get config from old config folder
        # XXX: Probably should have it go through the config_files dict and try
        # to reload based on the new config directory
        self.save()
        self.config_files = {}
        deluge.log.tweak_logging_levels()

        return True
Example #10
0
    def set_config_dir(self, directory):
        """
        Sets the config directory.

        :param directory: str, the directory where the config info should be

        :returns bool: True if successfully changed directory, False if not
        """

        if not directory:
            return False

        # Ensure absolute dirpath
        directory = os.path.abspath(directory)

        log.info('Setting config directory to: %s', directory)
        if not os.path.exists(directory):
            # Try to create the config folder if it doesn't exist
            try:
                os.makedirs(directory)
            except OSError as ex:
                log.error('Unable to make config directory: %s', ex)
                return False
        elif not os.path.isdir(directory):
            log.error('Config directory needs to be a directory!')
            return False

        self.__config_directory = directory

        # Reset the config_files so we don't get config from old config folder
        # XXX: Probably should have it go through the config_files dict and try
        # to reload based on the new config directory
        self.save()
        self.config_files = {}
        deluge.log.tweak_logging_levels()

        return True
Example #11
0
    def __init__(self, options, args, ui_args):
        from deluge.log import LOG as log

        log.debug("UI init..")

        # Set the config directory
        deluge.configmanager.set_config_dir(options.config)

        config = deluge.configmanager.ConfigManager("ui.conf", DEFAULT_PREFS)

        if not options.ui:
            selected_ui = config["default_ui"]
        else:
            selected_ui = options.ui

        setproctitle("deluge")

        config.save()
        del config

        try:
            if selected_ui == "gtk":
                log.info("Starting GtkUI..")
                from deluge.ui.gtkui.gtkui import GtkUI

                ui = GtkUI(args)
            elif selected_ui == "web":
                log.info("Starting WebUI..")
                from deluge.ui.web.web import WebUI

                ui = WebUI(args)
            elif selected_ui == "console":
                log.info("Starting ConsoleUI..")
                from deluge.ui.console.main import ConsoleUI

                ui = ConsoleUI(ui_args)
        except ImportError, e:
            import sys
            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 the requested UI: %s.  Please select a different UI with the '-u' option or alternatively use the '-s' option to select a different default UI.",
                    selected_ui,
                )
            else:
                log.exception(e)
                log.error("There was an error whilst launching the request UI: %s", selected_ui)
                log.error("Look at the traceback above for more information.")
            sys.exit(1)
Example #12
0
    def __init__(self, options, args, ui_args):
        import logging
        log = logging.getLogger(__name__)
        log.debug("UI init..")

        # Set the config directory
        deluge.configmanager.set_config_dir(options.config)

        config = deluge.configmanager.ConfigManager("ui.conf", DEFAULT_PREFS)

        if not options.ui:
            selected_ui = config["default_ui"]
        else:
            selected_ui = options.ui

        setproctitle("deluge")

        config.save()
        del config

        try:
            if selected_ui == "gtk":
                log.info("Starting GtkUI..")
                from deluge.ui.gtkui.gtkui import GtkUI
                ui = GtkUI(args)
            elif selected_ui == "web":
                log.info("Starting WebUI..")
                from deluge.ui.web.web import WebUI
                ui = WebUI(args)
            elif selected_ui == "console":
                log.info("Starting ConsoleUI..")
                from deluge.ui.console.main import ConsoleUI
                ui = ConsoleUI(ui_args)
        except ImportError, e:
            import sys
            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 the requested UI: %s.  Please select a different UI with the '-u' option or alternatively use the '-s' option to select a different default UI.",
                    selected_ui)
            else:
                log.exception(e)
                log.error(
                    "There was an error whilst launching the request UI: %s",
                    selected_ui)
                log.error("Look at the traceback above for more information.")
            sys.exit(1)
Example #13
0
    if options.quiet:
        options.loglevel = "none"
    if options.logfile:
        # Try to create the logfile's directory if it doesn't exist
        try:
            os.makedirs(os.path.abspath(os.path.dirname(options.logfile)))
        except OSError, e:
            if e.errno != EEXIST:
                print "There was an error creating the log directory, exiting... (%s)" % e
                sys.exit(1)
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile)
    from deluge.log import LOG as log

    if options.config:
        if not deluge.configmanager.set_config_dir(options.config):
            log.error("There was an error setting the config directory! Exiting...")
            sys.exit(1)

    # Sets the options.logfile to point to the default location
    def open_logfile():
        if not options.logfile:
            options.logfile = deluge.configmanager.get_config_dir("deluged.log")
            file_handler = FileHandler(options.logfile)
            log.addHandler(file_handler)

    # Writes out a pidfile if necessary
    def write_pidfile():
        if options.pidfile:
            open(options.pidfile, "wb").write("%s\n" % os.getpid())

    # If the donot daemonize is set, then we just skip the forking
Example #14
0
    def _handle_ui_options(self, options):
        """Handle UI common and process group options.

        Args:
            options (argparse.Namespace): The parsed options.

        Returns:
            argparse.Namespace: The parsed options.

        """
        if not self.common_setup:
            self.common_setup = True

            # Setup the logger
            if options.quiet:
                options.loglevel = 'none'
            if options.loglevel:
                options.loglevel = options.loglevel.lower()

            logfile_mode = 'w'
            logrotate = options.logrotate
            if options.logrotate:
                logfile_mode = 'a'
                logrotate = common.parse_human_size(options.logrotate)

            # Setup the logger
            deluge.log.setup_logger(
                level=options.loglevel,
                filename=options.logfile,
                filemode=logfile_mode,
                logrotate=logrotate,
                output_stream=self.log_stream,
            )

            if options.config:
                if not set_config_dir(options.config):
                    log = logging.getLogger(__name__)
                    log.error(
                        'There was an error setting the config dir! Exiting..')
                    sys.exit(1)
            else:
                if not os.path.exists(common.get_default_config_dir()):
                    os.makedirs(common.get_default_config_dir())

        if self.process_arg_group:
            self.process_arg_group = False
            # If donotdaemonize is set, skip process forking.
            if not (common.windows_check() or options.donotdaemonize):
                if os.fork():
                    os._exit(0)
                os.setsid()
                # Do second fork
                if os.fork():
                    os._exit(0)
                # Ensure process doesn't keep any directory in use that may prevent a filesystem unmount.
                os.chdir(get_config_dir())

            # Write pid file before chuid
            if options.pidfile:
                with open(options.pidfile, 'w') as _file:
                    _file.write('%d\n' % os.getpid())

            if not common.windows_check():
                if options.group:
                    if not options.group.isdigit():
                        import grp

                        options.group = grp.getgrnam(options.group)[2]
                    os.setgid(options.group)
                if options.user:
                    if not options.user.isdigit():
                        import pwd

                        options.user = pwd.getpwnam(options.user)[2]
                    os.setuid(options.user)

        return options
Example #15
0
    def _handle_ui_options(self, options):
        """Handle UI common and process group options.

        Args:
            options (argparse.Namespace): The parsed options.

        Returns:
            argparse.Namespace: The parsed options.

        """
        if not self.common_setup:
            self.common_setup = True

            # Setup the logger
            if options.quiet:
                options.loglevel = 'none'
            if options.loglevel:
                options.loglevel = options.loglevel.lower()

            logfile_mode = 'w'
            logrotate = options.logrotate
            if options.logrotate:
                logfile_mode = 'a'
                logrotate = common.parse_human_size(options.logrotate)

            # Setup the logger
            deluge.log.setup_logger(level=options.loglevel, filename=options.logfile, filemode=logfile_mode,
                                    logrotate=logrotate, output_stream=self.log_stream)

            if options.config:
                if not set_config_dir(options.config):
                    log = logging.getLogger(__name__)
                    log.error('There was an error setting the config dir! Exiting..')
                    sys.exit(1)
            else:
                if not os.path.exists(common.get_default_config_dir()):
                    os.makedirs(common.get_default_config_dir())

        if self.process_arg_group:
            self.process_arg_group = False
            # If donotdaemonize is set, skip process forking.
            if not (common.windows_check() or options.donotdaemonize):
                if os.fork():
                    os._exit(0)
                os.setsid()
                # Do second fork
                if os.fork():
                    os._exit(0)
                # Ensure process doesn't keep any directory in use that may prevent a filesystem unmount.
                os.chdir(get_config_dir())

            # Write pid file before chuid
            if options.pidfile:
                with open(options.pidfile, 'wb') as _file:
                    _file.write('%d\n' % os.getpid())

            if not common.windows_check():
                if options.user:
                    if not options.user.isdigit():
                        import pwd
                        options.user = pwd.getpwnam(options.user)[2]
                    os.setuid(options.user)
                if options.group:
                    if not options.group.isdigit():
                        import grp
                        options.group = grp.getgrnam(options.group)[2]
                    os.setuid(options.group)

        return options
Example #16
0
    if options.quiet:
        options.loglevel = "none"
    if options.logfile:
        # Try to create the logfile's directory if it doesn't exist
        try:
            os.makedirs(os.path.abspath(os.path.dirname(options.logfile)))
        except OSError, e:
            if e.errno != EEXIST:
                print "There was an error creating the log directory, exiting... (%s)" % e
                sys.exit(1)
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile)
    from deluge.log import LOG as log

    if options.config:
        if not deluge.configmanager.set_config_dir(options.config):
            log.error(
                "There was an error setting the config directory! Exiting...")
            sys.exit(1)

    # Sets the options.logfile to point to the default location
    def open_logfile():
        if not options.logfile:
            options.logfile = deluge.configmanager.get_config_dir(
                "deluged.log")
            file_handler = FileHandler(options.logfile)
            log.addHandler(file_handler)

    # Writes out a pidfile if necessary
    def write_pidfile():
        if options.pidfile:
            open(options.pidfile, "wb").write("%s\n" % os.getpid())
Example #17
0
def start_daemon():
    """Entry point for daemon script"""
    import deluge.common

    if 'dev' not in deluge.common.get_version():
        import warnings
        warnings.filterwarnings('ignore', category=DeprecationWarning, module='twisted')

    # Setup the argument parser
    parser = OptionParser(usage="%prog [options] [actions]",
                                           version=deluge.common.get_version())
    parser.add_option("-p", "--port", dest="port",
        help="Port daemon will listen on", action="store", type="int")
    parser.add_option("-i", "--interface", dest="interface",
        help="Interface daemon will listen for bittorrent connections on, \
this should be an IP address", metavar="IFACE",
        action="store", type="str")
    parser.add_option("-u", "--ui-interface", dest="ui_interface",
        help="Interface daemon will listen for UI connections on, this should be\
 an IP address", metavar="IFACE", action="store", type="str")
    if not (deluge.common.windows_check() or deluge.common.osx_check()):
        parser.add_option("-d", "--do-not-daemonize", dest="donot",
            help="Do not daemonize", action="store_true", default=False)
    parser.add_option("-c", "--config", dest="config",
        help="Set the config location", action="store", type="str")
    parser.add_option("-l", "--logfile", dest="logfile",
        help="Set the logfile location", action="store", type="str")
    parser.add_option("-P", "--pidfile", dest="pidfile",
        help="Use pidfile to store process id", action="store", type="str")
    if not deluge.common.windows_check():
        parser.add_option("-U", "--user", dest="user",
            help="User to switch to. Only use it when starting as root", action="store", type="str")
        parser.add_option("-g", "--group", dest="group",
            help="Group to switch to. Only use it when starting as root", action="store", type="str")
    parser.add_option("-L", "--loglevel", dest="loglevel",
        help="Set the log level: none, info, warning, error, critical, debug", action="store", type="str")
    parser.add_option("-q", "--quiet", dest="quiet",
        help="Sets the log level to 'none', this is the same as `-L none`", action="store_true", default=False)
    parser.add_option("-r", "--rotate-logs",
        help="Rotate logfiles.", action="store_true", default=False)
    parser.add_option("--profile", dest="profile", action="store_true", default=False,
        help="Profiles the daemon")

    # Get the options and args from the OptionParser
    (options, args) = parser.parse_args()

    if options.quiet:
        options.loglevel = "none"

    logfile_mode = 'w'
    if options.rotate_logs:
        logfile_mode = 'a'

    # Setup the logger
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile,
                           filemode=logfile_mode)
    deluge.common.setup_translations()

    import deluge.configmanager
    if options.config:
        if not deluge.configmanager.set_config_dir(options.config):
            print("There was an error setting the config dir! Exiting..")
            sys.exit(1)

    # Sets the options.logfile to point to the default location
    def open_logfile():
        if not options.logfile:
            options.logfile = deluge.configmanager.get_config_dir("deluged.log")

    # Writes out a pidfile if necessary
    def write_pidfile():
        if options.pidfile:
            open(options.pidfile, "wb").write("%s\n" % os.getpid())

    # If the donot daemonize is set, then we just skip the forking
    if not (deluge.common.windows_check() or deluge.common.osx_check() or options.donot):
        if os.fork():
            # We've forked and this is now the parent process, so die!
            os._exit(0)
        os.setsid()
        # Do second fork
        if os.fork():
            os._exit(0)

    # Write pid file before chuid
    write_pidfile()

    if options.user:
        if not options.user.isdigit():
            import pwd
            options.user = pwd.getpwnam(options.user)[2]
        os.setuid(options.user)
    if options.group:
        if not options.group.isdigit():
            import grp
            options.group = grp.getgrnam(options.group)[2]
        os.setuid(options.group)

    open_logfile()

    # Setup the logger
    try:
        # Try to make the logfile's directory if it doesn't exist
        os.makedirs(os.path.abspath(os.path.dirname(options.logfile)))
    except:
        pass

    import logging
    log = logging.getLogger(__name__)

    if options.profile:
        import hotshot
        hsp = hotshot.Profile(deluge.configmanager.get_config_dir("deluged.profile"))
        hsp.start()
    try:
        from deluge.core.daemon import Daemon
        Daemon(options, args)
    except deluge.error.DaemonRunningError, e:
        log.error(e)
        log.error("You cannot run multiple daemons with the same config directory set.")
        log.error("If you believe this is an error, you can force a start by deleting %s.", deluge.configmanager.get_config_dir("deluged.pid"))
        sys.exit(1)
Example #18
0
def start_daemon():
    """Entry point for daemon script"""
    import deluge.common
    deluge.common.setup_translations()

    if 'dev' not in deluge.common.get_version():
        import warnings
        warnings.filterwarnings('ignore', category=DeprecationWarning, module='twisted')

    # Setup the argument parser
    parser = OptionParser(usage="%prog [options] [actions]",
                  version= "%prog: " + deluge.common.get_version() + lt_version)
    parser.add_option("-p", "--port", dest="port",
        help="Port daemon will listen on", action="store", type="int")
    parser.add_option("-i", "--interface", dest="interface",
        help="Interface daemon will listen for bittorrent connections on, \
this should be an IP address", metavar="IFACE",
        action="store", type="str")
    parser.add_option("-u", "--ui-interface", dest="ui_interface",
        help="Interface daemon will listen for UI connections on, this should be\
 an IP address", metavar="IFACE", action="store", type="str")
    if not (deluge.common.windows_check() or deluge.common.osx_check()):
        parser.add_option("-d", "--do-not-daemonize", dest="donot",
            help="Do not daemonize", action="store_true", default=False)
    parser.add_option("-c", "--config", dest="config",
        help="Set the config location", action="store", type="str")
    parser.add_option("-l", "--logfile", dest="logfile",
        help="Set the logfile location", action="store", type="str")
    parser.add_option("-P", "--pidfile", dest="pidfile",
        help="Use pidfile to store process id", action="store", type="str")
    if not deluge.common.windows_check():
        parser.add_option("-U", "--user", dest="user",
            help="User to switch to. Only use it when starting as root", action="store", type="str")
        parser.add_option("-g", "--group", dest="group",
            help="Group to switch to. Only use it when starting as root", action="store", type="str")
    parser.add_option("-L", "--loglevel", dest="loglevel",
        help="Set the log level: none, info, warning, error, critical, debug", action="store", type="str")
    parser.add_option("-q", "--quiet", dest="quiet",
        help="Sets the log level to 'none', this is the same as `-L none`", action="store_true", default=False)
    parser.add_option("-r", "--rotate-logs",
        help="Rotate logfiles.", action="store_true", default=False)
    parser.add_option("--profile", dest="profile", action="store_true", default=False,
        help="Profiles the daemon")

    # Get the options and args from the OptionParser
    (options, args) = parser.parse_args()

    if options.quiet:
        options.loglevel = "none"

    logfile_mode = 'w'
    if options.rotate_logs:
        logfile_mode = 'a'

    # Setup the logger
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile,
                           filemode=logfile_mode)

    import deluge.configmanager
    if options.config:
        if not deluge.configmanager.set_config_dir(options.config):
            print("There was an error setting the config dir! Exiting..")
            sys.exit(1)

    # Sets the options.logfile to point to the default location
    def open_logfile():
        if not options.logfile:
            options.logfile = deluge.configmanager.get_config_dir("deluged.log")

    # Writes out a pidfile if necessary
    def write_pidfile():
        if options.pidfile:
            open(options.pidfile, "wb").write("%s\n" % os.getpid())

    # If the donot daemonize is set, then we just skip the forking
    if not (deluge.common.windows_check() or deluge.common.osx_check() or options.donot):
        if os.fork():
            # We've forked and this is now the parent process, so die!
            os._exit(0)
        os.setsid()
        # Do second fork
        if os.fork():
            os._exit(0)

    # Write pid file before chuid
    write_pidfile()

    if options.user:
        if not options.user.isdigit():
            import pwd
            options.user = pwd.getpwnam(options.user)[2]
        os.setuid(options.user)
    if options.group:
        if not options.group.isdigit():
            import grp
            options.group = grp.getgrnam(options.group)[2]
        os.setuid(options.group)

    open_logfile()

    # Setup the logger
    try:
        # Try to make the logfile's directory if it doesn't exist
        os.makedirs(os.path.abspath(os.path.dirname(options.logfile)))
    except:
        pass

    import logging
    log = logging.getLogger(__name__)

    if options.profile:
        import hotshot
        hsp = hotshot.Profile(deluge.configmanager.get_config_dir("deluged.profile"))
        hsp.start()
    try:
        from deluge.core.daemon import Daemon
        Daemon(options, args)
    except deluge.error.DaemonRunningError, e:
        log.error(e)
        log.error("You cannot run multiple daemons with the same config directory set.")
        log.error("If you believe this is an error, you can force a start by deleting %s.", deluge.configmanager.get_config_dir("deluged.pid"))
        sys.exit(1)
Example #19
0
def start_daemon():
    """Entry point for daemon script"""
    import deluge.common

    if 'dev' not in deluge.common.get_version():
        import warnings
        warnings.filterwarnings('ignore', category=DeprecationWarning, module='twisted')

    # Setup the argument parser
    parser = OptionParser(usage="%prog [options] [actions]")
    parser.add_option("-v", "--version", action="callback", callback=version_callback,
            help="Show program's version number and exit")
    parser.add_option("-p", "--port", dest="port",
        help="Port daemon will listen on", action="store", type="int")
    parser.add_option("-i", "--interface", dest="listen_interface",
        help="Interface daemon will listen for bittorrent connections on, \
this should be an IP address", metavar="IFACE",
        action="store", type="str")
    parser.add_option("-u", "--ui-interface", dest="ui_interface",
        help="Interface daemon will listen for UI connections on, this should be\
 an IP address", metavar="IFACE", action="store", type="str")
    parser.add_option("-d", "--do-not-daemonize", dest="donot",
        help="Do not daemonize", action="store_true", default=False)
    parser.add_option("-c", "--config", dest="config",
        help="Set the config location", action="store", type="str")
    parser.add_option("-P", "--pidfile", dest="pidfile",
        help="Use pidfile to store process id", action="store", type="str")
    parser.add_option("-l", "--logfile", dest="logfile",
        help="Set the logfile location", action="store", type="str")
    parser.add_option("-L", "--loglevel", dest="loglevel",
        help="Set the log level: none, info, warning, error, critical, debug", action="store", type="str")
    parser.add_option("-q", "--quiet", dest="quiet",
        help="Sets the log level to 'none', this is the same as `-L none`", action="store_true", default=False)
    parser.add_option("--profile", dest="profile", action="store_true", default=False,
        help="Profiles the daemon")

    # Get the options and args from the OptionParser
    (options, args) = parser.parse_args()

    if options.quiet:
        options.loglevel = "none"

    if options.config:
        if not deluge.configmanager.set_config_dir(options.config):
            print("There was an error setting the config dir! Exiting..")
            sys.exit(1)

    # Sets the options.logfile to point to the default location
    def open_logfile():
        if not options.logfile:
            options.logfile = deluge.configmanager.get_config_dir("deluged.log")

    # Writes out a pidfile if necessary
    def write_pidfile():
        if options.pidfile:
            open(options.pidfile, "wb").write("%s\n" % os.getpid())

    # If the donot daemonize is set, then we just skip the forking
    if not options.donot:
        # Windows check, we log to the config folder by default
        if deluge.common.windows_check() or deluge.common.osx_check():
            open_logfile()
            write_pidfile()
        else:
            if os.fork() == 0:
                os.setsid()
                if os.fork() == 0:
                    open_logfile()
                    write_pidfile()
                else:
                    os._exit(0)
            else:
                os._exit(0)
    else:
        # Do not daemonize
        write_pidfile()

    # Setup the logger
    try:
        # Try to make the logfile's directory if it doesn't exist
        os.makedirs(os.path.abspath(os.path.dirname(options.logfile)))
    except:
        pass
    deluge.log.setupLogger(level=options.loglevel, filename=options.logfile)
    from deluge.log import LOG as log

    if options.profile:
        import hotshot
        hsp = hotshot.Profile(deluge.configmanager.get_config_dir("deluged.profile"))
        hsp.start()
    try:
        from deluge.core.daemon import Daemon
        Daemon(options, args)
    except deluge.error.DaemonRunningError, e:
        log.error(e)
        log.error("You cannot run multiple daemons with the same config directory set.")
        log.error("If you believe this is an error, you can force a start by deleting %s.", deluge.configmanager.get_config_dir("deluged.pid"))
        sys.exit(1)