blob: a1022805b7ca550eacf01f5bfd50ef3db5d48d41 [file] [log] [blame]
David Rochberg7c79a812011-01-19 14:24:45 -05001# Copyright (c) 2009-2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Package builder for the dev server."""
Gilad Arnoldabb352e2012-09-23 01:24:27 -07006
Gilad Arnold77c51612015-06-05 15:48:29 -07007from __future__ import print_function
8
David Rochberg7c79a812011-01-19 14:24:45 -05009import os
Gilad Arnoldabb352e2012-09-23 01:24:27 -070010import subprocess
11import tempfile
12
David Jamesed079b12011-05-17 14:53:15 -070013from portage import dbapi
14from portage import xpak
Gilad Arnoldc65330c2012-09-20 15:17:48 -070015import cherrypy
David Jamesed079b12011-05-17 14:53:15 -070016import portage
David Rochberg7c79a812011-01-19 14:24:45 -050017
Gilad Arnoldc65330c2012-09-20 15:17:48 -070018import log_util
19
Gilad Arnoldabb352e2012-09-23 01:24:27 -070020
Bertrand SIMONNET0d138162015-04-30 17:25:15 -070021# Relative path to the wrapper directory inside the sysroot.
22_SYSROOT_BUILD_BIN = 'build/bin'
23
24
25def _SysrootCmd(sysroot, cmd):
26 """Path to the sysroot wrapper for |cmd|.
27
28 Args:
29 sysroot: Path to the sysroot.
30 cmd: Name of the command.
31 """
32 return os.path.join(sysroot, _SYSROOT_BUILD_BIN, cmd)
33
34
Gilad Arnoldc65330c2012-09-20 15:17:48 -070035# Module-local log function.
Chris Sosa6a3697f2013-01-29 16:44:43 -080036def _Log(message, *args):
37 return log_util.LogWithTag('BUILD', message, *args)
David Rochberg7c79a812011-01-19 14:24:45 -050038
39
40def _OutputOf(command):
41 """Runs command, a list of arguments beginning with an executable.
42
David Rochberg7c79a812011-01-19 14:24:45 -050043 Args:
44 command: A list of arguments, beginning with the executable
Gilad Arnold77c51612015-06-05 15:48:29 -070045
David Rochberg7c79a812011-01-19 14:24:45 -050046 Returns:
47 The output of the command
Gilad Arnold77c51612015-06-05 15:48:29 -070048
David Rochberg7c79a812011-01-19 14:24:45 -050049 Raises:
50 subprocess.CalledProcessError if the command fails
51 """
David Rochberg7c79a812011-01-19 14:24:45 -050052 command_name = ' '.join(command)
Gilad Arnoldc65330c2012-09-20 15:17:48 -070053 _Log('Executing: ' + command_name)
David Rochberg7c79a812011-01-19 14:24:45 -050054
55 p = subprocess.Popen(command, stdout=subprocess.PIPE)
56 output_blob = p.communicate()[0]
57 if p.returncode != 0:
58 raise subprocess.CalledProcessError(p.returncode, command_name)
59 return output_blob
60
61
David Jamesed079b12011-05-17 14:53:15 -070062def _FilterInstallMaskFromPackage(in_path, out_path):
63 """Filter files matching DEFAULT_INSTALL_MASK out of a tarball.
64
65 Args:
66 in_path: Unfiltered tarball.
67 out_path: Location to write filtered tarball.
68 """
69
70 # Grab metadata about package in xpak format.
Yusuke Satoe88ee542012-08-28 13:39:48 -070071 my_xpak = xpak.xpak_mem(xpak.tbz2(in_path).get_data())
David Jamesed079b12011-05-17 14:53:15 -070072
73 # Build list of files to exclude. The tar command uses a slightly
74 # different exclude format than gmerge, so it needs to be adjusted
75 # appropriately.
Yusuke Satoe88ee542012-08-28 13:39:48 -070076 masks = os.environ['DEFAULT_INSTALL_MASK'].split()
77 # Look for complete paths matching the specified pattern. Leading slashes
78 # are removed so that the paths are relative. Trailing slashes are removed
79 # so that we delete the directory itself when the '/usr/include/' path is
80 # given.
81 masks = [mask.strip('/') for mask in masks]
John Sheua62216e2013-03-04 20:25:18 -080082 masks = ['--exclude="./%s"' % mask for mask in masks]
83 excludes = '--anchored ' + ' '.join(masks)
David Jamesed079b12011-05-17 14:53:15 -070084
85 gmerge_dir = os.path.dirname(out_path)
86 subprocess.check_call(['mkdir', '-p', gmerge_dir])
87
88 tmpd = tempfile.mkdtemp()
89 try:
90 # Extract package to temporary directory (excluding masked files).
91 cmd = ('pbzip2 -dc --ignore-trailing-garbage=1 %s'
92 ' | sudo tar -x -C %s %s --wildcards')
93 subprocess.check_call(cmd % (in_path, tmpd, excludes), shell=True)
94
95 # Build filtered version of package.
96 cmd = 'sudo tar -c --use-compress-program=pbzip2 -C %s . > %s'
97 subprocess.check_call(cmd % (tmpd, out_path), shell=True)
98 finally:
99 subprocess.check_call(['sudo', 'rm', '-rf', tmpd])
100
101 # Copy package metadata over to new package file.
Yusuke Satoe88ee542012-08-28 13:39:48 -0700102 xpak.tbz2(out_path).recompose_mem(my_xpak)
David Jamesed079b12011-05-17 14:53:15 -0700103
104
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700105def UpdateGmergeBinhost(sysroot, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -0700106 """Add pkg to our gmerge-specific binhost.
107
108 Files matching DEFAULT_INSTALL_MASK are not included in the tarball.
109 """
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700110 # Portage internal api expects the sysroot to ends with a '/'.
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700111 sysroot = os.path.join(sysroot, '')
David Jamesed079b12011-05-17 14:53:15 -0700112
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700113 gmerge_pkgdir = os.path.join(sysroot, 'gmerge-packages')
114 stripped_link = os.path.join(sysroot, 'stripped-packages')
David Jamesed079b12011-05-17 14:53:15 -0700115
116 # Create gmerge pkgdir and give us permission to write to it.
117 subprocess.check_call(['sudo', 'mkdir', '-p', gmerge_pkgdir])
Ryan Cui0af7a912012-06-18 18:00:47 -0700118 subprocess.check_call(['sudo', 'ln', '-snf', os.path.basename(gmerge_pkgdir),
119 stripped_link])
120
David Jamesed079b12011-05-17 14:53:15 -0700121 username = os.environ['PORTAGE_USERNAME']
122 subprocess.check_call(['sudo', 'chown', username, gmerge_pkgdir])
123
124 # Load databases.
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700125 trees = portage.create_trees(config_root=sysroot, target_root=sysroot)
126 vardb = trees[sysroot]['vartree'].dbapi
127 bintree = trees[sysroot]['bintree']
David Jamesed079b12011-05-17 14:53:15 -0700128 bintree.populate()
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700129 gmerge_tree = dbapi.bintree.binarytree(sysroot, gmerge_pkgdir,
David Jamesed079b12011-05-17 14:53:15 -0700130 settings=bintree.settings)
131 gmerge_tree.populate()
132
David James3556d222011-05-20 15:58:41 -0700133 if deep:
134 # If we're in deep mode, fill in the binhost completely.
135 gmerge_matches = set(gmerge_tree.dbapi.cpv_all())
136 bindb_matches = set(bintree.dbapi.cpv_all())
137 installed_matches = set(vardb.cpv_all()) & bindb_matches
138 else:
139 # Otherwise, just fill in the requested package.
140 gmerge_matches = set(gmerge_tree.dbapi.match(pkg))
141 bindb_matches = set(bintree.dbapi.match(pkg))
142 installed_matches = set(vardb.match(pkg)) & bindb_matches
David Jamesed079b12011-05-17 14:53:15 -0700143
144 # Remove any stale packages that exist in the local binhost but are not
145 # installed anymore.
146 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700147 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700148
149 # Remove any stale packages that exist in the gmerge binhost but are not
150 # installed anymore.
151 changed = False
152 for pkg in gmerge_matches - installed_matches:
153 gmerge_path = gmerge_tree.getname(pkg)
154 if os.path.exists(gmerge_path):
155 os.unlink(gmerge_path)
156 changed = True
157
158 # Copy any installed packages that have been rebuilt to the gmerge binhost.
159 for pkg in installed_matches:
160 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
161 build_path = bintree.getname(pkg)
162 gmerge_path = gmerge_tree.getname(pkg)
163
164 # If a package exists in the gmerge binhost with the same build time,
165 # don't rebuild it.
166 if pkg in gmerge_matches and os.path.exists(gmerge_path):
167 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
168 if old_build_time == build_time:
169 continue
170
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700171 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700172 _FilterInstallMaskFromPackage(build_path, gmerge_path)
173 changed = True
174
175 # If the gmerge binhost was changed, update the Packages file to match.
176 if changed:
177 env_copy = os.environ.copy()
178 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700179 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700180 subprocess.check_call(cmd, env=env_copy)
181
182 return bool(installed_matches)
183
184
David Rochberg7c79a812011-01-19 14:24:45 -0500185class Builder(object):
186 """Builds packages for the devserver."""
187
188 def _ShouldBeWorkedOn(self, board, pkg):
189 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800190 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500191 return False
192
193 # If it's in the list of possible workon targets, we should be working on it
194 return pkg in _OutputOf([
David James0bc33fd2011-03-02 13:33:38 -0800195 'cros_workon', '--board=' + board, 'list', '--all'])
David Rochberg7c79a812011-01-19 14:24:45 -0500196
197 def SetError(self, text):
198 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700199 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500200 return text
201
202 def Build(self, board, pkg, additional_args):
203 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700204 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500205
Chris Sosadda923d2011-04-13 13:12:01 -0700206 def _AppendStrToEnvVar(env, var, additional_string):
207 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700208 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700209
210 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500211 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700212 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
213
214 if 'features' in additional_args:
215 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500216
217 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800218 if (not additional_args.get('accept_stable')
219 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500220 return self.SetError(
221 'Package is not cros_workon\'d on the devserver machine.\n'
222 'Either start working on the package or pass --accept_stable '
223 'to gmerge')
224
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700225 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700226 # If user did not supply -n, we want to rebuild the package.
227 usepkg = additional_args.get('usepkg')
228 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700229 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700230 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700231 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700232 if rc != 0:
233 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500234
David Jamesed079b12011-05-17 14:53:15 -0700235 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700236 deep = additional_args.get('deep')
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700237 if not UpdateGmergeBinhost(sysroot, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -0700238 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500239
David Rochberg7c79a812011-01-19 14:24:45 -0500240 return 'Success\n'
241 except OSError, e:
242 return self.SetError('Could not execute build command: ' + str(e))