File size: 23,714 Bytes
5980447
1
2
{"repo": "samschott/maestral", "pull_number": 146, "instance_id": "samschott__maestral-146", "issue_numbers": "", "base_commit": "9bc149fd9a478de4d6082208c9ffca31b1d7f508", "patch": "diff --git a/maestral/cli.py b/maestral/cli.py\n--- a/maestral/cli.py\n+++ b/maestral/cli.py\n@@ -445,16 +445,10 @@ def gui(config_name):\n def start(config_name: str, foreground: bool, verbose: bool):\n     \"\"\"Starts the Maestral daemon.\"\"\"\n \n-    from maestral.daemon import get_maestral_pid, get_maestral_proxy\n+    from maestral.daemon import get_maestral_proxy\n     from maestral.daemon import (start_maestral_daemon_thread, threads,\n                                  start_maestral_daemon_process, Start)\n \n-    # do nothing if already running\n-    if get_maestral_pid(config_name):\n-        click.echo('Maestral daemon is already running.')\n-        return\n-\n-    # start daemon\n     click.echo('Starting Maestral...', nl=False)\n \n     if foreground:\n@@ -464,6 +458,9 @@ def start(config_name: str, foreground: bool, verbose: bool):\n \n     if res == Start.Ok:\n         click.echo('\\rStarting Maestral...        ' + OK)\n+    elif res == Start.AlreadyRunning:\n+        click.echo('\\rStarting Maestral...        Already running.')\n+        return\n     else:\n         click.echo('\\rStarting Maestral...        ' + FAILED)\n         click.echo('Please check logs for more information.')\n@@ -841,14 +838,14 @@ def rebuild_index(config_name: str):\n @main.command(help_priority=16)\n def configs():\n     \"\"\"Lists all configured Dropbox accounts.\"\"\"\n-    from maestral.daemon import get_maestral_pid\n+    from maestral.daemon import is_running\n \n     # clean up stale configs\n     config_names = list_configs()\n \n     for name in config_names:\n         dbid = MaestralConfig(name).get('account', 'account_id')\n-        if dbid == '' and not get_maestral_pid(name):\n+        if dbid == '' and not is_running(name):\n             remove_configuration(name)\n \n     # display remaining configs\n@@ -1132,4 +1129,4 @@ def notify_snooze(config_name: str, minutes: int):\n             click.echo(f'Notifications snoozed for {minutes} min. '\n                        'Set snooze to 0 to reset.')\n         else:\n-            click.echo(f'Notifications enabled.')\n+            click.echo('Notifications enabled.')\ndiff --git a/maestral/daemon.py b/maestral/daemon.py\n--- a/maestral/daemon.py\n+++ b/maestral/daemon.py\n@@ -16,16 +16,22 @@\n import signal\n import traceback\n import enum\n+import subprocess\n+import threading\n+import fcntl\n+import struct\n+import tempfile\n \n # external imports\n import Pyro5.errors\n from Pyro5.api import Daemon, Proxy, expose, oneway\n from Pyro5.serializers import SerpentSerializer\n-from lockfile.pidlockfile import PIDLockFile, AlreadyLocked\n+from fasteners import InterProcessLock\n \n # local imports\n from maestral.errors import SYNC_ERRORS, FATAL_ERRORS\n from maestral.constants import IS_FROZEN\n+from maestral.utils.appdirs import get_runtime_path\n \n \n threads = dict()\n@@ -76,6 +82,151 @@ def serpent_deserialize_api_error(class_name, d):\n     )\n \n \n+# ==== interprocess locking ==============================================================\n+\n+def _get_lockdata():\n+\n+    try:\n+        os.O_LARGEFILE\n+    except AttributeError:\n+        start_len = 'll'\n+    else:\n+        start_len = 'qq'\n+\n+    if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd'))\n+            or sys.platform == 'darwin'):\n+        if struct.calcsize('l') == 8:\n+            off_t = 'l'\n+            pid_t = 'i'\n+        else:\n+            off_t = 'lxxxx'\n+            pid_t = 'l'\n+\n+        fmt = off_t + off_t + pid_t + 'hh'\n+        pid_index = 2\n+        lockdata = struct.pack(fmt, 0, 0, 0, fcntl.F_WRLCK, 0)\n+    # elif sys.platform.startswith('gnukfreebsd'):\n+    #     fmt = 'qqihhi'\n+    #     pid_index = 2\n+    #     lockdata = struct.pack(fmt, 0, 0, 0, fcntl.F_WRLCK, 0, 0)\n+    # elif sys.platform in ('hp-uxB', 'unixware7'):\n+    #     fmt = 'hhlllii'\n+    #     pid_index = 2\n+    #     lockdata = struct.pack(fmt, fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)\n+    elif sys.platform.startswith('linux'):\n+        fmt = 'hh' + start_len + 'ih'\n+        pid_index = 4\n+        lockdata = struct.pack(fmt, fcntl.F_WRLCK, 0, 0, 0, 0, 0)\n+    else:\n+        raise RuntimeError(f'Unsupported platform {sys.platform}')\n+\n+    return lockdata, fmt, pid_index\n+\n+\n+class Lock:\n+    \"\"\"\n+    A inter-process and inter-thread lock. This reuses uses code from oslo.concurrency\n+    but provides non-blocking acquire. Use the :meth:`singleton` class method to retrieve\n+    an existing instance for thread-safe usage.\n+    \"\"\"\n+\n+    _instances = dict()\n+    _singleton_lock = threading.Lock()\n+\n+    @classmethod\n+    def singleton(cls, name, lock_path=None):\n+\n+        with cls._singleton_lock:\n+            try:\n+                instance = cls._instances[name]\n+            except KeyError:\n+                instance = cls(name, lock_path)\n+                cls._instances[name] = instance\n+\n+            return instance\n+\n+    def __init__(self, name, lock_path=None):\n+\n+        self.name = name\n+        dirname = lock_path or tempfile.gettempdir()\n+        lock_path = os.path.join(dirname, name)\n+\n+        self._internal_lock = threading.Semaphore()\n+        self._external_lock = InterProcessLock(lock_path)\n+\n+        self._lock = threading.RLock()\n+\n+    def acquire(self):\n+        \"\"\"\n+        Attempts to acquire the given lock.\n+\n+        :returns: Whether or not the acquisition succeeded.\n+        :rtype: bool\n+        \"\"\"\n+\n+        with self._lock:\n+            locked_internal = self._internal_lock.acquire(blocking=False)\n+\n+            if not locked_internal:\n+                return False\n+\n+            try:\n+                locked_external = self._external_lock.acquire(blocking=False)\n+            except Exception:\n+                self._internal_lock.release()\n+                raise\n+            else:\n+\n+                if locked_external:\n+                    return True\n+                else:\n+                    self._internal_lock.release()\n+                    return False\n+\n+    def release(self):\n+        \"\"\"Release the previously acquired lock.\"\"\"\n+        with self._lock:\n+            self._external_lock.release()\n+            self._internal_lock.release()\n+\n+    def locked(self):\n+        \"\"\"Checks if the lock is currently held by any thread or process.\"\"\"\n+        with self._lock:\n+            gotten = self.acquire()\n+            if gotten:\n+                self.release()\n+            return not gotten\n+\n+    def locking_pid(self):\n+        \"\"\"\n+        Returns the PID of the process which currently holds the lock or None.\n+\n+        :returns: The PID of the process which currently holds the lock or None.\n+        :rtype: int\n+        \"\"\"\n+\n+        with self._lock:\n+\n+            if self._external_lock.acquired:\n+                return os.getpid()\n+\n+            try:\n+                # don't close again in case we are the locking process\n+                self._external_lock._do_open()\n+                lockdata, fmt, pid_index = _get_lockdata()\n+                lockdata = fcntl.fcntl(self._external_lock.lockfile,\n+                                       fcntl.F_GETLK, lockdata)\n+\n+                lockdata_list = struct.unpack(fmt, lockdata)\n+                pid = lockdata_list[pid_index]\n+\n+                if pid > 0:\n+                    return pid\n+\n+            except OSError:\n+                pass\n+\n+\n # ==== helpers for daemon management =====================================================\n \n def _escape_spaces(string):\n@@ -93,12 +244,15 @@ def _send_term(pid):\n         pass\n \n \n-def _process_exists(pid):\n-    try:\n-        os.kill(pid, signal.SIG_DFL)\n-        return True\n-    except ProcessLookupError:\n-        return False\n+class MaestralLock:\n+    \"\"\"\n+    A inter-process and inter-thread lock for Maestral.\n+    \"\"\"\n+\n+    def __new__(cls, config_name):\n+        name = f'{config_name}.lock'\n+        path = get_runtime_path('maestral')\n+        return Lock.singleton(name, path)\n \n \n def sockpath_for_config(config_name):\n@@ -106,28 +260,11 @@ def sockpath_for_config(config_name):\n     Returns the unix socket location to be used for the config. This should default to\n     the apps runtime directory + '/maestral/CONFIG_NAME.sock'.\n     \"\"\"\n-    from maestral.utils.appdirs import get_runtime_path\n-    return get_runtime_path('maestral', config_name + '.sock')\n-\n-\n-def pidpath_for_config(config_name):\n-    from maestral.utils.appdirs import get_runtime_path\n-    return get_runtime_path('maestral', config_name + '.pid')\n-\n+    return get_runtime_path('maestral', f'{config_name}.sock')\n \n-def is_pidfile_stale(pidfile):\n-    \"\"\"\n-    Determine whether a PID file is stale. Returns ``True`` if the PID file is stale,\n-    ``False`` otherwise. The PID file is stale if its contents are valid but do not\n-    match the PID of a currently-running process.\n-    \"\"\"\n-    result = False\n \n-    pid = pidfile.read_pid()\n-    if pid:\n-        return not _process_exists(pid)\n-    else:\n-        return result\n+def lockpath_for_config(config_name):\n+    return get_runtime_path('maestral', f'{config_name}.lock')\n \n \n def get_maestral_pid(config_name):\n@@ -139,39 +276,28 @@ def get_maestral_pid(config_name):\n     :rtype: int\n     \"\"\"\n \n-    lockfile = PIDLockFile(pidpath_for_config(config_name))\n-    pid = lockfile.read_pid()\n-\n-    if pid and not is_pidfile_stale(lockfile):\n-        return pid\n-    else:\n-        lockfile.break_lock()\n+    return MaestralLock(config_name).locking_pid()\n \n \n-def _wait_for_startup(config_name, timeout=8):\n-    \"\"\"Waits for the daemon to start and verifies Pyro communication. Returns ``Start.Ok``\n-    if startup and communication succeeds within timeout, ``Start.Failed`` otherwise.\"\"\"\n-    t0 = time.time()\n-    pid = None\n+def is_running(config_name):\n+    \"\"\"\n+    Checks if a daemon is currently running.\n \n-    while not pid and time.time() - t0 < timeout / 2:\n-        pid = get_maestral_pid(config_name)\n-        time.sleep(0.2)\n+    :param str config_name: The name of the Maestral configuration.\n+    :returns: Whether the daemon is running.\n+    :rtype: bool\n+    \"\"\"\n \n-    if pid:\n-        return _check_pyro_communication(config_name, timeout=int(timeout / 2))\n-    else:\n-        return Start.Failed\n+    return MaestralLock(config_name).locked()\n \n \n-def _check_pyro_communication(config_name, timeout=4):\n+def _wait_for_startup(config_name, timeout=8):\n     \"\"\"Checks if we can communicate with the maestral daemon. Returns ``Start.Ok`` if\n     communication succeeds within timeout, ``Start.Failed``  otherwise.\"\"\"\n \n     sock_name = sockpath_for_config(config_name)\n     maestral_daemon = Proxy(URI.format(_escape_spaces(config_name), './u:' + sock_name))\n \n-    # wait until we can communicate with daemon, timeout after :param:`timeout`\n     while timeout > 0:\n         try:\n             maestral_daemon._pyroBind()\n@@ -189,36 +315,30 @@ def _check_pyro_communication(config_name, timeout=4):\n \n def start_maestral_daemon(config_name='maestral', log_to_stdout=False):\n     \"\"\"\n+    Starts the Maestral daemon with event loop in the current thread. Startup is race\n+    free: there will never be two daemons running for the same config.\n+\n     Wraps :class:`main.Maestral` as Pyro daemon object, creates a new instance and starts\n     Pyro's event loop to listen for requests on a unix domain socket. This call will block\n     until the event loop shuts down.\n \n-    This command will return silently if the daemon is already running.\n-\n     :param str config_name: The name of the Maestral configuration to use.\n     :param bool log_to_stdout: If ``True``, write logs to stdout. Defaults to ``False``.\n+    :raises: :class:`RuntimeError` if a daemon for the given ``config_name`` is already\n+        running.\n     \"\"\"\n     import threading\n     from maestral.main import Maestral\n \n-    sock_name = sockpath_for_config(config_name)\n-    pid_name = pidpath_for_config(config_name)\n-\n-    lockfile = PIDLockFile(pid_name)\n+    sockpath = sockpath_for_config(config_name)\n \n     if threading.current_thread() is threading.main_thread():\n         signal.signal(signal.SIGTERM, _sigterm_handler)\n \n     # acquire PID lock file\n-\n-    try:\n-        lockfile.acquire(timeout=0.5)\n-    except AlreadyLocked:\n-        if is_pidfile_stale(lockfile):\n-            lockfile.break_lock()\n-            lockfile.acquire()\n-        else:\n-            return\n+    lock = MaestralLock(config_name)\n+    if not lock.acquire():\n+        raise RuntimeError('Maestral daemon is already running')\n \n     # Nice ourselves to give other processes priority. We will likely only\n     # have significant CPU usage in case of many concurrent downloads.\n@@ -227,7 +347,7 @@ def start_maestral_daemon(config_name='maestral', log_to_stdout=False):\n     try:\n         # clean up old socket\n         try:\n-            os.remove(sock_name)\n+            os.remove(sockpath)\n         except FileNotFoundError:\n             pass\n \n@@ -243,7 +363,7 @@ def start_maestral_daemon(config_name='maestral', log_to_stdout=False):\n \n         m = ExposedMaestral(config_name, log_to_stdout=log_to_stdout)\n \n-        with Daemon(unixsocket=sock_name) as daemon:\n+        with Daemon(unixsocket=sockpath) as daemon:\n             daemon.register(m, f'maestral.{_escape_spaces(config_name)}')\n             daemon.requestLoop(loopCondition=m._loop_condition)\n \n@@ -252,24 +372,24 @@ def start_maestral_daemon(config_name='maestral', log_to_stdout=False):\n     except (KeyboardInterrupt, SystemExit):\n         sys.exit(0)\n     finally:\n-        lockfile.release()\n+        lock.release()\n \n \n def start_maestral_daemon_thread(config_name='maestral', log_to_stdout=False):\n     \"\"\"\n-    Starts the Maestral daemon in a thread (by calling :func:`start_maestral_daemon`).\n+    Starts the Maestral daemon in a new thread by calling :func:`start_maestral_daemon`.\n+    Startup is race free: there will never be two daemons running for the same config.\n \n     :param str config_name: The name of the Maestral configuration to use.\n     :param bool log_to_stdout: If ``True``, write logs to stdout. Defaults to ``False``.\n     :returns: ``Start.Ok`` if successful, ``Start.AlreadyRunning`` if the daemon was\n-        already running or ``Start.Failed`` if startup failed.\n+        already running or ``Start.Failed`` if startup failed. It is possible that\n+        Start.Ok is returned instead of Start.AlreadyRunning in case of a race.\n     \"\"\"\n \n-    if config_name in threads and threads[config_name].is_alive():\n+    if is_running(config_name):\n         return Start.AlreadyRunning\n \n-    import threading\n-\n     t = threading.Thread(\n         target=start_maestral_daemon,\n         args=(config_name, log_to_stdout),\n@@ -288,17 +408,18 @@ def start_maestral_daemon_thread(config_name='maestral', log_to_stdout=False):\n \n def start_maestral_daemon_process(config_name='maestral', log_to_stdout=False):\n     \"\"\"\n-    Starts the Maestral daemon in a separate process by calling\n-    :func:`start_maestral_daemon`.\n+    Starts the Maestral daemon in a new process by calling :func:`start_maestral_daemon`.\n+    Startup is race free: there will never be two daemons running for the same config.\n \n-    This function assumes that ``sys.executable`` points to the Python executable. In\n-    case of a frozen app, the executable must take the command line argument\n-    ``--frozen-daemon to start`` a daemon process which is *not syncing*, .i.e., just run\n-    :meth:`start_maestral_daemon`. This is currently supported through the\n-    constole_script entry points of both `maestral` and `maestral_qt`.\n+    This function assumes that ``sys.executable`` points to the Python executable or a\n+    frozen executable. In case of a frozen executable, the executable must take the\n+    command line argument ``--frozen-daemon to start`` to start a daemon process which is\n+    *not syncing*, .i.e., just run :meth:`start_maestral_daemon`. This is currently\n+    supported through the console_script entry points of both `maestral` and\n+    `maestral_qt`.\n \n     Starting a detached daemon process is difficult from a standalone executable since\n-    the typical double-fork magic may fail on macOS and we do not have acccess to a\n+    the typical double-fork magic may fail on macOS and we do not have access to a\n     standalone Python interpreter to spawn a subprocess. Our approach mimics the \"freeze\n     support\" implemented by the multiprocessing module but fully detaches the spawned\n     process.\n@@ -306,18 +427,19 @@ def start_maestral_daemon_process(config_name='maestral', log_to_stdout=False):\n     :param str config_name: The name of the Maestral configuration to use.\n     :param bool log_to_stdout: If ``True``, write logs to stdout. Defaults to ``False``.\n     :returns: ``Start.Ok`` if successful, ``Start.AlreadyRunning`` if the daemon was\n-        already running or ``Start.Failed`` if startup failed.\n+        already running or ``Start.Failed`` if startup failed. It is possible that\n+        Start.Ok is returned instead of Start.AlreadyRunning in case of a race.\n     \"\"\"\n-    import subprocess\n+\n+    if is_running(config_name):\n+        return Start.AlreadyRunning\n+\n     from shlex import quote\n     import multiprocessing as mp\n \n     # use nested Popen and multiprocessing.Process to effectively create double fork\n     # see Unix 'double-fork magic'\n \n-    if get_maestral_pid(config_name):\n-        return Start.AlreadyRunning\n-\n     if IS_FROZEN:\n \n         def target():\n@@ -347,48 +469,49 @@ def target():\n def stop_maestral_daemon_process(config_name='maestral', timeout=10):\n     \"\"\"Stops a maestral daemon process by finding its PID and shutting it down.\n \n-    This function first tries to shut down Maestral gracefully. If this fails, it will\n-    send SIGTERM. If that fails as well, it will send SIGKILL to the process.\n+    This function first tries to shut down Maestral gracefully. If this fails and we know\n+    its PID, it will send SIGTERM. If that fails as well, it will send SIGKILL to the\n+    process.\n \n     :param str config_name: The name of the Maestral configuration to use.\n     :param float timeout: Number of sec to wait for daemon to shut down before killing it.\n-    :returns: ``Exit.Ok`` if successful, ``Exit.Killed`` if killed and ``Exit.NotRunning``\n-        if the daemon was not running.\n+    :returns: ``Exit.Ok`` if successful, ``Exit.Killed`` if killed, ``Exit.NotRunning`` if\n+        the daemon was not running and ``Exit.Failed`` if killing the process failed\n+        because we could not retrieve its PID.\n     \"\"\"\n \n-    lockfile = PIDLockFile(pidpath_for_config(config_name))\n-    pid = lockfile.read_pid()\n+    if not is_running(config_name):\n+        return Exit.NotRunning\n \n-    try:\n-        if not pid or not _process_exists(pid):\n-            return Exit.NotRunning\n+    pid = get_maestral_pid(config_name)\n \n-        try:\n-            with MaestralProxy(config_name) as m:\n-                m.stop_sync()\n-                m.shutdown_pyro_daemon()\n-        except Pyro5.errors.CommunicationError:\n+    try:\n+        with MaestralProxy(config_name) as m:\n+            m.stop_sync()\n+            m.shutdown_pyro_daemon()\n+    except Pyro5.errors.CommunicationError:\n+        if pid:\n             _send_term(pid)\n-        finally:\n-            while timeout > 0:\n-                if not _process_exists(pid):\n-                    return Exit.Ok\n-                else:\n-                    time.sleep(0.2)\n-                    timeout -= 0.2\n+    finally:\n+        while timeout > 0:\n+            if not is_running(config_name):\n+                return Exit.Ok\n+            else:\n+                time.sleep(0.2)\n+                timeout -= 0.2\n \n-            # send SIGTERM after timeout and delete PID file\n-            _send_term(pid)\n+        # send SIGTERM after timeout and delete PID file\n+        _send_term(pid)\n \n-            time.sleep(1)\n+        time.sleep(1)\n \n-            if not _process_exists(pid):\n-                return Exit.Ok\n-            else:\n-                os.kill(pid, signal.SIGKILL)\n-                return Exit.Killed\n-    finally:\n-        lockfile.break_lock()\n+        if not is_running(config_name):\n+            return Exit.Ok\n+        elif pid:\n+            os.kill(pid, signal.SIGKILL)\n+            return Exit.Killed\n+        else:\n+            return Exit.Failed\n \n \n def stop_maestral_daemon_thread(config_name='maestral', timeout=10):\n@@ -400,11 +523,7 @@ def stop_maestral_daemon_thread(config_name='maestral', timeout=10):\n         ``Exit.Failed`` if it could not be stopped within timeout.\n     \"\"\"\n \n-    lockfile = PIDLockFile(pidpath_for_config(config_name))\n-    t = threads[config_name]\n-\n-    if not t.is_alive():\n-        lockfile.break_lock()\n+    if not is_running(config_name):\n         return Exit.NotRunning\n \n     # tell maestral daemon to shut down\n@@ -416,11 +535,11 @@ def stop_maestral_daemon_thread(config_name='maestral', timeout=10):\n         return Exit.Failed\n \n     # wait for maestral to carry out shutdown\n+    t = threads.get(config_name)\n     t.join(timeout=timeout)\n     if t.is_alive():\n         return Exit.Failed\n     else:\n-        del threads[config_name]\n         return Exit.Ok\n \n \n@@ -436,9 +555,7 @@ def get_maestral_proxy(config_name='maestral', fallback=False):\n         ``fallback`` is ``False``.\n     \"\"\"\n \n-    pid = get_maestral_pid(config_name)\n-\n-    if pid:\n+    if is_running(config_name):\n         sock_name = sockpath_for_config(config_name)\n \n         sys.excepthook = Pyro5.errors.excepthook\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -1,35 +1,11 @@\n # -*- coding: utf-8 -*-\n \n # system imports\n-import sys\n-import os.path as osp\n from setuptools import setup, find_packages\n import importlib.util\n \n # local imports (must not depend on 3rd party packages)\n from maestral import __version__, __author__, __url__\n-from maestral.utils.appdirs import get_runtime_path\n-from maestral.config.base import list_configs\n-\n-\n-# abort install if there are running daemons\n-running_daemons = []\n-\n-for config in list_configs():\n-    pid_file = get_runtime_path('maestral', config + '.pid')\n-    if osp.exists(pid_file):\n-        running_daemons.append(config)\n-\n-if running_daemons:\n-    sys.stderr.write(f\"\"\"\n-Maestral daemons with the following configs are running:\n-\n-{', '.join(running_daemons)}\n-\n-Please stop the daemons before updating to ensure a clean upgrade\n-of config files and compatibility been the CLI and daemon.\n-    \"\"\")\n-    sys.exit(1)\n \n \n # proceed with actual install\n@@ -42,7 +18,7 @@\n     'jeepney;sys_platform==\"linux\"',\n     'keyring>=19.0.0',\n     'keyrings.alt>=3.1.0',\n-    'lockfile>=0.12.0',\n+    'fasteners',\n     'packaging',\n     'pathspec>=0.5.8',\n     'Pyro5>=5.7',\n", "test_patch": "", "problem_statement": "", "hints_text": "", "created_at": "2020-05-14T10:37:40Z"}