Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

email_mirror: Skip overlapping IMAP polls rather than piling up.

Alex Vandiver7aa4116676c1
diff --git a/zerver/lib/management.py b/zerver/lib/management.py
index 0f3d386baf3..3bead460d76 100644
--- a/zerver/lib/management.py
+++ b/zerver/lib/management.py
@@ -34,27 +34,54 @@ class HandleMethod(Protocol):
def __call__(self, *args: Any, **kwargs: Any) -> None: ...
+def lockfile_path(handle_func: HandleMethod) -> str:
+ os.makedirs(settings.LOCKFILE_DIRECTORY, exist_ok=True)
+ # Trim out just the last part of the module name, which is the
+ # command name, to use as the lockfile name;
+ # `zerver.management.commands.send_zulip_update_announcements`
+ # becomes `/srv/zulip-locks/send_zulip_update_announcements.lock`
+ lockfile_name = handle_func.__module__.split(".")[-1]
+ return settings.LOCKFILE_DIRECTORY + "/" + lockfile_name + ".lock"
+
+
def abort_unless_locked(handle_func: HandleMethod) -> HandleMethod:
+ """Take a per-command lock, exiting with an error if it is already
+ held. For cron jobs wrapped in Sentry's `monitors run`, that error
+ surfaces as a failed check-in; use this only for commands whose
+ runtime is reliably shorter than their cron interval, where an
+ overlapping run signals something is wrong and is worth alerting on."""
+
@wraps(handle_func)
def our_handle(self: BaseCommand, *args: Any, **kwargs: Any) -> None:
- os.makedirs(settings.LOCKFILE_DIRECTORY, exist_ok=True)
- # Trim out just the last part of the module name, which is the
- # command name, to use as the lockfile name;
- # `zerver.management.commands.send_zulip_update_announcements`
- # becomes `/srv/zulip-locks/send_zulip_update_announcements.lock`
- lockfile_name = handle_func.__module__.split(".")[-1]
- lockfile_path = settings.LOCKFILE_DIRECTORY + "/" + lockfile_name + ".lock"
- with lockfile_nonblocking(lockfile_path) as lock_acquired:
+ path = lockfile_path(handle_func)
+ with lockfile_nonblocking(path) as lock_acquired:
if not lock_acquired: # nocoverage
- self.stdout.write(
- self.style.ERROR(f"Lock {lockfile_path} is unavailable; exiting.")
- )
+ self.stdout.write(self.style.ERROR(f"Lock {path} is unavailable; exiting."))
sys.exit(1)
handle_func(self, *args, **kwargs)
return our_handle
+def skip_unless_locked(handle_func: HandleMethod) -> HandleMethod:
+ """Like abort_unless_locked, but for commands where an overlapping
+ run is an expected, benign condition -- for instance a network-bound
+ job polled every minute, where a still-running previous invocation
+ just means this one should do nothing. If the lock is already held,
+ exit successfully and silently -- in particular emitting no output,
+ since under cron any output is mailed to the administrator."""
+
+ @wraps(handle_func)
+ def our_handle(self: BaseCommand, *args: Any, **kwargs: Any) -> None:
+ path = lockfile_path(handle_func)
+ with lockfile_nonblocking(path) as lock_acquired:
+ if not lock_acquired: # nocoverage
+ return
+ handle_func(self, *args, **kwargs)
+
+ return our_handle
+
+
def abort_cron_during_deploy(handle_func: HandleMethod) -> HandleMethod:
@wraps(handle_func)
def our_handle(self: BaseCommand, *args: Any, **kwargs: Any) -> None:
diff --git a/zerver/management/commands/email_mirror.py b/zerver/management/commands/email_mirror.py
index fc9c81cf920..b958f011712 100644
--- a/zerver/management/commands/email_mirror.py
+++ b/zerver/management/commands/email_mirror.py
@@ -30,7 +30,7 @@ from django.core.management.base import CommandError
from typing_extensions import override
from zerver.lib.email_mirror import logger, process_message
-from zerver.lib.management import ZulipBaseCommand
+from zerver.lib.management import ZulipBaseCommand, skip_unless_locked
## Setup ##
@@ -83,6 +83,7 @@ class Command(ZulipBaseCommand):
help = __doc__
@override
+ @skip_unless_locked
def handle(self, *args: Any, **options: str) -> None:
for message in get_imap_messages():
process_message(message)
diff --git a/zerver/tests/test_management_commands.py b/zerver/tests/test_management_commands.py
index 5e203da3840..61e6613dcf2 100644
--- a/zerver/tests/test_management_commands.py
+++ b/zerver/tests/test_management_commands.py
@@ -1,5 +1,7 @@
+import fcntl
import os
import re
+import tempfile
from datetime import timedelta
from typing import Any
from unittest import mock, skipUnless
@@ -9,7 +11,7 @@ from urllib.parse import quote, quote_plus
from django.apps import apps
from django.conf import settings
from django.core.management import call_command, find_commands
-from django.core.management.base import CommandError
+from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.db.models.functions import Lower
from django.test import override_settings
@@ -18,7 +20,7 @@ from typing_extensions import override
from confirmation.models import Confirmation, generate_realm_creation_url
from zerver.actions.create_user import do_create_user
from zerver.actions.user_settings import do_change_user_setting
-from zerver.lib.management import ZulipBaseCommand
+from zerver.lib.management import ZulipBaseCommand, skip_unless_locked
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import most_recent_message, stdout_suppressed
from zerver.models import Realm, RealmAuditLog, Recipient, UserProfile
@@ -381,6 +383,31 @@ class TestCalculateFirstVisibleMessageID(ZulipTestCase):
m.assert_has_calls(calls, any_order=True)
+class TestSkipUnlessLocked(ZulipTestCase):
+ def test_skip_when_lock_is_held(self) -> None:
+ ran = []
+
+ @skip_unless_locked
+ def handle(self: BaseCommand, *args: Any, **kwargs: Any) -> None:
+ ran.append(True)
+
+ command = BaseCommand()
+ with tempfile.TemporaryDirectory() as lock_dir, self.settings(LOCKFILE_DIRECTORY=lock_dir):
+ # With the lock free, the wrapped command runs.
+ handle(command)
+ self.assertEqual(ran, [True])
+
+ # While the lock is held -- as it would be by a previous
+ # invocation still running -- the command is skipped, with
+ # no error and no output.
+ ran.clear()
+ lock_path = os.path.join(lock_dir, "test_management_commands.lock")
+ with open(lock_path, "w") as held:
+ fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ handle(command)
+ self.assertEqual(ran, [])
+
+
class TestPasswordRestEmail(ZulipTestCase):
COMMAND_NAME = "send_password_reset_email"