-
Notifications
You must be signed in to change notification settings - Fork 0
/
keeper.py
executable file
·1680 lines (1388 loc) · 56.9 KB
/
keeper.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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020-2024 Érik Martin-Dorel
#
# Contributed under the terms of the MIT license,
# cf. <https://spdx.org/licenses/MIT.html>
from bash_formatter import BashLike
from datetime import datetime
from itertools import chain
import argparse
import base64
import copy
import json
import requests
import os
import re
import sys
import time
import yaml
prog = os.path.basename(__file__)
output_directory = 'generated'
images_filename = 'images.yml'
json_indent = 2
upstream_project = 'erikmd/docker-keeper'
upstream_url = 'https://gitlab.com/%s' % upstream_project
desc = """
§ docker-keeper
This python3 script is devised to help maintain Docker Hub repositories of
stable and dev (from webhooks or for nightly builds) Docker images from a
YAML-specified, single-branch Git repository - typically created as a fork of
the following GitLab repo: <https://gitlab.com/erikmd/docker-keeper-template>.
For more details, follow the instructions of the README.md in your own fork.
Note: this script is meant to be run by GitLab CI.
docker-keeper offers customizable propagate strategies (declarative cURL calls)
It supports both single modes given in variable CRON_MODE (and optionally ITEM)
and multiple modes, from CLI as well as from HEAD's commit message, typically:
$ git commit --allow-empty -m "…" -m "docker-keeper: rebuild-all"
$ git commit -m "docker-keeper: propagate: I1: minimal; propagate: I2: nightly"
$ git commit -m "docker-keeper: propagate: ID: rebuild-all"
$ git commit -m "docker-keeper: propagate: ID: rebuild-keyword: KW1,KW2"
$ git commit -m "docker-keeper: propagate: ()"
If the commit message (or equivalently, the CLI) contains propagate…,
then it overrides the automatic default propagation.
If the commit is rebuilt with the same SHA1 in a given branch,
then it switches to the default behavior (automatic propagate strategy)."""
def print_stderr(message):
print(message, file=sys.stderr, flush=True)
def dump(data):
"""Debug"""
print_stderr(json.dumps(data, indent=json_indent))
# def error(msg, flush=True):
# print(msg, file=sys.stderr, flush=flush)
# exit(1)
class Error(Exception):
"""Base class for exceptions in this module."""
pass
def error(msg):
raise Error(msg)
def first_shortest_tag(list_tags):
return sorted(list_tags, key=(lambda s: (len(s), s)))[0]
def uniqify(s):
"""Remove duplicates and sort the result list."""
return sorted(set(s))
def uniqify_tags(list_tags):
"""Might be improved to mimic 'sort -V'"""
return sorted(set(list_tags), key=(lambda s: (len(s), s)))
def diff_list(l1, l2):
"""Compute the set-difference (l1 - l2), preserving duplicates."""
return list(filter(lambda e: e not in l2, l1))
def meet_list(l1, l2):
"""Return the sublist of l1, intersecting l2."""
return list(filter(lambda e: e in l2, l1))
def subset_list(l1, l2):
"""Check if l1 is included in l2."""
return not diff_list(l1, l2)
def is_unique(s):
"""Check if the list s has no duplicate."""
return len(s) == len(set(s))
def merge_dict(a, b):
"""Merge the fields of a and b, the latter overriding the former."""
res = copy.deepcopy(a) if a else {}
copyb = copy.deepcopy(b) if b else {}
for key in copyb:
res[key] = copyb[key]
return res
def check_domain(text):
if not re.match(r'^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+$',
text):
error("Error: '%s' is not a valid domain name." % text)
def check_string(value, ident=None):
if not isinstance(value, str):
if ident:
error("Error: expecting a string value, but was given '%s: %s'."
% (ident, value))
else:
error("Error: expecting a string value, but was given '%s'."
% value)
def check_list(value, text=None):
if not isinstance(value, list):
if not text:
text = str(value)
error("Error: not (JSON) list\nText: %s"
% text)
def check_dict(value, text=None):
if not isinstance(value, dict):
if not text:
text = str(value)
error("Error: not (JSON) dict\nText: %s"
% text)
def ignore_fields(obj, lst):
for field in lst:
obj.pop(field, None)
def check_no_fields(text, obj):
if obj:
print_stderr('Unexpected fields in %s:' % text)
dump(obj)
exit(1)
def remove_spaces(text):
return text.replace(' ', '')
def trim_comma_split(text):
"""Turn a comma-separated string into a list of nonempty strings"""
check_string(text)
# the filter is useful to drop empty strings (e.g., for '8.19,8.20,')
return list(filter(lambda e: e, remove_spaces(text).split(',')))
def flat_map_trim_comma_split(lst):
"""Apply trim_comma_split to each list elt then flatten; needs itertools"""
if lst:
return list(chain(*map(trim_comma_split, lst)))
else: # lst = None
return []
def subset_comma_list(cstr1, cstr2):
"""Check if cstr1 is included in cstr2."""
return subset_list(trim_comma_split(cstr1), trim_comma_split(cstr2))
def eval_bashlike(template, matrix, gvars=None, defaults=None):
b = BashLike()
return b.format(template, matrix=matrix, vars=gvars, defaults=defaults)
def eval_bashlike2(expr, matrix, tags, keywords):
b = BashLike()
return b.format(expr, matrix=matrix, tags=tags, keywords=keywords)
def eval_propagate(expr, build_elt):
return eval_bashlike2(expr, build_elt['matrix'], build_elt['tags'],
build_elt['keywords'])
def uniq_cat_eval_propagate(expr, build_data):
list_str = list(map(lambda elt: eval_propagate(expr, elt), build_data))
return uniqify_tags(flat_map_trim_comma_split(list_str))
def get_build_date():
"""ISO 8601 UTC timestamp"""
return datetime.utcnow().strftime("%FT%TZ")
def naive_url_encode(name):
"""https://gitlab.com/help/api/README.md#namespaced-path-encoding"""
check_string(name)
return name.replace('/', '%2F')
def gitlab_lambda_query_sha1(response):
"""Return the "commit.id" field from 'response.json()'."""
return response.json()['commit']['id']
def lambda_query_text(response):
return response.text
def get_url(url, headers=None, params=None, lambda_query=(lambda r: r)):
"""Some examples of lambda_query:
- gitlab_lambda_query_sha1
- lambda_query_text
"""
print_stderr('GET %s\n' % url)
response = requests.get(url, headers=headers, params=params)
if not response:
error("Error!\nCode: %d\nText: %s"
% (response.status_code, response.text))
return lambda_query(response)
def get_commit(commit_api):
"""Get GitHub or GitLab SHA1 of a given branch."""
fetcher = commit_api['fetcher']
repo = commit_api['repo']
branch = commit_api['branch']
if fetcher == 'github':
url = 'https://api.github.com/repos/%s/commits/%s' % (repo, branch)
headers = {"Accept": "application/vnd.github.v3.sha"}
lambda_query = lambda_query_text
elif fetcher == 'gitlab':
# https://gitlab.com/help/api/branches.md#get-single-repository-branch
url = ('https://gitlab.com/api/v4/projects/%s/repository/branches/%s'
% (naive_url_encode(repo), naive_url_encode(branch)))
headers = None
lambda_query = gitlab_lambda_query_sha1
else:
error("Error: do not support 'fetcher: %s'" % fetcher)
return get_url(url, headers, None, lambda_query)
def load_spec():
"""Parse the YAML file and return a dict."""
print_stderr("Loading '%s'..." % images_filename)
with open(images_filename) as f:
j = yaml.safe_load(f)
if 'active' not in j or not j['active']:
print_stderr("""
WARNING: the 'docker-keeper' tasks are not yet active.
Please update your %s specification and Dockerfile templates.
Then, set the option 'active: true' in the %s file."""
% (images_filename, images_filename))
exit(1)
return j
def product_build_matrix(matrix):
"""Get the list of dicts grouping 1 item per list mapped to matrix keys."""
assert matrix
old = [{}]
res = []
for key in matrix:
for value in matrix[key]:
for e in old:
enew = copy.deepcopy(e)
enew[key] = value
res.append(enew)
old = res
res = []
return old
def check_trim_relative_path(path):
"""Fail if path is absolute and remove leading './'."""
check_string(path)
if path[0] == '/':
error("Error: expecting a relative path, but was given '%s'." % path)
elif path[:2] == './':
return path[2:]
else:
return path
def check_filename(filename):
check_string(filename)
if '/' in filename:
error("Error: expecting a filename, but was given '%s'." % filename)
def eval_if(raw_condition, matrix, gvars):
"""Evaluate YAML condition.
Supported forms:
'{matrix[key]} == "string"'
'{matrix[key]} != "string"'
'"{matrix[key]}" == "string"'
'"{matrix[key]}" != "string"'
"""
# Conjunction
if isinstance(raw_condition, list):
for item_condition in raw_condition:
e = eval_if(item_condition, matrix, gvars)
if not e:
return False
return True
elif raw_condition is None:
return True
check_string(raw_condition)
equality = (raw_condition.find("==") > -1)
inequality = (raw_condition.find("!=") > -1)
if equality:
args = raw_condition.split("==")
elif inequality:
args = raw_condition.split("!=")
else:
error("Unsupported condition: '%s'." % raw_condition)
if len(args) != 2:
error("Wrong number of arguments: '%s'." % raw_condition)
a = eval_bashlike(args[0].strip().replace('"', ''), matrix, gvars)
b = eval_bashlike(args[1].strip().replace('"', ''), matrix, gvars)
if equality:
return a == b
else:
return a != b
def get_list_dict_dockerfile_matrix_tags_args(json, debug):
"""Directly called by main on the result of load_spec().
Get list of dicts containing the following keys:
- "context": "…"
- "dockerfile": "…/Dockerfile"
- "path": "…/…/Dockerfile"
- "matrix": […]
- "tags": […]
- "args": […]
- "keywords": […]
- "after_deploy_script": […]
"""
# TODO later-on: fix (dockerfile / path) semantics
res = []
images = json['images']
args1 = json['args'] if 'args' in json else {}
gvars = json['vars'] if 'vars' in json else {}
# = global vars, interpolated in:
# - args
# - build.args
# - build.tags
# - build.after_deploy_export
for item in images:
list_matrix = product_build_matrix(item['matrix'])
if 'dockerfile' in item['build']:
dfile = check_trim_relative_path(item['build']['dockerfile'])
else:
dfile = 'Dockerfile'
context = check_trim_relative_path(item['build']['context'])
path = '%s/%s' % (context, dfile)
raw_tags = item['build']['tags']
args2 = item['build']['args'] if 'args' in item['build'] else {}
raw_args = merge_dict(args1, args2)
if 'keywords' in item['build']:
raw_keywords = item['build']['keywords']
else:
raw_keywords = []
if 'after_deploy' in item['build']:
raw_after_deploy = item['build']['after_deploy']
# support both
# after_deploy: 'code'
# and
# after_deploy:
# - 'code'
# as well as
# after_deploy:
# - run: 'code'
# if: '{matrix[base]} == 4.07.1-flambda'
# and regarding interpolation, we can add:
# after_deploy_export:
# variable_name: 'value-{matrix[coq]}'
# to prepend the after_deploy_script with export commands
if isinstance(raw_after_deploy, str):
raw_after_deploy = [raw_after_deploy]
else:
raw_after_deploy = []
if 'after_deploy_export' in item['build']:
raw_after_deploy_export = item['build']['after_deploy_export']
check_dict(raw_after_deploy_export)
else:
raw_after_deploy_export = {}
for matrix in list_matrix:
tags = []
for tag_item in raw_tags:
tag_template = tag_item['tag']
tag_cond = tag_item['if'] if 'if' in tag_item else None
if eval_if(tag_cond, matrix, gvars):
# otherwise skip the tag synonym
tag = eval_bashlike(tag_template, matrix,
gvars) # NOT defaults
tags.append(tag)
defaults = {"build_date": get_build_date()}
if 'commit_api' in item['build']:
commit_api = item['build']['commit_api']
defaults['commit'] = get_commit(commit_api) # TODO: auth?
args = {}
for arg_key in raw_args:
arg_template = raw_args[arg_key]
args[arg_key] = eval_bashlike(arg_template, matrix,
gvars, defaults)
keywords = list(map(lambda k: eval_bashlike(k, matrix,
gvars, defaults),
raw_keywords))
after_deploy_export = []
# Note: This could be a map:
for var in raw_after_deploy_export:
check_string(var)
var_template = raw_after_deploy_export[var]
var_value = eval_bashlike(var_template, matrix,
gvars, defaults)
# TODO soon: think about quoting var_value
after_deploy_export.append("export %s='%s'" % (var, var_value))
if raw_after_deploy:
after_deploy_script = after_deploy_export
else:
after_deploy_script = []
for ad_item in raw_after_deploy:
if isinstance(ad_item, str):
after_deploy_script.append(ad_item) # no { } interpolation
# otherwise sth like ${BASH_VARIABLE} would raise an error
else:
script_item = ad_item['run']
script_cond = ad_item['if'] if 'if' in ad_item else None
if eval_if(script_cond, matrix, gvars):
# otherwise skip the script item
after_deploy_script.append(script_item)
newitem = {"context": context, "dockerfile": dfile,
"path": path,
"matrix": matrix, "tags": tags, "args": args,
"keywords": keywords,
"after_deploy_script": after_deploy_script}
res.append(newitem)
if debug:
print_stderr('get_list_dict_dockerfile_matrix_tags_args():')
dump(res)
return res
def gitlab_build_params_pagination(page, per_page):
"""https://docs.gitlab.com/ce/api/README.html#pagination"""
return {
'page': str(page),
'per_page': str(per_page)
}
def hub_build_params_pagination(page, per_page):
return {
'page': str(page),
'page_size': str(per_page)
}
def hub_lambda_list(j):
"""https://registry.hub.docker.com/v2/repositories/library/debian/tags"""
return list(map(lambda e: e['name'], j['results']))
def get_list_paginated(url, headers, params, lambda_list, max_per_sec=5):
"""Generic wrapper to handle GET requests with pagination.
If the response is a JSON list, use lambda_list=(lambda l: l).
REM: for https://registry.hub.docker.com/v2/repositories/_/_/tags,
one could use the "next" field to guess the following page."""
assert isinstance(max_per_sec, int)
assert max_per_sec > 0
assert max_per_sec <= 10
per_page = 50 # max allowed (by gitlab.com & hub.docker.com): 100
page = 0
allj = []
while True:
page += 1
if page % max_per_sec == 0:
time.sleep(1.1)
page_params = hub_build_params_pagination(page, per_page)
all_params = merge_dict(params, page_params)
print_stderr("GET %s\n # page: %d" % (url, page))
response = requests.get(url, headers=headers, params=all_params)
if response.status_code == 404:
j = []
elif not response:
error("Error!\nCode: %d\nText: %s"
% (response.status_code, response.text))
else:
j = lambda_list(response.json())
check_list(j, text=response.text)
if j:
allj += j
else:
break
return allj
def get_remote_tags(spec):
repo = spec['docker_repo']
check_string(repo)
return get_list_paginated(
'https://registry.hub.docker.com/v2/repositories/%s/tags' % repo,
None, None, hub_lambda_list)
def get_gitlab_ci_tags(spec):
if 'gitlab_ci_tags' not in spec:
gitlab_ci_tags = []
else:
gitlab_ci_tags = spec['gitlab_ci_tags']
check_list(gitlab_ci_tags)
return gitlab_ci_tags
def yaml_safe_quote(text):
return '"' + text.replace('"', '\\"') + '"'
def oneliner_str_of_list(json):
check_list(json)
return '[' + ", ".join(map(lambda s: yaml_safe_quote(s), json)) + ']'
def minimal_rebuild(build_tags, remote_tags):
def pred(item):
return not subset_list(item['tags'], remote_tags)
return list(filter(pred, build_tags))
def to_rm(all_tags, remote_tags):
return diff_list(remote_tags, all_tags)
def get_script_directory():
"""$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd) in Python."""
return os.path.dirname(__file__)
def get_script_rel2_directory():
"""relative path that's equivalent to: relpath(dirname(__file__), ../..)"""
keeper_dir = get_script_directory()
keeper_rel_dir = os.path.relpath(
keeper_dir, os.path.dirname(os.path.dirname(keeper_dir)))
return check_trim_relative_path(keeper_rel_dir)
def mkdir_dirname(filename):
"""Python3 equivalent to 'mkdir -p $(dirname $filename)"'."""
os.makedirs(os.path.dirname(filename), mode=0o755, exist_ok=True)
def fullpath(filename):
"""Get path of filename in output_directory/."""
return os.path.join(output_directory, filename)
def write_json_artifact(j, basename):
filename = fullpath(basename)
print_stderr("Generating '%s'..." % filename)
mkdir_dirname(filename)
with open(filename, 'w') as f:
json.dump(j, f, indent=json_indent)
def write_text_artifact(text, basename):
filename = fullpath(basename)
print_stderr("Generating '%s'..." % filename)
mkdir_dirname(filename)
with open(filename, 'w') as f:
f.write(text)
def write_list_text_artifact(seq, basename):
check_list(seq)
write_text_artifact('\n'.join(seq) + '\n', basename)
def write_build_data_all(build_data_all):
write_json_artifact(build_data_all, 'build_data_all.json')
def write_build_data_chosen(build_data):
write_json_artifact(build_data, 'build_data_chosen.json')
def write_build_data_min(build_data_min):
write_json_artifact(build_data_min, 'build_data_min.json')
def write_remote_tags(remote_tags):
write_list_text_artifact(remote_tags, 'remote_tags.txt')
def write_gitlab_ci_tags(gitlab_ci_tags):
check_list(gitlab_ci_tags)
write_text_artifact(oneliner_str_of_list(gitlab_ci_tags),
'gitlab_ci_tags.txt')
def write_remote_tags_to_rm(remote_tags_to_rm):
write_json_artifact(remote_tags_to_rm, 'remote_tags_to_rm.json')
def write_propagate(propagate_data):
write_json_artifact(propagate_data, 'propagate.json')
def write_list_dockerfile(seq):
"""To be used on the value of get_list_dict_dockerfile_matrix_tags_args."""
dockerfiles = uniqify(map(lambda e: e['path'], seq))
write_list_text_artifact(dockerfiles, 'Dockerfiles.txt')
def write_docker_repo(spec):
repo = spec['docker_repo'] + '\n'
write_text_artifact(repo, 'docker_repo.txt')
def read_json_artifact(basename):
filename = fullpath(basename)
print_stderr("Reading '%s'..." % filename)
with open(filename, 'r') as json_data:
j = json.load(json_data)
return j
def read_build_data_chosen():
return read_json_artifact('build_data_chosen.json')
def read_propagate():
return read_json_artifact('propagate.json')
def write_readme(base_url, build_data):
"""Read README.md and replace <!-- tags --> with a list of images
with https://gitlab.com/foo/bar/blob/master/Dockerfile hyperlinks.
"""
pattern = '<!-- tags -->'
check_string(base_url)
if base_url[-1] == '/':
base_url = base_url[:-1]
def readme_image(item):
return '- [`{tags}`]({url})'.format(
tags=('`, `'.join(item['tags'])),
url=('%s/blob/master/%s' % (base_url, item['path'])))
print_stderr("Reading the template 'README.md'...")
with open('README.md', 'r') as f:
template = f.read()
tags = ('# <a name="supported-tags"></a>'
'Supported tags and respective `Dockerfile` links\n\n%s'
% '\n'.join(map(readme_image, build_data)))
readme = template.replace(pattern, tags)
filename = fullpath('README.md')
print_stderr("Generating '%s'..." % filename)
mkdir_dirname(filename)
with open(filename, 'w') as f:
f.write(readme)
def get_check_tags(seq):
"""To be used on the value of get_list_dict_dockerfile_matrix_tags_args."""
res = []
for e in seq:
res.extend(e['tags'])
if is_unique(res):
print_stderr("OK: no duplicate tag found.")
else:
error("Error: there are some tags duplicates.")
return res
def merge_data(l1, l2):
"""Append to l1 the elements of l2 that do not belong to l1."""
extra = diff_list(l2, l1)
return l1 + extra
def get_nightly_only(spec, debug):
spec2 = copy.deepcopy(spec)
images = spec2.pop('images')
def nightly(item):
return 'nightly' in item['build'] and item['build']['nightly']
images2 = list(filter(nightly, images))
spec2['images'] = images2
return get_list_dict_dockerfile_matrix_tags_args(spec2, debug)
def print_list(title, seq):
print_stderr(title + ':' + ''.join(map(lambda e: '\n- ' + e, seq)))
def get_file_only(build_data_all, dockerfiles):
print_list('Specified Dockerfiles', dockerfiles)
# TODO later-on: fix (dockerfile / path) semantics
def matching(item):
return item['path'] in dockerfiles
return list(filter(matching, build_data_all))
def get_tag_only(build_data_all, tags):
print_list('Specified tags', tags)
def matching(item):
return meet_list(item['tags'], tags)
return list(filter(matching, build_data_all))
def get_keyword_only(build_data_all, keywords):
print_list('Specified keywords', keywords)
def matching(item):
return meet_list(item['keywords'], keywords)
return list(filter(matching, build_data_all))
def get_files_list(items_filename):
with open(items_filename, 'r') as fh:
dockerfiles = [item.strip() for item in fh.readlines()]
return dockerfiles
def get_tags_list(items_filename):
with open(items_filename, 'r') as fh:
tags = [item.strip() for item in fh.readlines()]
return tags
def get_keywords_list(items_filename):
with open(items_filename, 'r') as fh:
keywords = [item.strip() for item in fh.readlines()]
return keywords
def check_output_mode(mode):
match mode:
case 'nil': # can only be used in 'images.yml'.propagate.strategy
return
case 'minimal':
return
case 'nightly':
return
case 'rebuild-keyword':
return
case 'rebuild-all':
return
case _:
error("Error: invalid output value 'mode: %s'." % mode)
def check_manual_mode(mode):
match mode:
case 'minimal':
return
case 'nightly':
return
case 'rebuild-keyword':
return
case 'rebuild-all':
return
case _:
error("Error: invalid manual value 'mode: %s'." % mode)
def get_propagate_strategy(spec, build_data_chosen,
triggered, manual_propagate):
"""Get propagate_strategy from images.yml, build_data_chosen, --propagate
Regarding --propagate: can be specified by means of HEAD's commit message:
git commit --allow-empty -m "…" -m "docker-keeper: nightly; propagate: ()"
'images.yml'.'propagate' Syntax: sequence of:
when: 'nightly' | 'rebuild-all' | 'forall' | 'exists'
# when OPTIONAL for last sequence element
expr: # (forall/exisgts) 's,t'-list, interp({matrix},{tags},{keywords})
subset: # (forall/exists) 's,t'-list, interpolation, expr subset of this
mode: 'nil' | 'minimal' | 'nightly' | 'rebuild-keyword' | 'rebuild-all'
item: # (rebuild-keyword) concat; 's,t'-list; interpolation; uniqify
'images.yml'.'propagate' Full example:
propagate:
random-slug:
api_token_env_var: 'VAR_NAME'
gitlab_domain: 'gitlab.com'
gitlab_project: '42'
strategy:
# the first that matches (unless manual --propagate)
# current limitation: triggers only 1 mode in child docker-keeper(§)
- # when MANDATORY because not the last rule
when: 'nightly' # this is the 1st possible (arg-free) input mode
mode: 'nightly' # (§)so this cannot be a list
- when: 'rebuild-all' # this is the 2d possible (arg-free) input mode
mode: 'rebuild-all' # (§)so this cannot be a list
- when: 'forall' # forall built image, the property holds
expr: '{matrix[coq][//pl/.][%.*]}' # string or 's,t' list
subset: '8.4,8.5' # is a subset of {8.4, 8.5}
mode: 'nil' # do not propagate then
# no explicit neg, but eval order + previous steps -> implicit neg
- when: 'forall'
expr: '{matrix[coq]}'
subset: 'dev'
# trigger a 'rebuild-keyword: dev'
mode: 'rebuild-keyword' # (§)so this cannot be a list
item: 'dev' # string or 's,t' list; uniqify
- # when OPTIONAL for last rule
mode: 'minimal'
mathcomp:
api_token_env_var: 'VAR_NAME'
gitlab_domain: 'gitlab.inria.fr'
gitlab_project: '40'
strategy:
- when: 'rebuild-all'
mode: 'rebuild-all'
- when: 'forall'
expr: '{matrix[coq][//pl/.][%.*]}'
subset: '8.4,8.5'
mode: 'nil'
- # when OPTIONAL for last rule
mode: 'rebuild-keyword' # trigger a 'rebuild-keyword: s,t'
item: '{keywords[/#/,][#,]}' # concat; 's,t' list; interp; uniqify
mathcomp-dev:
api_token_env_var: 'VAR_NAME'
gitlab_domain: 'gitlab.inria.fr'
gitlab_project: '41'
strategy:
- when: 'rebuild-all'
mode: 'minimal'
- when: 'forall'
expr: '{matrix[coq]}'
subset: 'dev'
mode: 'nightly'
- when: 'exists' # there exists a built image s.t. the property holds
expr: '{matrix[coq][//pl/.][%.*]}' # string or 's,t' list
subset: '8.19,8.20,dev' # is a subset of {8.19,8.20,dev}
mode: 'minimal'
- # when OPTIONAL for last rule
mode: 'nil'"""
prop = spec['propagate'] if 'propagate' in spec else {}
res_prop = {}
at_least_one_manual = bool(manual_propagate)
for slug in prop:
prop1 = prop[slug]
res_prop1 = {}
api_token_env_var = prop1.pop('api_token_env_var')
if not re.match(r'^[a-zA-Z_]+[a-zA-Z0-9_]*$', api_token_env_var):
error("Error: invalid api_token_env_var for %s (was given '%s')."
% (slug, api_token_env_var))
res_prop1['api_token_env_var'] = api_token_env_var
gitlab_domain = prop1.pop('gitlab_domain')
check_domain(gitlab_domain)
res_prop1['gitlab_domain'] = gitlab_domain
res_prop1['gitlab_project'] = prop1.pop('gitlab_project')
strat = prop1.pop('strategy')
check_no_fields(slug, prop1)
check_list(strat)
# check that each elt (except maybe the last one) has a 'when' property
strat_drop1 = strat[:-1]
for elt in strat_drop1:
if 'when' not in elt:
error("Error: propagate: %s: strategy: 'when' is mandatory %s."
% (slug, "(except for last list element)"))
# 1a. manual strategy
if slug in manual_propagate:
res_prop1['strategy'] = manual_propagate.pop(slug)
res_prop[slug] = res_prop1
continue
else:
if at_least_one_manual:
# disable automatic strategy; will try other (manual) slugs
continue
# 1b. otherwise, automatic strategy
res_strat = {}
# detect the first strategy elt that matches the 'when' property
# and retrieve the output 'mode' (and interpolated 'item') in res_strat
for elt in strat:
if 'when' in elt:
when = elt.pop('when')
match when:
case 'nightly':
if 'nightly' in triggered and triggered['nightly']:
# BEGIN idem1
res_strat['mode'] = elt.pop('mode')
if res_strat['mode'] == 'rebuild-keyword':
raw_item = elt.pop('item')
res_strat['item'] = \
uniq_cat_eval_propagate(raw_item,
build_data_chosen)
else:
check_output_mode(res_strat['mode'])
check_no_fields('strategy', elt)
break
# END idem1
case 'rebuild-all':
if 'rebuild_all' in triggered \
and triggered['rebuild_all']:
# BEGIN idem2
res_strat['mode'] = elt.pop('mode')
if res_strat['mode'] == 'rebuild-keyword':
raw_item = elt.pop('item')
res_strat['item'] = \
uniq_cat_eval_propagate(raw_item,
build_data_chosen)
else:
check_output_mode(res_strat['mode'])
check_no_fields('strategy', elt)
break
# END idem2
case 'forall':
acc = True
expr = elt.pop('expr')
subset = elt.pop('subset')
for build in build_data_chosen:
e_expr = eval_propagate(expr, build)
e_subset = eval_propagate(subset, build)
if not subset_comma_list(e_expr, e_subset):
acc = False
break
if acc:
# BEGIN idem3
res_strat['mode'] = elt.pop('mode')
if res_strat['mode'] == 'rebuild-keyword':
raw_item = elt.pop('item')
res_strat['item'] = \
uniq_cat_eval_propagate(raw_item,
build_data_chosen)
else:
check_output_mode(res_strat['mode'])
check_no_fields('strategy', elt)
break
# END idem3
else:
ignore_fields(elt, ['mode', 'item'])
check_no_fields('strategy', elt)
case 'exists':
acc = False # dual
expr = elt.pop('expr')
subset = elt.pop('subset')
for build in build_data_chosen:
e_expr = eval_propagate(expr, build)
e_subset = eval_propagate(subset, build)
if subset_comma_list(e_expr, e_subset): # dual
acc = True # dual
break
if acc:
# BEGIN idem4
res_strat['mode'] = elt.pop('mode')
if res_strat['mode'] == 'rebuild-keyword':
raw_item = elt.pop('item')
res_strat['item'] = \
uniq_cat_eval_propagate(raw_item,
build_data_chosen)
else:
check_output_mode(res_strat['mode'])
check_no_fields('strategy', elt)
break
# END idem4