blob: 200cb35923fe2ba54e7e46340f4a315d2b7be735 [file] [log] [blame]
Achuith Bhandarkar662fb722019-10-31 16:12:49 -07001# -*- coding: utf-8 -*-
David Rochberg7c79a812011-01-19 14:24:45 -05002# Copyright (c) 2009-2011 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Package builder for the dev server."""
Gilad Arnoldabb352e2012-09-23 01:24:27 -07007
Gilad Arnold77c51612015-06-05 15:48:29 -07008from __future__ import print_function
9
David Rochberg7c79a812011-01-19 14:24:45 -050010import os
Gilad Arnoldabb352e2012-09-23 01:24:27 -070011import subprocess
12import tempfile
13
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070014import portage # pylint: disable=import-error
15import cherrypy # pylint: disable=import-error
David Rochberg7c79a812011-01-19 14:24:45 -050016
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070017import setup_chromite # pylint: disable=unused-import
18from chromite.lib.xbuddy import cherrypy_log_util
Gilad Arnoldc65330c2012-09-20 15:17:48 -070019
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):
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070037 return cherrypy_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.
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070071 my_xpak = portage.xpak.xpak_mem(portage.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.
Mike Frysinger441bb522018-01-29 03:11:36 -050076 masks = os.environ.get('DEFAULT_INSTALL_MASK', '').split()
Yusuke Satoe88ee542012-08-28 13:39:48 -070077 # 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.
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700102 portage.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()
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700129 gmerge_tree = portage.dbapi.bintree.binarytree(sysroot, gmerge_pkgdir,
130 settings=bintree.settings)
David Jamesed079b12011-05-17 14:53:15 -0700131 gmerge_tree.populate()
132
Mike Frysinger441bb522018-01-29 03:11:36 -0500133 # The portage API here is subtle. Results from these lookups are a pkg_str
134 # object which derive from Python strings but attach some extra metadata
135 # (like package file sizes and build times). Helpers like __cmp__ aren't
136 # changed, so the set logic can works. But if you use a pkg_str from one
137 # bintree in another, it can fail to resolve, while stripping off the extra
138 # metadata allows the bintree to do the resolution internally. Hence we
139 # normalize all results here to strings.
140 strmatches = lambda matches: set(str(x) for x in matches)
David James3556d222011-05-20 15:58:41 -0700141 if deep:
142 # If we're in deep mode, fill in the binhost completely.
Mike Frysinger441bb522018-01-29 03:11:36 -0500143 gmerge_matches = strmatches(gmerge_tree.dbapi.cpv_all())
144 bindb_matches = strmatches(bintree.dbapi.cpv_all())
145 installed_matches = strmatches(vardb.cpv_all()) & bindb_matches
David James3556d222011-05-20 15:58:41 -0700146 else:
147 # Otherwise, just fill in the requested package.
Mike Frysinger441bb522018-01-29 03:11:36 -0500148 gmerge_matches = set()
149 bindb_matches = set()
150 installed_matches = set()
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700151 for pkg in pkgs:
Mike Frysinger441bb522018-01-29 03:11:36 -0500152 gmerge_matches.update(strmatches(gmerge_tree.dbapi.match(pkg)))
153 bindb_matches.update(strmatches(bintree.dbapi.match(pkg)))
154 installed_matches.update(strmatches(vardb.match(pkg)) & bindb_matches)
David Jamesed079b12011-05-17 14:53:15 -0700155
156 # Remove any stale packages that exist in the local binhost but are not
157 # installed anymore.
158 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700159 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700160
161 # Remove any stale packages that exist in the gmerge binhost but are not
162 # installed anymore.
163 changed = False
164 for pkg in gmerge_matches - installed_matches:
165 gmerge_path = gmerge_tree.getname(pkg)
166 if os.path.exists(gmerge_path):
167 os.unlink(gmerge_path)
168 changed = True
169
170 # Copy any installed packages that have been rebuilt to the gmerge binhost.
171 for pkg in installed_matches:
172 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
173 build_path = bintree.getname(pkg)
174 gmerge_path = gmerge_tree.getname(pkg)
175
176 # If a package exists in the gmerge binhost with the same build time,
177 # don't rebuild it.
178 if pkg in gmerge_matches and os.path.exists(gmerge_path):
179 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
180 if old_build_time == build_time:
181 continue
182
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700183 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700184 _FilterInstallMaskFromPackage(build_path, gmerge_path)
185 changed = True
186
187 # If the gmerge binhost was changed, update the Packages file to match.
188 if changed:
189 env_copy = os.environ.copy()
190 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700191 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700192 subprocess.check_call(cmd, env=env_copy)
193
194 return bool(installed_matches)
195
196
David Rochberg7c79a812011-01-19 14:24:45 -0500197class Builder(object):
198 """Builds packages for the devserver."""
199
200 def _ShouldBeWorkedOn(self, board, pkg):
201 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800202 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500203 return False
204
205 # If it's in the list of possible workon targets, we should be working on it
206 return pkg in _OutputOf([
Mattias Nissler8d2c82c2017-08-15 14:59:52 +0200207 'cros_workon', '--board=' + board, '--all', 'list'])
David Rochberg7c79a812011-01-19 14:24:45 -0500208
209 def SetError(self, text):
210 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700211 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500212 return text
213
214 def Build(self, board, pkg, additional_args):
215 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700216 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500217
Chris Sosadda923d2011-04-13 13:12:01 -0700218 def _AppendStrToEnvVar(env, var, additional_string):
219 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700220 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700221
222 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500223 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700224 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
225
226 if 'features' in additional_args:
227 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500228
229 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800230 if (not additional_args.get('accept_stable')
231 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500232 return self.SetError(
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700233 "Package is not cros_workon'd on the devserver machine.\n"
David Rochberg7c79a812011-01-19 14:24:45 -0500234 'Either start working on the package or pass --accept_stable '
235 'to gmerge')
236
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700237 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700238 # If user did not supply -n, we want to rebuild the package.
239 usepkg = additional_args.get('usepkg')
240 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700241 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700242 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700243 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700244 if rc != 0:
245 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500246
David Jamesed079b12011-05-17 14:53:15 -0700247 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700248 deep = additional_args.get('deep')
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700249 if not UpdateGmergeBinhost(sysroot, [pkg], deep):
David Jamesed079b12011-05-17 14:53:15 -0700250 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500251
David Rochberg7c79a812011-01-19 14:24:45 -0500252 return 'Success\n'
Chris McDonald82160742020-08-11 15:28:18 -0600253 except OSError as e:
David Rochberg7c79a812011-01-19 14:24:45 -0500254 return self.SetError('Could not execute build command: ' + str(e))