summaryrefslogtreecommitdiff
path: root/morphlib/plugins/build_plugin.py
blob: 8da66358ccd6139955797e84a1164d3cdd8b27f8 (plain)
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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# Copyright (C) 2012-2015  Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.


import collections
import contextlib
import uuid
import logging

import cliapp

import morphlib


class ComponentNotInSystemError(morphlib.Error):

    def __init__(self, components, system):
        components = ', '.join(components)
        self.msg = ('Components %s are not in %s. Ensure you provided '
                    'component names rather than filenames.'
                    % (components, system))


class BuildPlugin(cliapp.Plugin):

    def enable(self):
        self.app.add_subcommand('build-morphology', self.build_morphology,
                                arg_synopsis='REPO REF FILENAME '
                                             '[COMPONENT...]')
        self.app.add_subcommand('build', self.build,
                                arg_synopsis='SYSTEM [COMPONENT...]')
        self.app.add_subcommand('distbuild-morphology',
                                self.distbuild_morphology,
                                arg_synopsis='REPO REF FILENAME '
                                             '[COMPONENT...]')
        self.app.add_subcommand('distbuild', self.distbuild,
                                arg_synopsis='SYSTEM [COMPONENT...]')
        self.app.add_subcommand('distbuild-start', self.distbuild_start,
                                arg_synopsis='SYSTEM [COMPONENT...]')
        self.use_distbuild = False
        self.allow_detach = False

    def disable(self):
        self.use_distbuild = False
        self.allow_detach = False

    def distbuild_morphology(self, args):
        '''Distbuild a system, outside of a system branch.

        Command line arguments:

        * `REPO` is a git repository URL.
        * `REF` is a branch or other commit reference in that repository.
        * `FILENAME` is a morphology filename at that ref.
        * `COMPONENT...` is the names of one or more chunks or strata to
          build. If none are given the the system at FILENAME is built.

        See 'help distbuild' and 'help build-morphology' for more information.

        '''

        addr = self.app.settings['controller-initiator-address']
        port = self.app.settings['controller-initiator-port']

        self.use_distbuild = True
        build_command = morphlib.buildcommand.InitiatorBuildCommand(
            self.app, addr, port)
        repo, ref, filename = args[0:3]
        filename = morphlib.util.sanitise_morphology_path(filename)
        component_names = [morphlib.util.sanitise_morphology_path(name)
                               for name in args[3:]]
        self.start_build(repo, ref, build_command, filename,
                         component_names)

    def distbuild(self, args):
        '''Distbuild a system image in the current system branch

        Command line arguments:

        * `SYSTEM` is the name of the system to build.
        * `COMPONENT...` is the names of one or more chunks or strata to
          build. If none are given then SYSTEM is built.

        This command launches a distributed build, to use this command
        you must first set up a distbuild cluster.

        Artifacts produced during the build will be stored on your trove.

        Once the build completes you can use morph deploy to the deploy
        your system, the system artifact will be copied from your trove
        and cached locally.

        Log information can be found in the current working directory, in
        directories called build-xx.

        If you do not have a persistent connection to the server on which
        the distbuild runs, consider using `morph distbuild-start` instead.

        Example:

            morph distbuild devel-system-x86_64-generic.morph

        '''

        self.use_distbuild = True
        self.build(args)

    def distbuild_start(self, args):
        '''Distbuild a system image without a lasting client-server connection.

        This command launches a distributed build, and disconnects from the
        distbuild cluster once the build starts, leaving the build running
        remotely.

        The command will return a build-ID which can be used to cancel the
        distbuild via `morph distbuild-cancel`. Builds started in this manner
        can be found via `morph distbuild-list-jobs`

        See `morph help distbuild` for more information and example usage.

        '''

        self.use_distbuild = True
        self.allow_detach = True
        self.build(args)

    def build_morphology(self, args):
        '''Build a system, outside of a system branch.

        Command line arguments:

        * `REPO` is a git repository URL.
        * `REF` is a branch or other commit reference in that repository.
        * `FILENAME` is a morphology filename at that ref.
        * `COMPONENT...` is the names of one or more chunks or strata to
          build. If none are given then the system at FILENAME is built.

        You probably want `morph build` instead. However, in some
        cases it is more convenient to not have to create a Morph
        workspace and check out the relevant system branch, and only
        just run the build. For those times, this command exists.

        This subcommand does not automatically commit changes to a
        temporary branch, so you can only build from properly committed
        sources that have been pushed to the git server.

        Example:

            morph build-morphology baserock:baserock/definitions \\
                master systems/devel-system-x86_64-generic.morph

        Partial build example:

            morph build-morphology baserock:baserock/definitions \\
                master systems/devel-system-x86_64-generic.morph \\
                build-essential

        '''

        # Raise an exception if there is not enough space
        morphlib.util.check_disk_available(
            self.app.settings['tempdir'],
            self.app.settings['tempdir-min-space'],
            self.app.settings['cachedir'],
            self.app.settings['cachedir-min-space'])

        build_command = morphlib.buildcommand.BuildCommand(self.app)
        repo, ref, filename = args[0:3]
        filename = morphlib.util.sanitise_morphology_path(filename)
        component_names = [morphlib.util.sanitise_morphology_path(name)
                               for name in args[3:]]
        self.start_build(repo, ref, build_command, filename,
                         component_names)

    def build(self, args):
        '''Build a system image in the current system branch

        Command line arguments:

        * `SYSTEM` is the filename of the system to build.
        * `COMPONENT...` is the names of one or more chunks or strata to
          build. If this is not given then the SYSTEM is built.

        This builds a system image, and any of its components that
        need building.  The system name is the basename of the system
        morphology, in the root repository of the current system branch,
        without the `.morph` suffix in the filename.

        The location of the resulting system image artifact is printed
        at the end of the build output.

        If the 'local-changes' setting is set to 'include', you do not need
        to commit your changes before building. Morph does that for you, in a
        temporary branch for each build. Note that any system produced this way
        will not be reproducible later on as the branch it is built from will
        have been deleted. Also note that Morph does not add untracked files to
        the temporary branch, only uncommitted changes to files git already
        knows about. You need to `git add` and commit each new file yourself.

        Example:

            morph build systems/devel-system-x86_64-generic.morph

        Partial build example:

            morph build systems/devel-system-x86_64-generic.morph \\
                build-essential

        '''
        if not self.use_distbuild:
            # Raise an exception if there is not enough space
            morphlib.util.check_disk_available(
                self.app.settings['tempdir'],
                self.app.settings['tempdir-min-space'],
                self.app.settings['cachedir'],
                self.app.settings['cachedir-min-space'])

        ws = morphlib.workspace.open('.')
        sb = morphlib.sysbranchdir.open_from_within('.')

        system_filename = morphlib.util.sanitise_morphology_path(args[0])
        system_filename = sb.relative_to_root_repo(system_filename)
        component_names = args[1:]

        logging.debug('System branch is %s' % sb.root_directory)

        if self.use_distbuild:
            addr = self.app.settings['controller-initiator-address']
            port = self.app.settings['controller-initiator-port']

            build_command = morphlib.buildcommand.InitiatorBuildCommand(
                self.app, addr, port, self.allow_detach)
        else:
            build_command = morphlib.buildcommand.BuildCommand(self.app)

        if self.app.settings['local-changes'] == 'include':
            self._build_with_local_changes(build_command, sb, system_filename,
                                           component_names)
        else:
            self._build_local_commit(build_command, sb, system_filename,
                                     component_names)

    def _build_with_local_changes(self, build_command, sb, system_filename,
                                  component_names):
        '''Construct a branch including user's local changes, and build that.

        It is often a slow process to check all repos in the system branch for
        local changes. However, when using a distributed build cluster, all
        code being built must be pushed to the associated Trove, and it can be
        helpful to have this automated as part of the `morph build` command.

        '''
        build_uuid = uuid.uuid4().hex

        loader = morphlib.morphloader.MorphologyLoader()
        push = self.app.settings['push-build-branches']
        name = morphlib.git.get_user_name(self.app.runcmd)
        email = morphlib.git.get_user_email(self.app.runcmd)
        build_ref_prefix = self.app.settings['build-ref-prefix']

        self.app.status(msg='Looking for uncommitted changes (pass '
                            '--local-changes=ignore to skip)')

        self.app.status(msg='Collecting morphologies involved in '
                            'building %(system)s from %(branch)s',
                            chatty=True,
                            system=system_filename,
                            branch=sb.system_branch_name)

        bb = morphlib.buildbranch.BuildBranch(sb, build_ref_prefix)
        pbb = morphlib.buildbranch.pushed_build_branch(
                bb, loader=loader, changes_need_pushing=push,
                name=name, email=email, build_uuid=build_uuid,
                status=self.app.status)
        with pbb as (repo, commit, original_ref):
            self.start_build(repo, commit, build_command, system_filename,
                             component_names, original_ref=original_ref)

    def _build_local_commit(self, build_command, sb, system_filename,
                            component_names):
        '''Build whatever commit the user has checked-out locally.

        This ignores any uncommitted changes. Also, if the user has a commit
        checked out locally that hasn't been pushed to the Trove that Morph is
        configured to work with, the build will fail in this sort of way:

            ERROR: Ref c55b853d92a52a5b5fe62edbfbf351169eb79c0a is an invalid
            reference for repo
            git://git.baserock.org/baserock/baserock/definitions

        The build process doesn't use the checked-out definitions repo at all,
        except to resolve the checked-out commit (HEAD). Instead, it uses the
        cached version of the definitions repo, updating the cache if
        necessary.

        We don't detect and warn the user about any uncommitted changes because
        doing so is slow when there are no changes (around 5 seconds on my
        machine for Baserock's definitions.git).

        '''
        root_repo_url = sb.get_config('branch.root')
        ref = sb.get_config('branch.name')

        definitions_repo_path = sb.get_git_directory_name(root_repo_url)
        definitions_repo = morphlib.gitdir.GitDirectory(definitions_repo_path)
        commit = definitions_repo.resolve_ref_to_commit(ref)

        self.start_build(root_repo_url, commit, build_command,
                         system_filename, component_names, original_ref=ref)

    def _find_artifacts(self, names, root_artifact):
        found = collections.OrderedDict()
        not_found = names
        for a in root_artifact.walk():
            name = a.source.morphology['name']
            if name in names and name not in found:
                found[name] = a
                not_found.remove(name)
        return found, not_found

    def start_build(self, repo, commit, bc, system_filename,
                    component_names, original_ref=None):
        '''Actually run the build.

        If a set of components was given, only build those. Otherwise,
        build the whole system.

        '''
        if self.use_distbuild:
            bc.build(repo, commit, system_filename,
                     original_ref=original_ref,
                     component_names=component_names)
            return

        self.app.status(msg='Deciding on task order')
        srcpool = bc.create_source_pool(repo, commit, system_filename,
                                        original_ref)
        bc.validate_sources(srcpool)
        root = bc.resolve_artifacts(srcpool)
        if not component_names:
            component_names = [root.source.name]
        components, not_found = self._find_artifacts(component_names, root)
        if not_found:
            raise ComponentNotInSystemError(not_found, system_filename)

        for name, component in components.iteritems():
            component.build_env = root.build_env
            bc.build_in_order(component)
            self.app.status(msg='%(kind)s %(name)s is cached at %(path)s',
                            kind=component.source.morphology['kind'],
                            name=name,
                            path=bc.lac.artifact_filename(component))