-
Notifications
You must be signed in to change notification settings - Fork 3
/
thunorbld.py
295 lines (248 loc) · 11.1 KB
/
thunorbld.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
import argparse
import os
from thunorweb import __version__ as thunorweb_version
from thunorctl import ThunorCmdHelper
class ThunorBld(ThunorCmdHelper):
_DEFAULT_TAGS = 'alubbock/thunorweb:dev'
def __init__(self):
super(ThunorBld, self).__init__()
self.cwd = os.path.abspath(os.path.dirname(__file__))
self.deploy_dir = os.path.join(self.cwd, '_state/deploy-test')
self.buildx_archs = 'linux/amd64,linux/arm64'
def _build_webpack(self):
self._log.info('Build webpack container')
return self._run_cmd(['docker', 'build', '-t', 'thunorweb_webpack',
'thunorweb/webpack'])
@property
def _volume_webpack_bundles(self):
return os.path.join(
self.cwd if self.args.dev else self.deploy_dir,
'_state/webpack-bundles'
) + ':/thunor/_state/webpack-bundles'
@property
def _volume_webpack_static(self):
return os.path.join(
self.cwd if self.args.dev else self.deploy_dir,
'_state/thunor-static-build'
) + ':/thunor/_state/thunor-static'
@property
def _volume_thunor_files(self):
return os.path.join(
self.cwd if self.args.dev else self.deploy_dir,
'_state/thunor-files'
) + ':/thunor/_state/thunor-files'
def generate_static(self):
self._build_webpack()
cmd = ['docker', 'run', '--rm']
if self.args.dev:
cmd += ['-e', 'DJANGO_DEBUG=True']
cmd += ['-v', self._volume_webpack_bundles, 'thunorweb_webpack']
self._log.info('Generate static files')
return self._run_cmd(cmd)
# def _init_buildx(self):
# self._log.info("Init docker buildx")
# return self._run_cmd([
# 'docker', 'buildx', 'create', '--name', 'thunorbuild', '--use', '--append'
# ])
# def _deinit_buildx(self):
# self._log.info("Deinit docker buildx")
# return self._run_cmd([
# 'docker', 'buildx', 'rm', 'thunorbuild'
# ])
def _build_base_image(self):
self._log.info('Build thunorweb_base image')
base_cmd = ['docker']
if self.args.use_buildx:
base_cmd += ['buildx', 'build', '--platform=' + self.buildx_archs]
else:
base_cmd += ['build']
return self._run_cmd(base_cmd +
['-t',
'thunorweb_base',
'--target',
'thunorweb_base',
'--build-arg',
'THUNORWEB_VERSION={}'.format(
thunorweb_version),
self.cwd])
def collect_static(self):
cmd = ['python', 'manage.py', 'collectstatic', '--no-input']
if not self.args.dev:
self._log.debug('Collect static not used in non-dev mode')
return True
self._log.info('Collect static files')
return self._run_cmd(cmd)
def make_static(self):
self.generate_static()
self.collect_static()
def thunorweb_build(self):
if self.args.dev:
raise ValueError('Cannot build Docker container in dev mode')
# self.make_static()
self.generate_static()
self._log.info('Build main container')
base_cmd = ['docker']
if self.args.use_buildx:
base_cmd += ['buildx', 'build', '--platform=' + self.buildx_archs]
else:
base_cmd += ['build']
if self.args.push:
base_cmd += ['--push']
for tag in self.args.tags.split(','):
base_cmd += ['-t', tag]
self._run_cmd(base_cmd +
['--build-arg',
'THUNORWEB_VERSION={}'.format(
thunorweb_version),
self.cwd])
if 'cleanup' in self.args and self.args.cleanup:
self._rmdir('_state/thunor-static-build')
def _init_test_files(self):
self._log.info('Initialize staging environment files')
self._mkdir(self.deploy_dir)
self._prepare_deployment_common(self.deploy_dir)
self._copy('config-examples/nginx.site-basic.conf',
os.path.join(self.deploy_dir,
'_state/nginx-config/nginx.site.conf'))
self._copy('config-examples/docker-compose.complete.yml',
os.path.join(self.deploy_dir,
'docker-compose.yml'))
self._copy('docker-compose.services.yml',
os.path.join(self.deploy_dir, 'docker-compose.services.yml'))
self._replace_in_file(
os.path.join(self.deploy_dir, 'docker-compose.services.yml'),
'image: alubbock/thunorweb:latest',
'image: alubbock/thunorweb:dev'
)
def init_test(self):
""" Minimal init for unit testing/CI purposes """
self._init_test_files()
self.args.use_buildx = False
self.args.tags = self._DEFAULT_TAGS
self.args.push = False
self.thunorweb_build()
def run_tests(self):
if self.args.dev:
self._log.info('Run tests (dev environment)')
self._run_cmd(['coverage', 'run', 'manage.py', 'test'])
else:
compose_file = os.path.join(self.deploy_dir,
'docker-compose.yml')
base_cmd = ['docker', 'compose', '-f', compose_file]
self._log.info('Start database (if not already up)')
self._run_cmd(base_cmd + ['up', '-d', 'postgres', 'redis'])
self._wait_postgres(compose_file=compose_file)
try:
self._log.info('Run tests (staging environment)')
self._run_cmd(base_cmd + ['run', '--rm',
'-e', 'THUNORHOME=/thunor',
'app',
'python', 'manage.py', 'test'])
finally:
self._log.info('Shutdown and clean up containers')
self._run_cmd(base_cmd + ['down', '-v'])
def init_dev(self):
""" Initialise development environment """
self.args.dev = True
self._check_docker_compose()
if os.path.exists(os.path.join(self.cwd, '_state')):
raise ValueError('_state directory already exists. Is Thunor Web '
'already installed?')
self._log.info('Initialize dev environment files')
# Dev config
self._copy('config-examples/thunor-dev.env', 'thunor-dev.env')
self._generate_random_key('thunor-dev.env', '{{DJANGO_SECRET_KEY}}')
self._generate_random_key('thunor-dev.env', '{{POSTGRES_PASSWORD}}')
self._copy('config-examples/docker-compose.postgresonly.yml',
'docker-compose.yml')
self._replace_in_file(
os.path.join(self.cwd, 'docker-compose.yml'),
'- thunor-db.env',
'- thunor-dev.env'
)
self._init_test_files()
# Both
self._mkdir('_state/postgres-data')
self._log.info('Start database')
self._run_cmd(['docker', 'compose', 'up', '-d', 'postgres'])
# Install Python reqs
self._log.info('Install python requirements')
self._run_cmd(['pip', 'install', '-r', 'requirements-dev.txt'])
# Build static files
self.make_static()
self._wait_postgres()
self._log.info('Migrate database')
self._run_cmd(['python', 'manage.py', 'migrate'])
self._log.info('Create database cache table')
self._run_cmd(['python', 'manage.py', 'createcachetable'])
print('\nQuickstart complete! Next steps:')
print('* Create an admin account with '
'"python thunorctl.py createsuperuser"')
print('* Run "python manage.py runserver" to start the development '
'server')
def _parser(self):
parser = argparse.ArgumentParser(prog='thunorctl.py')
parser.add_argument('--dev', action='store_true',
help='Developer mode (app runs outside of Docker)')
parser.add_argument('--debug', action='store_true', default=False,
help='Debug mode (increase verbosity)')
parser.add_argument('--dry-run', action='store_true', default=False,
help='Dry run (don\'t execute any commands, '
'just show them)')
subparsers = parser.add_subparsers()
parser_make_static = subparsers.add_parser(
'makestatic', help='Generate static files and collect them in '
'Django. Equivalent to generatestatic and '
'collectstatic called sequentially.'
)
parser_make_static.set_defaults(func=self.make_static)
parser_generate_static = subparsers.add_parser(
'generatestatic', help='Generate static files'
)
parser_generate_static.set_defaults(func=self.generate_static)
parser_collect_static = subparsers.add_parser(
'collectstatic', help='Collect static files in Django'
)
parser_collect_static.set_defaults(func=self.collect_static)
parser_build = subparsers.add_parser(
'build', help='Build Thunor Web Docker container'
)
parser_build.add_argument(
'--cleanup', action='store_true', default=False,
help='Cleanup intermediate build files'
)
parser_build.add_argument('--use-buildx', action='store_true', default=False,
help='Use docker buildx for cross-platform builds')
parser_build.add_argument('--push', action='store_true', default=False,
help='Push to repo after build')
parser_build.add_argument('--tags', default=ThunorBld._DEFAULT_TAGS,
help='Tags to use when building container (comma separated)')
parser_build.set_defaults(func=self.thunorweb_build)
parser_init = subparsers.add_parser(
'init', help='Generate example configuration and prepare '
'development environment'
)
parser_init.set_defaults(func=self.init_dev)
parser_test_init = subparsers.add_parser(
'testinit', help='Generate an environment for testing only. '
'Intended for continuous integration services.'
)
parser_test_init.set_defaults(func=self.init_test)
parser_tests = subparsers.add_parser(
'test', help='Run unit tests; use --dev flag to run outside of '
'Docker, or build Docker container first'
)
parser_tests.set_defaults(func=self.run_tests)
parser.add_argument('--version', action='version',
version=thunorweb_version)
return parser
if __name__ == '__main__':
thunorbld = ThunorBld()
parser = thunorbld._parser()
parser_args = parser.parse_args()
thunorbld._set_args(parser_args)
try:
if hasattr(parser_args, 'func'):
parser_args.func()
finally:
pass