blob: cff38a84cf7f3f323949af312e8377e9685385d6 [file] [log] [blame]
Aviv Keshetb1238c32013-04-01 11:42:13 -07001#!/usr/bin/python
2
3# Copyright (c) 2013 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
8"""
9Simple script to be run inside the chroot. Used as a fast approximation of
10emerge-$board autotest-all, by simply rsync'ing changes from trunk to sysroot.
11"""
12
Aviv Keshete7b20192013-04-24 14:05:53 -070013import argparse
14import errno
Aviv Keshete00caeb2013-04-17 14:03:25 -070015import logging
Aviv Keshetb1238c32013-04-01 11:42:13 -070016import os
Aviv Keshet787ffcd2013-04-08 15:14:56 -070017import re
Aviv Keshetb1238c32013-04-01 11:42:13 -070018import sys
Aviv Keshet787ffcd2013-04-08 15:14:56 -070019from collections import namedtuple
20
Aviv Keshetb1238c32013-04-01 11:42:13 -070021from chromite.buildbot import constants
Aviv Keshet940c17f2013-04-11 18:41:42 -070022from chromite.buildbot import portage_utilities
Aviv Keshetb1238c32013-04-01 11:42:13 -070023from chromite.lib import cros_build_lib
24from chromite.lib import git
25
Aviv Keshetb1238c32013-04-01 11:42:13 -070026
Aviv Keshet940c17f2013-04-11 18:41:42 -070027if cros_build_lib.IsInsideChroot():
28 # Only import portage after we've checked that we're inside the chroot.
29 import portage
30
Aviv Keshetb1238c32013-04-01 11:42:13 -070031INCLUDE_PATTERNS_FILENAME = 'autotest-quickmerge-includepatterns'
32AUTOTEST_PROJECT_NAME = 'chromiumos/third_party/autotest'
Aviv Keshet940c17f2013-04-11 18:41:42 -070033AUTOTEST_TESTS_EBUILD = 'chromeos-base/autotest-tests'
Aviv Keshet3cc4e9e2013-04-24 10:47:23 -070034DOWNGRADE_EBUILDS = ['chromeos-base/autotest',
35 'chromeos-base/autotest-tests',
36 'chromeos-base/autotest-chrome',
37 'chromeos-base/autotest-factory',
38 'chromeos-base/autotest-telemetry',
39 'chromeos-base/autotest-tests-ltp',
40 'chromeos-base/autotest-tests-ownershipapi']
Aviv Keshet787ffcd2013-04-08 15:14:56 -070041
42# Data structure describing a single rsync filesystem change.
43#
44# change_description: An 11 character string, the rsync change description
45# for the particular file.
46# absolute_path: The absolute path of the created or modified file.
47ItemizedChange = namedtuple('ItemizedChange', ['change_description',
48 'absolute_path'])
49
50
51# Data structure describing the rsync new/modified files or directories.
52#
53# new_files: A list of ItemizedChange objects for new files.
54# modified_files: A list of ItemizedChange objects for modified files.
55# new_directories: A list of ItemizedChange objects for new directories.
56ItemizedChangeReport = namedtuple('ItemizedChangeReport',
57 ['new_files', 'modified_files',
58 'new_directories'])
59
60
Aviv Keshet75d65962013-04-17 16:15:23 -070061def GetStalePackageNames(change_list, autotest_sysroot):
Aviv Keshete7b20192013-04-24 14:05:53 -070062 """Given a rsync change report, returns the names of stale test packages.
Aviv Keshet75d65962013-04-17 16:15:23 -070063
64 This function pulls out test package names for client-side tests, stored
65 within the client/site_tests directory tree, that had any files added or
66 modified and for whom any existing bzipped test packages may now be stale.
67
68 Arguments:
69 change_list: A list of ItemizedChange objects corresponding to changed
70 or modified files.
71 autotest_sysroot: Absolute path of autotest in the sysroot,
72 e.g. '/build/lumpy/usr/local/autotest'
73
74 Returns:
75 A list of test package names, eg ['factory_Leds', 'login_UserPolicyKeys'].
76 May contain duplicate entries if multiple files within a test directory
77 were modified.
78 """
79 exp = os.path.abspath(autotest_sysroot) + r'/client/site_tests/(.*?)/.*'
80 matches = [re.match(exp, change.absolute_path) for change in change_list]
81 return [match.group(1) for match in matches if match]
82
83
Aviv Keshet787ffcd2013-04-08 15:14:56 -070084def ItemizeChangesFromRsyncOutput(rsync_output, destination_path):
85 """Convert the output of an rsync with `-i` to a ItemizedChangeReport object.
86
87 Arguments:
88 rsync_output: String stdout of rsync command that was run with `-i` option.
89 destination_path: String absolute path of the destination directory for the
90 rsync operations. This argument is necessary because
91 rsync's output only gives the relative path of
92 touched/added files.
93
94 Returns:
95 ItemizedChangeReport object giving the absolute paths of files that were
96 created or modified by rsync.
97 """
98 modified_matches = re.findall(r'([.>]f[^+]{9}) (.*)', rsync_output)
99 new_matches = re.findall(r'(>f\+{9}) (.*)', rsync_output)
100 new_symlink_matches = re.findall(r'(cL\+{9}) (.*) -> .*', rsync_output)
101 new_dir_matches = re.findall(r'(cd\+{9}) (.*)', rsync_output)
102
103 absolute_modified = [ItemizedChange(c, os.path.join(destination_path, f))
104 for (c, f) in modified_matches]
105
106 # Note: new symlinks are treated as new files.
107 absolute_new = [ItemizedChange(c, os.path.join(destination_path, f))
108 for (c, f) in new_matches + new_symlink_matches]
109
110 absolute_new_dir = [ItemizedChange(c, os.path.join(destination_path, f))
111 for (c, f) in new_dir_matches]
112
113 return ItemizedChangeReport(new_files=absolute_new,
114 modified_files=absolute_modified,
115 new_directories=absolute_new_dir)
116
117
Aviv Keshete00caeb2013-04-17 14:03:25 -0700118def GetPackageAPI(portage_root, package_cp):
Aviv Keshete7b20192013-04-24 14:05:53 -0700119 """Gets portage API handles for the given package.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700120
121 Arguments:
Aviv Keshete00caeb2013-04-17 14:03:25 -0700122 portage_root: Root directory of portage tree. Eg '/' or '/build/lumpy'
123 package_cp: A string similar to 'chromeos-base/autotest-tests'.
124
125 Returns:
126 Returns (package, vartree) tuple, where
127 package is of type portage.dbapi.vartree.dblink
128 vartree is of type portage.dbapi.vartree.vartree
Aviv Keshet940c17f2013-04-11 18:41:42 -0700129 """
130 if portage_root is None:
Aviv Keshete7b20192013-04-24 14:05:53 -0700131 # pylint: disable-msg=E1101
132 portage_root = portage.root
Aviv Keshet940c17f2013-04-11 18:41:42 -0700133 # Ensure that portage_root ends with trailing slash.
134 portage_root = os.path.join(portage_root, '')
135
Aviv Keshete7b20192013-04-24 14:05:53 -0700136 # Create a vartree object corresponding to portage_root.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700137 trees = portage.create_trees(portage_root, portage_root)
138 vartree = trees[portage_root]['vartree']
139
Aviv Keshete7b20192013-04-24 14:05:53 -0700140 # List the matching installed packages in cpv format.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700141 matching_packages = vartree.dbapi.cp_list(package_cp)
142
143 if not matching_packages:
144 raise ValueError('No matching package for %s in portage_root %s' % (
Aviv Keshete7b20192013-04-24 14:05:53 -0700145 package_cp, portage_root))
Aviv Keshet940c17f2013-04-11 18:41:42 -0700146
147 if len(matching_packages) > 1:
148 raise ValueError('Too many matching packages for %s in portage_root '
Aviv Keshete7b20192013-04-24 14:05:53 -0700149 '%s' % (package_cp, portage_root))
Aviv Keshet940c17f2013-04-11 18:41:42 -0700150
Aviv Keshete7b20192013-04-24 14:05:53 -0700151 # Convert string match to package dblink.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700152 package_cpv = matching_packages[0]
153 package_split = portage_utilities.SplitCPV(package_cpv)
Aviv Keshete7b20192013-04-24 14:05:53 -0700154 # pylint: disable-msg=E1101
155 package = portage.dblink(package_split.category,
Aviv Keshet940c17f2013-04-11 18:41:42 -0700156 package_split.pv, settings=vartree.settings,
157 vartree=vartree)
158
Aviv Keshete00caeb2013-04-17 14:03:25 -0700159 return package, vartree
160
161
162def DowngradePackageVersion(portage_root, package_cp,
163 downgrade_to_version='0'):
Aviv Keshete7b20192013-04-24 14:05:53 -0700164 """Downgrade the specified portage package version.
Aviv Keshete00caeb2013-04-17 14:03:25 -0700165
166 Arguments:
167 portage_root: Root directory of portage tree. Eg '/' or '/build/lumpy'
168 package_cp: A string similar to 'chromeos-base/autotest-tests'.
169 downgrade_to_version: String version to downgrade to. Default: '0'
170
171 Returns:
172 Returns the return value of the `mv` command used to perform operation.
173 """
174 package, _ = GetPackageAPI(portage_root, package_cp)
175
176 source_directory = package.dbdir
177 destination_path = os.path.join(
178 package.dbroot, package_cp + '-' + downgrade_to_version)
179 if os.path.abspath(source_directory) == os.path.abspath(destination_path):
180 return 0
181 command = ['mv', source_directory, destination_path]
182 return cros_build_lib.SudoRunCommand(command).returncode
183
184
Aviv Keshete7b20192013-04-24 14:05:53 -0700185def UpdatePackageContents(change_report, package_cp, portage_root=None):
186 """Add newly created files/directors to package contents.
Aviv Keshete00caeb2013-04-17 14:03:25 -0700187
188 Given an ItemizedChangeReport, add the newly created files and directories
189 to the CONTENTS of an installed portage package, such that these files are
190 considered owned by that package.
191
192 Arguments:
193 changereport: ItemizedChangeReport object for the changes to be
194 made to the package.
195 package_cp: A string similar to 'chromeos-base/autotest-tests' giving
196 the package category and name of the package to be altered.
197 portage_root: Portage root path, corresponding to the board that
198 we are working on. Defaults to '/'
199 """
200 package, vartree = GetPackageAPI(portage_root, package_cp)
201
Aviv Keshete7b20192013-04-24 14:05:53 -0700202 # Append new contents to package contents dictionary.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700203 contents = package.getcontents().copy()
204 for _, filename in change_report.new_files:
205 contents.setdefault(filename, (u'obj', '0', '0'))
206 for _, dirname in change_report.new_directories:
Aviv Keshete7b20192013-04-24 14:05:53 -0700207 # Strip trailing slashes if present.
208 contents.setdefault(dirname.rstrip('/'), (u'dir',))
Aviv Keshet940c17f2013-04-11 18:41:42 -0700209
Aviv Keshete7b20192013-04-24 14:05:53 -0700210 # Write new contents dictionary to file.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700211 vartree.dbapi.writeContentsToContentsFile(package, contents)
212
213
Aviv Keshet75d65962013-04-17 16:15:23 -0700214def RemoveTestPackages(stale_packages, autotest_sysroot):
Aviv Keshete7b20192013-04-24 14:05:53 -0700215 """Remove bzipped test packages from sysroot.
Aviv Keshet75d65962013-04-17 16:15:23 -0700216
217 Arguments:
218 stale_packages: List of test packages names to be removed.
219 e.g. ['factory_Leds', 'login_UserPolicyKeys']
220 autotest_sysroot: Absolute path of autotest in the sysroot,
221 e.g. '/build/lumpy/usr/local/autotest'
222 """
223 for package in set(stale_packages):
224 package_filename = 'test-' + package + '.tar.bz2'
225 package_file_fullpath = os.path.join(autotest_sysroot, 'packages',
Aviv Keshete7b20192013-04-24 14:05:53 -0700226 package_filename)
Aviv Keshet75d65962013-04-17 16:15:23 -0700227 try:
228 os.remove(package_file_fullpath)
229 logging.info('Removed stale %s', package_file_fullpath)
230 except OSError as err:
231 # Suppress no-such-file exceptions. Raise all others.
Aviv Keshete7b20192013-04-24 14:05:53 -0700232 if err.errno != errno.ENOENT:
Aviv Keshet75d65962013-04-17 16:15:23 -0700233 raise
234
235
Aviv Keshetb1238c32013-04-01 11:42:13 -0700236def RsyncQuickmerge(source_path, sysroot_autotest_path,
237 include_pattern_file=None, pretend=False,
Aviv Keshet60968ec2013-04-11 18:44:14 -0700238 overwrite=False):
Aviv Keshetb1238c32013-04-01 11:42:13 -0700239 """Run rsync quickmerge command, with specified arguments.
Aviv Keshete7b20192013-04-24 14:05:53 -0700240
Aviv Keshetb1238c32013-04-01 11:42:13 -0700241 Command will take form `rsync -a [options] --exclude=**.pyc
242 --exclude=**.pyo
243 [optional --include-from argument]
244 --exclude=* [source_path] [sysroot_autotest_path]`
245
246 Arguments:
247 pretend: True to use the '-n' option to rsync, to perform dry run.
248 overwrite: True to omit '-u' option, overwrite all files in sysroot,
249 not just older files.
Aviv Keshetb1238c32013-04-01 11:42:13 -0700250 """
251 command = ['rsync', '-a']
252
253 if pretend:
254 command += ['-n']
255
256 if not overwrite:
257 command += ['-u']
258
Aviv Keshet60968ec2013-04-11 18:44:14 -0700259 command += ['-i']
Aviv Keshetb1238c32013-04-01 11:42:13 -0700260
261 command += ['--exclude=**.pyc']
262 command += ['--exclude=**.pyo']
263
Aviv Keshet787ffcd2013-04-08 15:14:56 -0700264 # Exclude files with a specific substring in their name, because
265 # they create an ambiguous itemized report. (see unit test file for details)
266 command += ['--exclude=** -> *']
267
Aviv Keshetb1238c32013-04-01 11:42:13 -0700268 if include_pattern_file:
269 command += ['--include-from=%s' % include_pattern_file]
270
271 command += ['--exclude=*']
272
273 command += [source_path, sysroot_autotest_path]
274
Aviv Keshet60968ec2013-04-11 18:44:14 -0700275 return cros_build_lib.SudoRunCommand(command, redirect_stdout=True)
Aviv Keshetb1238c32013-04-01 11:42:13 -0700276
277
278def ParseArguments(argv):
279 """Parse command line arguments
280
281 Returns: parsed arguments.
282 """
283 parser = argparse.ArgumentParser(description='Perform a fast approximation '
284 'to emerge-$board autotest-all, by '
285 'rsyncing source tree to sysroot.')
286
287 parser.add_argument('--board', metavar='BOARD', default=None, required=True)
288 parser.add_argument('--pretend', action='store_true',
289 help='Dry run only, do not modify sysroot autotest.')
290 parser.add_argument('--overwrite', action='store_true',
291 help='Overwrite existing files even if newer.')
Aviv Keshete00caeb2013-04-17 14:03:25 -0700292 parser.add_argument('--verbose', action='store_true',
293 help='Print detailed change report.')
Aviv Keshetb1238c32013-04-01 11:42:13 -0700294
295 return parser.parse_args(argv)
296
297
298def main(argv):
299 cros_build_lib.AssertInsideChroot()
300
301 args = ParseArguments(argv)
302
Aviv Keshete7b20192013-04-24 14:05:53 -0700303 if os.geteuid() != 0:
Aviv Keshet940c17f2013-04-11 18:41:42 -0700304 try:
305 cros_build_lib.SudoRunCommand([sys.executable] + sys.argv)
306 except cros_build_lib.RunCommandError:
307 return 1
308 return 0
309
Aviv Keshetb1238c32013-04-01 11:42:13 -0700310 if not args.board:
Aviv Keshete00caeb2013-04-17 14:03:25 -0700311 print 'No board specified. Aborting.'
Aviv Keshetb1238c32013-04-01 11:42:13 -0700312 return 1
313
314 manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT)
315 source_path = manifest.GetProjectPath(AUTOTEST_PROJECT_NAME, absolute=True)
316 source_path = os.path.join(source_path, '')
317
318 script_path = os.path.dirname(__file__)
319 include_pattern_file = os.path.join(script_path, INCLUDE_PATTERNS_FILENAME)
320
321 # TODO: Determine the following string programatically.
Aviv Keshet940c17f2013-04-11 18:41:42 -0700322 sysroot_path = os.path.join('/build', args.board, '')
323 sysroot_autotest_path = os.path.join(sysroot_path, 'usr', 'local',
Aviv Keshetb1238c32013-04-01 11:42:13 -0700324 'autotest', '')
325
Aviv Keshet60968ec2013-04-11 18:44:14 -0700326 rsync_output = RsyncQuickmerge(source_path, sysroot_autotest_path,
Aviv Keshete7b20192013-04-24 14:05:53 -0700327 include_pattern_file, args.pretend,
328 args.overwrite)
Aviv Keshetb1238c32013-04-01 11:42:13 -0700329
Aviv Keshete00caeb2013-04-17 14:03:25 -0700330 if args.verbose:
331 logging.info(rsync_output.output)
332
Aviv Keshet60968ec2013-04-11 18:44:14 -0700333 change_report = ItemizeChangesFromRsyncOutput(rsync_output.output,
334 sysroot_autotest_path)
335
Aviv Keshet940c17f2013-04-11 18:41:42 -0700336 if not args.pretend:
337 UpdatePackageContents(change_report, AUTOTEST_TESTS_EBUILD,
338 sysroot_path)
Aviv Keshet3cc4e9e2013-04-24 10:47:23 -0700339 for ebuild in DOWNGRADE_EBUILDS:
340 if DowngradePackageVersion(sysroot_path, ebuild) != 0:
341 logging.warning('Unable to downgrade package %s version number.',
Aviv Keshete7b20192013-04-24 14:05:53 -0700342 ebuild)
Aviv Keshet75d65962013-04-17 16:15:23 -0700343 stale_packages = GetStalePackageNames(
344 change_report.new_files + change_report.modified_files,
345 sysroot_autotest_path)
346 RemoveTestPackages(stale_packages, sysroot_autotest_path)
Aviv Keshetb1238c32013-04-01 11:42:13 -0700347
Aviv Keshet940c17f2013-04-11 18:41:42 -0700348 if args.pretend:
Aviv Keshete00caeb2013-04-17 14:03:25 -0700349 logging.info('The following message is pretend only. No filesystem '
Aviv Keshete7b20192013-04-24 14:05:53 -0700350 'changes made.')
Aviv Keshete00caeb2013-04-17 14:03:25 -0700351 logging.info('Quickmerge complete. Created or modified %s files.',
Aviv Keshete7b20192013-04-24 14:05:53 -0700352 len(change_report.new_files) +
353 len(change_report.modified_files))
Aviv Keshete00caeb2013-04-17 14:03:25 -0700354
355 return 0