Add changelog entry with my recent changes
[invirt/packages/invirt-dev.git] / invirtibuilder
1 #!/usr/bin/python
2
3 """Process the Invirt build queue.
4
5 The Invirtibuilder handles package builds and uploads. On demand, it
6 attempts to build a particular package.
7
8 If the build succeeds, the new version of the package is uploaded to
9 the apt repository, tagged in its git repository, and the Invirt
10 superproject is updated to point at the new version.
11
12 If the build fails, the Invirtibuilder sends mail with the build log.
13
14 The build queue is tracked via files in /var/lib/invirt-dev/queue. In
15 order to maintain ordering, all filenames in that directory are the
16 timestamp of their creation time.
17
18 Each queue file contains a file of the form
19
20     pocket package hash principal
21
22 where pocket is one of the pockets globally configured in
23 build.pockets. For instance, the pockets in XVM are "prod" and "dev".
24
25 principal is the Kerberos principal that requested the build.
26 """
27
28
29 from __future__ import with_statement
30
31 import contextlib
32 import glob
33 import os
34 import re
35 import shutil
36 import subprocess
37 import tempfile
38 import traceback
39
40 import pyinotify
41
42 from debian_bundle import deb822
43
44 import invirt.builder as b
45 import invirt.common as c
46 from invirt import database
47 from invirt.config import structs as config
48
49
50 logfile = None
51
52 def logAndRun(cmd, *args, **kwargs):
53     # Always grab stdout, even if the caller doesn't need it.
54     # TODO: don't slurp it all into memory in that case.
55     if 'stdout' in kwargs and kwargs['stdout'] is None:
56         del kwargs['stdout']
57     kwargs['stderr'] = logfile
58     logfile.write('---> Ran %s\n' % (cmd, ))
59     if 'stdin_str' in kwargs:
60         logfile.write('STDIN:\n')
61         logfile.write(kwargs['stdin_str'])
62     logfile.write('STDERR:\n')
63     output = c.captureOutput(cmd, *args, **kwargs)
64     logfile.write('STDOUT:\n')
65     logfile.write(output)
66     return output
67
68 def getControl(package, ref):
69     """Get the parsed debian/control file for a given package.
70
71     This returns a list of debian_bundle.deb822.Deb822 objects, one
72     for each section of the debian/control file. Each Deb822 object
73     acts roughly like a dict.
74     """
75     return deb822.Deb822.iter_paragraphs(
76         b.getGitFile(package, ref, 'debian/control').split('\n'))
77
78
79 def getBinaries(package, ref):
80     """Get a list of binary packages in a package at a given ref."""
81     return [p['Package'] for p in getControl(package, ref)
82             if 'Package' in p]
83
84
85 def getArches(package, ref):
86     """Get the set of all architectures in any binary package."""
87     arches = set()
88     for section in getControl(package, ref):
89         if 'Architecture' in section:
90             arches.update(section['Architecture'].split())
91     return arches
92
93
94 def getDscName(package, ref):
95     """Return the .dsc file that will be generated for this package."""
96     v = b.getVersion(package, ref)
97     if v.debian_version:
98         v_str = '%s-%s' % (v.upstream_version,
99                            v.debian_version)
100     else:
101         v_str = v.upstream_version
102     return '%s_%s.dsc' % (
103         package,
104         v_str)
105
106
107 def sanitizeVersion(version):
108     """Sanitize a Debian package version for use as a git tag.
109
110     This function strips the epoch from the version number and
111     replaces any tildes with underscores."""
112     if version.debian_version:
113         v = '%s-%s' % (version.upstream_version,
114                        version.debian_version)
115     else:
116         v = version.upstream_version
117     return v.replace('~', '_')
118
119
120 def aptCopy(package, commit, dst_pocket, src_pocket):
121     """Copy a package from one pocket to another."""
122     binaries = getBinaries(package, commit)
123     logAndRun(['reprepro-env', 'copy',
124                b.pocketToApt(dst_pocket),
125                b.pocketToApt(src_pocket),
126                package] + binaries)
127
128
129 def sbuild(package, ref, distro, arch, workdir, arch_all=False):
130     """Build a package for a particular architecture and distro."""
131     # We append a suffix like ~ubuntu8.04 to differentiate the same
132     # version built for multiple distros
133     nmutag = b.distroToSuffix(distro)
134     env = os.environ.copy()
135     env['NMUTAG'] = nmutag
136
137     # Run sbuild with a hack in place to append arbitrary versions
138     args = ['perl', '-I/usr/share/invirt-dev', '-MSbuildHack',
139             '/usr/bin/sbuild',
140             '--binNMU=171717', '--make-binNMU=Build with sbuild',
141             '-v', '-d', distro, '--arch', arch]
142     if arch_all:
143         args.append('-A')
144     args.append(getDscName(package, ref))
145     logAndRun(args, cwd=workdir, env=env)
146
147
148 def sbuildAll(package, ref, distro, workdir):
149     """Build a package for all architectures it supports."""
150     arches = getArches(package, ref)
151     if 'all' in arches or 'any' in arches or 'amd64' in arches:
152         sbuild(package, ref, distro, 'amd64', workdir, arch_all=True)
153     if 'any' in arches or 'i386' in arches:
154         sbuild(package, ref, distro, 'i386', workdir)
155
156
157 def tagSubmodule(pocket, package, commit, principal, version, env):
158     """Tag a new version of a submodule.
159
160     If this pocket does not allow_backtracking, then this will create
161     a new tag of the version at ref.
162
163     This function doesn't need to care about lock
164     contention. git-receive-pack updates one ref at a time, and only
165     takes out a lock for that ref after it's passed the update
166     hook. Because we reject pushes to tags in the update hook, no push
167     can ever take out a lock on any tags.
168
169     I'm sure that long description gives you great confidence in the
170     legitimacy of my reasoning.
171     """
172     if not config.build.pockets[pocket].get('allow_backtracking', False):
173         branch = b.pocketToGit(pocket)
174         tag_msg = ('Tag %s of %s\n\n'
175                    'Requested by %s' % (version.full_version,
176                                         package,
177                                         principal))
178
179         logAndRun(
180             ['git', 'tag', '-m', tag_msg, '--', sanitizeVersion(version),
181              commit],
182             env=env,
183             cwd=b.getRepo(package))
184
185
186 def updateSubmoduleBranch(pocket, package, commit):
187     """Update the appropriately named branch in the submodule."""
188     branch = b.pocketToGit(pocket)
189     logAndRun(
190         ['git', 'update-ref', 'refs/heads/%s' % branch, commit], cwd=b.getRepo(package))
191
192
193 def uploadBuild(pocket, workdir):
194     """Upload all build products in the work directory."""
195     force = config.build.pockets[pocket].get('allow_backtracking', False)
196     apt = b.pocketToApt(pocket)
197     for changes in glob.glob(os.path.join(workdir, '*.changes')):
198         upload = ['reprepro-env', '--ignore=wrongdistribution',
199                   'include', apt, changes]
200         try:
201             logAndRun(upload)
202         except subprocess.CalledProcessError, e:
203             if not force:
204                 raise
205             changelog = deb822.Changes(open(changes).read())
206             packages = set(changelog['Binary'].split())
207             packages.add(changelog['Source'])
208             for package in packages:
209                 logAndRun(['reprepro-env', 'remove', apt, package])
210             logAndRun(upload)
211
212
213 def updateSuperproject(pocket, package, commit, principal, version, env):
214     """Update the superproject.
215
216     This will create a new commit on the branch for the given pocket
217     that sets the commit for the package submodule to commit.
218
219     Note that there's no locking issue here, because we disallow all
220     pushes to the superproject.
221     """
222     superproject = os.path.join(b._REPO_DIR, 'invirt/packages.git')
223     branch = b.pocketToGit(pocket)
224     tree = logAndRun(['git', 'ls-tree', branch],
225                      cwd=superproject).strip()
226
227     tree_items = dict((k, v) for (v, k) in (x.split("\t") for x in tree.split("\n")))
228
229     created = not (package in tree_items)
230
231     tree_items[package] = "160000 commit "+commit
232
233     # If "created" is true, we need to check if the package is
234     # mentioned in .gitmodules, and add it if not.
235     if created:
236         gitmodules = logAndRun(['git', 'cat-file', 'blob', '%s:.gitmodules' % (branch)],
237                                cwd=superproject)
238         if ('[submodule "%s"]' % (package)) not in gitmodules.split("\n"):
239             gitmodules += """[submodule "%s"]
240 \tpath = %s
241 \turl = ../packages/%s.git
242 """ % (package, package, package)
243             gitmodules_hash = logAndRun(['git', 'hash-object', '-w', '--stdin'],
244                                         cwd=superproject,
245                                         stdin_str=gitmodules).strip()
246             tree_items[package] = "100644 blob "+gitmodules_hash
247
248     new_tree = "\n".join("%s\t%s" % (v, k) for (k, v) in tree_items.iteritems())
249
250     new_tree_id = logAndRun(['git', 'mktree', '--missing'],
251                             cwd=superproject,
252                             stdin_str=new_tree).strip()
253
254     if created:
255         commit_msg = 'Add %s at version %s'
256     else:
257         commit_msg = 'Update %s to version %s'
258     commit_msg = ((commit_msg + '\n\n'
259                    'Requested by %s') % (package,
260                                          version.full_version,
261                                          principal))
262     new_commit = logAndRun(
263         ['git', 'commit-tree', new_tree_id, '-p', branch],
264         cwd=superproject,
265         env=env,
266         stdin_str=commit_msg).strip()
267
268     logAndRun(
269         ['git', 'update-ref', 'refs/heads/%s' % branch, new_commit],
270         cwd=superproject)
271
272
273 def makeReadable(workdir):
274     os.chmod(workdir, 0755)
275
276 @contextlib.contextmanager
277 def packageWorkdir(package, commit, build_id):
278     """Checkout the package in a temporary working directory.
279
280     This context manager returns that working directory. The requested
281     package is checked out into a subdirectory of the working
282     directory with the same name as the package.
283
284     When the context wrapped with this context manager is exited, the
285     working directory is automatically deleted.
286     """
287     workdir = tempfile.mkdtemp(prefix=("b%d-" % build_id))
288     try:
289         p_archive = subprocess.Popen(
290             ['git', '--git-dir=%s' % (b.getRepo(package),),
291              'archive',
292              '--prefix=%s/' % package,
293              commit,
294              ],
295             stdout=subprocess.PIPE,
296             )
297         p_tar = subprocess.Popen(
298             ['tar', '-x'],
299             stdin=p_archive.stdout,
300             cwd=workdir,
301             )
302         p_archive.wait()
303         p_tar.wait()
304
305         yield workdir
306     finally:
307         shutil.rmtree(workdir)
308
309 def build():
310     """Deal with items in the build queue.
311
312     When triggered, iterate over build queue items one at a time,
313     until there are no more pending build jobs.
314     """
315     global logfile
316
317     while True:
318         stage = 'processing incoming job'
319         queue = os.listdir(b._QUEUE_DIR)
320         if not queue:
321             break
322
323         build = min(queue)
324         job = open(os.path.join(b._QUEUE_DIR, build)).read().strip()
325         pocket, package, commit, principal = job.split()
326
327         database.session.begin()
328         db = database.Build()
329         db.package = package
330         db.pocket = pocket
331         db.commit = commit
332         db.principal = principal
333         database.session.save_or_update(db)
334         database.session.commit()
335
336         database.session.begin()
337
338         logdir = os.path.join(b._LOG_DIR, str(db.build_id))
339         if not os.path.exists(logdir):
340             os.makedirs(logdir)
341
342         try:
343             db.failed_stage = 'validating job'
344             # Don't expand the commit in the DB until we're sure the user
345             # isn't trying to be tricky.
346             b.ensureValidPackage(package)
347
348             logfile = open(os.path.join(logdir, '%s.log' % db.package), 'w')
349
350             db.commit = commit = b.canonicalize_commit(package, commit)
351             src = b.validateBuild(pocket, package, commit)
352             version = b.getVersion(package, commit)
353             db.version = str(version)
354             b.runHook('pre-build', [str(db.build_id)])
355
356             env = dict(os.environ)
357             env['GIT_COMMITTER_NAME'] = config.build.tagger.name
358             env['GIT_COMMITTER_EMAIL'] = config.build.tagger.email
359
360             # If validateBuild returns something other than True, then
361             # it means we should copy from that pocket to our pocket.
362             #
363             # (If the validation failed, validateBuild would have
364             # raised an exception)
365             if src != True:
366                 # TODO: cut out this code duplication
367                 db.failed_stage = 'tagging submodule before copying package'
368                 tagSubmodule(pocket, package, commit, principal, version, env)
369                 db.failed_stage = 'updating submodule branches before copying package'
370                 updateSubmoduleBranch(pocket, package, commit)
371                 db.failed_stage = 'updating superproject before copying package'
372                 updateSuperproject(pocket, package, commit, principal, version, env)
373                 db.failed_stage = 'copying package from another pocket'
374                 aptCopy(package, commit, pocket, src)
375                 
376             # If we can't copy the package from somewhere, but
377             # validateBuild didn't raise an exception, then we need to
378             # do the build ourselves
379             else:
380                 db.failed_stage = 'checking out package source'
381                 with packageWorkdir(package, commit, db.build_id) as workdir:
382                     db.failed_stage = 'preparing source package'
383                     packagedir = os.path.join(workdir, package)
384
385                     # We should be more clever about dealing with
386                     # things like non-Debian-native packages than we
387                     # are.
388                     #
389                     # If we were, we could use debuild and get nice
390                     # environment scrubbing. Since we're not, debuild
391                     # complains about not having an orig.tar.gz
392                     logAndRun(['dpkg-buildpackage', '-us', '-uc', '-S'],
393                               cwd=packagedir)
394
395                     db.failed_stage = 'building binary packages'
396                     sbuildAll(package, commit, b.pocketToDistro(pocket), workdir)
397                     db.failed_stage = 'tagging submodule'
398                     tagSubmodule(pocket, package, commit, principal, version, env)
399                     db.failed_stage = 'updating submodule branches'
400                     updateSubmoduleBranch(pocket, package, commit)
401                     db.failed_stage = 'updating superproject'
402                     updateSuperproject(pocket, package, commit, principal, version, env)
403                     db.failed_stage = 'relaxing permissions on workdir'
404                     makeReadable(workdir)
405                     db.failed_stage = 'uploading packages to apt repo'
406                     uploadBuild(pocket, workdir)
407
408                     db.failed_stage = 'cleaning up'
409         except:
410             db.traceback = traceback.format_exc()
411         else:
412             db.succeeded = True
413             db.failed_stage = None
414         finally:
415             if logfile is not None:
416                 logfile.close()
417
418             database.session.save_or_update(db)
419             database.session.commit()
420
421             # Finally, now that everything is done, remove the
422             # build queue item
423             os.unlink(os.path.join(b._QUEUE_DIR, build))
424
425             if db.succeeded:
426                 b.runHook('post-build', [str(db.build_id)])
427             else:
428                 b.runHook('failed-build', [str(db.build_id)])
429
430 class Invirtibuilder(pyinotify.ProcessEvent):
431     """Process inotify triggers to build new packages."""
432     def process_default(self, event):
433         """Handle an inotify event.
434
435         When an inotify event comes in, trigger the builder.
436         """
437         build()
438
439
440 def main():
441     """Initialize the inotifications and start the main loop."""
442     database.connect()
443
444     watch_manager = pyinotify.WatchManager()
445     invirtibuilder = Invirtibuilder()
446     notifier = pyinotify.Notifier(watch_manager, invirtibuilder)
447     watch_manager.add_watch(b._QUEUE_DIR,
448                             pyinotify.EventsCodes.ALL_FLAGS['IN_CREATE'] |
449                             pyinotify.EventsCodes.ALL_FLAGS['IN_MOVED_TO'])
450
451     # Before inotifying, run any pending builds; otherwise we won't
452     # get notified for them.
453     build()
454
455     while True:
456         notifier.process_events()
457         if notifier.check_events():
458             notifier.read_events()
459
460
461 if __name__ == '__main__':
462     main()