~allanlesage/uci-engine/coverage-extractor

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
#!/usr/bin/env python
# Ubuntu CI Engine
# Copyright 2014 Canonical Ltd.

# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License version 3, as
# published by the Free Software Foundation.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import copy
import datetime
import os
import subprocess
import shutil
import sys

from charmhelpers import (
    core,
    fetch,
)

CHROOT_USER_HOME = '/root'
CHROOT_ROOT_PATH = '/var/cache/pbuilder'


def juju_info(msg, level='INFO'):
    core.hookenv.log(msg, level)


def chroot_exists(path, dist, arch):
    chroot_path = os.path.join(path, '{}-{}'.format(dist, arch))
    return os.path.isdir(chroot_path)


def get_chroot_from_url(path, dist, arch, url):
    if not url:
        return False
    chroot_path = os.path.join(path, '{}-{}'.format(dist, arch))
    wget_path = os.path.join(path, '{}-{}.tgz'.format(dist, arch))
    url_path = '{}/{}-{}.tgz'.format(url, dist, arch)
    try:
        subprocess.check_call(['wget', '-O', wget_path, url_path])
        subprocess.check_call(['tar', '-xzf', wget_path, '-C', path])
    except subprocess.CalledProcessError:
        juju_info('Could not download or extract {}'.format(url_path),
                  'WARNING')
        # Clean up
        try:
            subprocess.check_call(['rm', '-rf', chroot_path])
            subprocess.check_call(['rm', '-rf', wget_path])
        except subprocess.CalledProcessError:
            raise EnvironmentError(
                'Could not cleanup chroot {}'.format(chroot_path))
        return False
    return True


def update_chroot(path, dist, arch):
    chroot_path = os.path.join(path, '{}-{}'.format(dist, arch))
    chroot_env = copy.copy(os.environ)
    chroot_env['DIST'] = dist
    chroot_env['ARCH'] = arch
    chroot_env['HOME'] = CHROOT_USER_HOME
    try:
        start = datetime.datetime.now()
        subprocess.check_call(['cowbuilder', '--update'],
                              env=chroot_env)
        end = datetime.datetime.now()
        juju_info('chroot update: {}'.format(end - start))
    except subprocess.CalledProcessError:
        raise EnvironmentError(
            'Could not update chroot {}'.format(chroot_path))


def create_chroot(path, dist, arch):
    '''Creates a cowbuilder chroot given the dist and arch.'''
    chroot_env = copy.copy(os.environ)
    chroot_env['DIST'] = dist
    chroot_env['ARCH'] = arch
    chroot_env['HOME'] = CHROOT_USER_HOME
    start = datetime.datetime.now()
    juju_info('Attempting: cowbuilder --create for {}-{}'.format(dist, arch))
    try:
        subprocess.check_call(['cowbuilder', '--create',
                               '--distribution', dist,
                               '--architecture', arch,
                               '--debootstrapopts', '--variant=buildd'],
                              env=chroot_env)
        subprocess.check_call(['cowbuilder', '--save',
                               '--execute', '--', '/usr/bin/apt-get',
                               'install', 'eatmydata', 'bzr-builddeb',
                               'software-properties-common', '-yq',
                               '--force-yes'],
                              env=chroot_env)
    except subprocess.CalledProcessError as e:
        raise EnvironmentError(
            'Could not create chroot for {}-{} return: {}'.format(
                dist, arch, e.returncode))
    end = datetime.datetime.now()
    juju_info('chroot create: {}'.format(end - start))


def setup_chroots(config):
    distros = config['distros']
    architectures = config['architectures']
    base_url = config.get('chroot_base_url', '')

    try:
        dist_list = distros.split()
    except:
        juju_info('''Can't determine distros from [{}]'''.format(distros),
                  'ERROR')
        return 1

    try:
        architecture_list = architectures.split()
    except:
        juju_info('''Can't determine architectures from [{}]'''.format(
            architectures), 'ERROR')
        return 1

    for dist in dist_list:
        for arch in architecture_list:
            try:
                if chroot_exists(CHROOT_ROOT_PATH, dist, arch):
                    update_chroot(CHROOT_ROOT_PATH, dist, arch)
                elif get_chroot_from_url(CHROOT_ROOT_PATH, dist, arch,
                                         base_url):
                    update_chroot(CHROOT_ROOT_PATH, dist, arch)
                else:
                    create_chroot(CHROOT_ROOT_PATH, dist, arch)
            except EnvironmentError as e:
                juju_info('{}'.format(e), 'ERROR')
                return 1
    return 0


def setup_dependencies(config):
    required_packages = ['bzr', 'cowbuilder']
    fetch.apt_update()
    juju_info('installing apt packages...')
    fetch.apt_install(required_packages, fatal=True)


def setup_pbuilderrc(config):
    cu2d_dir = '/srv/cu2d'
    if os.path.exists(cu2d_dir):
        subprocess.check_call(['bzr', 'update', cu2d_dir])
    else:
        try:
            subprocess.check_call(['bzr', 'branch',
                                   'lp:cupstream2distro/uci-airline',
                                   cu2d_dir])
        except subprocess.CalledProcessError as e:
            raise EnvironmentError(
                'Could not get cu2d (return: {})'.format(e.returncode))

    shutil.copy(os.path.join(cu2d_dir, 'chroot-tools', '.pbuilderrc'),
                CHROOT_USER_HOME)


def config_changed(config):
    setup_dependencies(config)
    setup_pbuilderrc(config)
    setup_chroots(config)


def main():
    hook = os.path.basename(sys.argv[0])
    juju_info('Running hook: {}'.format(hook))

    hook_py = hook.replace('-', '_')
    funcs = globals()
    if hook_py not in funcs:
        print('Unknown hook: {}'.format(hook))
        return 1

    config = core.hookenv.config()
    juju_info('Config: {}'.format(config))
    try:
        return funcs[hook_py](config)
    except subprocess.CalledProcessError as e:
        juju_info('Error running: {}: {}'.format(e.cmd, e.output))
        return e.returncode


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