blob: 454ac96af4671675058ac1046635eb19ccc145ac [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
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700105def UpdateGmergeBinhost(sysroot, pkgs, deep):
106 """Add packages to our gmerge-specific binhost.
David Jamesed079b12011-05-17 14:53:15 -0700107
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
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700133 gmerge_matches = set()
134 bindb_matches = set()
135 installed_matches = set()
David James3556d222011-05-20 15:58:41 -0700136 if deep:
137 # If we're in deep mode, fill in the binhost completely.
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700138 gmerge_matches.update(gmerge_tree.dbapi.cpv_all())
139 bindb_matches.update(bintree.dbapi.cpv_all())
140 installed_matches.update(set(vardb.cpv_all()) & bindb_matches)
David James3556d222011-05-20 15:58:41 -0700141 else:
142 # Otherwise, just fill in the requested package.
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700143 for pkg in pkgs:
144 gmerge_matches.update(gmerge_tree.dbapi.match(pkg))
145 bindb_matches.update(bintree.dbapi.match(pkg))
146 installed_matches.update(set(vardb.match(pkg)) & bindb_matches)
David Jamesed079b12011-05-17 14:53:15 -0700147
148 # Remove any stale packages that exist in the local binhost but are not
149 # installed anymore.
150 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700151 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700152
153 # Remove any stale packages that exist in the gmerge binhost but are not
154 # installed anymore.
155 changed = False
156 for pkg in gmerge_matches - installed_matches:
157 gmerge_path = gmerge_tree.getname(pkg)
158 if os.path.exists(gmerge_path):
159 os.unlink(gmerge_path)
160 changed = True
161
162 # Copy any installed packages that have been rebuilt to the gmerge binhost.
163 for pkg in installed_matches:
164 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
165 build_path = bintree.getname(pkg)
166 gmerge_path = gmerge_tree.getname(pkg)
167
168 # If a package exists in the gmerge binhost with the same build time,
169 # don't rebuild it.
170 if pkg in gmerge_matches and os.path.exists(gmerge_path):
171 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
172 if old_build_time == build_time:
173 continue
174
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700175 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700176 _FilterInstallMaskFromPackage(build_path, gmerge_path)
177 changed = True
178
179 # If the gmerge binhost was changed, update the Packages file to match.
180 if changed:
181 env_copy = os.environ.copy()
182 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700183 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700184 subprocess.check_call(cmd, env=env_copy)
185
186 return bool(installed_matches)
187
188
David Rochberg7c79a812011-01-19 14:24:45 -0500189class Builder(object):
190 """Builds packages for the devserver."""
191
192 def _ShouldBeWorkedOn(self, board, pkg):
193 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800194 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500195 return False
196
197 # If it's in the list of possible workon targets, we should be working on it
198 return pkg in _OutputOf([
David James0bc33fd2011-03-02 13:33:38 -0800199 'cros_workon', '--board=' + board, 'list', '--all'])
David Rochberg7c79a812011-01-19 14:24:45 -0500200
201 def SetError(self, text):
202 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700203 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500204 return text
205
206 def Build(self, board, pkg, additional_args):
207 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700208 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500209
Chris Sosadda923d2011-04-13 13:12:01 -0700210 def _AppendStrToEnvVar(env, var, additional_string):
211 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700212 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700213
214 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500215 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700216 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
217
218 if 'features' in additional_args:
219 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500220
221 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800222 if (not additional_args.get('accept_stable')
223 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500224 return self.SetError(
225 'Package is not cros_workon\'d on the devserver machine.\n'
226 'Either start working on the package or pass --accept_stable '
227 'to gmerge')
228
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700229 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700230 # If user did not supply -n, we want to rebuild the package.
231 usepkg = additional_args.get('usepkg')
232 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700233 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700234 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700235 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700236 if rc != 0:
237 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500238
David Jamesed079b12011-05-17 14:53:15 -0700239 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700240 deep = additional_args.get('deep')
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700241 if not UpdateGmergeBinhost(sysroot, [pkg], deep):
David Jamesed079b12011-05-17 14:53:15 -0700242 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500243
David Rochberg7c79a812011-01-19 14:24:45 -0500244 return 'Success\n'
245 except OSError, e:
246 return self.SetError('Could not execute build command: ' + str(e))