~ubuntu-on-ec2/vmbuilder/automated-ec2-builds-fginther

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
#!/usr/bin/env python
import argparse
import os.path
import sys
import time
from collections import defaultdict
from multiprocessing import Process
from urllib import ContentTooShortError, urlretrieve

from launchpadlib.launchpad import Launchpad
from launchpadlib.credentials import UnencryptedFileCredentialStore
from lazr.restfulclient.errors import NotFound


LIVEFS_OWNER = '~cloud-images-release-managers'


def mangle_ppa_shortcut(shortcut):
    ppa_shortcut = shortcut.split(":")[1]
    user = ppa_shortcut.split("/")[0]
    if (user[0] == "~"):
        user = user[1:]
    ppa_path_objs = ppa_shortcut.split("/")[1:]
    ppa_path = []
    if (len(ppa_path_objs) < 1):
        ppa_path = ['ubuntu', 'ppa']
    elif (len(ppa_path_objs) == 1):
        ppa_path.insert(0, "ubuntu")
        ppa_path.extend(ppa_path_objs)
    else:
        ppa_path = ppa_path_objs
    ppa = "~%s/%s" % (user, "/".join(ppa_path))
    return ppa


def _get_livefs(lp, livefs_name, suite, image_format, project):
    kwargs = {
        'distro_series': '/ubuntu/{}'.format(suite),
        'name': livefs_name,
        'owner': '/{}'.format(LIVEFS_OWNER),
    }
    try:
        return lp.livefses.getByName(**kwargs)
    except NotFound:
        kwargs['metadata'] = {}
        return lp.livefses.new(**kwargs)


def trigger_build(lp, livefs_name, suite, arch, image_format, project,
                  archive=None, proposed=False):
    if archive is None:
        reference = 'ubuntu'
    elif archive.startswith('ppa:'):
        reference = mangle_ppa_shortcut(archive)
    else:
        raise Exception('We only support archives like ppa:person/ppa.')
    archive = lp.archives.getByReference(reference=reference)
    lfs = _get_livefs(lp, livefs_name, suite, image_format, project)
    metadata = {'image_format': image_format, 'project': project}
    build = lfs.requestBuild(
        pocket='Updates' if not proposed else 'Proposed',
        archive=archive,
        distro_arch_series='/ubuntu/{}/{}'.format(suite, arch),
        metadata_override=metadata)
    print "Build queued; track progress at {}".format(build.web_link)
    return build


def _start_download(file_url, target_path):
    def perform_download(file_url, target_path, iteration=0):
        print('Downloading {} to {}...'.format(file_url, target_path))
        try:
            urlretrieve(file_url, target_path)
        except ContentTooShortError:
            if iteration > 4:
                raise
            perform_download(file_url, target_path, iteration=iteration+1)
    p = Process(target=perform_download, args=(file_url, target_path))
    p.start()
    return p


def download(build, target_prefix):
    mapping = {
        '.ext4': '.ext4',
        '.img': '.ext4',
        '.manifest': '.manifest',
        '.tar.gz': '-root.tar.gz',
    }
    file_urls = build.getFileUrls()
    print("{} build completed; the following files were created:\n{}".format(
        build.distro_arch_series.architecture_tag, '\n'.join(file_urls)))
    download_processes = set()
    for file_url in file_urls:
        for suffix in mapping:
            if file_url.endswith(suffix):
                target_path = '{}{}'.format(target_prefix, mapping[suffix])
                download_processes.add(_start_download(file_url, target_path))
    print("Waiting for downloads to complete.")
    for process in download_processes:
        process.join()


def fetch_build_log(build, target_dir):
    target_path = os.path.join(target_dir, 'build_log.txt.gz')
    process = _start_download(build.build_log_url, target_path)
    process.join()


def main(livefs_name, suite, arch, download_directory, image_format, project,
         archive=None, cred_location=None, proposed=False):
    if not os.path.exists(download_directory):
        raise Exception(
            'Download directory {} does not exist.'.format(download_directory))
    if cred_location is None:
        cred_location = os.path.expanduser('~/.lp_creds')
    print "Using creds in {}".format(cred_location)
    credential_store = UnencryptedFileCredentialStore(cred_location)
    lp = Launchpad.login_with('cpc', 'production', version='devel',
                              credential_store=credential_store)
    build = trigger_build(lp, livefs_name, suite, arch, image_format, project,
                          archive=archive, proposed=proposed)
    try:
        previous_buildstate = defaultdict(unicode)
        while build.buildstate != 'Successfully built':
            if build.buildstate != previous_buildstate:
                print '{} build now in "{}" state'.format(
                    arch, build.buildstate)
                previous_buildstate = build.buildstate
            if build.buildstate in ['Cancelled build', 'Failed to build']:
                fetch_build_log(build, download_directory)
                sys.exit(1)
            time.sleep(10)
            build.lp_refresh()
    finally:
        build.lp_refresh()
        if build.can_be_cancelled:
            print 'Scheduling build cancellation...'
            build.cancel()
    fetch_build_log(build, download_directory)
    target_prefix = 'ubuntu-{}-core-cloudimg-{}'.format(suite, arch)
    target_path = os.path.join(download_directory, target_prefix)
    download(build, target_path)
    print("All downloads complete; done!")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Build an Ubuntu Core tarball using Launchpad's buildds.")
    parser.add_argument('--download-directory', default='.',
                        help='The directory to download files to.')
    parser.add_argument('--livefs-name', default='docker-ubuntu-core',
                        help="The name of the livefs to build in.")
    parser.add_argument('--livefs-owner', default=LIVEFS_OWNER,
                        help='The owner of the livefs to build in.')
    parser.add_argument('--suite', required=True, help="The suite to build.")
    parser.add_argument('--arch', required=True, help="The arch to build.")
    parser.add_argument('--archive',
                        help="An (optional) archive to build the image from.")
    parser.add_argument('--image-format', default='plain',
                        help='The image format to build.')
    parser.add_argument('--project', default='ubuntu-core',
                        help='The project to build.')
    parser.add_argument('--cred-location',
                        help='The location of the LP creds.')
    parser.add_argument('--proposed', action='store_true')
    args = parser.parse_args()
    main(args.livefs_name, args.suite, args.arch, args.download_directory,
         args.image_format, args.project, archive=args.archive,
         cred_location=args.cred_location, proposed=args.proposed)