blob: da77bc9db3ef641b1812b58988a0a79adfcbeba9 [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
Chris McDonald771446e2021-08-05 14:23:08 -060010import logging
David Rochberg7c79a812011-01-19 14:24:45 -050011import os
Gilad Arnoldabb352e2012-09-23 01:24:27 -070012import subprocess
13import tempfile
14
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070015import portage # pylint: disable=import-error
16import cherrypy # pylint: disable=import-error
David Rochberg7c79a812011-01-19 14:24:45 -050017
Gilad Arnoldabb352e2012-09-23 01:24:27 -070018
Bertrand SIMONNET0d138162015-04-30 17:25:15 -070019# Relative path to the wrapper directory inside the sysroot.
20_SYSROOT_BUILD_BIN = 'build/bin'
21
22
23def _SysrootCmd(sysroot, cmd):
24 """Path to the sysroot wrapper for |cmd|.
25
26 Args:
27 sysroot: Path to the sysroot.
28 cmd: Name of the command.
29 """
30 return os.path.join(sysroot, _SYSROOT_BUILD_BIN, cmd)
31
32
Gilad Arnoldc65330c2012-09-20 15:17:48 -070033# Module-local log function.
Chris Sosa6a3697f2013-01-29 16:44:43 -080034def _Log(message, *args):
Amin Hassani3587fb32021-04-28 10:10:01 -070035 return logging.info(message, *args)
David Rochberg7c79a812011-01-19 14:24:45 -050036
37
38def _OutputOf(command):
39 """Runs command, a list of arguments beginning with an executable.
40
David Rochberg7c79a812011-01-19 14:24:45 -050041 Args:
42 command: A list of arguments, beginning with the executable
Gilad Arnold77c51612015-06-05 15:48:29 -070043
David Rochberg7c79a812011-01-19 14:24:45 -050044 Returns:
45 The output of the command
Gilad Arnold77c51612015-06-05 15:48:29 -070046
David Rochberg7c79a812011-01-19 14:24:45 -050047 Raises:
48 subprocess.CalledProcessError if the command fails
49 """
David Rochberg7c79a812011-01-19 14:24:45 -050050 command_name = ' '.join(command)
Gilad Arnoldc65330c2012-09-20 15:17:48 -070051 _Log('Executing: ' + command_name)
David Rochberg7c79a812011-01-19 14:24:45 -050052
53 p = subprocess.Popen(command, stdout=subprocess.PIPE)
54 output_blob = p.communicate()[0]
55 if p.returncode != 0:
56 raise subprocess.CalledProcessError(p.returncode, command_name)
57 return output_blob
58
59
David Jamesed079b12011-05-17 14:53:15 -070060def _FilterInstallMaskFromPackage(in_path, out_path):
61 """Filter files matching DEFAULT_INSTALL_MASK out of a tarball.
62
63 Args:
64 in_path: Unfiltered tarball.
65 out_path: Location to write filtered tarball.
66 """
67
68 # Grab metadata about package in xpak format.
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070069 my_xpak = portage.xpak.xpak_mem(portage.xpak.tbz2(in_path).get_data())
David Jamesed079b12011-05-17 14:53:15 -070070
71 # Build list of files to exclude. The tar command uses a slightly
72 # different exclude format than gmerge, so it needs to be adjusted
73 # appropriately.
Mike Frysinger441bb522018-01-29 03:11:36 -050074 masks = os.environ.get('DEFAULT_INSTALL_MASK', '').split()
Yusuke Satoe88ee542012-08-28 13:39:48 -070075 # Look for complete paths matching the specified pattern. Leading slashes
76 # are removed so that the paths are relative. Trailing slashes are removed
77 # so that we delete the directory itself when the '/usr/include/' path is
78 # given.
79 masks = [mask.strip('/') for mask in masks]
John Sheua62216e2013-03-04 20:25:18 -080080 masks = ['--exclude="./%s"' % mask for mask in masks]
81 excludes = '--anchored ' + ' '.join(masks)
David Jamesed079b12011-05-17 14:53:15 -070082
83 gmerge_dir = os.path.dirname(out_path)
84 subprocess.check_call(['mkdir', '-p', gmerge_dir])
85
86 tmpd = tempfile.mkdtemp()
87 try:
88 # Extract package to temporary directory (excluding masked files).
Mike Frysinger32642ea2022-04-15 23:41:01 -040089 cmd = 'lbzip2 -dc %s | sudo tar -x -C %s %s --wildcards'
David Jamesed079b12011-05-17 14:53:15 -070090 subprocess.check_call(cmd % (in_path, tmpd, excludes), shell=True)
91
92 # Build filtered version of package.
Mike Frysinger32642ea2022-04-15 23:41:01 -040093 cmd = 'sudo tar -c --use-compress-program=lbzip2 -C %s . > %s'
David Jamesed079b12011-05-17 14:53:15 -070094 subprocess.check_call(cmd % (tmpd, out_path), shell=True)
95 finally:
96 subprocess.check_call(['sudo', 'rm', '-rf', tmpd])
97
98 # Copy package metadata over to new package file.
Achuith Bhandarkar662fb722019-10-31 16:12:49 -070099 portage.xpak.tbz2(out_path).recompose_mem(my_xpak)
David Jamesed079b12011-05-17 14:53:15 -0700100
101
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700102def UpdateGmergeBinhost(sysroot, pkgs, deep):
103 """Add packages to our gmerge-specific binhost.
David Jamesed079b12011-05-17 14:53:15 -0700104
105 Files matching DEFAULT_INSTALL_MASK are not included in the tarball.
106 """
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700107 # Portage internal api expects the sysroot to ends with a '/'.
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700108 sysroot = os.path.join(sysroot, '')
David Jamesed079b12011-05-17 14:53:15 -0700109
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700110 gmerge_pkgdir = os.path.join(sysroot, 'gmerge-packages')
111 stripped_link = os.path.join(sysroot, 'stripped-packages')
David Jamesed079b12011-05-17 14:53:15 -0700112
113 # Create gmerge pkgdir and give us permission to write to it.
114 subprocess.check_call(['sudo', 'mkdir', '-p', gmerge_pkgdir])
Ryan Cui0af7a912012-06-18 18:00:47 -0700115 subprocess.check_call(['sudo', 'ln', '-snf', os.path.basename(gmerge_pkgdir),
116 stripped_link])
117
David Jamesed079b12011-05-17 14:53:15 -0700118 username = os.environ['PORTAGE_USERNAME']
119 subprocess.check_call(['sudo', 'chown', username, gmerge_pkgdir])
120
121 # Load databases.
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700122 trees = portage.create_trees(config_root=sysroot, target_root=sysroot)
123 vardb = trees[sysroot]['vartree'].dbapi
124 bintree = trees[sysroot]['bintree']
David Jamesed079b12011-05-17 14:53:15 -0700125 bintree.populate()
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700126 gmerge_tree = portage.dbapi.bintree.binarytree(sysroot, gmerge_pkgdir,
127 settings=bintree.settings)
David Jamesed079b12011-05-17 14:53:15 -0700128 gmerge_tree.populate()
129
Mike Frysinger441bb522018-01-29 03:11:36 -0500130 # The portage API here is subtle. Results from these lookups are a pkg_str
131 # object which derive from Python strings but attach some extra metadata
132 # (like package file sizes and build times). Helpers like __cmp__ aren't
133 # changed, so the set logic can works. But if you use a pkg_str from one
134 # bintree in another, it can fail to resolve, while stripping off the extra
135 # metadata allows the bintree to do the resolution internally. Hence we
136 # normalize all results here to strings.
137 strmatches = lambda matches: set(str(x) for x in matches)
David James3556d222011-05-20 15:58:41 -0700138 if deep:
139 # If we're in deep mode, fill in the binhost completely.
Mike Frysinger441bb522018-01-29 03:11:36 -0500140 gmerge_matches = strmatches(gmerge_tree.dbapi.cpv_all())
141 bindb_matches = strmatches(bintree.dbapi.cpv_all())
142 installed_matches = strmatches(vardb.cpv_all()) & bindb_matches
David James3556d222011-05-20 15:58:41 -0700143 else:
144 # Otherwise, just fill in the requested package.
Mike Frysinger441bb522018-01-29 03:11:36 -0500145 gmerge_matches = set()
146 bindb_matches = set()
147 installed_matches = set()
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700148 for pkg in pkgs:
Mike Frysinger441bb522018-01-29 03:11:36 -0500149 gmerge_matches.update(strmatches(gmerge_tree.dbapi.match(pkg)))
150 bindb_matches.update(strmatches(bintree.dbapi.match(pkg)))
151 installed_matches.update(strmatches(vardb.match(pkg)) & bindb_matches)
David Jamesed079b12011-05-17 14:53:15 -0700152
153 # Remove any stale packages that exist in the local binhost but are not
154 # installed anymore.
155 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700156 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700157
158 # Remove any stale packages that exist in the gmerge binhost but are not
159 # installed anymore.
160 changed = False
161 for pkg in gmerge_matches - installed_matches:
162 gmerge_path = gmerge_tree.getname(pkg)
163 if os.path.exists(gmerge_path):
164 os.unlink(gmerge_path)
165 changed = True
166
167 # Copy any installed packages that have been rebuilt to the gmerge binhost.
168 for pkg in installed_matches:
169 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
170 build_path = bintree.getname(pkg)
171 gmerge_path = gmerge_tree.getname(pkg)
172
173 # If a package exists in the gmerge binhost with the same build time,
174 # don't rebuild it.
175 if pkg in gmerge_matches and os.path.exists(gmerge_path):
176 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
177 if old_build_time == build_time:
178 continue
179
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700180 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700181 _FilterInstallMaskFromPackage(build_path, gmerge_path)
182 changed = True
183
184 # If the gmerge binhost was changed, update the Packages file to match.
185 if changed:
186 env_copy = os.environ.copy()
187 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700188 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700189 subprocess.check_call(cmd, env=env_copy)
190
191 return bool(installed_matches)
192
193
David Rochberg7c79a812011-01-19 14:24:45 -0500194class Builder(object):
195 """Builds packages for the devserver."""
196
197 def _ShouldBeWorkedOn(self, board, pkg):
198 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800199 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500200 return False
201
202 # If it's in the list of possible workon targets, we should be working on it
203 return pkg in _OutputOf([
Mattias Nissler8d2c82c2017-08-15 14:59:52 +0200204 'cros_workon', '--board=' + board, '--all', 'list'])
David Rochberg7c79a812011-01-19 14:24:45 -0500205
206 def SetError(self, text):
207 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700208 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500209 return text
210
211 def Build(self, board, pkg, additional_args):
212 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700213 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500214
Chris Sosadda923d2011-04-13 13:12:01 -0700215 def _AppendStrToEnvVar(env, var, additional_string):
216 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700217 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700218
219 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500220 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700221 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
222
223 if 'features' in additional_args:
224 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500225
226 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800227 if (not additional_args.get('accept_stable')
228 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500229 return self.SetError(
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700230 "Package is not cros_workon'd on the devserver machine.\n"
David Rochberg7c79a812011-01-19 14:24:45 -0500231 'Either start working on the package or pass --accept_stable '
232 'to gmerge')
233
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700234 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700235 # If user did not supply -n, we want to rebuild the package.
236 usepkg = additional_args.get('usepkg')
237 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700238 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700239 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700240 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700241 if rc != 0:
242 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500243
David Jamesed079b12011-05-17 14:53:15 -0700244 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700245 deep = additional_args.get('deep')
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700246 if not UpdateGmergeBinhost(sysroot, [pkg], deep):
David Jamesed079b12011-05-17 14:53:15 -0700247 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500248
David Rochberg7c79a812011-01-19 14:24:45 -0500249 return 'Success\n'
Chris McDonald82160742020-08-11 15:28:18 -0600250 except OSError as e:
David Rochberg7c79a812011-01-19 14:24:45 -0500251 return self.SetError('Could not execute build command: ' + str(e))