forked from Netflix/metaflow-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_goose.py
88 lines (74 loc) · 2.69 KB
/
run_goose.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import os
import sys
import time
import argparse
from subprocess import Popen
from urllib.parse import quote
import psycopg2
import psycopg2.errorcodes
DB_SCHEMA_NAME = os.environ.get("DB_SCHEMA_NAME", "public")
def check_if_goose_table_exists(db_connection_string: str):
conn = psycopg2.connect(db_connection_string)
cur = conn.cursor()
try:
cur.execute("SELECT schemaname,tablename FROM pg_tables")
tables = [name for schema, name in cur.fetchall() if schema == DB_SCHEMA_NAME]
if "goose_db_version" not in tables:
print(
f"Goose migration table not found among tables in schema {DB_SCHEMA_NAME}. Found: {', '.join(tables)}",
file=sys.stderr,
)
return False
else:
print(f"Goose migration table found in schema {DB_SCHEMA_NAME}", file=sys.stderr)
return True
finally:
conn.close()
def wait_for_postgres(db_connection_string: str, timeout_seconds: int):
deadline = time.time() + timeout_seconds
while True:
try:
conn = psycopg2.connect(db_connection_string)
conn.close()
return
except psycopg2.OperationalError as e:
if time.time() < deadline:
print(f"Failed to connect to postgres ({e}), sleeping", file=sys.stderr)
time.sleep(.5)
else:
raise
def main():
parser = argparse.ArgumentParser(description="Run goose migrations")
parser.add_argument("--only-if-empty-db", default=False, action="store_true")
parser.add_argument("--wait", type=int, default=30, help="Wait for connection for X seconds")
args = parser.parse_args()
db_connection_string = "postgresql://{}:{}@{}:{}/{}?sslmode=disable".format(
quote(os.environ["MF_METADATA_DB_USER"]),
quote(os.environ["MF_METADATA_DB_PSWD"]),
os.environ["MF_METADATA_DB_HOST"],
os.environ["MF_METADATA_DB_PORT"],
os.environ["MF_METADATA_DB_NAME"],
)
if args.wait:
wait_for_postgres(db_connection_string, timeout_seconds=args.wait)
if args.only_if_empty_db:
if check_if_goose_table_exists(db_connection_string):
print(
f"Skipping migrations since --only-if-empty-db flag is used",
file=sys.stderr,
)
sys.exit(0)
p = Popen(
[
"/go/bin/goose",
"-dir",
"/root/services/migration_service/migration_files/",
"postgres",
db_connection_string,
"up",
]
)
if p.wait() != 0:
raise Exception("Failed to run initial migration")
if __name__ == "__main__":
main()