-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfabfile.py
232 lines (189 loc) · 5.46 KB
/
fabfile.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import os
import subprocess
from invoke import run as local
from invoke.tasks import task
# Process .env file
if os.path.exists(".env"):
with open(".env", "r") as f:
for line in f.readlines():
if not line or line.startswith("#") or "=" not in line:
continue
var, value = line.strip().split("=", 1)
os.environ.setdefault(var, value)
LOCAL_DATABASE_NAME = os.getenv("POSTGRES_DB")
LOCAL_DATABASE_USERNAME = os.getenv("POSTGRES_USER")
LOCAL_DB_DUMP_DIR = "database_dumps"
# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------
def container_exec(cmd, container_name="django", check_returncode=False):
result = subprocess.run(
["docker-compose", "exec", "-T", container_name, "bash", "-c", cmd]
)
if check_returncode:
result.check_returncode()
return result
def postgres_exec(cmd, check_returncode=False):
"Execute something in the 'postgres' Docker container."
return container_exec(cmd, "postgres", check_returncode)
def django_exec(cmd, check_returncode=False):
"Execute something in the 'django' Docker container."
return container_exec(cmd, "django", check_returncode)
# -----------------------------------------------------------------------------
# Container management
# -----------------------------------------------------------------------------
@task
def build(c):
"""
Build (or rebuild) local development containers.
"""
local("docker-compose build")
@task
def start(c, container_name=None):
"""
Start the local development environment.
"""
cmd = "docker-compose up -d"
if container_name:
cmd += f" {container_name}"
local(cmd)
@task
def run(c):
start(c, "django")
django_exec("pip install -r requirements/local.txt -U")
django_exec("DJANGO_SETTINGS_MODULE= django-admin compilemessages")
django_exec("python manage.py migrate")
django_exec("rm -rf /app/staticfiles")
django_exec("python manage.py collectstatic")
try:
django_exec("python manage.py runserver 0.0.0.0:3000")
except KeyboardInterrupt:
pass
stop(c, "django")
@task
def stop(c, container_name=None):
"""
Stop the local development environment.
"""
cmd = "docker-compose stop"
if container_name:
cmd += f" {container_name}"
local(cmd)
@task
def restart(c):
"""
Restart the local development environment.
"""
stop(c)
start(c)
@task
def sh(c):
"""
Run bash in a local container (with access to dependencies)
"""
subprocess.run(["docker-compose", "exec", "django", "bash"])
@task
def test(c):
"""
Run python tests in the web container
"""
# Static analysis
subprocess.run(
[
"docker-compose",
"exec",
"django",
"mypy",
"ds_judgements_public_ui",
]
)
# Pytest
subprocess.run(
[
"docker-compose",
"exec",
"django",
"pytest",
]
)
@task
def coverage(c):
# Run pytest with coverage
subprocess.run(
[
"docker-compose",
"exec",
"django",
"coverage",
"run",
"-m",
"pytest",
]
)
# Generate html report
subprocess.run(
[
"docker-compose",
"exec",
"django",
"coverage",
"html",
]
)
# -----------------------------------------------------------------------------
# Database operations
# -----------------------------------------------------------------------------
@task
def psql(c, command=None):
"""
Connect to the local postgres DB using psql
"""
cmd_list = [
"docker-compose",
"exec",
"postgres",
"psql",
*["-d", LOCAL_DATABASE_NAME],
*["-U", LOCAL_DATABASE_USERNAME],
]
if command:
cmd_list.extend(["-c", command])
subprocess.run(cmd_list)
def delete_db(c):
postgres_exec(
f"dropdb --if-exists --host db --username={LOCAL_DATABASE_USERNAME} {LOCAL_DATABASE_NAME}"
)
postgres_exec(
f"createdb --host db --username={LOCAL_DATABASE_USERNAME} {LOCAL_DATABASE_NAME}"
)
@task
def dump_db(c, filename):
"""Snapshot the database, files will be stored in the db container"""
if not filename.endswith(".dmp"):
filename += ".dmp"
postgres_exec(
f"pg_dump -d {LOCAL_DATABASE_NAME} -U {LOCAL_DATABASE_USERNAME} > {filename}"
)
print(f"Database dumped to: {filename}")
@task
def restore_db(c, filename, delete_dump_on_success=False, delete_dump_on_error=False):
"""Restore the database from a snapshot in the db container"""
print("Stopping 'web' to sever DB connection")
stop(c, "django")
if not filename.endswith(".dmp"):
filename += ".dmp"
delete_db(c)
try:
print(f"Restoring datbase from: {filename}")
postgres_exec(
f"psql -d {LOCAL_DATABASE_NAME} -U {LOCAL_DATABASE_USERNAME} < {filename}",
check_returncode=True,
)
except subprocess.CalledProcessError:
if delete_dump_on_error:
postgres_exec(f"rm {filename}")
raise
if delete_dump_on_success:
print(f"Deleting dump file: {filename}")
postgres_exec(f"rm {filename}")
start(c, "django")