Skip to content

Commit

Permalink
ping database with python instead of mysql client (CTFd#1862)
Browse files Browse the repository at this point in the history
* Replaces `mysqladmin ping` with a custom script
* Closes CTFd#725
  • Loading branch information
frankli0324 authored Apr 18, 2021
1 parent 5976830 commit 345706d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 18 deletions.
1 change: 0 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ RUN mkdir -p /opt/CTFd /var/log/CTFd /var/uploads
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
default-mysql-client \
python3-dev \
libffi-dev \
libssl-dev \
Expand Down
19 changes: 2 additions & 17 deletions docker-entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ ACCESS_LOG=${ACCESS_LOG:--}
ERROR_LOG=${ERROR_LOG:--}
WORKER_TEMP_DIR=${WORKER_TEMP_DIR:-/dev/shm}
SECRET_KEY=${SECRET_KEY:-}
DATABASE_URL=${DATABASE_URL:-}

# Check that a .ctfd_secret_key file or SECRET_KEY envvar is set
if [ ! -f .ctfd_secret_key ] && [ -z "$SECRET_KEY" ]; then
Expand All @@ -19,22 +18,8 @@ if [ ! -f .ctfd_secret_key ] && [ -z "$SECRET_KEY" ]; then
fi
fi

# Check that the database is available
if [ -n "$DATABASE_URL" ]
then
url=`echo $DATABASE_URL | awk -F[@//] '{print $4}'`
database=`echo $url | awk -F[:] '{print $1}'`
port=`echo $url | awk -F[:] '{print $2}'`
echo "Waiting for $database:$port to be ready"
while ! mysqladmin ping -h "$database" -P "$port" --silent; do
# Show some progress
echo -n '.';
sleep 1;
done
echo "$database is ready"
# Give it another second.
sleep 1;
fi
# Ensures that the database is available
python ping.py

# Initialize database
python manage.py db upgrade
Expand Down
34 changes: 34 additions & 0 deletions ping.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
Script for checking that a database server is available.
Essentially a cross-platform, database agnostic mysqladmin.
"""
import time

from sqlalchemy import create_engine
from sqlalchemy.engine.url import make_url

from CTFd.config import Config

url = make_url(Config.DATABASE_URL)

# Ignore sqlite databases
if url.drivername.startswith("sqlite"):
exit(0)

# Null out the database so raw_connection doesnt error if it doesnt exist
# CTFd will create the database if it doesnt exist
url.database = None

# Wait for the database server to be available
engine = create_engine(url)
print(f"Waiting for {url} to be ready")
while True:
try:
engine.raw_connection()
break
except Exception:
print(".", end="", flush=True)
time.sleep(1)

print(f"{url} is ready")
time.sleep(1)

0 comments on commit 345706d

Please sign in to comment.