blob: 84acfee5332cf6352f7e6f4961204ab90870ab30 [file] [log] [blame]
Alex Kleinf4047132019-05-30 11:25:38 -06001# Copyright 2019 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Simplified cros_mark_as_stable script."""
6
Chris McDonald59650c32021-07-20 15:29:28 -06007import logging
Alex Kleinf4047132019-05-30 11:25:38 -06008import os
Christian Flachfb8c9b32022-02-28 15:16:18 +01009from typing import Dict, List, Optional
Alex Kleinf4047132019-05-30 11:25:38 -060010
Chris McDonald59650c32021-07-20 15:29:28 -060011from chromite.cbuildbot import manifest_version
Alex Kleinf4047132019-05-30 11:25:38 -060012from chromite.lib import commandline
Chris McDonald59650c32021-07-20 15:29:28 -060013from chromite.lib import constants
Alex Kleinf4047132019-05-30 11:25:38 -060014from chromite.lib import cros_build_lib
Alex Kleinf4047132019-05-30 11:25:38 -060015from chromite.lib import git
16from chromite.lib import osutils
17from chromite.lib import parallel
18from chromite.lib import portage_util
19
Mike Frysinger2688ef62020-02-16 00:00:46 -050020
Alex Kleinf4047132019-05-30 11:25:38 -060021# Commit message subject for uprevving Portage packages.
22GIT_COMMIT_SUBJECT = 'Marking set of ebuilds as stable'
23
24# Commit message for uprevving Portage packages.
25_GIT_COMMIT_MESSAGE = 'Marking 9999 ebuild for %s as stable.'
26
27
Christian Flachfb8c9b32022-02-28 15:16:18 +010028def GetParser() -> commandline.ArgumentParser:
Alex Kleinf4047132019-05-30 11:25:38 -060029 """Build the argument parser."""
30 parser = commandline.ArgumentParser(description=__doc__)
31
32 parser.add_argument('--all', action='store_true',
33 help='Mark all packages as stable.')
34 parser.add_argument('--boards', help='Colon-separated list of boards.')
35 parser.add_argument('--chroot', type='path', help='The chroot path.')
36 parser.add_argument('--force', action='store_true',
Cindy Linb794fed2021-12-09 20:58:40 +000037 help='Force the stabilization of manually uprevved '
38 'packages. (only compatible with -p)')
Alex Kleinf4047132019-05-30 11:25:38 -060039 parser.add_argument('--overlay-type', required=True,
40 choices=['public', 'private', 'both'],
41 help='Populates --overlays based on "public", "private", '
42 'or "both".')
43 parser.add_argument('--packages',
44 help='Colon separated list of packages to rev.')
Alex Kleinf4047132019-05-30 11:25:38 -060045 parser.add_argument('--dump-files', action='store_true',
Mike Frysinger80de5012019-08-01 14:10:53 -040046 help='Dump the revved packages, new files list, and '
47 'removed files list files. This is mostly for'
48 'debugging right now.')
Alex Kleinf4047132019-05-30 11:25:38 -060049
50 return parser
51
52
Christian Flachfb8c9b32022-02-28 15:16:18 +010053def _ParseArguments(argv: List[str]) -> commandline.ArgumentNamespace:
Alex Kleinf4047132019-05-30 11:25:38 -060054 """Parse and validate arguments."""
55 parser = GetParser()
56 options = parser.parse_args(argv)
57
58 # Parse, cleanup, and populate options.
59 if options.packages:
60 options.packages = options.packages.split(':')
61 if options.boards:
62 options.boards = options.boards.split(':')
63 options.overlays = portage_util.FindOverlays(options.overlay_type)
64
65 # Verify options.
66 if not options.packages and not options.all:
67 parser.error('Please specify at least one package (--packages)')
68 if options.force and options.all:
69 parser.error('Cannot use --force with --all. You must specify a list of '
70 'packages you want to force uprev.')
71
72 options.Freeze()
73 return options
74
75
Christian Flachfb8c9b32022-02-28 15:16:18 +010076def main(argv: List[str]) -> None:
Alex Kleinf4047132019-05-30 11:25:38 -060077 options = _ParseArguments(argv)
78
79 if not options.boards:
80 overlays = portage_util.FindOverlays(options.overlay_type)
81 else:
82 overlays = set()
83 for board in options.boards:
84 board_overlays = portage_util.FindOverlays(options.overlay_type,
85 board=board)
86 overlays = overlays.union(board_overlays)
87
88 overlays = list(overlays)
89
90 manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT)
91
92 _WorkOnCommit(options, overlays, manifest, options.packages or None)
93
94
Christian Flachfb8c9b32022-02-28 15:16:18 +010095def CleanStalePackages(boards: List[str], package_atoms: List[str],
96 chroot: str) -> None:
Alex Kleinf4047132019-05-30 11:25:38 -060097 """Cleans up stale package info from a previous build.
98
99 Args:
100 boards: Boards to clean the packages from.
101 package_atoms: A list of package atoms to unmerge.
Christian Flachfb8c9b32022-02-28 15:16:18 +0100102 chroot: The chroot path.
Alex Kleinf4047132019-05-30 11:25:38 -0600103 """
104 if package_atoms:
105 logging.info('Cleaning up stale packages %s.', package_atoms)
106
107 # First unmerge all the packages for a board, then eclean it.
108 # We need these two steps to run in order (unmerge/eclean),
109 # but we can let all the boards run in parallel.
Christian Flachfb8c9b32022-02-28 15:16:18 +0100110 def _CleanStalePackages(board: str):
Alex Kleinf4047132019-05-30 11:25:38 -0600111 if board:
112 suffix = '-' + board
Mike Frysinger45602c72019-09-22 02:15:11 -0400113 runcmd = cros_build_lib.run
Alex Kleinf4047132019-05-30 11:25:38 -0600114 else:
115 suffix = ''
Mike Frysinger45602c72019-09-22 02:15:11 -0400116 runcmd = cros_build_lib.sudo_run
Alex Kleinf4047132019-05-30 11:25:38 -0600117
118 chroot_args = ['--chroot', chroot] if chroot else None
119 emerge, eclean = 'emerge' + suffix, 'eclean' + suffix
120 if not osutils.FindMissingBinaries([emerge, eclean]):
121 if package_atoms:
122 # If nothing was found to be unmerged, emerge will exit(1).
123 result = runcmd([emerge, '-q', '--unmerge'] + list(package_atoms),
124 enter_chroot=True, chroot_args=chroot_args,
125 extra_env={'CLEAN_DELAY': '0'},
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500126 check=False, cwd=constants.SOURCE_ROOT)
Alex Kleinf4047132019-05-30 11:25:38 -0600127 if result.returncode not in (0, 1):
128 raise cros_build_lib.RunCommandError('unexpected error', result)
129 runcmd([eclean, '-d', 'packages'],
130 cwd=constants.SOURCE_ROOT, enter_chroot=True,
Mike Frysinger0282d222019-12-17 17:15:48 -0500131 chroot_args=chroot_args, stdout=True,
132 stderr=True)
Alex Kleinf4047132019-05-30 11:25:38 -0600133
134 tasks = []
135 for board in boards:
136 tasks.append([board])
137 tasks.append([None])
138
139 parallel.RunTasksInProcessPool(_CleanStalePackages, tasks)
140
141
Christian Flachfb8c9b32022-02-28 15:16:18 +0100142def _WorkOnCommit(options: commandline.ArgumentNamespace, overlays: List[str],
143 manifest: git.ManifestCheckout,
144 package_list: Optional[List[str]]) -> None:
Alex Kleinf4047132019-05-30 11:25:38 -0600145 """Commit uprevs of overlays belonging to different git projects in parallel.
146
147 Args:
148 options: The options object returned by the argument parser.
149 overlays: A list of overlays to work on.
150 manifest: The manifest of the given source root.
151 package_list: A list of packages passed from commandline to work on.
152 """
153 overlay_ebuilds = _GetOverlayToEbuildsMap(overlays, package_list,
154 options.force)
155
156 with parallel.Manager() as manager:
157 # Contains the array of packages we actually revved.
158 revved_packages = manager.list()
159 new_package_atoms = manager.list()
160 new_ebuild_files = manager.list()
161 removed_ebuild_files = manager.list()
162
163 inputs = [[manifest, [overlay], overlay_ebuilds, revved_packages,
164 new_package_atoms, new_ebuild_files, removed_ebuild_files]
165 for overlay in overlays]
166 parallel.RunTasksInProcessPool(_UprevOverlays, inputs)
167
168 if options.chroot and os.path.exists(options.chroot):
169 CleanStalePackages(options.boards or [], new_package_atoms,
170 options.chroot)
171
172 if options.dump_files:
173 osutils.WriteFile('/tmp/revved_packages', '\n'.join(revved_packages))
174 osutils.WriteFile('/tmp/new_ebuild_files', '\n'.join(new_ebuild_files))
175 osutils.WriteFile('/tmp/removed_ebuild_files',
176 '\n'.join(removed_ebuild_files))
177
178
Christian Flachfb8c9b32022-02-28 15:16:18 +0100179def _GetOverlayToEbuildsMap(overlays: List[str],
180 package_list: Optional[List[str]],
181 force: bool) -> Dict:
Alex Kleinf4047132019-05-30 11:25:38 -0600182 """Get ebuilds for overlays.
183
184 Args:
185 overlays: A list of overlays to work on.
186 package_list: A list of packages passed from commandline to work on.
Christian Flachfb8c9b32022-02-28 15:16:18 +0100187 force: Whether to use packages even if in manual uprev list.
Alex Kleinf4047132019-05-30 11:25:38 -0600188
189 Returns:
190 A dict mapping each overlay to a list of ebuilds belonging to it.
191 """
192 root_version = manifest_version.VersionInfo.from_repo(constants.SOURCE_ROOT)
193 subdir_removal = manifest_version.VersionInfo('10363.0.0')
194 require_subdir_support = root_version < subdir_removal
195 use_all = not package_list
196
197 overlay_ebuilds = {}
198 inputs = [[overlay, use_all, package_list, force, require_subdir_support]
199 for overlay in overlays]
200 result = parallel.RunTasksInProcessPool(
201 portage_util.GetOverlayEBuilds, inputs)
202 for idx, ebuilds in enumerate(result):
203 overlay_ebuilds[overlays[idx]] = ebuilds
204
205 return overlay_ebuilds
206
207
Christian Flachfb8c9b32022-02-28 15:16:18 +0100208def _UprevOverlays(manifest: git.ManifestCheckout, overlays: List[str],
209 overlay_ebuilds: Dict, revved_packages: List[str],
210 new_package_atoms: List[str], new_ebuild_files: List[str],
211 removed_ebuild_files: List[str]) -> None:
Alex Kleinf4047132019-05-30 11:25:38 -0600212 """Execute uprevs for overlays in sequence.
213
214 Args:
215 manifest: The manifest of the given source root.
216 overlays: A list over overlays to commit.
217 overlay_ebuilds: A dict mapping overlays to their ebuilds.
218 revved_packages: A shared list of revved packages.
219 new_package_atoms: A shared list of new package atoms.
220 new_ebuild_files: New stable ebuild paths.
221 removed_ebuild_files: Old ebuild paths that were removed.
222 """
223 for overlay in overlays:
224 if not os.path.isdir(overlay):
225 logging.warning('Skipping %s, which is not a directory.', overlay)
226 continue
227
228 ebuilds = overlay_ebuilds.get(overlay, [])
229 if not ebuilds:
230 continue
231
232 with parallel.Manager() as manager:
233 # Contains the array of packages we actually revved.
234 messages = manager.list()
235
236 inputs = [[overlay, ebuild, manifest, new_ebuild_files,
237 removed_ebuild_files, messages, revved_packages,
238 new_package_atoms] for ebuild in ebuilds]
239 parallel.RunTasksInProcessPool(_WorkOnEbuild, inputs)
240
241
Christian Flachfb8c9b32022-02-28 15:16:18 +0100242def _WorkOnEbuild(overlay: str, ebuild: portage_util.EBuild,
243 manifest: git.ManifestCheckout, new_ebuild_files: List[str],
244 removed_ebuild_files: List[str], messages: List[str],
245 revved_packages: List[str],
246 new_package_atoms: List[str]) -> None:
Alex Kleinf4047132019-05-30 11:25:38 -0600247 """Work on a single ebuild.
248
249 Args:
250 overlay: The overlay where the ebuild belongs to.
251 ebuild: The ebuild to work on.
252 manifest: The manifest of the given source root.
253 new_ebuild_files: New stable ebuild paths that were created.
254 removed_ebuild_files: Old ebuild paths that were removed.
255 messages: A share list of commit messages.
256 revved_packages: A shared list of revved packages.
257 new_package_atoms: A shared list of new package atoms.
258 """
259 logging.debug('Working on %s, info %s', ebuild.package,
260 ebuild.cros_workon_vars)
261 try:
262 result = ebuild.RevWorkOnEBuild(os.path.join(constants.SOURCE_ROOT, 'src'),
263 manifest)
David Burger8cf4a762020-03-09 10:33:38 -0600264 except portage_util.InvalidUprevSourceError as e:
265 logging.error('An error occurred while uprevving %s: %s',
266 ebuild.package, e)
267 raise
Mike Frysingerb32cc472020-05-15 00:17:54 -0400268 except OSError:
Alex Kleinf4047132019-05-30 11:25:38 -0600269 logging.warning(
270 'Cannot rev %s\n'
271 'Note you will have to go into %s '
272 'and reset the git repo yourself.', ebuild.package, overlay)
273 raise
274
275 if result:
276 new_package, ebuild_path_to_add, ebuild_path_to_remove = result
277
278 if ebuild_path_to_add:
279 new_ebuild_files.append(ebuild_path_to_add)
280 if ebuild_path_to_remove:
281 osutils.SafeUnlink(ebuild_path_to_remove)
282 removed_ebuild_files.append(ebuild_path_to_remove)
283
284 messages.append(_GIT_COMMIT_MESSAGE % ebuild.package)
285 revved_packages.append(ebuild.package)
286 new_package_atoms.append('=%s' % new_package)