blob: 440f7f5df70fed17e096febb776e123a0762efef [file] [log] [blame]
Mike Frysinger2de7f042012-07-10 04:45:03 -04001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Brian Harringb938c782012-02-29 15:14:38 -08002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
Manoj Gupta7fad04d2019-06-14 20:12:25 -07004
Mike Frysinger2f95cfc2015-06-04 04:00:26 -04005"""Manage SDK chroots.
6
7This script is used for manipulating local chroot environments; creating,
8deleting, downloading, etc. If given --enter (or no args), it defaults
9to an interactive bash shell within the chroot.
10
11If given args those are passed to the chroot environment, and executed.
12"""
Brian Harringb938c782012-02-29 15:14:38 -080013
Mike Frysinger2f95cfc2015-06-04 04:00:26 -040014import argparse
Josh Triplett472a4182013-03-08 11:48:57 -080015import glob
Chris McDonaldb55b7032021-06-17 16:41:32 -060016import logging
Brian Harringb938c782012-02-29 15:14:38 -080017import os
Mike Frysinger23b5cf52021-06-16 23:18:00 -040018from pathlib import Path
Josh Triplett472a4182013-03-08 11:48:57 -080019import pwd
Benjamin Gordon2d7bf582017-07-12 10:11:26 -060020import random
Brian Norrisd37e2f72016-08-22 16:09:24 -070021import re
Ting-Yuan Huangf56d9af2017-06-19 16:08:32 -070022import resource
Sergey Frolov1cb46ec2020-12-09 21:46:16 -070023import subprocess
David James56e6c2c2012-10-24 23:54:41 -070024import sys
Mike Frysingere852b072021-05-21 12:39:03 -040025import urllib.parse
Brian Harringb938c782012-02-29 15:14:38 -080026
Chris McDonaldb55b7032021-06-17 16:41:32 -060027from chromite.cbuildbot import cbuildbot_alerts
Brian Harringb6cf9142012-09-01 20:43:17 -070028from chromite.lib import commandline
Chris McDonaldb55b7032021-06-17 16:41:32 -060029from chromite.lib import constants
Brian Harringb938c782012-02-29 15:14:38 -080030from chromite.lib import cros_build_lib
Benjamin Gordon74645232018-05-04 17:40:42 -060031from chromite.lib import cros_sdk_lib
Brian Harringb938c782012-02-29 15:14:38 -080032from chromite.lib import locking
Josh Triplette759b232013-03-08 13:03:43 -080033from chromite.lib import namespaces
Brian Harringae0a5322012-09-15 01:46:51 -070034from chromite.lib import osutils
Yong Hong84ba9172018-02-07 01:37:42 +080035from chromite.lib import path_util
Mike Frysingere2d8f0d2014-11-01 13:09:26 -040036from chromite.lib import process_util
David Jamesc93e6a4d2014-01-13 11:37:36 -080037from chromite.lib import retry_util
Michael Mortensenbf296fb2020-06-18 18:21:54 -060038from chromite.lib import timeout_util
Mike Frysinger8e727a32013-01-16 16:57:53 -050039from chromite.lib import toolchain
Mike Frysingere652ba12019-09-08 00:57:43 -040040from chromite.utils import key_value_store
41
Brian Harringb938c782012-02-29 15:14:38 -080042
Zdenek Behanaa52cea2012-05-30 01:31:11 +020043COMPRESSION_PREFERENCE = ('xz', 'bz2')
Zdenek Behanfd0efe42012-04-13 04:36:40 +020044
Brian Harringb938c782012-02-29 15:14:38 -080045# TODO(zbehan): Remove the dependency on these, reimplement them in python
Manoj Guptab12f7302019-06-03 16:40:14 -070046ENTER_CHROOT = [
47 os.path.join(constants.SOURCE_ROOT, 'src/scripts/sdk_lib/enter_chroot.sh')
48]
Brian Harringb938c782012-02-29 15:14:38 -080049
Josh Triplett472a4182013-03-08 11:48:57 -080050# Proxy simulator configuration.
51PROXY_HOST_IP = '192.168.240.1'
52PROXY_PORT = 8080
53PROXY_GUEST_IP = '192.168.240.2'
54PROXY_NETMASK = 30
55PROXY_VETH_PREFIX = 'veth'
56PROXY_CONNECT_PORTS = (80, 443, 9418)
57PROXY_APACHE_FALLBACK_USERS = ('www-data', 'apache', 'nobody')
58PROXY_APACHE_MPMS = ('event', 'worker', 'prefork')
59PROXY_APACHE_FALLBACK_PATH = ':'.join(
Manoj Guptab12f7302019-06-03 16:40:14 -070060 '/usr/lib/apache2/mpm-%s' % mpm for mpm in PROXY_APACHE_MPMS)
Josh Triplett472a4182013-03-08 11:48:57 -080061PROXY_APACHE_MODULE_GLOBS = ('/usr/lib*/apache2/modules', '/usr/lib*/apache2')
62
Josh Triplett9a495f62013-03-15 18:06:55 -070063# We need these tools to run. Very common tools (tar,..) are omitted.
Josh Triplette759b232013-03-08 13:03:43 -080064NEEDED_TOOLS = ('curl', 'xz')
Brian Harringb938c782012-02-29 15:14:38 -080065
Josh Triplett472a4182013-03-08 11:48:57 -080066# Tools needed for --proxy-sim only.
67PROXY_NEEDED_TOOLS = ('ip',)
Brian Harringb938c782012-02-29 15:14:38 -080068
Benjamin Gordon386b9eb2017-07-20 09:21:33 -060069# Tools needed when use_image is true (the default).
70IMAGE_NEEDED_TOOLS = ('losetup', 'lvchange', 'lvcreate', 'lvs', 'mke2fs',
Benjamin Gordoncfa9c162017-08-03 13:49:29 -060071 'pvscan', 'thin_check', 'vgchange', 'vgcreate', 'vgs')
Benjamin Gordon386b9eb2017-07-20 09:21:33 -060072
Benjamin Gordone3d5bd12017-11-16 15:42:28 -070073# As space is used inside the chroot, the empty space in chroot.img is
74# allocated. Deleting files inside the chroot doesn't automatically return the
75# used space to the OS. Over time, this tends to make the sparse chroot.img
76# less sparse even if the chroot contents don't currently need much space. We
77# can recover most of this unused space with fstrim, but that takes too much
78# time to run it every time. Instead, check the used space against the image
79# size after mounting the chroot and only call fstrim if it looks like we could
80# recover at least this many GiB.
81MAX_UNUSED_IMAGE_GBS = 20
82
Mike Frysingercc838832014-05-24 13:10:30 -040083
Brian Harring1790ac42012-09-23 08:53:33 -070084def GetArchStageTarballs(version):
Brian Harringb938c782012-02-29 15:14:38 -080085 """Returns the URL for a given arch/version"""
Manoj Guptab12f7302019-06-03 16:40:14 -070086 extension = {'bz2': 'tbz2', 'xz': 'tar.xz'}
87 return [
88 toolchain.GetSdkURL(
89 suburl='cros-sdk-%s.%s' % (version, extension[compressor]))
90 for compressor in COMPRESSION_PREFERENCE
91 ]
Brian Harring1790ac42012-09-23 08:53:33 -070092
93
Mike Frysingerdaf57b82019-11-23 17:26:51 -050094def FetchRemoteTarballs(storage_dir, urls, desc):
Mike Frysinger34db8692013-11-11 14:54:08 -050095 """Fetches a tarball given by url, and place it in |storage_dir|.
Zdenek Behanfd0efe42012-04-13 04:36:40 +020096
97 Args:
Mike Frysinger34db8692013-11-11 14:54:08 -050098 storage_dir: Path where to save the tarball.
Zdenek Behanfd0efe42012-04-13 04:36:40 +020099 urls: List of URLs to try to download. Download will stop on first success.
Gilad Arnold6a8f0452015-06-04 11:25:18 -0700100 desc: A string describing what tarball we're downloading (for logging).
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200101
102 Returns:
Mike Frysingerdaf57b82019-11-23 17:26:51 -0500103 Full path to the downloaded file.
Gilad Arnoldecc86fa2015-05-22 12:06:04 -0700104
105 Raises:
Mike Frysingerdaf57b82019-11-23 17:26:51 -0500106 ValueError: None of the URLs worked.
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200107 """
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200108
Brian Harring1790ac42012-09-23 08:53:33 -0700109 # Note we track content length ourselves since certain versions of curl
110 # fail if asked to resume a complete file.
Brian Harring1790ac42012-09-23 08:53:33 -0700111 # https://sourceforge.net/tracker/?func=detail&atid=100976&aid=3482927&group_id=976
Gilad Arnold6a8f0452015-06-04 11:25:18 -0700112 logging.notice('Downloading %s tarball...', desc)
Mike Frysingerdaf57b82019-11-23 17:26:51 -0500113 status_re = re.compile(br'^HTTP/[0-9]+(\.[0-9]+)? 200')
Mike Frysinger27e21b72018-07-12 14:20:21 -0400114 # pylint: disable=undefined-loop-variable
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200115 for url in urls:
Mike Frysinger3dcacee2019-08-23 17:09:11 -0400116 parsed = urllib.parse.urlparse(url)
Brian Harring1790ac42012-09-23 08:53:33 -0700117 tarball_name = os.path.basename(parsed.path)
118 if parsed.scheme in ('', 'file'):
119 if os.path.exists(parsed.path):
120 return parsed.path
121 continue
122 content_length = 0
Ralph Nathan7070e6a2015-04-02 10:16:43 -0700123 logging.debug('Attempting download from %s', url)
Manoj Guptab12f7302019-06-03 16:40:14 -0700124 result = retry_util.RunCurl(['-I', url],
125 print_cmd=False,
126 debug_level=logging.NOTICE,
127 capture_output=True)
Brian Harring1790ac42012-09-23 08:53:33 -0700128 successful = False
129 for header in result.output.splitlines():
Brian Norrisd37e2f72016-08-22 16:09:24 -0700130 # We must walk the output to find the 200 code for use cases where
Brian Harring1790ac42012-09-23 08:53:33 -0700131 # a proxy is involved and may have pushed down the actual header.
Brian Norrisd37e2f72016-08-22 16:09:24 -0700132 if status_re.match(header):
Brian Harring1790ac42012-09-23 08:53:33 -0700133 successful = True
Mike Frysingerdaf57b82019-11-23 17:26:51 -0500134 elif header.lower().startswith(b'content-length:'):
135 content_length = int(header.split(b':', 1)[-1].strip())
Brian Harring1790ac42012-09-23 08:53:33 -0700136 if successful:
137 break
138 if successful:
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200139 break
140 else:
Gilad Arnoldecc86fa2015-05-22 12:06:04 -0700141 raise ValueError('No valid URLs found!')
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200142
Brian Harringae0a5322012-09-15 01:46:51 -0700143 tarball_dest = os.path.join(storage_dir, tarball_name)
Brian Harring1790ac42012-09-23 08:53:33 -0700144 current_size = 0
145 if os.path.exists(tarball_dest):
146 current_size = os.path.getsize(tarball_dest)
147 if current_size > content_length:
David James56e6c2c2012-10-24 23:54:41 -0700148 osutils.SafeUnlink(tarball_dest)
Brian Harring1790ac42012-09-23 08:53:33 -0700149 current_size = 0
Zdenek Behanb2fa72e2012-03-16 04:49:30 +0100150
Brian Harring1790ac42012-09-23 08:53:33 -0700151 if current_size < content_length:
David Jamesc93e6a4d2014-01-13 11:37:36 -0800152 retry_util.RunCurl(
Hidehiko Abee55af7f2017-05-01 18:38:04 +0900153 ['--fail', '-L', '-y', '30', '-C', '-', '--output', tarball_dest, url],
Manoj Guptab12f7302019-06-03 16:40:14 -0700154 print_cmd=False,
155 debug_level=logging.NOTICE)
Brian Harringb938c782012-02-29 15:14:38 -0800156
Brian Harring1790ac42012-09-23 08:53:33 -0700157 # Cleanup old tarballs now since we've successfull fetched; only cleanup
Gilad Arnoldecc86fa2015-05-22 12:06:04 -0700158 # the tarballs for our prefix, or unknown ones. This gets a bit tricky
159 # because we might have partial overlap between known prefixes.
160 my_prefix = tarball_name.rsplit('-', 1)[0] + '-'
161 all_prefixes = ('stage3-amd64-', 'cros-sdk-', 'cros-sdk-overlay-')
162 ignored_prefixes = [prefix for prefix in all_prefixes if prefix != my_prefix]
Brian Harring1790ac42012-09-23 08:53:33 -0700163 for filename in os.listdir(storage_dir):
Gilad Arnoldecc86fa2015-05-22 12:06:04 -0700164 if (filename == tarball_name or
165 any([(filename.startswith(p) and
166 not (len(my_prefix) > len(p) and filename.startswith(my_prefix)))
167 for p in ignored_prefixes])):
Brian Harring1790ac42012-09-23 08:53:33 -0700168 continue
Gilad Arnoldecc86fa2015-05-22 12:06:04 -0700169 logging.info('Cleaning up old tarball: %s', filename)
David James56e6c2c2012-10-24 23:54:41 -0700170 osutils.SafeUnlink(os.path.join(storage_dir, filename))
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200171
Brian Harringb938c782012-02-29 15:14:38 -0800172 return tarball_dest
173
174
Brian Harringae0a5322012-09-15 01:46:51 -0700175def EnterChroot(chroot_path, cache_dir, chrome_root, chrome_root_mount,
Mike Frysinger0b2d9ee2019-02-28 17:05:47 -0500176 goma_dir, goma_client_json, working_dir, additional_args):
Brian Harringb938c782012-02-29 15:14:38 -0800177 """Enters an existing SDK chroot"""
Mike Frysingere5456972013-06-13 00:07:23 -0400178 st = os.statvfs(os.path.join(chroot_path, 'usr', 'bin', 'sudo'))
Alex Klein875b30e2021-01-05 14:56:33 -0700179 if st.f_flag & os.ST_NOSUID:
Mike Frysingere5456972013-06-13 00:07:23 -0400180 cros_build_lib.Die('chroot cannot be in a nosuid mount')
181
Brian Harringae0a5322012-09-15 01:46:51 -0700182 cmd = ENTER_CHROOT + ['--chroot', chroot_path, '--cache_dir', cache_dir]
Brian Harringb938c782012-02-29 15:14:38 -0800183 if chrome_root:
184 cmd.extend(['--chrome_root', chrome_root])
185 if chrome_root_mount:
186 cmd.extend(['--chrome_root_mount', chrome_root_mount])
Hidehiko Abeb5daf2f2017-03-02 17:57:43 +0900187 if goma_dir:
188 cmd.extend(['--goma_dir', goma_dir])
189 if goma_client_json:
190 cmd.extend(['--goma_client_json', goma_client_json])
Yong Hong84ba9172018-02-07 01:37:42 +0800191 if working_dir is not None:
192 cmd.extend(['--working_dir', working_dir])
Don Garrett230d1b22015-03-09 16:21:19 -0700193
Mike Frysinger53ffaae2019-08-27 16:30:27 -0400194 if additional_args:
Brian Harringb938c782012-02-29 15:14:38 -0800195 cmd.append('--')
196 cmd.extend(additional_args)
Brian Harring7199e7d2012-03-23 04:10:08 -0700197
Ting-Yuan Huangf56d9af2017-06-19 16:08:32 -0700198 # ThinLTO opens lots of files at the same time.
Bob Haarman7c9f31b2020-10-12 19:08:51 +0000199 # Set rlimit and vm.max_map_count to accommodate this.
200 file_limit = 262144
201 soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
202 resource.setrlimit(resource.RLIMIT_NOFILE,
203 (max(soft, file_limit), max(hard, file_limit)))
204 max_map_count = int(open('/proc/sys/vm/max_map_count').read())
205 if max_map_count < file_limit:
206 logging.notice(
207 'Raising vm.max_map_count from %s to %s', max_map_count, file_limit)
208 open('/proc/sys/vm/max_map_count', 'w').write(f'{file_limit}\n')
Mike Frysingere1407f62021-10-30 01:56:40 -0400209 return cros_build_lib.dbg_run(cmd, check=False)
Brian Harringb938c782012-02-29 15:14:38 -0800210
211
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600212def _ImageFileForChroot(chroot):
213 """Find the image file that should be associated with |chroot|.
214
215 This function does not check if the image exists; it simply returns the
216 filename that would be used.
217
218 Args:
219 chroot: Path to the chroot.
220
221 Returns:
222 Path to an image file that would be associated with chroot.
223 """
224 return chroot.rstrip('/') + '.img'
225
226
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600227def CreateChrootSnapshot(snapshot_name, chroot_vg, chroot_lv):
228 """Create a snapshot for the specified chroot VG/LV.
229
230 Args:
231 snapshot_name: The name of the new snapshot.
232 chroot_vg: The name of the VG containing the origin LV.
233 chroot_lv: The name of the origin LV.
234
235 Returns:
236 True if the snapshot was created, or False if a snapshot with the same
237 name already exists.
238
239 Raises:
240 SystemExit: The lvcreate command failed.
241 """
242 if snapshot_name in ListChrootSnapshots(chroot_vg, chroot_lv):
Manoj Guptab12f7302019-06-03 16:40:14 -0700243 logging.error(
244 'Cannot create snapshot %s: A volume with that name already '
245 'exists.', snapshot_name)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600246 return False
247
Manoj Guptab12f7302019-06-03 16:40:14 -0700248 cmd = [
249 'lvcreate', '-s', '--name', snapshot_name,
250 '%s/%s' % (chroot_vg, chroot_lv)
251 ]
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600252 try:
253 logging.notice('Creating snapshot %s from %s in VG %s.', snapshot_name,
254 chroot_lv, chroot_vg)
Mike Frysinger3e8de442020-02-14 16:46:28 -0500255 cros_build_lib.dbg_run(cmd, capture_output=True)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600256 return True
Mike Frysinger75634e32020-02-22 23:48:12 -0500257 except cros_build_lib.RunCommandError as e:
258 cros_build_lib.Die('Creating snapshot failed!\n%s', e)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600259
260
261def DeleteChrootSnapshot(snapshot_name, chroot_vg, chroot_lv):
262 """Delete the named snapshot from the specified chroot VG.
263
264 If the requested snapshot is not found, nothing happens. The main chroot LV
265 and internal thinpool LV cannot be deleted with this function.
266
267 Args:
268 snapshot_name: The name of the snapshot to delete.
269 chroot_vg: The name of the VG containing the origin LV.
270 chroot_lv: The name of the origin LV.
271
272 Raises:
273 SystemExit: The lvremove command failed.
274 """
Benjamin Gordon74645232018-05-04 17:40:42 -0600275 if snapshot_name in (cros_sdk_lib.CHROOT_LV_NAME,
276 cros_sdk_lib.CHROOT_THINPOOL_NAME):
Manoj Guptab12f7302019-06-03 16:40:14 -0700277 logging.error(
278 'Cannot remove LV %s as a snapshot. Use cros_sdk --delete '
279 'if you want to remove the whole chroot.', snapshot_name)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600280 return
281
282 if snapshot_name not in ListChrootSnapshots(chroot_vg, chroot_lv):
283 return
284
285 cmd = ['lvremove', '-f', '%s/%s' % (chroot_vg, snapshot_name)]
286 try:
287 logging.notice('Deleting snapshot %s in VG %s.', snapshot_name, chroot_vg)
Mike Frysinger3e8de442020-02-14 16:46:28 -0500288 cros_build_lib.dbg_run(cmd, capture_output=True)
Mike Frysinger75634e32020-02-22 23:48:12 -0500289 except cros_build_lib.RunCommandError as e:
290 cros_build_lib.Die('Deleting snapshot failed!\n%s', e)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600291
292
293def RestoreChrootSnapshot(snapshot_name, chroot_vg, chroot_lv):
294 """Restore the chroot to an existing snapshot.
295
296 This is done by renaming the original |chroot_lv| LV to a temporary name,
297 renaming the snapshot named |snapshot_name| to |chroot_lv|, and deleting the
298 now unused LV. If an error occurs, attempts to rename the original snapshot
299 back to |chroot_lv| to leave the chroot unchanged.
300
301 The chroot must be unmounted before calling this function, and will be left
302 unmounted after this function returns.
303
304 Args:
305 snapshot_name: The name of the snapshot to restore. This snapshot will no
306 longer be accessible at its original name after this function finishes.
307 chroot_vg: The VG containing the chroot LV and snapshot LV.
308 chroot_lv: The name of the original chroot LV.
309
310 Returns:
311 True if the chroot was restored to the requested snapshot, or False if
312 the snapshot wasn't found or isn't valid.
313
314 Raises:
315 SystemExit: Any of the LVM commands failed.
316 """
317 valid_snapshots = ListChrootSnapshots(chroot_vg, chroot_lv)
Benjamin Gordon74645232018-05-04 17:40:42 -0600318 if (snapshot_name in (cros_sdk_lib.CHROOT_LV_NAME,
319 cros_sdk_lib.CHROOT_THINPOOL_NAME) or
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600320 snapshot_name not in valid_snapshots):
321 logging.error('Chroot cannot be restored to %s. Valid snapshots: %s',
322 snapshot_name, ', '.join(valid_snapshots))
323 return False
324
325 backup_chroot_name = 'chroot-bak-%d' % random.randint(0, 1000)
326 cmd = ['lvrename', chroot_vg, chroot_lv, backup_chroot_name]
327 try:
Mike Frysinger3e8de442020-02-14 16:46:28 -0500328 cros_build_lib.dbg_run(cmd, capture_output=True)
Mike Frysinger75634e32020-02-22 23:48:12 -0500329 except cros_build_lib.RunCommandError as e:
330 cros_build_lib.Die('Restoring snapshot failed!\n%s', e)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600331
332 cmd = ['lvrename', chroot_vg, snapshot_name, chroot_lv]
333 try:
Mike Frysinger3e8de442020-02-14 16:46:28 -0500334 cros_build_lib.dbg_run(cmd, capture_output=True)
Mike Frysinger75634e32020-02-22 23:48:12 -0500335 except cros_build_lib.RunCommandError as e:
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600336 cmd = ['lvrename', chroot_vg, backup_chroot_name, chroot_lv]
337 try:
Mike Frysinger3e8de442020-02-14 16:46:28 -0500338 cros_build_lib.dbg_run(cmd, capture_output=True)
Mike Frysinger75634e32020-02-22 23:48:12 -0500339 except cros_build_lib.RunCommandError as e:
340 cros_build_lib.Die(
341 'Failed to rename %s to chroot and failed to restore %s back to '
342 'chroot!\n%s', snapshot_name, backup_chroot_name, e)
343 cros_build_lib.Die(
344 'Failed to rename %s to chroot! Original chroot LV has '
345 'been restored.\n%s', snapshot_name, e)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600346
347 # Some versions of LVM set snapshots to be skipped at auto-activate time.
348 # Other versions don't have this flag at all. We run lvchange to try
349 # disabling auto-skip and activating the volume, but ignore errors. Versions
350 # that don't have the flag should be auto-activated.
351 chroot_lv_path = '%s/%s' % (chroot_vg, chroot_lv)
352 cmd = ['lvchange', '-kn', chroot_lv_path]
Mike Frysinger45602c72019-09-22 02:15:11 -0400353 cros_build_lib.run(
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500354 cmd, print_cmd=False, capture_output=True, check=False)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600355
356 # Activate the LV in case the lvchange above was needed. Activating an LV
357 # that is already active shouldn't do anything, so this is safe to run even if
358 # the -kn wasn't needed.
359 cmd = ['lvchange', '-ay', chroot_lv_path]
Mike Frysinger3e8de442020-02-14 16:46:28 -0500360 cros_build_lib.dbg_run(cmd, capture_output=True)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600361
362 cmd = ['lvremove', '-f', '%s/%s' % (chroot_vg, backup_chroot_name)]
363 try:
Mike Frysinger3e8de442020-02-14 16:46:28 -0500364 cros_build_lib.dbg_run(cmd, capture_output=True)
Mike Frysinger75634e32020-02-22 23:48:12 -0500365 except cros_build_lib.RunCommandError as e:
366 cros_build_lib.Die('Failed to remove backup LV %s/%s!\n%s',
367 chroot_vg, backup_chroot_name, e)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600368
369 return True
370
371
372def ListChrootSnapshots(chroot_vg, chroot_lv):
373 """Return all snapshots in |chroot_vg| regardless of origin volume.
374
375 Args:
376 chroot_vg: The name of the VG containing the chroot.
377 chroot_lv: The name of the chroot LV.
378
379 Returns:
380 A (possibly-empty) list of snapshot LVs found in |chroot_vg|.
381
382 Raises:
383 SystemExit: The lvs command failed.
384 """
385 if not chroot_vg or not chroot_lv:
386 return []
387
Manoj Guptab12f7302019-06-03 16:40:14 -0700388 cmd = [
389 'lvs', '-o', 'lv_name,pool_lv,lv_attr', '-O', 'lv_name', '--noheadings',
390 '--separator', '\t', chroot_vg
391 ]
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600392 try:
Mike Frysinger45602c72019-09-22 02:15:11 -0400393 result = cros_build_lib.run(
Chris McDonaldffdf5aa2020-04-07 16:28:45 -0600394 cmd, print_cmd=False, stdout=True, encoding='utf-8')
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600395 except cros_build_lib.RunCommandError:
396 raise SystemExit('Running %r failed!' % cmd)
397
398 # Once the thin origin volume has been deleted, there's no way to tell a
399 # snapshot apart from any other volume. Since this VG is created and managed
400 # by cros_sdk, we'll assume that all volumes that share the same thin pool are
401 # valid snapshots.
402 snapshots = []
403 snapshot_attrs = re.compile(r'^V.....t.{2,}') # Matches a thin volume.
404 for line in result.output.splitlines():
405 lv_name, pool_lv, lv_attr = line.lstrip().split('\t')
Manoj Guptab12f7302019-06-03 16:40:14 -0700406 if (lv_name == chroot_lv or lv_name == cros_sdk_lib.CHROOT_THINPOOL_NAME or
Benjamin Gordon74645232018-05-04 17:40:42 -0600407 pool_lv != cros_sdk_lib.CHROOT_THINPOOL_NAME or
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600408 not snapshot_attrs.match(lv_attr)):
409 continue
410 snapshots.append(lv_name)
411 return snapshots
412
413
David James56e6c2c2012-10-24 23:54:41 -0700414def _SudoCommand():
415 """Get the 'sudo' command, along with all needed environment variables."""
416
David James5a73b4d2013-03-07 10:23:40 -0800417 # Pass in the ENVIRONMENT_WHITELIST and ENV_PASSTHRU variables so that
Mike Frysinger2bda4d12020-07-14 11:15:49 -0400418 # scripts in the chroot know what variables to pass through.
David James56e6c2c2012-10-24 23:54:41 -0700419 cmd = ['sudo']
Mike Frysinger2bda4d12020-07-14 11:15:49 -0400420 for key in constants.CHROOT_ENVIRONMENT_WHITELIST + constants.ENV_PASSTHRU:
David James56e6c2c2012-10-24 23:54:41 -0700421 value = os.environ.get(key)
422 if value is not None:
423 cmd += ['%s=%s' % (key, value)]
424
Mike Frysinger2bda4d12020-07-14 11:15:49 -0400425 # We keep PATH not for the chroot but for the re-exec & for programs we might
426 # run before we chroot into the SDK. The process that enters the SDK itself
427 # will take care of initializing PATH to the right value then. But we can't
428 # override the system's default PATH for root as that will hide /sbin.
429 cmd += ['CHROMEOS_SUDO_PATH=%s' % os.environ.get('PATH', '')]
430
David James56e6c2c2012-10-24 23:54:41 -0700431 # Pass in the path to the depot_tools so that users can access them from
432 # within the chroot.
Mike Frysinger08e75f12014-08-13 01:30:09 -0400433 cmd += ['DEPOT_TOOLS=%s' % constants.DEPOT_TOOLS_DIR]
Mike Frysinger749251e2014-01-29 05:04:27 -0500434
David James56e6c2c2012-10-24 23:54:41 -0700435 return cmd
436
437
Josh Triplett472a4182013-03-08 11:48:57 -0800438def _ReportMissing(missing):
439 """Report missing utilities, then exit.
440
441 Args:
442 missing: List of missing utilities, as returned by
443 osutils.FindMissingBinaries. If non-empty, will not return.
444 """
445
446 if missing:
447 raise SystemExit(
448 'The tool(s) %s were not found.\n'
449 'Please install the appropriate package in your host.\n'
450 'Example(ubuntu):\n'
Manoj Guptab12f7302019-06-03 16:40:14 -0700451 ' sudo apt-get install <packagename>' % ', '.join(missing))
Josh Triplett472a4182013-03-08 11:48:57 -0800452
453
454def _ProxySimSetup(options):
455 """Set up proxy simulator, and return only in the child environment.
456
457 TODO: Ideally, this should support multiple concurrent invocations of
458 cros_sdk --proxy-sim; currently, such invocations will conflict with each
459 other due to the veth device names and IP addresses. Either this code would
460 need to generate fresh, unused names for all of these before forking, or it
461 would need to support multiple concurrent cros_sdk invocations sharing one
462 proxy and allowing it to exit when unused (without counting on any local
463 service-management infrastructure on the host).
464 """
465
466 may_need_mpm = False
467 apache_bin = osutils.Which('apache2')
468 if apache_bin is None:
469 apache_bin = osutils.Which('apache2', PROXY_APACHE_FALLBACK_PATH)
470 if apache_bin is None:
471 _ReportMissing(('apache2',))
472 else:
473 may_need_mpm = True
474
475 # Module names and .so names included for ease of grepping.
476 apache_modules = [('proxy_module', 'mod_proxy.so'),
477 ('proxy_connect_module', 'mod_proxy_connect.so'),
478 ('proxy_http_module', 'mod_proxy_http.so'),
479 ('proxy_ftp_module', 'mod_proxy_ftp.so')]
480
481 # Find the apache module directory, and make sure it has the modules we need.
482 module_dirs = {}
483 for g in PROXY_APACHE_MODULE_GLOBS:
Mike Frysinger336f6b02020-05-09 00:03:28 -0400484 for _, so in apache_modules:
Josh Triplett472a4182013-03-08 11:48:57 -0800485 for f in glob.glob(os.path.join(g, so)):
486 module_dirs.setdefault(os.path.dirname(f), []).append(so)
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400487 for apache_module_path, modules_found in module_dirs.items():
Josh Triplett472a4182013-03-08 11:48:57 -0800488 if len(modules_found) == len(apache_modules):
489 break
490 else:
491 # Appease cros lint, which doesn't understand that this else block will not
492 # fall through to the subsequent code which relies on apache_module_path.
493 apache_module_path = None
494 raise SystemExit(
495 'Could not find apache module path containing all required modules: %s'
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500496 % ', '.join(so for mod, so in apache_modules))
Josh Triplett472a4182013-03-08 11:48:57 -0800497
498 def check_add_module(name):
499 so = 'mod_%s.so' % name
500 if os.access(os.path.join(apache_module_path, so), os.F_OK):
501 mod = '%s_module' % name
502 apache_modules.append((mod, so))
503 return True
504 return False
505
506 check_add_module('authz_core')
507 if may_need_mpm:
508 for mpm in PROXY_APACHE_MPMS:
509 if check_add_module('mpm_%s' % mpm):
510 break
511
512 veth_host = '%s-host' % PROXY_VETH_PREFIX
513 veth_guest = '%s-guest' % PROXY_VETH_PREFIX
514
Mike Frysinger77bf4af2016-02-26 17:13:15 -0500515 # Set up locks to sync the net namespace setup. We need the child to create
516 # the net ns first, and then have the parent assign the guest end of the veth
517 # interface to the child's new network namespace & bring up the proxy. Only
518 # then can the child move forward and rely on the network being up.
519 ns_create_lock = locking.PipeLock()
520 ns_setup_lock = locking.PipeLock()
Josh Triplett472a4182013-03-08 11:48:57 -0800521
522 pid = os.fork()
523 if not pid:
Mike Frysinger77bf4af2016-02-26 17:13:15 -0500524 # Create our new isolated net namespace.
Josh Triplett472a4182013-03-08 11:48:57 -0800525 namespaces.Unshare(namespaces.CLONE_NEWNET)
Mike Frysinger77bf4af2016-02-26 17:13:15 -0500526
527 # Signal the parent the ns is ready to be configured.
528 ns_create_lock.Post()
529 del ns_create_lock
530
531 # Wait for the parent to finish setting up the ns/proxy.
532 ns_setup_lock.Wait()
533 del ns_setup_lock
Josh Triplett472a4182013-03-08 11:48:57 -0800534
535 # Set up child side of the network.
536 commands = (
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500537 ('ip', 'link', 'set', 'up', 'lo'),
Manoj Guptab12f7302019-06-03 16:40:14 -0700538 ('ip', 'address', 'add', '%s/%u' % (PROXY_GUEST_IP, PROXY_NETMASK),
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500539 'dev', veth_guest),
540 ('ip', 'link', 'set', veth_guest, 'up'),
Josh Triplett472a4182013-03-08 11:48:57 -0800541 )
542 try:
543 for cmd in commands:
Mike Frysinger3e8de442020-02-14 16:46:28 -0500544 cros_build_lib.dbg_run(cmd)
Mike Frysinger75634e32020-02-22 23:48:12 -0500545 except cros_build_lib.RunCommandError as e:
546 cros_build_lib.Die('Proxy setup failed!\n%s', e)
Josh Triplett472a4182013-03-08 11:48:57 -0800547
548 proxy_url = 'http://%s:%u' % (PROXY_HOST_IP, PROXY_PORT)
549 for proto in ('http', 'https', 'ftp'):
550 os.environ[proto + '_proxy'] = proxy_url
551 for v in ('all_proxy', 'RSYNC_PROXY', 'no_proxy'):
552 os.environ.pop(v, None)
553 return
554
Josh Triplett472a4182013-03-08 11:48:57 -0800555 # Set up parent side of the network.
556 uid = int(os.environ.get('SUDO_UID', '0'))
557 gid = int(os.environ.get('SUDO_GID', '0'))
558 if uid == 0 or gid == 0:
559 for username in PROXY_APACHE_FALLBACK_USERS:
560 try:
561 pwnam = pwd.getpwnam(username)
562 uid, gid = pwnam.pw_uid, pwnam.pw_gid
563 break
564 except KeyError:
565 continue
566 if uid == 0 or gid == 0:
567 raise SystemExit('Could not find a non-root user to run Apache as')
568
569 chroot_parent, chroot_base = os.path.split(options.chroot)
570 pid_file = os.path.join(chroot_parent, '.%s-apache-proxy.pid' % chroot_base)
571 log_file = os.path.join(chroot_parent, '.%s-apache-proxy.log' % chroot_base)
572
Mike Frysinger77bf4af2016-02-26 17:13:15 -0500573 # Wait for the child to create the net ns.
574 ns_create_lock.Wait()
575 del ns_create_lock
576
Josh Triplett472a4182013-03-08 11:48:57 -0800577 apache_directives = [
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500578 'User #%u' % uid,
579 'Group #%u' % gid,
580 'PidFile %s' % pid_file,
581 'ErrorLog %s' % log_file,
582 'Listen %s:%u' % (PROXY_HOST_IP, PROXY_PORT),
583 'ServerName %s' % PROXY_HOST_IP,
584 'ProxyRequests On',
Mike Frysinger66ce4132019-07-17 22:52:52 -0400585 'AllowCONNECT %s' % ' '.join(str(x) for x in PROXY_CONNECT_PORTS),
Josh Triplett472a4182013-03-08 11:48:57 -0800586 ] + [
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500587 'LoadModule %s %s' % (mod, os.path.join(apache_module_path, so))
588 for (mod, so) in apache_modules
Josh Triplett472a4182013-03-08 11:48:57 -0800589 ]
590 commands = (
Manoj Guptab12f7302019-06-03 16:40:14 -0700591 ('ip', 'link', 'add', 'name', veth_host, 'type', 'veth', 'peer', 'name',
592 veth_guest),
593 ('ip', 'address', 'add', '%s/%u' % (PROXY_HOST_IP, PROXY_NETMASK), 'dev',
594 veth_host),
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500595 ('ip', 'link', 'set', veth_host, 'up'),
596 ([apache_bin, '-f', '/dev/null'] +
597 [arg for d in apache_directives for arg in ('-C', d)]),
598 ('ip', 'link', 'set', veth_guest, 'netns', str(pid)),
Josh Triplett472a4182013-03-08 11:48:57 -0800599 )
Manoj Guptab12f7302019-06-03 16:40:14 -0700600 cmd = None # Make cros lint happy.
Josh Triplett472a4182013-03-08 11:48:57 -0800601 try:
602 for cmd in commands:
Mike Frysinger3e8de442020-02-14 16:46:28 -0500603 cros_build_lib.dbg_run(cmd)
Mike Frysinger75634e32020-02-22 23:48:12 -0500604 except cros_build_lib.RunCommandError as e:
Josh Triplett472a4182013-03-08 11:48:57 -0800605 # Clean up existing interfaces, if any.
606 cmd_cleanup = ('ip', 'link', 'del', veth_host)
607 try:
Mike Frysinger45602c72019-09-22 02:15:11 -0400608 cros_build_lib.run(cmd_cleanup, print_cmd=False)
Josh Triplett472a4182013-03-08 11:48:57 -0800609 except cros_build_lib.RunCommandError:
Ralph Nathan59900422015-03-24 10:41:17 -0700610 logging.error('running %r failed', cmd_cleanup)
Mike Frysinger75634e32020-02-22 23:48:12 -0500611 cros_build_lib.Die('Proxy network setup failed!\n%s', e)
Mike Frysinger77bf4af2016-02-26 17:13:15 -0500612
613 # Signal the child that the net ns/proxy is fully configured now.
614 ns_setup_lock.Post()
615 del ns_setup_lock
Josh Triplett472a4182013-03-08 11:48:57 -0800616
Mike Frysingere2d8f0d2014-11-01 13:09:26 -0400617 process_util.ExitAsStatus(os.waitpid(pid, 0)[1])
Josh Triplett472a4182013-03-08 11:48:57 -0800618
619
Mike Frysingera78a56e2012-11-20 06:02:30 -0500620def _ReExecuteIfNeeded(argv):
David James56e6c2c2012-10-24 23:54:41 -0700621 """Re-execute cros_sdk as root.
622
623 Also unshare the mount namespace so as to ensure that processes outside
624 the chroot can't mess with our mounts.
625 """
626 if os.geteuid() != 0:
Mike Frysinger1f113512020-07-29 03:36:57 -0400627 # Make sure to preserve the active Python executable in case the version
628 # we're running as is not the default one found via the (new) $PATH.
629 cmd = _SudoCommand() + ['--'] + [sys.executable] + argv
Mike Frysinger3e8de442020-02-14 16:46:28 -0500630 logging.debug('Reexecing self via sudo:\n%s', cros_build_lib.CmdToStr(cmd))
Mike Frysingera78a56e2012-11-20 06:02:30 -0500631 os.execvp(cmd[0], cmd)
David James56e6c2c2012-10-24 23:54:41 -0700632
633
Mike Frysinger34db8692013-11-11 14:54:08 -0500634def _CreateParser(sdk_latest_version, bootstrap_latest_version):
635 """Generate and return the parser with all the options."""
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400636 usage = ('usage: %(prog)s [options] '
637 '[VAR1=val1 ... VAR2=val2] [--] [command [args]]')
Manoj Guptab12f7302019-06-03 16:40:14 -0700638 parser = commandline.ArgumentParser(
639 usage=usage, description=__doc__, caching=True)
Brian Harring218e13c2012-10-10 16:21:26 -0700640
Mike Frysinger34db8692013-11-11 14:54:08 -0500641 # Global options.
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500642 default_chroot = os.path.join(constants.SOURCE_ROOT,
643 constants.DEFAULT_CHROOT_DIR)
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400644 parser.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700645 '--chroot',
646 dest='chroot',
647 default=default_chroot,
648 type='path',
Brian Harring218e13c2012-10-10 16:21:26 -0700649 help=('SDK chroot dir name [%s]' % constants.DEFAULT_CHROOT_DIR))
Manoj Guptab12f7302019-06-03 16:40:14 -0700650 parser.add_argument(
651 '--nouse-image',
652 dest='use_image',
653 action='store_false',
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700654 default=False,
Manoj Guptab12f7302019-06-03 16:40:14 -0700655 help='Do not mount the chroot on a loopback image; '
656 'instead, create it directly in a directory.')
Benjamin Gordonacbaac22020-09-25 12:59:33 -0600657 parser.add_argument(
658 '--use-image',
659 dest='use_image',
660 action='store_true',
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700661 default=False,
Benjamin Gordonacbaac22020-09-25 12:59:33 -0600662 help='Mount the chroot on a loopback image '
663 'instead of creating it directly in a directory.')
Brian Harringb938c782012-02-29 15:14:38 -0800664
Manoj Guptab12f7302019-06-03 16:40:14 -0700665 parser.add_argument(
Alex Klein5e4b1bc2019-07-02 12:27:06 -0600666 '--chrome-root',
Manoj Guptab12f7302019-06-03 16:40:14 -0700667 '--chrome_root',
668 type='path',
669 help='Mount this chrome root into the SDK chroot')
670 parser.add_argument(
671 '--chrome_root_mount',
672 type='path',
673 help='Mount chrome into this path inside SDK chroot')
674 parser.add_argument(
675 '--nousepkg',
676 action='store_true',
677 default=False,
678 help='Do not use binary packages when creating a chroot.')
679 parser.add_argument(
680 '-u',
681 '--url',
682 dest='sdk_url',
683 help='Use sdk tarball located at this url. Use file:// '
684 'for local files.')
685 parser.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700686 '--sdk-version',
687 help=('Use this sdk version. For prebuilt, current is %r'
688 ', for bootstrapping it is %r.' % (sdk_latest_version,
689 bootstrap_latest_version)))
690 parser.add_argument(
691 '--goma_dir',
692 type='path',
693 help='Goma installed directory to mount into the chroot.')
694 parser.add_argument(
695 '--goma_client_json',
696 type='path',
697 help='Service account json file to use goma on bot. '
698 'Mounted into the chroot.')
Yong Hong84ba9172018-02-07 01:37:42 +0800699
700 # Use type=str instead of type='path' to prevent the given path from being
701 # transfered to absolute path automatically.
Manoj Guptab12f7302019-06-03 16:40:14 -0700702 parser.add_argument(
703 '--working-dir',
704 type=str,
705 help='Run the command in specific working directory in '
706 'chroot. If the given directory is a relative '
707 'path, this program will transfer the path to '
708 'the corresponding one inside chroot.')
Yong Hong84ba9172018-02-07 01:37:42 +0800709
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400710 parser.add_argument('commands', nargs=argparse.REMAINDER)
Mike Frysinger34db8692013-11-11 14:54:08 -0500711
712 # Commands.
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400713 group = parser.add_argument_group('Commands')
714 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700715 '--enter',
716 action='store_true',
717 default=False,
Mike Frysinger34db8692013-11-11 14:54:08 -0500718 help='Enter the SDK chroot. Implies --create.')
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400719 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700720 '--create',
721 action='store_true',
722 default=False,
Mike Frysinger34db8692013-11-11 14:54:08 -0500723 help='Create the chroot only if it does not already exist. '
724 'Implies --download.')
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400725 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700726 '--bootstrap',
727 action='store_true',
728 default=False,
Mike Frysinger34db8692013-11-11 14:54:08 -0500729 help='Build everything from scratch, including the sdk. '
730 'Use this only if you need to validate a change '
731 'that affects SDK creation itself (toolchain and '
732 'build are typically the only folk who need this). '
733 'Note this will quite heavily slow down the build. '
734 'This option implies --create --nousepkg.')
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400735 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700736 '-r',
737 '--replace',
738 action='store_true',
739 default=False,
Mike Frysinger34db8692013-11-11 14:54:08 -0500740 help='Replace an existing SDK chroot. Basically an alias '
741 'for --delete --create.')
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400742 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700743 '--delete',
744 action='store_true',
745 default=False,
Mike Frysinger34db8692013-11-11 14:54:08 -0500746 help='Delete the current SDK chroot if it exists.')
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400747 group.add_argument(
Michael Mortensene979a4d2020-06-24 13:09:42 -0600748 '--force',
749 action='store_true',
750 default=False,
751 help='Force unmount/delete of the current SDK chroot even if '
752 'obtaining the write lock fails.')
753 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700754 '--unmount',
755 action='store_true',
756 default=False,
Benjamin Gordon64a3f8d2018-06-08 10:34:39 -0600757 help='Unmount and clean up devices associated with the '
758 'SDK chroot if it exists. This does not delete the '
759 'backing image file, so the same chroot can be later '
760 're-mounted for reuse. To fully delete the chroot, use '
761 '--delete. This is primarily useful for working on '
762 'cros_sdk or the chroot setup; you should not need it '
763 'under normal circumstances.')
764 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700765 '--download',
766 action='store_true',
767 default=False,
Mike Frysinger34db8692013-11-11 14:54:08 -0500768 help='Download the sdk.')
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600769 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700770 '--snapshot-create',
771 metavar='SNAPSHOT_NAME',
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600772 help='Create a snapshot of the chroot. Requires that the chroot was '
Manoj Guptab12f7302019-06-03 16:40:14 -0700773 'created without the --nouse-image option.')
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600774 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700775 '--snapshot-restore',
776 metavar='SNAPSHOT_NAME',
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600777 help='Restore the chroot to a previously created snapshot.')
778 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700779 '--snapshot-delete',
780 metavar='SNAPSHOT_NAME',
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600781 help='Delete a previously created snapshot. Deleting a snapshot that '
Manoj Guptab12f7302019-06-03 16:40:14 -0700782 'does not exist is not an error.')
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600783 group.add_argument(
Manoj Guptab12f7302019-06-03 16:40:14 -0700784 '--snapshot-list',
785 action='store_true',
786 default=False,
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600787 help='List existing snapshots of the chroot and exit.')
Mike Frysinger34db8692013-11-11 14:54:08 -0500788 commands = group
789
Mike Frysinger80dfce92014-04-21 10:58:53 -0400790 # Namespace options.
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400791 group = parser.add_argument_group('Namespaces')
Manoj Guptab12f7302019-06-03 16:40:14 -0700792 group.add_argument(
793 '--proxy-sim',
794 action='store_true',
795 default=False,
796 help='Simulate a restrictive network requiring an outbound'
797 ' proxy.')
Mike Frysinger79024a32021-04-05 03:28:35 -0400798 for ns, default in (('pid', True), ('net', None)):
799 group.add_argument(
800 f'--ns-{ns}',
801 default=default,
802 action='store_true',
803 help=f'Create a new {ns} namespace.')
804 group.add_argument(
805 f'--no-ns-{ns}',
806 dest=f'ns_{ns}',
807 action='store_false',
808 help=f'Do not create a new {ns} namespace.')
Mike Frysinger80dfce92014-04-21 10:58:53 -0400809
Mike Frysinger34db8692013-11-11 14:54:08 -0500810 # Internal options.
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400811 group = parser.add_argument_group(
Mike Frysinger34db8692013-11-11 14:54:08 -0500812 'Internal Chromium OS Build Team Options',
813 'Caution: these are for meant for the Chromium OS build team only')
Manoj Guptab12f7302019-06-03 16:40:14 -0700814 group.add_argument(
815 '--buildbot-log-version',
816 default=False,
817 action='store_true',
818 help='Log SDK version for buildbot consumption')
Mike Frysinger34db8692013-11-11 14:54:08 -0500819
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400820 return parser, commands
Mike Frysinger34db8692013-11-11 14:54:08 -0500821
822
823def main(argv):
Greg Edelston97f4e302020-03-13 14:01:23 -0600824 # Turn on strict sudo checks.
825 cros_build_lib.STRICT_SUDO = True
Mike Frysingere652ba12019-09-08 00:57:43 -0400826 conf = key_value_store.LoadFile(
Mike Frysinger34db8692013-11-11 14:54:08 -0500827 os.path.join(constants.SOURCE_ROOT, constants.SDK_VERSION_FILE),
828 ignore_missing=True)
829 sdk_latest_version = conf.get('SDK_LATEST_VERSION', '<unknown>')
Manoj Gupta01927c12019-05-13 17:33:14 -0700830 bootstrap_frozen_version = conf.get('BOOTSTRAP_FROZEN_VERSION', '<unknown>')
Manoj Gupta55a63092019-06-13 11:47:13 -0700831
832 # Use latest SDK for bootstrapping if requested. Use a frozen version of SDK
833 # for bootstrapping if BOOTSTRAP_FROZEN_VERSION is set.
834 bootstrap_latest_version = (
835 sdk_latest_version
836 if bootstrap_frozen_version == '<unknown>' else bootstrap_frozen_version)
Mike Frysinger34db8692013-11-11 14:54:08 -0500837 parser, commands = _CreateParser(sdk_latest_version, bootstrap_latest_version)
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400838 options = parser.parse_args(argv)
839 chroot_command = options.commands
Brian Harringb938c782012-02-29 15:14:38 -0800840
841 # Some sanity checks first, before we ask for sudo credentials.
Mike Frysinger8fd67dc2012-12-03 23:51:18 -0500842 cros_build_lib.AssertOutsideChroot()
Brian Harringb938c782012-02-29 15:14:38 -0800843
Brian Harring1790ac42012-09-23 08:53:33 -0700844 host = os.uname()[4]
Brian Harring1790ac42012-09-23 08:53:33 -0700845 if host != 'x86_64':
Benjamin Gordon040a1162017-06-29 13:44:47 -0600846 cros_build_lib.Die(
Brian Harring1790ac42012-09-23 08:53:33 -0700847 "cros_sdk is currently only supported on x86_64; you're running"
Mike Frysinger80de5012019-08-01 14:10:53 -0400848 ' %s. Please find a x86_64 machine.' % (host,))
Brian Harring1790ac42012-09-23 08:53:33 -0700849
Mike Frysinger2bda4d12020-07-14 11:15:49 -0400850 # Merge the outside PATH setting if we re-execed ourselves.
851 if 'CHROMEOS_SUDO_PATH' in os.environ:
852 os.environ['PATH'] = '%s:%s' % (os.environ.pop('CHROMEOS_SUDO_PATH'),
853 os.environ['PATH'])
854
Josh Triplett472a4182013-03-08 11:48:57 -0800855 _ReportMissing(osutils.FindMissingBinaries(NEEDED_TOOLS))
856 if options.proxy_sim:
857 _ReportMissing(osutils.FindMissingBinaries(PROXY_NEEDED_TOOLS))
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600858 missing_image_tools = osutils.FindMissingBinaries(IMAGE_NEEDED_TOOLS)
Brian Harringb938c782012-02-29 15:14:38 -0800859
Benjamin Gordon040a1162017-06-29 13:44:47 -0600860 if (sdk_latest_version == '<unknown>' or
861 bootstrap_latest_version == '<unknown>'):
862 cros_build_lib.Die(
863 'No SDK version was found. '
864 'Are you in a Chromium source tree instead of Chromium OS?\n\n'
865 'Please change to a directory inside your Chromium OS source tree\n'
866 'and retry. If you need to setup a Chromium OS source tree, see\n'
Mike Frysingerdcad4e02018-08-03 16:20:02 -0400867 ' https://dev.chromium.org/chromium-os/developer-guide')
Benjamin Gordon040a1162017-06-29 13:44:47 -0600868
Manoj Guptab12f7302019-06-03 16:40:14 -0700869 any_snapshot_operation = (
870 options.snapshot_create or options.snapshot_restore or
871 options.snapshot_delete or options.snapshot_list)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600872
Manoj Guptab12f7302019-06-03 16:40:14 -0700873 if (options.snapshot_delete and
874 options.snapshot_delete == options.snapshot_restore):
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600875 parser.error('Cannot --snapshot_delete the same snapshot you are '
876 'restoring with --snapshot_restore.')
877
David James471532c2013-01-21 10:23:31 -0800878 _ReExecuteIfNeeded([sys.argv[0]] + argv)
879
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600880 lock_path = os.path.dirname(options.chroot)
881 lock_path = os.path.join(
882 lock_path, '.%s_lock' % os.path.basename(options.chroot).lstrip('.'))
883
Brian Harring218e13c2012-10-10 16:21:26 -0700884 # Expand out the aliases...
885 if options.replace:
886 options.delete = options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800887
Brian Harring218e13c2012-10-10 16:21:26 -0700888 if options.bootstrap:
889 options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800890
Brian Harring218e13c2012-10-10 16:21:26 -0700891 # If a command is not given, default to enter.
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400892 # pylint: disable=protected-access
893 # This _group_actions access sucks, but upstream decided to not include an
894 # alternative to optparse's option_list, and this is what they recommend.
Manoj Guptab12f7302019-06-03 16:40:14 -0700895 options.enter |= not any(
896 getattr(options, x.dest) for x in commands._group_actions)
Mike Frysinger2f95cfc2015-06-04 04:00:26 -0400897 # pylint: enable=protected-access
Brian Harring218e13c2012-10-10 16:21:26 -0700898 options.enter |= bool(chroot_command)
899
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600900 if (options.delete and not options.create and
901 (options.enter or any_snapshot_operation)):
Mike Frysinger80de5012019-08-01 14:10:53 -0400902 parser.error('Trying to enter or snapshot the chroot when --delete '
903 'was specified makes no sense.')
Brian Harring218e13c2012-10-10 16:21:26 -0700904
Benjamin Gordon64a3f8d2018-06-08 10:34:39 -0600905 if (options.unmount and
906 (options.create or options.enter or any_snapshot_operation)):
907 parser.error('--unmount cannot be specified with other chroot actions.')
908
Yong Hong84ba9172018-02-07 01:37:42 +0800909 if options.working_dir is not None and not os.path.isabs(options.working_dir):
910 options.working_dir = path_util.ToChrootPath(options.working_dir)
911
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700912 # If there is an existing chroot image and we're not removing it then force
913 # use_image on. This ensures that people don't have to remember to pass
914 # --use-image after a reboot to avoid losing access to their existing chroot.
Benjamin Gordon7b44bef2018-06-08 08:13:59 -0600915 chroot_exists = cros_sdk_lib.IsChrootReady(options.chroot)
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700916 img_path = _ImageFileForChroot(options.chroot)
Benjamin Gordon832a4412020-12-08 10:39:16 -0700917 if (not options.use_image and not options.delete and not options.unmount
918 and os.path.exists(img_path)):
919 if chroot_exists:
920 # If the chroot is already populated, make sure it has something
921 # mounted on it before we assume it came from an image.
922 cmd = ['mountpoint', '-q', options.chroot]
923 if cros_build_lib.dbg_run(cmd, check=False).returncode == 0:
924 options.use_image = True
925
926 else:
927 logging.notice('Existing chroot image %s found. Forcing --use-image on.',
928 img_path)
929 options.use_image = True
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700930
Benjamin Gordon9bce7032020-11-19 09:58:44 -0700931 if any_snapshot_operation and not options.use_image:
932 if os.path.exists(img_path):
933 options.use_image = True
934 else:
935 cros_build_lib.Die('Snapshot operations are not compatible with '
936 '--nouse-image.')
937
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700938 # Discern if we need to create the chroot.
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600939 if (options.use_image and not chroot_exists and not options.delete and
Benjamin Gordon64a3f8d2018-06-08 10:34:39 -0600940 not options.unmount and not missing_image_tools and
Benjamin Gordon87b068a2020-11-02 11:22:16 -0700941 os.path.exists(img_path)):
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600942 # Try to re-mount an existing image in case the user has rebooted.
Mike Frysingerbf47cce2021-01-20 13:46:30 -0500943 with locking.FileLock(lock_path, 'chroot lock') as lock:
944 logging.debug('Checking if existing chroot image can be mounted.')
945 lock.write_lock()
946 cros_sdk_lib.MountChroot(options.chroot, create=False)
947 chroot_exists = cros_sdk_lib.IsChrootReady(options.chroot)
948 if chroot_exists:
949 logging.notice('Mounted existing image %s on chroot', img_path)
Brian Harring218e13c2012-10-10 16:21:26 -0700950
951 # Finally, flip create if necessary.
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600952 if options.enter or options.snapshot_create:
Brian Harring218e13c2012-10-10 16:21:26 -0700953 options.create |= not chroot_exists
Brian Harringb938c782012-02-29 15:14:38 -0800954
Benjamin Gordon7b44bef2018-06-08 08:13:59 -0600955 # Make sure we will download if we plan to create.
956 options.download |= options.create
957
Benjamin Gordon2d7bf582017-07-12 10:11:26 -0600958 # Anything that needs to manipulate the main chroot mount or communicate with
959 # LVM needs to be done here before we enter the new namespaces.
960
961 # If deleting, do it regardless of the use_image flag so that a
962 # previously-created loopback chroot can also be cleaned up.
Benjamin Gordon386b9eb2017-07-20 09:21:33 -0600963 if options.delete:
Mike Frysingerbf47cce2021-01-20 13:46:30 -0500964 # Set a timeout of 300 seconds when getting the lock.
965 with locking.FileLock(lock_path, 'chroot lock',
966 blocking_timeout=300) as lock:
967 try:
968 lock.write_lock()
969 except timeout_util.TimeoutError as e:
970 logging.error('Acquiring write_lock on %s failed: %s', lock_path, e)
971 if not options.force:
972 cros_build_lib.Die('Exiting; use --force to continue w/o lock.')
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600973 else:
Mike Frysingerbf47cce2021-01-20 13:46:30 -0500974 logging.warning(
975 'cros_sdk was invoked with force option, continuing.')
Mike Frysingerf6fe6d02021-06-16 20:26:35 -0400976 logging.notice('Deleting chroot.')
977 cros_sdk_lib.CleanupChrootMount(options.chroot, delete=True)
Benjamin Gordonabb3e372017-08-09 10:21:05 -0600978
Benjamin Gordon64a3f8d2018-06-08 10:34:39 -0600979 # If cleanup was requested, we have to do it while we're still in the original
980 # namespace. Since cleaning up the mount will interfere with any other
981 # commands, we exit here. The check above should have made sure that no other
982 # action was requested, anyway.
983 if options.unmount:
Michael Mortensenbf296fb2020-06-18 18:21:54 -0600984 # Set a timeout of 300 seconds when getting the lock.
985 with locking.FileLock(lock_path, 'chroot lock',
986 blocking_timeout=300) as lock:
987 try:
988 lock.write_lock()
989 except timeout_util.TimeoutError as e:
990 logging.error('Acquiring write_lock on %s failed: %s', lock_path, e)
Michael Mortensen1a176922020-07-14 20:53:35 -0600991 logging.warning(
992 'Continuing with CleanupChroot(%s), which will umount the tree.',
993 options.chroot)
Michael Mortensenbf296fb2020-06-18 18:21:54 -0600994 # We can call CleanupChroot (which calls cros_sdk_lib.CleanupChrootMount)
995 # even if we don't get the lock because it will attempt to unmount the
996 # tree and will print diagnostic information from 'fuser', 'lsof', and
997 # 'ps'.
Mike Frysingerf6fe6d02021-06-16 20:26:35 -0400998 cros_sdk_lib.CleanupChrootMount(options.chroot, delete=False)
Benjamin Gordon64a3f8d2018-06-08 10:34:39 -0600999 sys.exit(0)
1000
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001001 # Make sure the main chroot mount is visible. Contents will be filled in
1002 # below if needed.
Benjamin Gordonabb3e372017-08-09 10:21:05 -06001003 if options.create and options.use_image:
1004 if missing_image_tools:
Mike Frysinger80de5012019-08-01 14:10:53 -04001005 raise SystemExit("""The tool(s) %s were not found.
Benjamin Gordonabb3e372017-08-09 10:21:05 -06001006Please make sure the lvm2 and thin-provisioning-tools packages
1007are installed on your host.
1008Example(ubuntu):
1009 sudo apt-get install lvm2 thin-provisioning-tools
1010
1011If you want to run without lvm2, pass --nouse-image (chroot
Mike Frysinger80de5012019-08-01 14:10:53 -04001012snapshots will be unavailable).""" % ', '.join(missing_image_tools))
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001013
Benjamin Gordonabb3e372017-08-09 10:21:05 -06001014 logging.debug('Making sure chroot image is mounted.')
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001015 with locking.FileLock(lock_path, 'chroot lock') as lock:
1016 lock.write_lock()
1017 if not cros_sdk_lib.MountChroot(options.chroot, create=True):
1018 cros_build_lib.Die('Unable to mount %s on chroot',
1019 _ImageFileForChroot(options.chroot))
1020 logging.notice('Mounted %s on chroot',
1021 _ImageFileForChroot(options.chroot))
Benjamin Gordon386b9eb2017-07-20 09:21:33 -06001022
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001023 # Snapshot operations will always need the VG/LV, but other actions won't.
1024 if any_snapshot_operation:
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001025 with locking.FileLock(lock_path, 'chroot lock') as lock:
1026 chroot_vg, chroot_lv = cros_sdk_lib.FindChrootMountSource(options.chroot)
1027 if not chroot_vg or not chroot_lv:
1028 cros_build_lib.Die('Unable to find VG/LV for chroot %s', options.chroot)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001029
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001030 # Delete snapshot before creating a new one. This allows the user to
1031 # throw out old state, create a new snapshot, and enter the chroot in a
1032 # single call to cros_sdk. Since restore involves deleting, also do it
1033 # before creating.
1034 if options.snapshot_restore:
1035 lock.write_lock()
1036 valid_snapshots = ListChrootSnapshots(chroot_vg, chroot_lv)
1037 if options.snapshot_restore not in valid_snapshots:
1038 cros_build_lib.Die(
1039 '%s is not a valid snapshot to restore to. Valid snapshots: %s',
1040 options.snapshot_restore, ', '.join(valid_snapshots))
1041 osutils.UmountTree(options.chroot)
1042 if not RestoreChrootSnapshot(options.snapshot_restore, chroot_vg,
1043 chroot_lv):
1044 cros_build_lib.Die('Unable to restore chroot to snapshot.')
1045 if not cros_sdk_lib.MountChroot(options.chroot, create=False):
1046 cros_build_lib.Die('Unable to mount restored snapshot onto chroot.')
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001047
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001048 # Use a read lock for snapshot delete and create even though they modify
1049 # the filesystem, because they don't modify the mounted chroot itself.
1050 # The underlying LVM commands take their own locks, so conflicting
1051 # concurrent operations here may crash cros_sdk, but won't corrupt the
1052 # chroot image. This tradeoff seems worth it to allow snapshot
1053 # operations on chroots that have a process inside.
1054 if options.snapshot_delete:
1055 lock.read_lock()
1056 DeleteChrootSnapshot(options.snapshot_delete, chroot_vg, chroot_lv)
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001057
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001058 if options.snapshot_create:
1059 lock.read_lock()
1060 if not CreateChrootSnapshot(options.snapshot_create, chroot_vg,
1061 chroot_lv):
1062 cros_build_lib.Die('Unable to create snapshot.')
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001063
Benjamin Gordone3d5bd12017-11-16 15:42:28 -07001064 img_path = _ImageFileForChroot(options.chroot)
1065 if (options.use_image and os.path.exists(options.chroot) and
1066 os.path.exists(img_path)):
1067 img_stat = os.stat(img_path)
1068 img_used_bytes = img_stat.st_blocks * 512
1069
1070 mount_stat = os.statvfs(options.chroot)
Manoj Guptab12f7302019-06-03 16:40:14 -07001071 mount_used_bytes = mount_stat.f_frsize * (
1072 mount_stat.f_blocks - mount_stat.f_bfree)
Benjamin Gordone3d5bd12017-11-16 15:42:28 -07001073
Mike Frysinger93e8ffa2019-07-03 20:24:18 -04001074 extra_gbs = (img_used_bytes - mount_used_bytes) // 2**30
Benjamin Gordone3d5bd12017-11-16 15:42:28 -07001075 if extra_gbs > MAX_UNUSED_IMAGE_GBS:
1076 logging.notice('%s is using %s GiB more than needed. Running '
Sergey Frolov1cb46ec2020-12-09 21:46:16 -07001077 'fstrim in background.', img_path, extra_gbs)
1078 pid = os.fork()
1079 if pid == 0:
1080 try:
1081 # Directly call Popen to run fstrim concurrently.
1082 cmd = ['fstrim', options.chroot]
1083 subprocess.Popen(cmd, close_fds=True, shell=False)
1084 except subprocess.SubprocessError as e:
1085 logging.warning(
1086 'Running fstrim failed. Consider running fstrim on '
1087 'your chroot manually.\n%s', e)
1088 os._exit(0) # pylint: disable=protected-access
1089 os.waitpid(pid, 0)
Benjamin Gordone3d5bd12017-11-16 15:42:28 -07001090
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001091 # Enter a new set of namespaces. Everything after here cannot directly affect
1092 # the hosts's mounts or alter LVM volumes.
Mike Frysinger79024a32021-04-05 03:28:35 -04001093 namespaces.SimpleUnshare(net=options.ns_net, pid=options.ns_pid)
Benjamin Gordon386b9eb2017-07-20 09:21:33 -06001094
Benjamin Gordon2d7bf582017-07-12 10:11:26 -06001095 if options.snapshot_list:
1096 for snap in ListChrootSnapshots(chroot_vg, chroot_lv):
1097 print(snap)
1098 sys.exit(0)
1099
Brian Harringb938c782012-02-29 15:14:38 -08001100 if not options.sdk_version:
Manoj Guptab12f7302019-06-03 16:40:14 -07001101 sdk_version = (
1102 bootstrap_latest_version if options.bootstrap else sdk_latest_version)
Brian Harringb938c782012-02-29 15:14:38 -08001103 else:
1104 sdk_version = options.sdk_version
Mike Frysinger34db8692013-11-11 14:54:08 -05001105 if options.buildbot_log_version:
Chris McDonaldb55b7032021-06-17 16:41:32 -06001106 cbuildbot_alerts.PrintBuildbotStepText(sdk_version)
Brian Harringb938c782012-02-29 15:14:38 -08001107
Gilad Arnoldecc86fa2015-05-22 12:06:04 -07001108 # Based on selections, determine the tarball to fetch.
Yong Hong4e29b622018-02-05 14:31:10 +08001109 if options.download:
1110 if options.sdk_url:
1111 urls = [options.sdk_url]
Yong Hong4e29b622018-02-05 14:31:10 +08001112 else:
1113 urls = GetArchStageTarballs(sdk_version)
Brian Harring1790ac42012-09-23 08:53:33 -07001114
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001115 with locking.FileLock(lock_path, 'chroot lock') as lock:
1116 if options.proxy_sim:
1117 _ProxySimSetup(options)
Josh Triplett472a4182013-03-08 11:48:57 -08001118
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001119 sdk_cache = os.path.join(options.cache_dir, 'sdks')
1120 distfiles_cache = os.path.join(options.cache_dir, 'distfiles')
1121 osutils.SafeMakedirsNonRoot(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -07001122
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001123 for target in (sdk_cache, distfiles_cache):
1124 src = os.path.join(constants.SOURCE_ROOT, os.path.basename(target))
1125 if not os.path.exists(src):
1126 osutils.SafeMakedirsNonRoot(target)
1127 continue
1128 lock.write_lock(
1129 'Upgrade to %r needed but chroot is locked; please exit '
1130 'all instances so this upgrade can finish.' % src)
1131 if not os.path.exists(src):
1132 # Note that while waiting for the write lock, src may've vanished;
1133 # it's a rare race during the upgrade process that's a byproduct
1134 # of us avoiding taking a write lock to do the src check. If we
1135 # took a write lock for that check, it would effectively limit
1136 # all cros_sdk for a chroot to a single instance.
1137 osutils.SafeMakedirsNonRoot(target)
1138 elif not os.path.exists(target):
1139 # Upgrade occurred, but a reversion, or something whacky
1140 # occurred writing to the old location. Wipe and continue.
1141 os.rename(src, target)
1142 else:
1143 # Upgrade occurred once already, but either a reversion or
1144 # some before/after separate cros_sdk usage is at play.
1145 # Wipe and continue.
1146 osutils.RmDir(src)
Brian Harringae0a5322012-09-15 01:46:51 -07001147
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001148 if options.download:
1149 lock.write_lock()
1150 sdk_tarball = FetchRemoteTarballs(
1151 sdk_cache, urls, 'stage3' if options.bootstrap else 'SDK')
Brian Harring218e13c2012-10-10 16:21:26 -07001152
Mike Frysinger65b7b242021-06-17 21:11:25 -04001153 mounted = False
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001154 if options.create:
1155 lock.write_lock()
1156 # Recheck if the chroot is set up here before creating to make sure we
1157 # account for whatever the various delete/unmount/remount steps above
1158 # have done.
1159 if cros_sdk_lib.IsChrootReady(options.chroot):
1160 logging.debug('Chroot already exists. Skipping creation.')
1161 else:
Mike Frysinger23b5cf52021-06-16 23:18:00 -04001162 cros_sdk_lib.CreateChroot(
1163 Path(options.chroot),
1164 Path(sdk_tarball),
1165 Path(options.cache_dir),
1166 usepkg=not options.bootstrap and not options.nousepkg)
Mike Frysinger65b7b242021-06-17 21:11:25 -04001167 mounted = True
Brian Harring1790ac42012-09-23 08:53:33 -07001168
Mike Frysingerbf47cce2021-01-20 13:46:30 -05001169 if options.enter:
1170 lock.read_lock()
Mike Frysinger65b7b242021-06-17 21:11:25 -04001171 if not mounted:
1172 cros_sdk_lib.MountChrootPaths(options.chroot)
Mike Frysingere1407f62021-10-30 01:56:40 -04001173 ret = EnterChroot(options.chroot, options.cache_dir, options.chrome_root,
1174 options.chrome_root_mount, options.goma_dir,
1175 options.goma_client_json, options.working_dir,
1176 chroot_command)
1177 sys.exit(ret.returncode)