lifecycle/migrate: only acquire lock once (#9856)
This commit is contained in:

committed by
GitHub

parent
0974456ac8
commit
a841743c74
@ -53,19 +53,20 @@ class BaseMigration:
|
||||
|
||||
def wait_for_lock(cursor: Cursor):
|
||||
"""lock an advisory lock to prevent multiple instances from migrating at once"""
|
||||
global LOCKED # noqa: PLW0603
|
||||
LOGGER.info("waiting to acquire database lock")
|
||||
cursor.execute("SELECT pg_advisory_lock(%s)", (ADV_LOCK_UID,))
|
||||
|
||||
global LOCKED # noqa: PLW0603
|
||||
LOCKED = True
|
||||
|
||||
|
||||
def release_lock(cursor: Cursor):
|
||||
"""Release database lock"""
|
||||
global LOCKED # noqa: PLW0603
|
||||
if not LOCKED:
|
||||
return
|
||||
LOGGER.info("releasing database lock")
|
||||
cursor.execute("SELECT pg_advisory_unlock(%s)", (ADV_LOCK_UID,))
|
||||
LOCKED = False
|
||||
|
||||
|
||||
def run_migrations():
|
||||
@ -82,6 +83,7 @@ def run_migrations():
|
||||
)
|
||||
curr = conn.cursor()
|
||||
try:
|
||||
wait_for_lock(curr)
|
||||
for migration_path in Path(__file__).parent.absolute().glob("system_migrations/*.py"):
|
||||
spec = spec_from_file_location("lifecycle.system_migrations", migration_path)
|
||||
if not spec:
|
||||
@ -94,14 +96,11 @@ def run_migrations():
|
||||
continue
|
||||
migration = sub(curr, conn)
|
||||
if migration.needs_migration():
|
||||
wait_for_lock(curr)
|
||||
LOGGER.info("Migration needs to be applied", migration=migration_path.name)
|
||||
migration.run()
|
||||
LOGGER.info("Migration finished applying", migration=migration_path.name)
|
||||
release_lock(curr)
|
||||
LOGGER.info("applying django migrations")
|
||||
environ.setdefault("DJANGO_SETTINGS_MODULE", "authentik.root.settings")
|
||||
wait_for_lock(curr)
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
|
Reference in New Issue
Block a user