build.py 7.57 KB
Newer Older
Philippe Pepiot's avatar
Philippe Pepiot committed
1
2
3
4
5
6
#!/usr/bin/env python3

import itertools
import subprocess
import sys
import logging
7
from dataclasses import dataclass
8
from typing import Optional
9
10
11
12
13
14

@dataclass
class CubicWebImage:
    python: str
    debian: str
    package_name: str
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    package_version: str

    @property
    def cubicweb_version(self):
        return self.package_version.split('-', 1)[0]

    @property
    def cubicweb_major_version(self):
        return self.cubicweb_version.rsplit('.', 1)[0]

    @property
    def tag(self):
        return f"{REGISTRY}:{self.base_docker_image}-{self.cubicweb_version}"

    @property
    def base_docker_image(self):
        return f"{self.python}-{self.debian}"
Philippe Pepiot's avatar
Philippe Pepiot committed
32
33
34


LOG = logging.getLogger(__name__)
35
REGISTRY = 'logilab/cubicweb'
36
CWREPO = 'https://forge.extranet.logilab.fr/cubicweb/cubicweb/'
Philippe Pepiot's avatar
Philippe Pepiot committed
37
38
39
MATRIX = [
    (['py27'], ['stretch', 'buster'], [None, '3.25', '3.26'],
        [None, 'onbuild']),
Philippe Pepiot's avatar
Philippe Pepiot committed
40
    (['py35'], ['stretch'], [None, '3.26', '3.27'], [None, 'onbuild']),
41
    (['py37'], ['buster'], [None, '3.26', '3.27', '3.28', '3.29', 'dev'], [None, 'onbuild']),
Philippe Pepiot's avatar
Philippe Pepiot committed
42
43
44
45
]
ALIASES = (
    ('3.25', 'py27-buster-3.25'),
    ('3.26', 'py37-buster-3.26'),
Philippe Pepiot's avatar
Philippe Pepiot committed
46
    ('3.27', 'py37-buster-3.27'),
47
    ('3.28', 'py37-buster-3.28'),
48
    ('3.29', 'py37-buster-3.29'),
Philippe Pepiot's avatar
Philippe Pepiot committed
49
    ('dev', 'py37-buster-dev'),
50
    ('latest', 'py37-buster-3.29'),
51
    ('buildpackage', 'buster-buildpackage'),
Philippe Pepiot's avatar
Philippe Pepiot committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
)


def run(*args):
    LOG.info('%s', ' '.join(args))
    return subprocess.run(args, stdout=subprocess.PIPE)


def check_call(*args):
    LOG.info('%s', ' '.join(args))
    return subprocess.check_call(args)


def check_output(*args):
    LOG.info('%s', ' '.join(args))
    return subprocess.check_output(args).decode().strip()


def _cwdev(_cache={}):
    if not _cache:
        rev = check_output('hg', 'id', '-r', 'default', CWREPO)
73
74
        # url anchor is used to invalidate docker cache.
        _cache[None] = '{0}-/archive/branch/default/cubicweb-branch-default.tar.gz#rev={1}'.format(
Philippe Pepiot's avatar
Philippe Pepiot committed
75
76
77
78
79
80
            CWREPO, rev)
    return _cache[None]


def tag_aliases():
    for alias, source in ALIASES:
81
82
83
        if alias == 'buildpackage':
            check_call('docker', 'tag', _tag(source), _tag(alias))
            continue
Philippe Pepiot's avatar
Philippe Pepiot committed
84
85
86
87
88
89
90
91
92
        for onbuild in [None, 'onbuild']:
            if alias == 'latest' and onbuild == 'onbuild':
                tag = _tag('onbuild')
            else:
                tag = _tag(alias, onbuild)
            src = _tag(source, onbuild)
            check_call('docker', 'tag', src, tag)


93
def build_image(image: CubicWebImage, onbuild: Optional[str], no_cache=False, registry=None):
Philippe Pepiot's avatar
Philippe Pepiot committed
94
95
96
97
    args = {}
    dockerfile = 'Dockerfile'
    if onbuild is not None:
        dockerfile = 'Dockerfile.onbuild'
98
99
100
101
102
103
104
        args['FROM'] = image.tag
        tag = image.tag + '-onbuild'
    else:
        args['PYTHON'] = 'python' if image.python == 'py27' else 'python3'
        dockerfile = 'Dockerfile'
        args['FROM'] = image.base_docker_image
        args['DIST'] = image.debian
Carine Dengler's avatar
Carine Dengler committed
105
        args['PACKAGES'] = f"{image.package_name}={image.package_version}"
106
107
        tag = image.tag
        if image.package_version == 'dev':
108
109
110
            args['SOURCE_TARBALL'] = _cwdev()
            args['COMPONENT'] = 'main'
        else:
111
112
            args['COMPONENT'] = 'cubicweb-{}'.format(image.cubicweb_major_version)

Philippe Pepiot's avatar
Philippe Pepiot committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    cmd = [
        'docker', 'build', '-t', tag,
        '-f', dockerfile,
    ]
    if no_cache:
        cmd += ['--no-cache']
    for key, value in args.items():
        cmd += ['--build-arg', '{}={}'.format(key, value)]
    cmd += ['.']
    check_call(*cmd)


def green(text):
    return '\033[0;32m' + text + '\033[0m'


def red(text):
    return '\033[0;31m' + text + '\033[0m'


133
134
135
136
137
138
def build_buildpackage(dist):
    tag = '{}:{}-buildpackage'.format(REGISTRY, dist)
    check_call('docker', 'build', '-t', tag,
               '--build-arg', 'DIST={}'.format(dist),
               '-f', 'Dockerfile.buildpackage', '.')

139
def get_cubicweb_images(debian_dists: list[str], python_versions: list[str]):
140
    images = []
Carine Dengler's avatar
Carine Dengler committed
141
    for dist in debian_dists:
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        for python_version in python_versions:
            python = 'python' if python_version == 'py27' else 'python3'
            check_call(
                'docker',
                'build',
                '.',
                '-f',
                'Dockerfile.getversion',
                '-t',
                'cubicweb:getversion',
                '--build-arg',
                f'DIST={dist}',
                '--build-arg',
                f"PYTHON={python}"
Carine Dengler's avatar
Carine Dengler committed
156
            )
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
            versions = check_output(
                'docker', 'run', '--rm', 'cubicweb:getversion'
            ).splitlines()

            # filter release candidate version
            valid_versions = [
                version for version in versions if '~rc' not in version
            ]
            for version in valid_versions:
                image = CubicWebImage(
                    python=python_version,
                    debian=dist,
                    package_name=f'{python}-cubicweb',
                    package_version=version
                )
                images.append(image)
173
174
    return images

Carine Dengler's avatar
Carine Dengler committed
175
176
177
178
179
180
def build(debian_dists, images=[], rebuild=False):
    for dist in debian_dists:
        if rebuild:
            # pull base images
            check_call('docker', 'pull', f'debian:{dist}-slim')
        build_buildpackage(dist)
181
182
183
184
    for image in images:
        for image_type in (None, 'onbuild'):
            build_image(image, image_type)

Carine Dengler's avatar
Carine Dengler committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
            if rebuild and image_type is None:
                tag = image.tag
                out = run(
                    'docker', 'run', '--rm', '-t',
                    '--user', 'root',
                    '--entrypoint', 'check-docker-updates.sh',
                    tag, 'apt')
                if out.returncode == 1:
                    LOG.warning(red(
                        '%s debian packages updates are available: %s'),
                        tag, out.stdout)
                    build_image(image, image_type, no_cache=True)
                else:
                    assert (out.returncode, out.stdout) == (0, b''), out
                    LOG.info(green('%s debian packages are up-to-date'), tag)
Philippe Pepiot's avatar
Philippe Pepiot committed
200
201
202
203
204
205
206
207


def push():
    for matrix in MATRIX:
        for python, dist, cw, onbuild in itertools.product(*matrix):
            tag = _tag(python, dist, cw, onbuild)
            check_call('docker', 'push', tag)
    for alias, source in ALIASES:
208
209
210
211
        if alias == "buildpackage":
            check_call('docker', 'push', _tag(source))
            check_call('docker', 'push', _tag(alias))
            continue
Philippe Pepiot's avatar
Philippe Pepiot committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
        for onbuild in [None, 'onbuild']:
            if alias == 'latest' and onbuild == 'onbuild':
                tag = _tag('onbuild')
            else:
                tag = _tag(alias, onbuild)
            check_call('docker', 'push', tag)


if __name__ == '__main__':
    import argparse
    logging.basicConfig(format='%(asctime)-15s %(message)s')
    LOG.setLevel(logging.INFO)
    parser = argparse.ArgumentParser(sys.argv[0])
    parser.add_argument('--registry', action='store', default=REGISTRY)
    parser.add_argument(
        '--checkrebuild', action='store_true', default=False,
        help='Rebuild images in case of outdated debian or python package')
    parser.add_argument(
        '--push', action='store_true', default=False,
        help='push images')
    args = parser.parse_args()
    REGISTRY = args.registry
234
235
236
    images = get_cubicweb_images(["stretch", "buster"], ["py27"])
    images += get_cubicweb_images(["stretch"], ["py35"])
    images += get_cubicweb_images(["buster"], ["py37"])
Philippe Pepiot's avatar
Philippe Pepiot committed
237
238
239
    if args.push:
        push()
    else:
240
        build(images=images, rebuild=args.checkrebuild)
Philippe Pepiot's avatar
Philippe Pepiot committed
241
        tag_aliases()