blob: 29d179e6eeec067546a50934ef459ad7649f684a [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)
Mike Frysinger50203cb2022-04-15 23:34:25 -040084 os.makedirs(gmerge_dir, mode=0o755, exist_ok=True)
85
86 with open(in_path, 'rb') as f:
87 data = f.read(3)
88 if data == b'BZh':
89 decomp = 'lbzip2 -dc'
90 else:
91 decomp = 'zstd -dcf'
David Jamesed079b12011-05-17 14:53:15 -070092
93 tmpd = tempfile.mkdtemp()
94 try:
95 # Extract package to temporary directory (excluding masked files).
Mike Frysinger50203cb2022-04-15 23:34:25 -040096 cmd = f'{decomp} %s | sudo tar -x -C %s %s --wildcards'
David Jamesed079b12011-05-17 14:53:15 -070097 subprocess.check_call(cmd % (in_path, tmpd, excludes), shell=True)
98
99 # Build filtered version of package.
Mike Frysinger50203cb2022-04-15 23:34:25 -0400100 cmd = 'sudo tar -c --use-compress-program=zstd -C %s . > %s'
David Jamesed079b12011-05-17 14:53:15 -0700101 subprocess.check_call(cmd % (tmpd, out_path), shell=True)
102 finally:
103 subprocess.check_call(['sudo', 'rm', '-rf', tmpd])
104
105 # Copy package metadata over to new package file.
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700106 portage.xpak.tbz2(out_path).recompose_mem(my_xpak)
David Jamesed079b12011-05-17 14:53:15 -0700107
108
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700109def UpdateGmergeBinhost(sysroot, pkgs, deep):
110 """Add packages to our gmerge-specific binhost.
David Jamesed079b12011-05-17 14:53:15 -0700111
112 Files matching DEFAULT_INSTALL_MASK are not included in the tarball.
113 """
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700114 # Portage internal api expects the sysroot to ends with a '/'.
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700115 sysroot = os.path.join(sysroot, '')
David Jamesed079b12011-05-17 14:53:15 -0700116
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700117 gmerge_pkgdir = os.path.join(sysroot, 'gmerge-packages')
118 stripped_link = os.path.join(sysroot, 'stripped-packages')
David Jamesed079b12011-05-17 14:53:15 -0700119
120 # Create gmerge pkgdir and give us permission to write to it.
121 subprocess.check_call(['sudo', 'mkdir', '-p', gmerge_pkgdir])
Ryan Cui0af7a912012-06-18 18:00:47 -0700122 subprocess.check_call(['sudo', 'ln', '-snf', os.path.basename(gmerge_pkgdir),
123 stripped_link])
124
David Jamesed079b12011-05-17 14:53:15 -0700125 username = os.environ['PORTAGE_USERNAME']
126 subprocess.check_call(['sudo', 'chown', username, gmerge_pkgdir])
127
128 # Load databases.
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700129 trees = portage.create_trees(config_root=sysroot, target_root=sysroot)
130 vardb = trees[sysroot]['vartree'].dbapi
131 bintree = trees[sysroot]['bintree']
David Jamesed079b12011-05-17 14:53:15 -0700132 bintree.populate()
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700133 gmerge_tree = portage.dbapi.bintree.binarytree(sysroot, gmerge_pkgdir,
134 settings=bintree.settings)
David Jamesed079b12011-05-17 14:53:15 -0700135 gmerge_tree.populate()
136
Mike Frysinger441bb522018-01-29 03:11:36 -0500137 # The portage API here is subtle. Results from these lookups are a pkg_str
138 # object which derive from Python strings but attach some extra metadata
139 # (like package file sizes and build times). Helpers like __cmp__ aren't
140 # changed, so the set logic can works. But if you use a pkg_str from one
141 # bintree in another, it can fail to resolve, while stripping off the extra
142 # metadata allows the bintree to do the resolution internally. Hence we
143 # normalize all results here to strings.
144 strmatches = lambda matches: set(str(x) for x in matches)
David James3556d222011-05-20 15:58:41 -0700145 if deep:
146 # If we're in deep mode, fill in the binhost completely.
Mike Frysinger441bb522018-01-29 03:11:36 -0500147 gmerge_matches = strmatches(gmerge_tree.dbapi.cpv_all())
148 bindb_matches = strmatches(bintree.dbapi.cpv_all())
149 installed_matches = strmatches(vardb.cpv_all()) & bindb_matches
David James3556d222011-05-20 15:58:41 -0700150 else:
151 # Otherwise, just fill in the requested package.
Mike Frysinger441bb522018-01-29 03:11:36 -0500152 gmerge_matches = set()
153 bindb_matches = set()
154 installed_matches = set()
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700155 for pkg in pkgs:
Mike Frysinger441bb522018-01-29 03:11:36 -0500156 gmerge_matches.update(strmatches(gmerge_tree.dbapi.match(pkg)))
157 bindb_matches.update(strmatches(bintree.dbapi.match(pkg)))
158 installed_matches.update(strmatches(vardb.match(pkg)) & bindb_matches)
David Jamesed079b12011-05-17 14:53:15 -0700159
160 # Remove any stale packages that exist in the local binhost but are not
161 # installed anymore.
162 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700163 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700164
165 # Remove any stale packages that exist in the gmerge binhost but are not
166 # installed anymore.
167 changed = False
168 for pkg in gmerge_matches - installed_matches:
169 gmerge_path = gmerge_tree.getname(pkg)
170 if os.path.exists(gmerge_path):
171 os.unlink(gmerge_path)
172 changed = True
173
174 # Copy any installed packages that have been rebuilt to the gmerge binhost.
175 for pkg in installed_matches:
176 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
177 build_path = bintree.getname(pkg)
178 gmerge_path = gmerge_tree.getname(pkg)
179
180 # If a package exists in the gmerge binhost with the same build time,
181 # don't rebuild it.
182 if pkg in gmerge_matches and os.path.exists(gmerge_path):
183 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
184 if old_build_time == build_time:
185 continue
186
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700187 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700188 _FilterInstallMaskFromPackage(build_path, gmerge_path)
189 changed = True
190
191 # If the gmerge binhost was changed, update the Packages file to match.
192 if changed:
193 env_copy = os.environ.copy()
194 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700195 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700196 subprocess.check_call(cmd, env=env_copy)
197
198 return bool(installed_matches)
199
200
David Rochberg7c79a812011-01-19 14:24:45 -0500201class Builder(object):
202 """Builds packages for the devserver."""
203
204 def _ShouldBeWorkedOn(self, board, pkg):
205 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800206 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500207 return False
208
209 # If it's in the list of possible workon targets, we should be working on it
210 return pkg in _OutputOf([
Mattias Nissler8d2c82c2017-08-15 14:59:52 +0200211 'cros_workon', '--board=' + board, '--all', 'list'])
David Rochberg7c79a812011-01-19 14:24:45 -0500212
213 def SetError(self, text):
214 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700215 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500216 return text
217
218 def Build(self, board, pkg, additional_args):
219 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700220 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500221
Chris Sosadda923d2011-04-13 13:12:01 -0700222 def _AppendStrToEnvVar(env, var, additional_string):
223 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700224 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700225
226 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500227 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700228 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
229
230 if 'features' in additional_args:
231 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500232
233 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800234 if (not additional_args.get('accept_stable')
235 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500236 return self.SetError(
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700237 "Package is not cros_workon'd on the devserver machine.\n"
David Rochberg7c79a812011-01-19 14:24:45 -0500238 'Either start working on the package or pass --accept_stable '
239 'to gmerge')
240
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700241 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700242 # If user did not supply -n, we want to rebuild the package.
243 usepkg = additional_args.get('usepkg')
244 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700245 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700246 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700247 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700248 if rc != 0:
249 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500250
David Jamesed079b12011-05-17 14:53:15 -0700251 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700252 deep = additional_args.get('deep')
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700253 if not UpdateGmergeBinhost(sysroot, [pkg], deep):
David Jamesed079b12011-05-17 14:53:15 -0700254 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500255
David Rochberg7c79a812011-01-19 14:24:45 -0500256 return 'Success\n'
Chris McDonald82160742020-08-11 15:28:18 -0600257 except OSError as e:
David Rochberg7c79a812011-01-19 14:24:45 -0500258 return self.SetError('Could not execute build command: ' + str(e))