blob: df93d206f10553dbac2ca7b28d49b817d7227e8d [file] [log] [blame]
David Rochberg7c79a812011-01-19 14:24:45 -05001#!/usr/bin/python
2
3# Copyright (c) 2009-2011 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Package builder for the dev server."""
8import os
David Jamesed079b12011-05-17 14:53:15 -07009from portage import dbapi
10from portage import xpak
11import portage
David Rochberg7c79a812011-01-19 14:24:45 -050012import subprocess
Andrew de los Reyes20666872011-02-17 10:43:07 -080013import sys
David Jamesed079b12011-05-17 14:53:15 -070014import tempfile
David Rochberg7c79a812011-01-19 14:24:45 -050015
16import cherrypy
17
18
19def _OutputOf(command):
20 """Runs command, a list of arguments beginning with an executable.
21
David Rochberg7c79a812011-01-19 14:24:45 -050022 Args:
23 command: A list of arguments, beginning with the executable
24 Returns:
25 The output of the command
26 Raises:
27 subprocess.CalledProcessError if the command fails
28 """
David Rochberg7c79a812011-01-19 14:24:45 -050029 command_name = ' '.join(command)
30 cherrypy.log('Executing: ' + command_name, 'BUILD')
31
32 p = subprocess.Popen(command, stdout=subprocess.PIPE)
33 output_blob = p.communicate()[0]
34 if p.returncode != 0:
35 raise subprocess.CalledProcessError(p.returncode, command_name)
36 return output_blob
37
38
David Jamesed079b12011-05-17 14:53:15 -070039def _FilterInstallMaskFromPackage(in_path, out_path):
40 """Filter files matching DEFAULT_INSTALL_MASK out of a tarball.
41
42 Args:
43 in_path: Unfiltered tarball.
44 out_path: Location to write filtered tarball.
45 """
46
47 # Grab metadata about package in xpak format.
48 x = xpak.xpak_mem(xpak.tbz2(in_path).get_data())
49
50 # Build list of files to exclude. The tar command uses a slightly
51 # different exclude format than gmerge, so it needs to be adjusted
52 # appropriately.
53 #
54 # 1. tar matches against relative paths instead of absolute paths,
55 # so we need to prepend '.' to any paths that don't start with
56 # a wildcard.
57 # 2. tar expects the full filename to match (instead of a prefix),
58 # so we need to append a wildcard to any paths that don't already
59 # end with a wildcard.
60 excludes = []
61 for pattern in os.environ['DEFAULT_INSTALL_MASK'].split():
62 if not pattern.startswith('*'):
63 pattern = '.' + pattern
64 elif not pattern.endswith('*'):
65 pattern = pattern + '*'
66 excludes.append('--exclude="%s"' % pattern)
67 excludes = ' '.join(excludes)
68
69 gmerge_dir = os.path.dirname(out_path)
70 subprocess.check_call(['mkdir', '-p', gmerge_dir])
71
72 tmpd = tempfile.mkdtemp()
73 try:
74 # Extract package to temporary directory (excluding masked files).
75 cmd = ('pbzip2 -dc --ignore-trailing-garbage=1 %s'
76 ' | sudo tar -x -C %s %s --wildcards')
77 subprocess.check_call(cmd % (in_path, tmpd, excludes), shell=True)
78
79 # Build filtered version of package.
80 cmd = 'sudo tar -c --use-compress-program=pbzip2 -C %s . > %s'
81 subprocess.check_call(cmd % (tmpd, out_path), shell=True)
82 finally:
83 subprocess.check_call(['sudo', 'rm', '-rf', tmpd])
84
85 # Copy package metadata over to new package file.
86 xpak.tbz2(out_path).recompose_mem(x)
87
88
David James3556d222011-05-20 15:58:41 -070089def _UpdateGmergeBinhost(board, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -070090 """Add pkg to our gmerge-specific binhost.
91
92 Files matching DEFAULT_INSTALL_MASK are not included in the tarball.
93 """
94
95 root = '/build/%s/' % board
96 pkgdir = '/build/%s/packages' % board
97 gmerge_pkgdir = '/build/%s/gmerge-packages' % board
98
99 # Create gmerge pkgdir and give us permission to write to it.
100 subprocess.check_call(['sudo', 'mkdir', '-p', gmerge_pkgdir])
101 username = os.environ['PORTAGE_USERNAME']
102 subprocess.check_call(['sudo', 'chown', username, gmerge_pkgdir])
103
104 # Load databases.
105 trees = portage.create_trees(config_root=root, target_root=root)
106 vardb = trees[root]['vartree'].dbapi
107 bintree = trees[root]['bintree']
108 bintree.populate()
109 gmerge_tree = dbapi.bintree.binarytree(root, gmerge_pkgdir,
110 settings=bintree.settings)
111 gmerge_tree.populate()
112
David James3556d222011-05-20 15:58:41 -0700113 if deep:
114 # If we're in deep mode, fill in the binhost completely.
115 gmerge_matches = set(gmerge_tree.dbapi.cpv_all())
116 bindb_matches = set(bintree.dbapi.cpv_all())
117 installed_matches = set(vardb.cpv_all()) & bindb_matches
118 else:
119 # Otherwise, just fill in the requested package.
120 gmerge_matches = set(gmerge_tree.dbapi.match(pkg))
121 bindb_matches = set(bintree.dbapi.match(pkg))
122 installed_matches = set(vardb.match(pkg)) & bindb_matches
David Jamesed079b12011-05-17 14:53:15 -0700123
124 # Remove any stale packages that exist in the local binhost but are not
125 # installed anymore.
126 if bindb_matches - installed_matches:
127 subprocess.check_call(['eclean-%s' % board, '-d', 'packages'])
128
129 # Remove any stale packages that exist in the gmerge binhost but are not
130 # installed anymore.
131 changed = False
132 for pkg in gmerge_matches - installed_matches:
133 gmerge_path = gmerge_tree.getname(pkg)
134 if os.path.exists(gmerge_path):
135 os.unlink(gmerge_path)
136 changed = True
137
138 # Copy any installed packages that have been rebuilt to the gmerge binhost.
139 for pkg in installed_matches:
140 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
141 build_path = bintree.getname(pkg)
142 gmerge_path = gmerge_tree.getname(pkg)
143
144 # If a package exists in the gmerge binhost with the same build time,
145 # don't rebuild it.
146 if pkg in gmerge_matches and os.path.exists(gmerge_path):
147 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
148 if old_build_time == build_time:
149 continue
150
David James3556d222011-05-20 15:58:41 -0700151 cherrypy.log('Filtering install mask from %s' % pkg, 'BUILD')
David Jamesed079b12011-05-17 14:53:15 -0700152 _FilterInstallMaskFromPackage(build_path, gmerge_path)
153 changed = True
154
155 # If the gmerge binhost was changed, update the Packages file to match.
156 if changed:
157 env_copy = os.environ.copy()
158 env_copy['PKGDIR'] = gmerge_pkgdir
159 env_copy['ROOT'] = root
160 env_copy['PORTAGE_CONFIGROOT'] = root
161 cmd = ['/usr/lib/portage/bin/emaint', '-f', 'binhost']
162 subprocess.check_call(cmd, env=env_copy)
163
164 return bool(installed_matches)
165
166
David Rochberg7c79a812011-01-19 14:24:45 -0500167class Builder(object):
168 """Builds packages for the devserver."""
169
170 def _ShouldBeWorkedOn(self, board, pkg):
171 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800172 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500173 return False
174
175 # If it's in the list of possible workon targets, we should be working on it
176 return pkg in _OutputOf([
David James0bc33fd2011-03-02 13:33:38 -0800177 'cros_workon', '--board=' + board, 'list', '--all'])
David Rochberg7c79a812011-01-19 14:24:45 -0500178
179 def SetError(self, text):
180 cherrypy.response.status = 500
181 cherrypy.log(text, 'BUILD')
182 return text
183
184 def Build(self, board, pkg, additional_args):
185 """Handles a build request from the cherrypy server."""
Chris Sosadda923d2011-04-13 13:12:01 -0700186 cherrypy.log('Additional build request arguments: ' + str(additional_args),
David Rochberg7c79a812011-01-19 14:24:45 -0500187 'BUILD')
188
Chris Sosadda923d2011-04-13 13:12:01 -0700189 def _AppendStrToEnvVar(env, var, additional_string):
190 env[var] = env.get(var, '') + ' ' + additional_string
191 cherrypy.log('%s flags modified to %s' % (var, env[var]), 'BUILD')
192
193 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500194 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700195 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
196
197 if 'features' in additional_args:
198 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500199
200 try:
201 if (self._ShouldBeWorkedOn(board, pkg) and
202 not additional_args.get('accept_stable')):
203 return self.SetError(
204 'Package is not cros_workon\'d on the devserver machine.\n'
205 'Either start working on the package or pass --accept_stable '
206 'to gmerge')
207
David Jamesed079b12011-05-17 14:53:15 -0700208 # If user did not supply -n, we want to rebuild the package.
209 usepkg = additional_args.get('usepkg')
210 if not usepkg:
211 rc = subprocess.call(['emerge-%s' % board, pkg], env=env_copy)
212 if rc != 0:
213 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500214
David Jamesed079b12011-05-17 14:53:15 -0700215 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700216 deep = additional_args.get('deep')
217 if not _UpdateGmergeBinhost(board, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -0700218 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500219
David Rochberg7c79a812011-01-19 14:24:45 -0500220 return 'Success\n'
221 except OSError, e:
222 return self.SetError('Could not execute build command: ' + str(e))