blob: e37e215fe5bfa16398c9c4ee3e369fa538c50266 [file] [log] [blame]
David Rochberg7c79a812011-01-19 14:24:45 -05001#!/usr/bin/python
2
3# Copyright (c) 2009-2011 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Package builder for the dev server."""
Gilad Arnoldabb352e2012-09-23 01:24:27 -07008
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
45 Returns:
46 The output of the command
47 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.
Yusuke Satoe88ee542012-08-28 13:39:48 -070069 my_xpak = xpak.xpak_mem(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.
Yusuke Satoe88ee542012-08-28 13:39:48 -070074 masks = os.environ['DEFAULT_INSTALL_MASK'].split()
75 # 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.
Yusuke Satoe88ee542012-08-28 13:39:48 -0700100 xpak.tbz2(out_path).recompose_mem(my_xpak)
David Jamesed079b12011-05-17 14:53:15 -0700101
102
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700103def UpdateGmergeBinhost(sysroot, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -0700104 """Add pkg to our gmerge-specific binhost.
105
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()
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700127 gmerge_tree = dbapi.bintree.binarytree(sysroot, gmerge_pkgdir,
David Jamesed079b12011-05-17 14:53:15 -0700128 settings=bintree.settings)
129 gmerge_tree.populate()
130
David James3556d222011-05-20 15:58:41 -0700131 if deep:
132 # If we're in deep mode, fill in the binhost completely.
133 gmerge_matches = set(gmerge_tree.dbapi.cpv_all())
134 bindb_matches = set(bintree.dbapi.cpv_all())
135 installed_matches = set(vardb.cpv_all()) & bindb_matches
136 else:
137 # Otherwise, just fill in the requested package.
138 gmerge_matches = set(gmerge_tree.dbapi.match(pkg))
139 bindb_matches = set(bintree.dbapi.match(pkg))
140 installed_matches = set(vardb.match(pkg)) & bindb_matches
David Jamesed079b12011-05-17 14:53:15 -0700141
142 # Remove any stale packages that exist in the local binhost but are not
143 # installed anymore.
144 if bindb_matches - installed_matches:
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700145 subprocess.check_call([_SysrootCmd(sysroot, 'eclean'), '-d', 'packages'])
David Jamesed079b12011-05-17 14:53:15 -0700146
147 # Remove any stale packages that exist in the gmerge binhost but are not
148 # installed anymore.
149 changed = False
150 for pkg in gmerge_matches - installed_matches:
151 gmerge_path = gmerge_tree.getname(pkg)
152 if os.path.exists(gmerge_path):
153 os.unlink(gmerge_path)
154 changed = True
155
156 # Copy any installed packages that have been rebuilt to the gmerge binhost.
157 for pkg in installed_matches:
158 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
159 build_path = bintree.getname(pkg)
160 gmerge_path = gmerge_tree.getname(pkg)
161
162 # If a package exists in the gmerge binhost with the same build time,
163 # don't rebuild it.
164 if pkg in gmerge_matches and os.path.exists(gmerge_path):
165 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
166 if old_build_time == build_time:
167 continue
168
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700169 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700170 _FilterInstallMaskFromPackage(build_path, gmerge_path)
171 changed = True
172
173 # If the gmerge binhost was changed, update the Packages file to match.
174 if changed:
175 env_copy = os.environ.copy()
176 env_copy['PKGDIR'] = gmerge_pkgdir
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700177 cmd = [_SysrootCmd(sysroot, 'emaint'), '-f', 'binhost']
David Jamesed079b12011-05-17 14:53:15 -0700178 subprocess.check_call(cmd, env=env_copy)
179
180 return bool(installed_matches)
181
182
David Rochberg7c79a812011-01-19 14:24:45 -0500183class Builder(object):
184 """Builds packages for the devserver."""
185
186 def _ShouldBeWorkedOn(self, board, pkg):
187 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800188 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500189 return False
190
191 # If it's in the list of possible workon targets, we should be working on it
192 return pkg in _OutputOf([
David James0bc33fd2011-03-02 13:33:38 -0800193 'cros_workon', '--board=' + board, 'list', '--all'])
David Rochberg7c79a812011-01-19 14:24:45 -0500194
195 def SetError(self, text):
196 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700197 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500198 return text
199
200 def Build(self, board, pkg, additional_args):
201 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700202 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500203
Chris Sosadda923d2011-04-13 13:12:01 -0700204 def _AppendStrToEnvVar(env, var, additional_string):
205 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700206 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700207
208 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500209 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700210 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
211
212 if 'features' in additional_args:
213 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500214
215 try:
Chris Sosaee1e9722013-03-06 11:04:31 -0800216 if (not additional_args.get('accept_stable')
217 and self._ShouldBeWorkedOn(board, pkg)):
David Rochberg7c79a812011-01-19 14:24:45 -0500218 return self.SetError(
219 'Package is not cros_workon\'d on the devserver machine.\n'
220 'Either start working on the package or pass --accept_stable '
221 'to gmerge')
222
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700223 sysroot = '/build/%s/' % board
David Jamesed079b12011-05-17 14:53:15 -0700224 # If user did not supply -n, we want to rebuild the package.
225 usepkg = additional_args.get('usepkg')
226 if not usepkg:
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700227 rc = subprocess.call(
Bertrand SIMONNET0d138162015-04-30 17:25:15 -0700228 [_SysrootCmd(sysroot, 'emerge'), pkg],
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700229 env=env_copy)
David Jamesed079b12011-05-17 14:53:15 -0700230 if rc != 0:
231 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500232
David Jamesed079b12011-05-17 14:53:15 -0700233 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700234 deep = additional_args.get('deep')
Bertrand SIMONNETdface902015-04-29 15:06:54 -0700235 if not UpdateGmergeBinhost(sysroot, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -0700236 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500237
David Rochberg7c79a812011-01-19 14:24:45 -0500238 return 'Success\n'
239 except OSError, e:
240 return self.SetError('Could not execute build command: ' + str(e))