forked from nationalarchives/ds-wagtail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fabfile.py
353 lines (275 loc) · 9.28 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import datetime
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("DATABASE_NAME")
LOCAL_DATABASE_USERNAME = os.getenv("DATABASE_USER")
PLATFORM_PROJECT_ID = "rasrzs7pi6sd4"
STAGING_APP_INSTANCE = "ohos"
LOCAL_DB_DUMP_DIR = "database_dumps"
# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------
def container_exec(cmd, container_name="web", check_returncode=False):
result = subprocess.run(
["docker-compose", "exec", "-T", container_name, "bash", "-c", cmd]
)
if check_returncode:
result.check_returncode()
return result
def db_exec(cmd, check_returncode=False):
"Execute something in the 'db' Docker container."
return container_exec(cmd, "db", check_returncode)
def web_exec(cmd, check_returncode=False):
"Execute something in the 'web' Docker container."
return container_exec(cmd, "web", check_returncode)
def dev_exec(cmd, check_returncode=False):
"Execute something in the 'dev' Docker container."
return container_exec(cmd, "dev", check_returncode)
def cli_exec(cmd, check_returncode=False):
return container_exec(cmd, "cli", check_returncode)
@task
def run_management_command(c, cmd, check_returncode=False):
"""
Run a Django management command in the 'web' Docker container
with access to Django and other Python dependencies.
"""
return web_exec(f"poetry run python manage.py {cmd}", check_returncode)
# -----------------------------------------------------------------------------
# Container management
# -----------------------------------------------------------------------------
@task
def build(c):
"""
Build (or rebuild) local development containers.
"""
# bash copy .env.example .env if .env does not exist
if not os.path.exists(".env"):
local("cp .env.example .env")
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 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 update_deps(c):
"""
Update npm and poetry dependencies through Docker containers
"""
local("docker-compose --profile update up -d")
@task
def restart(c):
"""
Restart the local development environment.
"""
start(c)
stop(c)
@task
def sh(c):
"""
Run bash in a local container (with access to dependencies)
"""
subprocess.run(["docker-compose", "exec", "web", "poetry", "run", "bash"])
@task
def dev(c):
"""
Run bash in the local development helper container (with access to dependencies)
"""
subprocess.run(["docker", "exec", "-it", "dev", "/bin/bash"])
@task
def format(c):
"""
Apply formatters to code python code
"""
start(c, "dev")
dev_exec("format")
@task
def test(c, lint=False, parallel=False):
"""
Run python tests in the web container
"""
start(c, "dev")
if lint:
print("Checking isort compliance...")
dev_exec("isort . --check --diff")
print("Checking Black compliance...")
dev_exec("black . --check --diff --color --fast")
print("Checking flake8 compliance...")
dev_exec("flake8 .")
print("Running Django tests...")
cmd = "manage test"
if parallel:
cmd += " --parallel"
dev_exec(cmd)
# -----------------------------------------------------------------------------
# Database operations
# -----------------------------------------------------------------------------
@task
def create_superuser(c):
"""
Run bash in a local container (with access to dependencies)
"""
subprocess.run(
[
"docker-compose",
"exec",
"web",
"poetry",
"run",
"python",
"manage.py",
"createsuperuser",
"--noinput",
]
)
# -----------------------------------------------------------------------------
# Database operations
# -----------------------------------------------------------------------------
@task
def psql(c, command=None):
"""
Connect to the local postgres DB using psql
"""
cmd_list = [
"docker-compose",
"exec",
"db",
"psql",
*["-d", LOCAL_DATABASE_NAME],
*["-U", LOCAL_DATABASE_USERNAME],
]
if command:
cmd_list.extend(["-c", command])
subprocess.run(cmd_list)
def delete_local_renditions(c):
psql(c, "TRUNCATE wagtailimages_rendition;")
def delete_db(c):
db_exec(
f"dropdb --if-exists --host db --username={LOCAL_DATABASE_USERNAME} {LOCAL_DATABASE_NAME}"
)
db_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(".psql"):
filename += ".psql"
db_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, "web")
if not filename.endswith(".psql"):
filename += ".psql"
delete_db(c)
try:
print(f"Restoring datbase from: {filename}")
db_exec(
f"psql -d {LOCAL_DATABASE_NAME} -U {LOCAL_DATABASE_USERNAME} < {filename}",
check_returncode=True,
)
except subprocess.CalledProcessError:
if delete_dump_on_error:
db_exec(f"rm {filename}")
raise
if delete_dump_on_success:
print(f"Deleting dump file: {filename}")
db_exec(f"rm {filename}")
start(c, "web")
# -----------------------------------------------------------------------------
# Pull from Staging
# -----------------------------------------------------------------------------
@task
def pull_staging_data(c):
"""Pull database from the staging platform.sh env"""
pull_database_from_platform(c, STAGING_APP_INSTANCE)
@task
def pull_staging_media(c):
"""Pull all media from the staging platform.sh env"""
pull_media_from_platform(c, STAGING_APP_INSTANCE)
subprocess.run(["docker-compose", "exec", "cli", "chmod", "-fR", "777", "media"])
# -----------------------------------------------------------------------------
# Platform.sh helpers
# -----------------------------------------------------------------------------
def pull_database_from_platform(c, environment_name):
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
print("Fetching data from platform.sh")
start(c, "cli")
cli_exec(
f"platform db:dump -e {environment_name} -p {PLATFORM_PROJECT_ID} -f {timestamp}.psql -d {LOCAL_DB_DUMP_DIR}"
)
print("Replacing local database with downloaded version")
start(c, "db")
restore_db(
c,
f"app/{LOCAL_DB_DUMP_DIR}/{timestamp}.psql",
delete_dump_on_success=True,
delete_dump_on_error=True,
)
try:
print("Applying migrations from local environment...")
run_management_command(c, "migrate", check_returncode=True)
except subprocess.CalledProcessError:
print("Failed to apply migrations. Deleting database.")
delete_db(c)
raise
try:
print("Anonymising downloaded data...")
run_management_command(c, "run_birdbath", check_returncode=True)
except subprocess.CalledProcessError:
print("Failed to anonymise data. Deleting database.")
delete_db(c)
raise
print("Database updated successfully")
print("NOTE: Any Django users you were using before will no longer exist.")
try:
print("Creating superuser with credentials setup from docker compose.")
run_management_command(c, "createsuperuser --no-input", check_returncode=True)
except subprocess.CalledProcessError:
print("*** Failed to create superuser *** ")
print(
"You may want to run `python manage.py createsuperuser` from a container "
"shell to create yourself a new one."
)
def pull_media_from_platform(
c,
environment_name,
):
"""
Copies the entire 'media' folder from a platform.sh environment
to a local one (including original image, documents, videos, and audio),
but excluding thumnails generated by Wagtail.
"""
cli_exec(
f"platform mount:download -e {environment_name} -p {PLATFORM_PROJECT_ID} -m media "
"--target=media --exclude='/images/*' --yes"
)
delete_local_renditions(c)