This repository has been archived by the owner on Nov 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdodo.py
529 lines (488 loc) · 13.6 KB
/
dodo.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import pwd
import sys
import glob
from doit import get_var
from ruamel import yaml
from pathlib import Path
from subprocess import check_call, check_output, CalledProcessError, PIPE
from newbie.bot.config import CFG, call, CalledProcessError
## https://docs.docker.com/compose/compose-file/compose-versioning/
MINIMUM_DOCKER_COMPOSE_VERSION = '1.13' # allows compose format 3.0
LOG_LEVELS = [
'DEBUG',
'INFO',
'WARNING',
'ERROR',
'CRITICAL',
]
DOIT_CONFIG = {
'default_tasks': [
'pull',
'deploy',
'rmimages',
'rmvolumes',
'count'
],
'verbosity': 2,
}
DOCKER_COMPOSE_YML = yaml.safe_load(open(f'{CFG.APP_PROJPATH}/docker-compose.yml'))
SVCS = DOCKER_COMPOSE_YML['services'].keys()
class UnknownPkgmgrError(Exception):
def __init__(self):
super(UnknownPkgmgrError, self).__init__('unknown pkgmgr!')
def check_hash(program):
try:
check_call(f'hash {program}', shell=True, stdout=PIPE, stderr=PIPE)
return True
except CalledProcessError:
return False
def get_pkgmgr():
if check_hash('dpkg'):
return 'deb'
elif check_hash('rpm'):
return 'rpm'
elif check_hash('brew'):
return 'brew'
raise UnknownPkgmgrError
def pyfiles(path, exclude=None):
pyfiles = set(Path(path).rglob('*.py')) - set(Path(exclude).rglob('*.py') if exclude else [])
return [pyfile.as_posix() for pyfile in pyfiles]
def env():
return ' '.join([
'env',
f'APP_PROJNAME={CFG.APP_PROJNAME}',
f'APP_PROJPATH={CFG.APP_PROJPATH}',
f'APP_VERSION={CFG.APP_VERSION}',
f'APP_BRANCH={CFG.APP_BRANCH}',
f'APP_REVISION={CFG.APP_REVISION}',
f'APP_REMOTE_ORIGIN_URL={CFG.APP_REMOTE_ORIGIN_URL}',
])
def task_count():
'''
use the cloc utility to count lines of code
'''
excludes = [
'dist',
'venv',
'__pycache__',
'*.egg-info',
]
excludes = '--exclude-dir=' + ','.join(excludes)
scandir = os.path.dirname(__file__)
return {
'actions': [
f'cloc {excludes} {scandir}',
],
'uptodate': [
lambda: not check_hash('cloc'),
],
}
def task_checkreqs():
'''
check for required software
'''
DEBS = [
'docker-ce',
]
RPMS = [
'docker-ce',
]
return {
'deb': {
'actions': [f'dpkg -s {deb} 2>&1 >/dev/null' for deb in DEBS],
},
'rpm': {
'actions': ['rpm -q ' + rpm for rpm in RPMS], #FIXME: probably silent this?
},
'brew': {
'actions': ['true'], #FIXME: check that this works?
}
}[get_pkgmgr()]
def task_dockercompose():
'''
assert docker-compose version ({0}) or higher
'''
def check_docker_compose():
import re
from subprocess import check_output
from packaging.version import parse as version_parse
pattern = '(docker-compose version) ([0-9.]+(-rc[0-9])?)(, build [a-z0-9]+)'
output = check_output('docker-compose --version', shell=True).decode('utf-8').strip()
regex = re.compile(pattern)
match = regex.search(output)
version = match.groups()[1]
assert version_parse(version) >= version_parse(MINIMUM_DOCKER_COMPOSE_VERSION)
return {
'actions': [
check_docker_compose,
],
}
def task_noroot():
'''
make sure script isn't run as root
'''
then = 'echo " DO NOT RUN AS ROOT!"; echo; exit 1'
bash = f'if [[ $(id -u) -eq 0 ]]; then {then}; fi'
return {
'actions': [
f'bash -c \'{bash}\'',
],
}
def task_pull():
'''
do a safe git pull
'''
submods = check_output("git submodule status | awk '{print $2}'", shell=True).decode('utf-8').split()
test = '`git diff-index --quiet HEAD --`'
pull = 'git pull --rebase'
update = 'git submodule update --remote'
dirty = 'echo "refusing to \'{cmd}\' because the tree is dirty"'
dirty_pull, dirty_update = [dirty.format(cmd=cmd) for cmd in (pull, update)]
yield {
'name': 'mozilla-it/props-bot',
'actions': [
f'if {test}; then {pull}; else {dirty_pull}; exit 1; fi',
],
}
for submod in submods:
yield {
'name': submod,
'actions': [
f'cd {submod} && if {test}; then {update}; else {dirty_update}; exit 1; fi',
],
}
def task_venv():
'''
setup venv
'''
yield {
'name': 'main',
'task_dep': [
'noroot',
],
'actions': [
'virtualenv --python=$(which python3) venv',
'venv/bin/pip3 install --upgrade pip',
f'venv/bin/pip3 install -r {CFG.APP_TESTPATH}/requirements.txt',
],
}
for svc in SVCS:
reqfile = f'{CFG.APP_PROJPATH}/{svc}/requirements.txt'
yield {
'name': svc,
'task_dep': [
'noroot',
'venv:main',
],
'actions': [
f'[ -f {reqfile} ] && venv/bin/pip3 install -r {reqfile} || true',
],
}
def task_pyfiles():
'''
list all of the pyfiles
'''
pyfiles_list = '\n'.join(pyfiles(CFG.APP_PROJPATH, f'{CFG.APP_BOTPATH}/utils'))
return {
'task_dep': [
],
'actions': [
f'echo "{pyfiles_list}"',
],
}
def task_pylint():
'''
run pylint before the build
'''
for svc in SVCS:
pyfiles_list = pyfiles(f'{CFG.APP_PROJPATH}/{svc}', f'{CFG.APP_PROJPATH}/{svc}/utils')
for pyfile in pyfiles_list:
yield {
'name': f'{svc}/{pyfile}',
'task_dep': [
'noroot',
],
'actions': [
f'cd {CFG.APP_PROJPATH}/{svc} && pylint -j{CFG.APP_JOBS} --rcfile {CFG.APP_TESTPATH}/pylint.rc {pyfile} || true',
],
}
def task_test():
'''
run pytest
'''
def has_tests(svc):
try:
call('env PYTHONPATH={CFG.APP_PROJPATH}/{svc} pytest --collect-only {CFG.APP_TESTPATH}')
return True
except CalledProcessError as cpe:
return False
for svc in SVCS:
PYTHONPATH = f'PYTHONPATH=.:{CFG.APP_PROJPATH}:{CFG.APP_PROJPATH}/{svc}:$PYTHONPATH'
if has_tests(svc):
yield {
'name': svc,
'task_dep': [
'noroot',
'pylint',
'venv'
],
'actions': [
f'{PYTHONPATH} venv/bin/python3 -m pytest -s -vv {CFG.APP_TESTPATH}/{svc}',
],
}
def task_tls():
'''
create server key, csr and crt files
'''
name = 'server'
tls = f'/data/{CFG.APP_PROJNAME}/tls'
env = 'PASS=TEST'
envp = 'env:PASS'
targets = [
f'{tls}/{name}.key',
f'{tls}/{name}.crt',
]
subject = '/C=US/ST=Oregon/L=Portland/O=Connected-Workplace Server/OU=Server/CN=0.0.0.0'
def uptodate():
return all([os.path.isfile(t) for t in targets])
return {
'actions': [
f'mkdir -p {tls}',
f'{env} openssl genrsa -aes256 -passout {envp} -out {tls}/{name}.key 2048',
f'{env} openssl req -new -passin {envp} -subj "{subject}" -key {tls}/{name}.key -out {tls}/{name}.csr',
f'{env} openssl x509 -req -days 365 -in {tls}/{name}.csr -signkey {tls}/{name}.key -passin {envp} -out {tls}/{name}.crt',
f'{env} openssl rsa -passin {envp} -in {tls}/{name}.key -out {tls}/{name}.key',
],
'targets': targets,
'uptodate': [uptodate],
}
def task_tar():
'''
tar up source files, dereferncing symlinks
'''
excludes = ' '.join([
f'--exclude={CFG.APP_SRCTAR}',
'--exclude=__pycache__',
'--exclude=*.pyc',
'--exclude=.env',
'--exclude=.git',
])
for svc in SVCS:
## it is important to not that this is required to keep the tarballs from
## genereating different checksums and therefore different layers in docker
cmd = f'cd {CFG.APP_PROJPATH}/{svc} && echo "$(git status -s)" > {CFG.APP_REVISION} && tar cvh {excludes} . | gzip -n > {CFG.APP_SRCTAR} && rm {CFG.APP_REVISION}'
yield {
'name': svc,
'task_dep': [
'noroot',
'test',
],
'actions': [
f'echo "{cmd}"',
f'{cmd}',
],
}
def task_build():
'''
build flask|quart app via docker-compose
'''
return {
'task_dep': [
'noroot',
'tar',
'dockercompose',
],
'actions': [
f'echo "cd {CFG.APP_PROJPATH} && {env()} docker-compose build"',
f'cd {CFG.APP_PROJPATH} && {env()} docker-compose build',
],
}
def task_tag():
'''
tag the docker images with the tagname
'''
for svc in SVCS:
imagename = f'itcw/{CFG.APP_PROJNAME}_{svc}'
yield {
'name': svc,
'task_dep': [
'noroot',
'build',
],
'actions': [
f'echo created tagged image: {imagename}:{CFG.APP_TAGNAME}',
f'docker tag {imagename}:{CFG.APP_VERSION} {imagename}:{CFG.APP_TAGNAME}',
],
}
def task_publish():
'''
publish docker image(s) to docker hub
'''
for svc in SVCS:
imagename = f'itcw/{CFG.APP_PROJNAME}_{svc}'
yield {
'name': svc,
'task_dep': [
'noroot',
'build',
'tag',
],
'actions': [
f'docker push {imagename}:{CFG.APP_TAGNAME}',
],
}
def task_local():
'''
deloy flask|quart app via docker-compose
'''
return {
'task_dep': [
'noroot',
'checkreqs',
'test',
'build',
'dockercompose',
],
'actions': [
f'echo "cd {CFG.APP_PROJPATH} && {env()} docker-compose up --remove-orphans -d"',
f'cd {CFG.APP_PROJPATH} && {env()} docker-compose up --remove-orphans -d',
],
}
def task_stop():
'''
stop running containers
'''
def check_docker_ps():
cmd = 'docker ps --format "{{.Names}}" | grep ' + CFG.APP_PROJNAME + ' | { grep -v grep || true; }'
out = check_output(cmd, shell=True).decode('utf-8').strip()
return out.split('\n') if out else []
containers = ' '.join(check_docker_ps())
return {
'actions': [
f'docker rm -f {containers}',
],
'uptodate': [
lambda: len(check_docker_ps()) == 0,
],
}
def task_rmtagged():
'''
remove all tagged images matching: itcw/{CFG.APP_PROJNAME}_
'''
awk = """awk '{print $1 ":" $2}'"""
query = f'$(docker images | grep itcw/{CFG.APP_PROJNAME}_ | {awk})'
return {
'actions': [
f'docker rmi {query}',
],
'uptodate': [
f'[ -z "{query}" ] && exit 0 || exit 1',
],
}
def task_rmcontainers():
'''
remove stopped containers
'''
query = '$(docker ps -q -f "status=exited")'
return {
'actions': [
f'docker rm {query}',
],
'uptodate': [
f'[ -z "{query}" ] && exit 0 || exit 1',
],
}
def task_rmimages():
'''
remove dangling docker images
'''
query = '$(docker images -q -f dangling=true)'
return {
'task_dep': [
'rmcontainers',
],
'actions': [
f'docker rmi {query}',
],
'uptodate': [
f'[ -z "{query}" ] && exit 0 || exit 1',
],
}
def task_rmvolumes():
'''
remove dangling docker volumes
'''
query = '$(docker volume ls -q -f dangling=true)'
return {
'actions': [
f'docker volume rm {query}',
],
'uptodate': [
f'[ -z "{query}" ] && exit 0 || exit 1',
],
}
def task_logs():
'''
simple wrapper that calls 'docker-compose logs'
'''
return {
'actions': [
f'echo "cd {CFG.APP_PROJPATH} && {env()} docker-compose logs"',
f'cd {CFG.APP_PROJPATH} && {env()} docker-compose logs',
],
}
def task_rmcache():
'''
recursively delete python cache files
'''
rmrf = 'rm -rf "{}" \;'
return dict(
actions=[
f'sudo find {CFG.APP_REPOROOT} -depth -name __pycache__ -type d -exec {rmrf}',
f'sudo find {CFG.APP_REPOROOT} -depth -name *.pyc -type f -exec {rmrf}',
]
)
def task_tidy():
'''
delete cached files
'''
TIDY_FILES = [
'.doit.db',
'venv/',
'.pytest_cache/',
]
return {
'actions': [
'rm -rf ' + ' '.join(TIDY_FILES),
'find . | grep -E "(__pycache__|\.pyc$)" | xargs rm -rf',
],
}
def task_nuke():
'''
git clean and reset
'''
return {
'task_dep': ['tidy'],
'actions': [
'docker-compose kill',
'docker-compose rm -f',
'git clean -fd',
'git reset --hard HEAD',
],
}
def task_prune():
'''
prune stopped containers
'''
return {
'actions': ['docker rm `docker ps -q -f "status=exited"`'],
'uptodate': ['[ -n "`docker ps -q -f status=exited`" ] && exit 1 || exit 0']
}
if __name__ == '__main__':
print('should be run with doit installed')
import doit
doit.run(globals())