blob: fdfb50f02e2b99379a09efbedb94286f0b415b26 [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."""
8import os
David Jamesed079b12011-05-17 14:53:15 -07009from portage import dbapi
10from portage import xpak
Gilad Arnoldc65330c2012-09-20 15:17:48 -070011import cherrypy
David Jamesed079b12011-05-17 14:53:15 -070012import portage
David Rochberg7c79a812011-01-19 14:24:45 -050013import subprocess
Andrew de los Reyes20666872011-02-17 10:43:07 -080014import sys
David Jamesed079b12011-05-17 14:53:15 -070015import tempfile
David Rochberg7c79a812011-01-19 14:24:45 -050016
Gilad Arnoldc65330c2012-09-20 15:17:48 -070017import log_util
18
19# Module-local log function.
20def _Log(message, *args, **kwargs):
21 return log_util.LogWithTag('BUILD', message, *args, **kwargs)
David Rochberg7c79a812011-01-19 14:24:45 -050022
23
24def _OutputOf(command):
25 """Runs command, a list of arguments beginning with an executable.
26
David Rochberg7c79a812011-01-19 14:24:45 -050027 Args:
28 command: A list of arguments, beginning with the executable
29 Returns:
30 The output of the command
31 Raises:
32 subprocess.CalledProcessError if the command fails
33 """
David Rochberg7c79a812011-01-19 14:24:45 -050034 command_name = ' '.join(command)
Gilad Arnoldc65330c2012-09-20 15:17:48 -070035 _Log('Executing: ' + command_name)
David Rochberg7c79a812011-01-19 14:24:45 -050036
37 p = subprocess.Popen(command, stdout=subprocess.PIPE)
38 output_blob = p.communicate()[0]
39 if p.returncode != 0:
40 raise subprocess.CalledProcessError(p.returncode, command_name)
41 return output_blob
42
43
David Jamesed079b12011-05-17 14:53:15 -070044def _FilterInstallMaskFromPackage(in_path, out_path):
45 """Filter files matching DEFAULT_INSTALL_MASK out of a tarball.
46
47 Args:
48 in_path: Unfiltered tarball.
49 out_path: Location to write filtered tarball.
50 """
51
52 # Grab metadata about package in xpak format.
Yusuke Satoe88ee542012-08-28 13:39:48 -070053 my_xpak = xpak.xpak_mem(xpak.tbz2(in_path).get_data())
David Jamesed079b12011-05-17 14:53:15 -070054
55 # Build list of files to exclude. The tar command uses a slightly
56 # different exclude format than gmerge, so it needs to be adjusted
57 # appropriately.
Yusuke Satoe88ee542012-08-28 13:39:48 -070058 masks = os.environ['DEFAULT_INSTALL_MASK'].split()
59 # Look for complete paths matching the specified pattern. Leading slashes
60 # are removed so that the paths are relative. Trailing slashes are removed
61 # so that we delete the directory itself when the '/usr/include/' path is
62 # given.
63 masks = [mask.strip('/') for mask in masks]
64 masks = ['--exclude="' + mask + '"' for mask in masks]
65 excludes = ' '.join(masks)
David Jamesed079b12011-05-17 14:53:15 -070066
67 gmerge_dir = os.path.dirname(out_path)
68 subprocess.check_call(['mkdir', '-p', gmerge_dir])
69
70 tmpd = tempfile.mkdtemp()
71 try:
72 # Extract package to temporary directory (excluding masked files).
73 cmd = ('pbzip2 -dc --ignore-trailing-garbage=1 %s'
74 ' | sudo tar -x -C %s %s --wildcards')
75 subprocess.check_call(cmd % (in_path, tmpd, excludes), shell=True)
76
77 # Build filtered version of package.
78 cmd = 'sudo tar -c --use-compress-program=pbzip2 -C %s . > %s'
79 subprocess.check_call(cmd % (tmpd, out_path), shell=True)
80 finally:
81 subprocess.check_call(['sudo', 'rm', '-rf', tmpd])
82
83 # Copy package metadata over to new package file.
Yusuke Satoe88ee542012-08-28 13:39:48 -070084 xpak.tbz2(out_path).recompose_mem(my_xpak)
David Jamesed079b12011-05-17 14:53:15 -070085
86
Ryan Cui0af7a912012-06-18 18:00:47 -070087def UpdateGmergeBinhost(board, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -070088 """Add pkg to our gmerge-specific binhost.
89
90 Files matching DEFAULT_INSTALL_MASK are not included in the tarball.
91 """
92
93 root = '/build/%s/' % board
Ryan Cui0af7a912012-06-18 18:00:47 -070094 gmerge_pkgdir = os.path.join(root, 'gmerge-packages')
95 stripped_link = os.path.join(root, 'stripped-packages')
David Jamesed079b12011-05-17 14:53:15 -070096
97 # Create gmerge pkgdir and give us permission to write to it.
98 subprocess.check_call(['sudo', 'mkdir', '-p', gmerge_pkgdir])
Ryan Cui0af7a912012-06-18 18:00:47 -070099 subprocess.check_call(['sudo', 'ln', '-snf', os.path.basename(gmerge_pkgdir),
100 stripped_link])
101
David Jamesed079b12011-05-17 14:53:15 -0700102 username = os.environ['PORTAGE_USERNAME']
103 subprocess.check_call(['sudo', 'chown', username, gmerge_pkgdir])
104
105 # Load databases.
106 trees = portage.create_trees(config_root=root, target_root=root)
107 vardb = trees[root]['vartree'].dbapi
108 bintree = trees[root]['bintree']
109 bintree.populate()
110 gmerge_tree = dbapi.bintree.binarytree(root, gmerge_pkgdir,
111 settings=bintree.settings)
112 gmerge_tree.populate()
113
David James3556d222011-05-20 15:58:41 -0700114 if deep:
115 # If we're in deep mode, fill in the binhost completely.
116 gmerge_matches = set(gmerge_tree.dbapi.cpv_all())
117 bindb_matches = set(bintree.dbapi.cpv_all())
118 installed_matches = set(vardb.cpv_all()) & bindb_matches
119 else:
120 # Otherwise, just fill in the requested package.
121 gmerge_matches = set(gmerge_tree.dbapi.match(pkg))
122 bindb_matches = set(bintree.dbapi.match(pkg))
123 installed_matches = set(vardb.match(pkg)) & bindb_matches
David Jamesed079b12011-05-17 14:53:15 -0700124
125 # Remove any stale packages that exist in the local binhost but are not
126 # installed anymore.
127 if bindb_matches - installed_matches:
128 subprocess.check_call(['eclean-%s' % board, '-d', 'packages'])
129
130 # Remove any stale packages that exist in the gmerge binhost but are not
131 # installed anymore.
132 changed = False
133 for pkg in gmerge_matches - installed_matches:
134 gmerge_path = gmerge_tree.getname(pkg)
135 if os.path.exists(gmerge_path):
136 os.unlink(gmerge_path)
137 changed = True
138
139 # Copy any installed packages that have been rebuilt to the gmerge binhost.
140 for pkg in installed_matches:
141 build_time, = bintree.dbapi.aux_get(pkg, ['BUILD_TIME'])
142 build_path = bintree.getname(pkg)
143 gmerge_path = gmerge_tree.getname(pkg)
144
145 # If a package exists in the gmerge binhost with the same build time,
146 # don't rebuild it.
147 if pkg in gmerge_matches and os.path.exists(gmerge_path):
148 old_build_time, = gmerge_tree.dbapi.aux_get(pkg, ['BUILD_TIME'])
149 if old_build_time == build_time:
150 continue
151
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700152 _Log('Filtering install mask from %s' % pkg)
David Jamesed079b12011-05-17 14:53:15 -0700153 _FilterInstallMaskFromPackage(build_path, gmerge_path)
154 changed = True
155
156 # If the gmerge binhost was changed, update the Packages file to match.
157 if changed:
158 env_copy = os.environ.copy()
159 env_copy['PKGDIR'] = gmerge_pkgdir
160 env_copy['ROOT'] = root
161 env_copy['PORTAGE_CONFIGROOT'] = root
162 cmd = ['/usr/lib/portage/bin/emaint', '-f', 'binhost']
163 subprocess.check_call(cmd, env=env_copy)
164
165 return bool(installed_matches)
166
167
David Rochberg7c79a812011-01-19 14:24:45 -0500168class Builder(object):
169 """Builds packages for the devserver."""
170
171 def _ShouldBeWorkedOn(self, board, pkg):
172 """Is pkg a package that could be worked on, but is not?"""
David James0bc33fd2011-03-02 13:33:38 -0800173 if pkg in _OutputOf(['cros_workon', '--board=' + board, 'list']):
David Rochberg7c79a812011-01-19 14:24:45 -0500174 return False
175
176 # If it's in the list of possible workon targets, we should be working on it
177 return pkg in _OutputOf([
David James0bc33fd2011-03-02 13:33:38 -0800178 'cros_workon', '--board=' + board, 'list', '--all'])
David Rochberg7c79a812011-01-19 14:24:45 -0500179
180 def SetError(self, text):
181 cherrypy.response.status = 500
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700182 _Log(text)
David Rochberg7c79a812011-01-19 14:24:45 -0500183 return text
184
185 def Build(self, board, pkg, additional_args):
186 """Handles a build request from the cherrypy server."""
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700187 _Log('Additional build request arguments: ' + str(additional_args))
David Rochberg7c79a812011-01-19 14:24:45 -0500188
Chris Sosadda923d2011-04-13 13:12:01 -0700189 def _AppendStrToEnvVar(env, var, additional_string):
190 env[var] = env.get(var, '') + ' ' + additional_string
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700191 _Log('%s flags modified to %s' % (var, env[var]))
Chris Sosadda923d2011-04-13 13:12:01 -0700192
193 env_copy = os.environ.copy()
David Rochberg7c79a812011-01-19 14:24:45 -0500194 if 'use' in additional_args:
Chris Sosadda923d2011-04-13 13:12:01 -0700195 _AppendStrToEnvVar(env_copy, 'USE', additional_args['use'])
196
197 if 'features' in additional_args:
198 _AppendStrToEnvVar(env_copy, 'FEATURES', additional_args['features'])
David Rochberg7c79a812011-01-19 14:24:45 -0500199
200 try:
201 if (self._ShouldBeWorkedOn(board, pkg) and
202 not additional_args.get('accept_stable')):
203 return self.SetError(
204 'Package is not cros_workon\'d on the devserver machine.\n'
205 'Either start working on the package or pass --accept_stable '
206 'to gmerge')
207
David Jamesed079b12011-05-17 14:53:15 -0700208 # If user did not supply -n, we want to rebuild the package.
209 usepkg = additional_args.get('usepkg')
210 if not usepkg:
211 rc = subprocess.call(['emerge-%s' % board, pkg], env=env_copy)
212 if rc != 0:
213 return self.SetError('Could not emerge ' + pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500214
David Jamesed079b12011-05-17 14:53:15 -0700215 # Sync gmerge binhost.
David James3556d222011-05-20 15:58:41 -0700216 deep = additional_args.get('deep')
Ryan Cui0af7a912012-06-18 18:00:47 -0700217 if not UpdateGmergeBinhost(board, pkg, deep):
David Jamesed079b12011-05-17 14:53:15 -0700218 return self.SetError('Package %s is not installed' % pkg)
David Rochberg7c79a812011-01-19 14:24:45 -0500219
David Rochberg7c79a812011-01-19 14:24:45 -0500220 return 'Success\n'
221 except OSError, e:
222 return self.SetError('Could not execute build command: ' + str(e))