forked from HumanSignal/label-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ci: SRE-477: implement migrate lock (HumanSignal#3977)
- Loading branch information
Showing
3 changed files
with
43 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import logging | ||
from django.db import connections | ||
from django.conf import settings | ||
from django.core.management.commands.migrate import Command as MigrateCommand | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
DEFAULT_LOCK_ID = getattr(settings, "MIGRATE_LOCK_ID", 1000) | ||
|
||
|
||
class Command(MigrateCommand): | ||
help = "Run Django migrations safely, using a lock" | ||
|
||
def add_arguments(self, parser): | ||
MigrateCommand.add_arguments(self, parser) | ||
parser.add_argument( | ||
"--migrate-lock-id", | ||
default=DEFAULT_LOCK_ID, | ||
type=int, | ||
help="The id of the advisory lock to use", | ||
) | ||
|
||
def handle(self, *args, **options): | ||
database = options["database"] | ||
if not options["skip_checks"]: | ||
self.check(databases=[database]) | ||
|
||
# Get the database we're operating from | ||
connection = connections[database] | ||
# Hook for backends needing any database preparation | ||
connection.prepare_database() | ||
|
||
lock_id = options["migrate_lock_id"] | ||
with connection.cursor() as cursor: | ||
try: | ||
logger.debug(f"Trying to acquire lock: {lock_id}") | ||
cursor.execute(f"SELECT pg_advisory_xact_lock({lock_id})") | ||
logger.debug(f"Successfully acquired lock. Starting migrations...") | ||
MigrateCommand.handle(self, *args, **options) | ||
finally: | ||
logger.debug(f"Lock released.") |