Browse Source

Ensure database is up before server start

pull/72/head
Clemens Wolff 5 years ago
parent
commit
714c460639
2 changed files with 36 additions and 0 deletions
  1. 35
      app/server/management/commands/wait_for_db.py
  2. 1
      tools/run.sh

35
app/server/management/commands/wait_for_db.py

@ -0,0 +1,35 @@
import sys
import time
from django.db import connection
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Blocks until the database is available'
def add_arguments(self, parser):
parser.add_argument('--poll_seconds', type=float, default=3)
parser.add_argument('--max_retries', type=int, default=60)
def handle(self, *args, **options):
max_retries = options['max_retries']
poll_seconds = options['poll_seconds']
for retry in range(max_retries):
try:
connection.ensure_connection()
except OperationalError as ex:
self.stdout.write(
'Database unavailable on attempt {attempt}/{max_retries}:'
' {error}'.format(
attempt=retry + 1,
max_retries=max_retries,
error=ex))
time.sleep(poll_seconds)
else:
break
else:
self.stdout.write(self.style.ERROR('Database unavailable'))
sys.exit(1)

1
tools/run.sh

@ -4,5 +4,6 @@ set -o errexit
if [[ ! -d "app/staticfiles" ]]; then python app/manage.py collectstatic --noinput; fi if [[ ! -d "app/staticfiles" ]]; then python app/manage.py collectstatic --noinput; fi
python app/manage.py wait_for_db
python app/manage.py migrate python app/manage.py migrate
gunicorn --bind="${BIND:-127.0.0.1:8000}" --workers="${WORKERS:-1}" --pythonpath=app app.wsgi gunicorn --bind="${BIND:-127.0.0.1:8000}" --workers="${WORKERS:-1}" --pythonpath=app app.wsgi
Loading…
Cancel
Save