blob: 6b160fd20a3ab64f3e2113bb35b524bfb1486396 [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).
89 cmd = ('pbzip2 -dc --ignore-trailing-garbage=1 %s'
90 ' | sudo tar -x -C %s %s --wildcards')
91 subprocess.check_call(cmd % (in_path, tmpd, excludes), shell=True)
92
93 # Build filtered version of package.
94 cmd = 'sudo tar -c --use-compress-program=pbzip2 -C %s . > %s'
95 subprocess.check_call(cmd % (tmpd, out_path), shell=True)
96 finally:
97 subprocess.check_call(['sudo', 'rm', '-rf', tmpd])
98
99 # Copy package metadata over to new package file.
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700100 portage.xpak.tbz2(out_path).recompose_mem(my_xpak)
David Jamesed079b12011-05-17 14:53:15 -0700101
102
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700103def UpdateGmergeBinhost(sysroot, pkgs, deep):
104 """Add packages to our gmerge-specific binhost.
David Jamesed079b12011-05-17 14:53:15 -0700105
106 Files matching DEFAULT_INSTALL_MASK are not included in the tarball.
107 """
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700108 # Portage internal api expects the sysroot to ends with a '/'.
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700109 sysroot = os.path.join(sysroot, '')
David Jamesed079b12011-05-17 14:53:15 -0700110
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700111 gmerge_pkgdir = os.path.join(sysroot, 'gmerge-packages')
112 stripped_link = os.path.join(sysroot, 'stripped-packages')
David Jamesed079b12011-05-17 14:53:15 -0700113
114 # Create gmerge pkgdir and give us permission to write to it.
115 subprocess.check_call(['sudo', 'mkdir', '-p', gmerge_pkgdir])
Ryan Cui0af7a912012-06-18 18:00:47 -0700116 subprocess.check_call(['sudo', 'ln', '-snf', os.path.basename(gmerge_pkgdir),
117 stripped_link])
118
David Jamesed079b12011-05-17 14:53:15 -0700119 username = os.environ['PORTAGE_USERNAME']
120 subprocess.check_call(['sudo', 'chown', username, gmerge_pkgdir])
121
122 # Load databases.
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700123 trees = portage.create_trees(config_root=sysroot, target_root=sysroot)
124 vardb = trees[sysroot]['vartree'].dbapi
125 bintree = trees[sysroot]['bintree']
David Jamesed079b12011-05-17 14:53:15 -0700126 bintree.populate()
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700127 gmerge_tree = portage.dbapi.bintree.binarytree(sysroot, gmerge_pkgdir,
128 settings=bintree.settings)
David Jamesed079b12011-05-17 14:53:15 -0700129 gmerge_tree.populate()
130
Mike Frysinger441bb522018-01-29 03:11:36 -0500131 # The portage API here is subtle. Results from these lookups are a pkg_str
132 # object which derive from Python strings but attach some extra metadata
133 # (like package file sizes and build times). Helpers like __cmp__ aren't
134 # changed, so the set logic can works. But if you use a pkg_str from one
135 # bintree in another, it can fail to resolve, while stripping off the extra
136 # metadata allows the bintree to do the resolution internally. Hence we
137 # normalize all results here to strings.
138 strmatches = lambda matches: set(str(x) for x in matches)
David James3556d222011-05-20 15:58:41 -0700139 if deep:
140 # If we're in deep mode, fill in the binhost completely.
Mike Frysinger441bb522018-01-29 03:11:36 -0500141 gmerge_matches = strmatches(gmerge_tree.dbapi.cpv_all())
142 bindb_matches = strmatches(bintree.dbapi.cpv_all())
143 installed_matches = strmatches(vardb.cpv_all()) & bindb_matches
David James3556d222011-05-20 15:58:41 -0700144 else:
145 # Otherwise, just fill in the requested package.
Mike Frysinger441bb522018-01-29 03:11:36 -0500146 gmerge_matches = set()
147 bindb_matches = set()
148 installed_matches = set()
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700149 for pkg in pkgs:
Mike Frysinger441bb522018-01-29 03:11:36 -0500150 gmerge_matches.update(strmatches(gmerge_tree.dbapi.match(pkg)))
151 bindb_matches.update(strmatches(bintree.dbapi.match(pkg)))
152 installed_matches.update(strmatches(vardb.match(pkg)) & bindb_matches)
David Jamesed079b12011-05-17 14:53:15 -0700153
154 # Remove any stale packages that exist in the local binhost but are not
155 # installed anymore.
156 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700157 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700158
159 # Remove any stale packages that exist in the gmerge binhost but are not
160 # installed anymore.
161 changed = False
162 for pkg in gmerge_matches - installed_matches:
163 gmerge_path = gmerge_tree.getname(pkg)
164 if os.path.exists(gmerge_path):
165 os.unlink(gmerge_path)
166 changed = True
167
168 # Copy any installed packages that have been rebuilt to the gmerge binhost.
169 for pkg in installed_matches:
170 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
171 build_path = bintree.getname(pkg)
172 gmerge_path = gmerge_tree.getname(pkg)
173
174 # If a package exists in the gmerge binhost with the same build time,
175 # don't rebuild it.
176 if pkg in gmerge_matches and os.path.exists(gmerge_path):
177 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
178 if old_build_time == build_time:
179 continue
180
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700181 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700182 _FilterInstallMaskFromPackage(build_path, gmerge_path)
183 changed = True
184
185 # If the gmerge binhost was changed, update the Packages file to match.
186 if changed:
187 env_copy = os.environ.copy()
188 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700189 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700190 subprocess.check_call(cmd, env=env_copy)
191
192 return bool(installed_matches)
193
194
David Rochberg7c79a812011-01-19 14:24:45 -0500195class Builder(object):
196 """Builds packages for the devserver."""
197
198 def _ShouldBeWorkedOn(self, board, pkg):
199 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800200 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500201 return False
202
203 # If it's in the list of possible workon targets, we should be working on it
204 return pkg in _OutputOf([
Mattias Nissler8d2c82c2017-08-15 14:59:52 +0200205 'cros_workon', '--board=' + board, '--all', 'list'])
David Rochberg7c79a812011-01-19 14:24:45 -0500206
207 def SetError(self, text):
208 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700209 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500210 return text
211
212 def Build(self, board, pkg, additional_args):
213 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700214 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500215
Chris Sosadda923d2011-04-13 13:12:01 -0700216 def _AppendStrToEnvVar(env, var, additional_string):
217 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700218 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700219
220 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500221 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700222 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
223
224 if 'features' in additional_args:
225 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500226
227 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800228 if (not additional_args.get('accept_stable')
229 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500230 return self.SetError(
Achuith Bhandarkar662fb722019-10-31 16:12:49 -0700231 "Package is not cros_workon'd on the devserver machine.\n"
David Rochberg7c79a812011-01-19 14:24:45 -0500232 'Either start working on the package or pass --accept_stable '
233 'to gmerge')
234
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700235 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700236 # If user did not supply -n, we want to rebuild the package.
237 usepkg = additional_args.get('usepkg')
238 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700239 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700240 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700241 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700242 if rc != 0:
243 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500244
David Jamesed079b12011-05-17 14:53:15 -0700245 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700246 deep = additional_args.get('deep')
Gilad Arnold8f0df7f2015-06-05 15:03:08 -0700247 if not UpdateGmergeBinhost(sysroot, [pkg], deep):
David Jamesed079b12011-05-17 14:53:15 -0700248 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500249
David Rochberg7c79a812011-01-19 14:24:45 -0500250 return 'Success\n'
Chris McDonald82160742020-08-11 15:28:18 -0600251 except OSError as e:
David Rochberg7c79a812011-01-19 14:24:45 -0500252 return self.SetError('Could not execute build command: ' + str(e))