librem5-devkit-flash-image 8.06 KB
Newer Older
1
2
3
4
#!/usr/bin/python3

import argparse
import datetime
5
import hashlib
6
7
8
9
10
11
12
13
14
15
import jenkins
import logging
import lzma
import os
import requests
import shutil
import subprocess
import sys
import tempfile
import tqdm
16
import yaml
17
18
19
20
21
22
23
24
25
26
27
28
29
30

try:
    import coloredlogs
    have_colored_logs = True
except ImportError:
    have_colored_logs = False


from urllib.parse import urljoin

JENKINS = 'https://arm01.puri.sm'
TYPE = 'devkit'
DIST = 'buster+ci'
IMAGE = 'devkit.img'
31
META_YAML = 'files/meta.yml'
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
IMAGE_JOB_NAME = 'Images/Image Build'
UBOOT = 'u-boot-devkit-recovery.imx'
UBOOT_JOB_NAME = 'u-boot_builds/devkit-recovery_uboot_build'
UUU_SCRIPT = 'flash_devkit.lst'
UUU_SCRIPT_TMPL = '''uuu_version 1.0.1

SDP: boot -f {uboot}
# This command will be run when use SPL
SDPU: delay 1000
SDPU: write -f {uboot} -offset 0x57c00
SDPU: jump
# This command will be run when ROM support stream mode
SDPS: boot -f {uboot}
SDPU: delay 1000
#FB: ucmd setenv fastboot_buffer 0x43000000
FB: ucmd setenv fastboot_dev mmc
FB: ucmd setenv mmcdev 0
FB: flash -raw2sparse all {image}
FB: Done
'''
BLOCK_SIZE = 8192
UNCOMPRESSED_SIZE = 3600000000


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
class VerifyImageException(Exception):
    pass


def verify_image(image, meta):
    m = hashlib.sha256()
    size = int(meta['image']['size'])
    hexdigest = meta['image']['sha256sum']

    logging.info("Calculating sha256sum of {}".format(image))
    bar = tqdm.tqdm(total=size,
                    desc='Checking',
                    leave=False)
    with open(image, 'rb') as f:
        while True:
            data = f.read(BLOCK_SIZE)
            if data:
                m.update(data)
                bar.update(n=len(data))
            else:
                break
    bar.close()
    if m.hexdigest() != hexdigest:
        raise VerifyImageException("Checksum of image {} "
                                   "does not match {}".format(m.hexdigest(), hexdigest))


83
84
85
def download_image(url, target):
    decomp = lzma.LZMADecompressor()
    logging.info("Downloading image from {}".format(url))
86
87
88
89
90
91
92
93
94
95
96

    # We expect metadata to be right next to the image
    meta_yml_url = "{}/{}".format(url.rsplit('/', 1)[0], META_YAML)
    resp = requests.get(meta_yml_url)
    # No meta data is no yet fatal
    try:
        resp.raise_for_status()
        meta = yaml.safe_load(resp.text)
        uncompressed_size = int(meta['image']['size'])
        logging.debug("Image size is %d", uncompressed_size)
    except requests.exceptions.HTTPError:
97
        logging.warning("No meta data found, skipping integrity check")
98
99
100
        meta = None
        uncompressed_size = UNCOMPRESSED_SIZE

101
102
103
104
105
106
    resp = requests.get(url, stream=True)
    resp.raise_for_status()
    ts = int(resp.headers.get('content-length', 0))
    download_bar = tqdm.tqdm(total=ts,
                             desc='Download',
                             leave=False)
107
    decompress_bar = tqdm.tqdm(total=uncompressed_size,
108
109
110
111
112
113
114
115
116
117
118
                               desc='Decompr.',
                               leave=False)
    with open(target, 'wb+') as f:
        for data in resp.iter_content(BLOCK_SIZE):
            if data:
                out = decomp.decompress(data)
                decompress_bar.update(len(out))
                f.write(out)
            download_bar.update(n=len(data))
    download_bar.close()
    decompress_bar.close()
119
120
    if meta:
        verify_image(target, meta)
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


def find_image(jobname, type, dist):
    server = jenkins.Jenkins(JENKINS)
    logging.info("Looking for {} {} image".format(type, dist))
    info = server.get_job_info(jobname)
    for build in info['builds']:
        resp = requests.get(build['url'] + '/api/json')
        resp.raise_for_status()
        json = resp.json()
        if (json['description'].startswith(type + ' ') and
                dist in json['description'] and
                json['result'] == 'SUCCESS'):
            found = json
            break
    else:
        found = None
    return found


def find_uboot(jobname):
    server = jenkins.Jenkins(JENKINS)

    info = server.get_job_info(jobname)
    for build in info['builds']:
        resp = requests.get(build['url'] + '/api/json')
        resp.raise_for_status()
        json = resp.json()
        if (json['result'] == 'SUCCESS'):
            found = json
            break
    else:
        found = None
    return found


def download_uboot(url, target):
    logging.info("Downloading uboot from {}".format(url))
    resp = requests.get(url, stream=True)
    resp.raise_for_status()
    ts = int(resp.headers.get('content-length', 0))
    bar = tqdm.tqdm(total=ts, leave=False)
    with open(target, 'wb+') as f:
        for data in resp.iter_content(BLOCK_SIZE):
            if data:
                f.write(data)
            bar.update(n=len(data))


def write_uuu_script(target, image, uboot):
    with open(target, 'w+') as f:
        f.write(UUU_SCRIPT_TMPL.format(image=os.path.basename(image),
                                       uboot=os.path.basename(uboot)))


def flash_image(uuu_target):
    subprocess.check_call(['uuu', uuu_target])


def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('--dir', type=str, default=None,
                        help='Download files to dir (instead of a temporary directory)')
    parser.add_argument('--dist', type=str, default=DIST,
                        help="Download an image for this distribution, default is '{}'".format(DIST))
    parser.add_argument('--skip-cleanup', action='store_true', default=False,
                        help='Skip temporary directory cleanup')

    group = parser.add_argument_group(title='Testing and debugging options')
    group.add_argument('--debug', action="store_true", default=False,
                       help='Enable debug output')
    group.add_argument('--image-job', type=str, default=IMAGE_JOB_NAME,
                       help='Jenkins job to download the image from')
    group.add_argument('--uboot-job', type=str, default=UBOOT_JOB_NAME,
                       help='Jenkins job to download the uboot from')
    args = parser.parse_args()

    level = logging.DEBUG if args.debug else logging.INFO
    if have_colored_logs:
        coloredlogs.install(level=level, fmt='%(asctime)s %(levelname)s %(message)s')
    else:
        logging.basicConfig(level=level, format='%(asctime)s %(levelname)s %(message)s')

    # Check available downloads upfront so it's less likely we fail
    # later:
    image_ref = find_image(args.image_job, TYPE, args.dist)
    if image_ref:
        image_ref['ts'] = datetime.datetime.fromtimestamp(image_ref['timestamp'] / 1000).strftime('%c')
        logging.info("Found disk image Build {id} '{description}' from {ts}".format(**image_ref))
    else:
        logging.error("No matching image found")
        return 1

    uboot_ref = find_uboot(args.uboot_job)
    if uboot_ref:
        uboot_ref['ts'] = datetime.datetime.fromtimestamp(uboot_ref['timestamp'] / 1000).strftime('%c')
        logging.info("Found uboot Build {id} from {ts}".format(**uboot_ref))
    else:
        logging.error("No matching uboot found")
        return 1

    outdir = args.dir if args.dir is not None else tempfile.mkdtemp(prefix='devkit_image_', dir='.')
    try:
        logging.info("Downloading to {}".format(outdir))
        if args.dir == outdir:
            os.makedirs(args.dir, exist_ok=True)

        image_target = os.path.join(outdir, IMAGE)
        uboot_target = os.path.join(outdir, UBOOT)
        uuu_target = os.path.join(outdir, UUU_SCRIPT)

        download_image(urljoin(image_ref['url'], 'artifact/{}.xz').format(IMAGE),
                       image_target)
        download_uboot(urljoin(uboot_ref['url'], 'artifact/build/{}'.format(UBOOT)),
                       uboot_target)
        write_uuu_script(uuu_target, image_target, uboot_target)
        flash_image(uuu_target)
238
239
240
    except VerifyImageException as e:
        logging.error(e)
        return 1
241
242
243
244
245
246
247
248
249
250
251
252
253
    except KeyboardInterrupt:
        logging.error("CTRL-C pressed.")
        return 1
    finally:
        if args.dir != outdir and not args.skip_cleanup:
            logging.info("Cleaning up.")
            shutil.rmtree(outdir)

    return 0


if __name__ == '__main__':
    sys.exit(main())