|
| 1 | +# Copyright 2024 Red Hat, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import time |
| 15 | + |
| 16 | +from django.core.management.base import BaseCommand |
| 17 | +from django.db import connection |
| 18 | +from django.db.migrations.executor import MigrationExecutor |
| 19 | + |
| 20 | + |
| 21 | +class Command(BaseCommand): |
| 22 | + help = "Wait for all migrations to be applied within a timeout period." |
| 23 | + |
| 24 | + def add_arguments(self, parser): |
| 25 | + parser.add_argument( |
| 26 | + "-t", |
| 27 | + "--timeout", |
| 28 | + type=int, |
| 29 | + default=10, |
| 30 | + help=( |
| 31 | + "Time in seconds to wait for migrations to be applied " |
| 32 | + "(default is 10 seconds)." |
| 33 | + ), |
| 34 | + ) |
| 35 | + |
| 36 | + def handle(self, *args, **options): |
| 37 | + timeout = options["timeout"] |
| 38 | + start_time = time.time() |
| 39 | + elapsed_time = 0 |
| 40 | + |
| 41 | + while elapsed_time < timeout: |
| 42 | + if not self.migrations_pending(): |
| 43 | + self.stdout.write( |
| 44 | + self.style.SUCCESS("All migrations are applied.") |
| 45 | + ) |
| 46 | + return |
| 47 | + time.sleep(1) |
| 48 | + elapsed_time = time.time() - start_time |
| 49 | + |
| 50 | + self.stderr.write( |
| 51 | + self.style.ERROR("Timeout exceeded. There are pending migrations.") |
| 52 | + ) |
| 53 | + raise SystemExit(1) |
| 54 | + |
| 55 | + def migrations_pending(self) -> bool: |
| 56 | + """Check if there are pending migrations.""" |
| 57 | + executor = MigrationExecutor(connection) |
| 58 | + targets = executor.loader.graph.leaf_nodes() |
| 59 | + plan = executor.migration_plan(targets) |
| 60 | + return bool(plan) |
0 commit comments