File size: 4,048 Bytes
3e51297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build missing images from an extracted tmax task archive, with resumable logs.

Example:
  python build_dataset_images.py --task-data-dir ./tasks --manifest task-manifest.json

Requires Docker Buildx and a Docker Hub login with write access to image repos.
Targets Linux AMD64; leaves source task files and verifiers unchanged.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
from pathlib import Path
import subprocess
import time
import urllib.error
import urllib.request


def existing_tags(repository):
    url = f'https://hub.docker.com/v2/repositories/{repository}/tags?page_size=100'
    tags = set()
    while url:
        try:
            with urllib.request.urlopen(url, timeout=30) as response:
                data = json.load(response)
        except urllib.error.HTTPError as exc:
            if exc.code == 404:
                return tags
            raise
        tags.update(item['name'] for item in data['results'])
        url = data.get('next')
    return tags


def build(entry, args):
    image = entry['image']
    name = image.rsplit(':', 1)[-1]
    state = args.log_dir / f'{name}.json'
    if not args.force and state.exists() and json.loads(state.read_text()).get('ok'):
        return dict(image=image,ok=True,skipped=True)
    context = args.task_data_dir / entry['task_id'] / 'environment'
    assert (context / 'Dockerfile').is_file(), str(context)
    log = args.log_dir / f'{name}.log'
    metadata = args.log_dir / f'{name}.metadata.json'
    command = ['docker','buildx','build','--platform',args.platform,'--provenance=false','--push','--metadata-file',str(metadata),'-t',image]
    if args.builder:
        command += ['--builder',args.builder]
    command.append(str(context))
    start = time.monotonic()
    try:
        with log.open('w') as output:
            proc = subprocess.run(command,stdout=output,stderr=subprocess.STDOUT,timeout=args.timeout)
        result = dict(image=image,task_id=entry['task_id'],ok=proc.returncode==0,exit_code=proc.returncode,seconds=round(time.monotonic()-start,2))
        if result['ok']:
            result['digest'] = json.loads(metadata.read_text())['containerimage.digest']
    except subprocess.TimeoutExpired:
        result = dict(image=image,task_id=entry['task_id'],ok=False,error='build timeout')
    state.write_text(json.dumps(result,indent=2)+'\n')
    return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--task-data-dir',required=True,type=Path)
    parser.add_argument('--manifest',default=Path('task-manifest.json'),type=Path)
    parser.add_argument('--log-dir',default=Path('image-build-logs'),type=Path)
    parser.add_argument('--workers',default=8,type=int)
    parser.add_argument('--timeout',default=900,type=int)
    parser.add_argument('--platform',default='linux/amd64')
    parser.add_argument('--builder')
    parser.add_argument('--max-images',type=int)
    parser.add_argument('--force',action='store_true')
    args = parser.parse_args()
    args.log_dir.mkdir(parents=True,exist_ok=True)
    entries = list({r['image']:r for r in json.loads(args.manifest.read_text()) if '@sha256:' not in r['image']}.values())
    if not args.force:
        repos = {r['image'].rsplit(':',1)[0] for r in entries}
        published = {f'{repo}:{tag}' for repo in repos for tag in existing_tags(repo)}
        entries = [r for r in entries if r['image'] not in published]
    if args.max_images is not None:
        entries = entries[:args.max_images]
    print(f'{len(entries)} missing image(s) to build',flush=True)
    failures = 0
    with ThreadPoolExecutor(max_workers=args.workers) as pool:
        for future in as_completed([pool.submit(build,entry,args) for entry in entries]):
            result = future.result()
            failures += not result['ok']
            print(json.dumps(result),flush=True)
    print(f'Complete: {failures} failed build(s); rerun to retry.',flush=True)
    raise SystemExit(bool(failures))