Ejemplo n.º 1
0
 def clicked_force_shutdown(self):
     process_checker = ProcessChecker()
     if process_checker.already_running:
         core_pid = process_checker.get_pid_from_lock_file()
         os.kill(int(core_pid), 9)
     # Stop the Qt application
     QApplication.quit()
Ejemplo n.º 2
0
def test_dead_pid_in_lock_file(tmpdir):
    """Testing whether the process checker returns false when there is a dead pid in the lock file."""
    dead_pid = 134824733
    create_lock_file_with_pid(tmpdir, dead_pid)
    process_checker = ProcessChecker(state_directory=Path(tmpdir))
    assert not process_checker.is_pid_running(dead_pid)
    assert not process_checker.already_running
Ejemplo n.º 3
0
def test_invalid_pid_in_lock_file(tmpdir):
    """
    Testing pid should be -1 if the lock file is invalid
    """
    with open(tmpdir / LOCK_FILE_NAME, 'wb') as lock_file:
        lock_file.write(b"Hello world")

    process_checker = ProcessChecker(state_directory=Path(tmpdir))
    assert process_checker.get_pid_from_lock_file() == -1
Ejemplo n.º 4
0
def test_own_pid_in_lock_file(tmpdir):
    """
    Testing whether the process checker returns True when it finds its own pid in the lock file
    """
    create_lock_file_with_pid(tmpdir, os.getpid())
    process_checker = ProcessChecker(state_directory=Path(tmpdir))
    assert process_checker.already_running
Ejemplo n.º 5
0
    def _check_already_running(self):
        self.logger.info(f'Check if we are already running a Tribler instance in: {self.working_dir}')

        self.process_checker = ProcessChecker()
        if self.process_checker.already_running:
            self.logger.error(f"Another Tribler instance is already using directory: {self.working_dir}")
            asyncio.get_running_loop().stop()
Ejemplo n.º 6
0
    async def start_tribler(self, options):
        """
        Main method to startup Tribler.
        """

        async def signal_handler(sig):
            print("Received shut down signal %s" % sig)
            if not self._stopping:
                self._stopping = True
                await self.session.shutdown()
                print("Tribler shut down")
                get_event_loop().stop()
                self.process_checker.remove_lock_file()

        signal.signal(signal.SIGINT, lambda sig, _: ensure_future(signal_handler(sig)))
        signal.signal(signal.SIGTERM, lambda sig, _: ensure_future(signal_handler(sig)))

        statedir = Path(options.statedir or Path(get_appstate_dir(), '.Tribler'))
        config = TriblerConfig(statedir, config_file=statedir / 'triblerd.conf')

        # Check if we are already running a Tribler instance
        self.process_checker = ProcessChecker()
        if self.process_checker.already_running:
            print("Another Tribler instance is already using statedir %s" % config.get_state_dir())
            get_event_loop().stop()
            return

        print("Starting Tribler")

        if options.restapi > 0:
            config.set_http_api_enabled(True)
            config.set_http_api_port(options.restapi)

        if options.ipv8 > 0:
            config.set_ipv8_port(options.ipv8)
        elif options.ipv8 == 0:
            config.set_ipv8_enabled(False)

        if options.libtorrent != -1 and options.libtorrent > 0:
            config.set_libtorrent_port(options.libtorrent)

        if options.ipv8_bootstrap_override is not None:
            config.set_ipv8_bootstrap_override(options.ipv8_bootstrap_override)

        if options.testnet:
            config.set_testnet(True)

        self.session = Session(config)
        try:
            await self.session.start()
        except Exception as e:
            print(str(e))
            get_event_loop().stop()
        else:
            print("Tribler started")
Ejemplo n.º 7
0
    async def start_tribler():
        # Check if we are already running a Tribler instance
        process_checker = ProcessChecker(root_state_dir)
        if process_checker.already_running:
            return
        process_checker.create_lock_file()

        # Before any upgrade, prepare a separate state directory for the update version so it does not
        # affect the older version state directory. This allows for safe rollback.
        version_history = VersionHistory(root_state_dir)
        version_history.fork_state_directory_if_necessary()
        version_history.save_if_necessary()
        state_dir = version_history.code_version.directory

        config = TriblerConfig(state_dir,
                               config_file=state_dir / CONFIG_FILENAME,
                               reset_config_on_error=True)

        if not config.get_core_error_reporting_requires_user_consent():
            SentryReporter.global_strategy = SentryStrategy.SEND_ALLOWED

        config.set_api_http_port(int(api_port))
        # If the API key is set to an empty string, it will remain disabled
        if config.get_api_key() not in ('', api_key):
            config.set_api_key(api_key)
            config.write(
            )  # Immediately write the API key so other applications can use it
        config.set_api_http_enabled(True)

        priority_order = config.get_cpu_priority_order()
        set_process_priority(pid=os.getpid(), priority_order=priority_order)

        global trace_logger
        # Enable tracer if --trace-debug or --trace-exceptions flag is present in sys.argv
        trace_logger = check_and_enable_code_tracing('core',
                                                     config.get_log_dir())

        session = Session(config, core_test_mode=core_test_mode)

        signal.signal(signal.SIGTERM,
                      lambda signum, stack: shutdown(session, signum, stack))
        await session.start()
Ejemplo n.º 8
0
class ShutdownEndpoint(RESTEndpoint):
    """
    With this endpoint you can shutdown Tribler.
    """

    def __init__(self, session):
        super(ShutdownEndpoint, self).__init__(session)
        self.process_checker = ProcessChecker()

    def setup_routes(self):
        self.app.add_routes([web.put('', self.shutdown)])

    @docs(
        tags=["General"],
        summary="Shutdown Tribler.",
        responses={
            200: {
                "schema": schema(TriblerShutdownResponse={
                    'shutdown': Boolean
                })
            }
        }
    )
    async def shutdown(self, request):
        async def shutdown():
            try:
                keep_loop_running = await self.session.shutdown()
            except Exception as e:
                self._logger.error(e)
                keep_loop_running = False

            self.process_checker.remove_lock_file()
            # Flush the logs to the file before exiting
            for handler in logging.getLogger().handlers:
                handler.flush()
            if not keep_loop_running:
                get_event_loop().stop()

        ensure_future(shutdown())
        return RESTResponse({"shutdown": True})
Ejemplo n.º 9
0
 def __init__(self, session):
     super().__init__(session)
     self.process_checker = ProcessChecker()
Ejemplo n.º 10
0
def test_other_instance_running(tmpdir, background_process):
    """Testing whether the process checker returns true when another process is running."""
    create_lock_file_with_pid(tmpdir, background_process.pid)
    process_checker = ProcessChecker(state_directory=Path(tmpdir))
    assert process_checker.is_pid_running(background_process.pid)
    assert process_checker.already_running
Ejemplo n.º 11
0
def process_checker(tmpdir):
    return ProcessChecker(state_directory=Path(tmpdir))
Ejemplo n.º 12
0
    def start_tribler(self, options):
        """
        Main method to startup Tribler.
        """
        def on_tribler_shutdown(_):
            msg("Tribler shut down")
            reactor.stop()
            self.process_checker.remove_lock_file()

        def signal_handler(sig, _):
            msg("Received shut down signal %s" % sig)
            if not self._stopping:
                self._stopping = True
                self.session.shutdown().addCallback(on_tribler_shutdown)

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        config = TriblerConfig()

        self.process_checker = ProcessChecker()
        if self.process_checker.already_running:
            self.shutdown_process(
                "Another Tribler instance is already using statedir %s" %
                config.get_state_dir())
            return

        # Enable exitnode if set in options
        if "exitnode" in options and options["exitnode"]:
            msg("Enabling exitnode")
            config.set_tunnel_community_enabled(True)
            config.set_tunnel_community_exitnode_enabled(True)
        else:
            config.set_tunnel_community_exitnode_enabled(False)

        # Enable bitcoin testnet
        if "testnet" in options and options["testnet"]:
            msg("Enabling bitcoin testnet")
            config.set_testnet(True)

        # Enable dummy wallets
        if "dummy" in options and options["dummy"]:
            msg("Enabling dummy wallets")
            config.set_dummy_wallets_enabled(True)

        # Enable record transactions
        msg("Enabling record transactions")
        config.set_record_transactions(True)

        # Minimize functionality enabled for plebnet
        # For now, config taken from market_plugin in devos tribler repo
        config.set_http_api_enabled(True)
        config.set_video_server_enabled(False)
        config.set_torrent_search_enabled(False)
        config.set_channel_search_enabled(False)
        config.set_mainline_dht_enabled(True)
        config.set_dht_enabled(True)
        config.set_chant_enabled(False)
        config.set_bitcoinlib_enabled(True)

        msg("Starting Tribler")

        if options["statedir"]:
            config.set_state_dir(options["statedir"])

        if options["restapi"] > 0:
            config.set_http_api_enabled(True)
            config.set_http_api_port(options["restapi"])

        if options["dispersy"] != -1 and options["dispersy"] > 0:
            config.set_dispersy_port(options["dispersy"])

        if options["libtorrent"] != -1 and options["libtorrent"] > 0:
            config.set_libtorrent_port(options["libtorrent"])

        self.session = Session(config)
        self.session.start().addErrback(
            lambda failure: self.shutdown_process(failure.getErrorMessage()))

        msg("Tribler started")
Ejemplo n.º 13
0
def get_existing_tribler_pid():
    """ Get PID of existing instance if present from the lock file (if any)"""
    process_checker = ProcessChecker()
    if process_checker.already_running:
        return process_checker.get_pid_from_lock_file()
    return -1
Ejemplo n.º 14
0
 def __init__(self, session):
     super(ShutdownEndpoint, self).__init__(session)
     self.process_checker = ProcessChecker()