diff --git a/ippisite/ippisite/db_finder.py b/ippisite/ippisite/db_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..36921dddca7886694f63a591c25cb4e0d7a9658a --- /dev/null +++ b/ippisite/ippisite/db_finder.py @@ -0,0 +1,59 @@ +import os +import subprocess + + +def get_db_ip(): + result = subprocess.run( + [ + "docker", + "ps", + "-f", + "name=%s" % get_guessed_container_name(), + "-q", + ], + stdout=subprocess.PIPE, + ) + ids = result.stdout.decode("utf-8").strip().split("\n") + if len(ids) > 1: + raise Exception("Can't find the DB, too much match") + if len(ids) == 0 or len(ids[0]) == 0: + result = subprocess.run( + [ + "docker", + "ps", + "-f", + "name=_db", + "-q", + ], + stdout=subprocess.PIPE, + ) + ids = result.stdout.decode("utf-8").strip().split("\n") + if len(ids) > 1: + raise Exception( + "Can't find the DB, couldn't guess container name (tried '%s'), " + "and too much match with '_db'" % get_guessed_container_name() + ) + if len(ids) == 0 or len(ids[0]) == 0: + raise Exception("Can't find the DB") + result = subprocess.run( + [ + "docker", + "inspect", + "-f", + "'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'", + ids[0], + ], + stdout=subprocess.PIPE, + ) + return result.stdout.decode("utf-8").strip().replace("'", "") + + +def get_guessed_container_name(): + return ( + str(os.path.dirname(__file__).split(os.path.sep)[-2]).lower().replace("-", "") + + "_db" + ) + + +if __name__ == "__main__": + print(get_db_ip()) diff --git a/ippisite/ippisite/settings.py b/ippisite/ippisite/settings.py index 7d8911659fb21257e24d9e2f3557d95d8a5644e8..2649bc0029c4b6380ed3df10deb4255c4557448b 100644 --- a/ippisite/ippisite/settings.py +++ b/ippisite/ippisite/settings.py @@ -17,6 +17,8 @@ from decouple import config from django.utils.translation import gettext_lazy from socket import gethostname, gethostbyname +from ippisite import db_finder + BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PERSISTENT_DIR = os.path.join(BASE_DIR, 'persistent') @@ -122,13 +124,16 @@ if config("USE_SQLITE_AS_DB", default="False").upper() == "TRUE": } } else: + POSTGRES_HOST = config("POSTGRES_HOST", '') + if not POSTGRES_HOST: + POSTGRES_HOST = db_finder.get_db_ip() DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": config("POSTGRES_DB"), "USER": config("POSTGRES_USER"), "PASSWORD": config("POSTGRES_PASSWORD"), - "HOST": config("POSTGRES_HOST"), + "HOST": POSTGRES_HOST, "PORT": 5432, } }