1
0
mirror of https://github.com/Mailu/Mailu.git synced 2024-12-14 10:53:30 +02:00
Mailu/optional/postgresql/start.py

68 lines
2.3 KiB
Python
Raw Normal View History

2018-11-18 18:35:13 +02:00
#!/usr/bin/python3
import anosql
import psycopg2
import jinja2
import glob
import os
import subprocess
from socrate import conf
2018-11-18 18:35:13 +02:00
def setup():
conn = psycopg2.connect(user='postgres')
2018-11-18 18:35:13 +02:00
queries = anosql.load_queries('postgres', '/conf/queries.sql')
2018-11-19 11:55:41 +02:00
# Mailu user
queries.create_mailu_user(conn)
2019-01-07 14:16:59 +02:00
queries.update_pw(conn, pw=os.environ.get("DB_PW"))
2018-11-19 11:55:41 +02:00
# Healthcheck user
queries.create_health_user(conn)
2018-11-30 13:54:12 +02:00
queries.grant_health(conn)
2018-11-18 18:35:13 +02:00
conn.commit()
# create db cannot be atomic. But this script is the only active connection, this is kinda safe.
if not queries.check_db(conn):
conn.set_isolation_level(0)
queries.create_db(conn)
conn.set_isolation_level(1)
conn.close()
# Check if /data is empty
if not os.listdir("/data"):
os.system("chown -R postgres:postgres /data")
os.system("chmod 0700 /data")
base_backups=sorted(glob.glob("/backup/base-*"))
if base_backups:
# Restore the latest backup
subprocess.call(["tar", "--same-owner", "-zpxf", base_backups[-1] + "/base.tar.gz" , "-C", "/data"])
if os.listdir("/backup/wal_archive"):
with open("/data/recovery.conf", "w") as rec:
2018-11-30 17:46:59 +02:00
rec.write("restore_command = 'gunzip < /backup/wal_archive/%f > %p'\n")
rec.write("standby_mode = off\n")
os.system("chown postgres:postgres /data/recovery.conf")
#os.system("sudo -u postgres pg_ctl start -D /data -o '-h \"''\" '")
else:
# Bootstrap the database
os.system("sudo -u postgres initdb -D /data")
2018-11-18 18:35:13 +02:00
2018-11-22 07:46:57 +02:00
# Create backup directory structure, if it does not yet exist
os.system("mkdir -p /backup/wal_archive")
os.system("chown -R postgres:postgres /backup")
# Render config files
2018-11-18 18:35:13 +02:00
for pg_file in glob.glob("/conf/*.conf"):
conf.jinja(pg_file, os.environ, os.path.join("/data", os.path.basename(pg_file)))
2018-11-18 18:35:13 +02:00
# (Re)start postgresql locally for DB and user creation
2018-11-30 13:54:12 +02:00
os.system("sudo -u postgres pg_ctl start -D /data -o '-h \"''\" '")
while os.path.isfile("recovery.conf"):
pass
os.system("sudo -u postgres pg_ctl -D /data promote")
2018-11-18 18:35:13 +02:00
setup()
2018-11-30 13:54:12 +02:00
os.system("sudo -u postgres pg_ctl stop -m smart -w -D /data")
2018-11-18 18:35:13 +02:00
out=open("/proc/1/fd/1", "w")
err=open("/proc/1/fd/2", "w")
# Run the cron deamon
2018-11-30 13:54:12 +02:00
subprocess.Popen(["crond", "-f"], stdout=out, stderr=err)
2018-11-18 18:35:13 +02:00
# Run postgresql service
2018-11-30 13:54:12 +02:00
os.system("sudo -u postgres postgres -D /data -h \*")