blob: 8c1da1522e4bb55092f96d7c40ec22f5dbdc4ef7 [file] [log] [blame]
Yilin Yang19da6932019-12-10 13:39:28 +08001#!/usr/bin/env python3
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +08002#
Hung-Te Lin1990b742017-08-09 17:34:57 +08003# Copyright 2014 The Chromium OS Authors. All rights reserved.
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +08004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Factory toolkit installer.
8
9The factory toolkit is a self-extracting shellball containing factory test
10related files and this installer. This installer is invoked when the toolkit
11is deployed and is responsible for installing files.
12"""
13
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080014import argparse
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080015from contextlib import contextmanager
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +080016import getpass
Hung-Te Lineb7632b2016-07-29 15:38:34 +080017import glob
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080018import os
Wei-Ning Huang4855e792015-06-11 15:33:39 +080019import shutil
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080020import sys
Jon Salz4f3ade52014-02-20 17:55:09 +080021import tempfile
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +080022import time
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080023
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080024from cros.factory.test.env import paths
Cheng-Han Yang3f746e82019-04-10 14:33:29 +080025from cros.factory.test.test_lists import test_list_common
Jon Salz25590302014-07-11 16:07:20 +080026from cros.factory.tools import install_symlinks
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +080027from cros.factory.utils import file_utils
Yong Hong89938e62018-10-26 11:59:21 +080028from cros.factory.utils import json_utils
Youcheng Syuac391772017-04-20 09:08:58 +000029from cros.factory.utils.process_utils import Spawn
Peter Shihfe221582017-06-15 13:40:53 +080030from cros.factory.utils import sys_utils
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080031
32
Wei-Han Chen1efb9142019-10-03 17:42:01 +080033PYTHONPATH = 'usr/local/factory/py_pkg'
34INSTALLER_MODULE = 'cros.factory.toolkit.installer'
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +080035VERSION_PATH = 'usr/local/factory/TOOLKIT_VERSION'
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +080036
Jon Salz4f3ade52014-02-20 17:55:09 +080037# Short and sweet help header for the executable generated by makeself.
38HELP_HEADER = """
39Installs the factory toolkit, transforming a test image into a factory test
40image. You can:
41
42- Install the factory toolkit on a CrOS device that is running a test
43 image. To do this, copy install_factory_toolkit.run to the device and
44 run it. The factory tests will then come up on the next boot.
45
46 rsync -a install_factory_toolkit.run crosdevice:/tmp
47 ssh crosdevice '/tmp/install_factory_toolkit.run && sync && reboot'
48
49- Modify a test image, turning it into a factory test image. When you
50 use the image on a device, the factory tests will come up.
51
52 install_factory_toolkit.run chromiumos_test_image.bin
53"""
54
55HELP_HEADER_ADVANCED = """
56- (advanced) Modify a mounted stateful partition, turning it into a factory
57 test image. This is equivalent to the previous command:
58
59 mount_partition -rw chromiumos_test_image.bin 1 /mnt/stateful
60 install_factory_toolkit.run /mnt/stateful
61 umount /mnt/stateful
62
63- (advanced) Unpack the factory toolkit, modify a file, and then repack it.
64
65 # Unpack but don't actually install
66 install_factory_toolkit.run --target /tmp/toolkit --noexec
67 # Edit some files in /tmp/toolkit
68 emacs /tmp/toolkit/whatever
69 # Repack
70 install_factory_toolkit.run -- --repack /tmp/toolkit \\
71 --pack-into /path/to/new/install_factory_toolkit.run
72"""
73
74# The makeself-generated header comes next. This is a little confusing,
75# so explain.
76HELP_HEADER_MAKESELF = """
77For complete usage information and advanced operations, run
78"install_factory_toolkit.run -- --help" (note the extra "--").
79
80Following is the help message from makeself, which was used to create
81this self-extracting archive.
82
83-----
84"""
85
Vic Yangdb1e20e2014-10-05 12:10:33 +080086SERVER_FILE_MASK = [
87 # Exclude Umpire server but keep Umpire client
88 '--include', 'py/umpire/__init__.*',
89 '--include', 'py/umpire/common.*',
90 '--include', 'py/umpire/client',
91 '--include', 'py/umpire/client/**',
92 '--exclude', 'py/umpire/**',
Peter Shihac904782017-06-14 15:24:09 +080093 '--exclude', 'bin/umpire',
94 '--exclude', 'bin/umpired',
Vic Yangdb1e20e2014-10-05 12:10:33 +080095]
96
Jon Salz4f3ade52014-02-20 17:55:09 +080097
Fei Shaobd07c9a2020-06-15 19:04:50 +080098class FactoryToolkitInstaller:
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080099 """Factory toolkit installer.
100
101 Args:
102 src: Source path containing usr/ and var/.
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800103 dest: Installation destination path. Set this to the mount point of the
104 stateful partition if patching a test image.
105 no_enable: True to not install the tag file.
106 system_root: The path to the root of the file system. This must be left
107 as its default value except for unit testing.
Peter Shih2f1f8c42017-06-15 15:05:55 +0800108 apps: The list of apps to enable/disable under factory/init/main.d/.
109 active_test_list: The id of active test list for Goofy.
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800110 """
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800111
Jon Salzb7e44262014-05-07 15:53:37 +0800112 # Whether to sudo when rsyncing; set to False for testing.
113 _sudo = True
114
Hung-Te Linfc162e62017-09-21 00:45:04 +0800115 def __init__(self, src, dest, no_enable, non_cros=False, system_root='/',
Peter Shih2f1f8c42017-06-15 15:05:55 +0800116 apps=None, active_test_list=None):
Jon Salz4f3ade52014-02-20 17:55:09 +0800117 self._src = src
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800118 self._system_root = system_root
119 if dest == self._system_root:
120 self._usr_local_dest = os.path.join(dest, 'usr', 'local')
Jon Salz4f3ade52014-02-20 17:55:09 +0800121
122 # Make sure we're on a CrOS device.
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800123 if not non_cros and not sys_utils.InCrOSDevice():
Jon Salz4f3ade52014-02-20 17:55:09 +0800124 sys.stderr.write(
Vic Yang196d5242014-08-05 13:51:35 +0800125 "ERROR: You're not on a CrOS device (for more details, please\n"
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800126 'check sys_utils.py:InCrOSDevice), so you must specify a test\n'
Hung-Te Lin56b18402015-01-16 14:52:30 +0800127 'image or a mounted stateful partition on which to install the\n'
128 'factory toolkit. Please run\n'
129 '\n'
130 ' install_factory_toolkit.run -- --help\n'
131 '\n'
Vic Yang70fdae92015-02-17 19:21:08 -0800132 'for help.\n'
133 '\n'
Hung-Te Linfc162e62017-09-21 00:45:04 +0800134 'If you want to install on a non-CrOS host,\n'
Vic Yang70fdae92015-02-17 19:21:08 -0800135 'please run\n'
136 '\n'
Hung-Te Linfc162e62017-09-21 00:45:04 +0800137 ' install_factory_toolkit.run -- --non-cros \n'
Vic Yang70fdae92015-02-17 19:21:08 -0800138 '\n')
Jon Salz4f3ade52014-02-20 17:55:09 +0800139 sys.exit(1)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800140 if os.getuid() != 0:
Jon Salz4f3ade52014-02-20 17:55:09 +0800141 raise Exception('You must be root to install the factory toolkit on a '
142 'CrOS device.')
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800143 else:
144 self._usr_local_dest = os.path.join(dest, 'dev_image')
Hung-Te Lin4aeabe62016-10-21 15:45:20 +0800145 if not os.path.exists(self._usr_local_dest):
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800146 raise Exception(
147 'The destination path %s is not a stateful partition!' % dest)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800148
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800149 self._dest = dest
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800150 self._usr_local_src = os.path.join(src, 'usr', 'local')
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800151 self._no_enable = no_enable
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800152 self._tag_file = os.path.join(self._usr_local_dest, 'factory', 'enabled')
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800153
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800154 self._apps = apps
Peter Shih2f1f8c42017-06-15 15:05:55 +0800155 self._active_test_list = active_test_list
Vic Yang7039f422014-07-07 15:38:13 -0700156
Hung-Te Lin4aeabe62016-10-21 15:45:20 +0800157 if not os.path.exists(self._usr_local_src):
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800158 raise Exception(
159 'This installer must be run from within the factory toolkit!')
160
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800161 def WarningMessage(self, target_test_image=None):
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +0800162 ret = file_utils.ReadFile(os.path.join(self._src, VERSION_PATH))
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800163 if target_test_image:
Jon Salz4f3ade52014-02-20 17:55:09 +0800164 ret += (
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800165 '\n'
166 '\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800167 '*** You are about to patch the factory toolkit into:\n'
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800168 '*** %s\n'
169 '***' % target_test_image)
170 else:
Jon Salz4f3ade52014-02-20 17:55:09 +0800171 ret += (
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800172 '\n'
173 '\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800174 '*** You are about to install the factory toolkit to:\n'
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800175 '*** %s\n'
176 '***' % self._dest)
177 if self._dest == self._system_root:
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800178 if self._no_enable:
Hung-Te Lin7b596ff2015-01-16 20:19:15 +0800179 ret += ('\n*** Factory tests will be disabled after this process is '
Hung-Te Lin56b18402015-01-16 14:52:30 +0800180 'done, but\n*** you can enable them by creating the factory '
181 'enabled tag:\n*** %s\n***' % self._tag_file)
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800182 else:
Hung-Te Lin7b596ff2015-01-16 20:19:15 +0800183 ret += ('\n*** After this process is done, your device will start '
Hung-Te Lin56b18402015-01-16 14:52:30 +0800184 'factory\n*** tests on the next reboot.\n***\n*** Factory '
185 'tests can be disabled by deleting the factory enabled\n*** '
186 'tag:\n*** %s\n***' % self._tag_file)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800187 return ret
188
Vic Yang7039f422014-07-07 15:38:13 -0700189 def _SetTagFile(self, name, path, enabled):
190 """Install or remove a tag file."""
191 if enabled:
Yilin Yang71e39412019-09-24 09:26:46 +0800192 print('*** Installing %s enabled tag...' % name)
Youcheng Syuac391772017-04-20 09:08:58 +0000193 Spawn(['touch', path], sudo=True, log=True, check_call=True)
194 Spawn(['chmod', 'go+r', path], sudo=True, log=True, check_call=True)
Vic Yang7039f422014-07-07 15:38:13 -0700195 else:
Yilin Yang71e39412019-09-24 09:26:46 +0800196 print('*** Removing %s enabled tag...' % name)
Youcheng Syuac391772017-04-20 09:08:58 +0000197 Spawn(['rm', '-f', path], sudo=True, log=True, check_call=True)
Vic Yang7039f422014-07-07 15:38:13 -0700198
Peter Shih2f1f8c42017-06-15 15:05:55 +0800199 def _SetActiveTestList(self):
200 """Set the active test list for Goofy."""
201 if self._active_test_list is not None:
Cheng-Han Yang5242a1f2019-01-16 20:00:05 +0800202 path = os.path.join(self._usr_local_dest, 'factory',
Cheng-Han Yang3f746e82019-04-10 14:33:29 +0800203 test_list_common.ACTIVE_TEST_LIST_CONFIG_RELPATH)
204 json_utils.DumpFile(
205 path,
206 test_list_common.GenerateActiveTestListConfig(self._active_test_list))
Peter Shih2f1f8c42017-06-15 15:05:55 +0800207
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800208 def _EnableApp(self, app, enabled):
209 """Enable / disable @app.
210
211 In factory/init/startup, a main app is considered disabled if and only:
212 1. file "factory/init/main.d/disable-@app" exists OR
213 2. file "factory/init/main.d/enable-@app" doesn't exist AND
214 file "factory/init/main.d/@app.sh" is not executable.
215
216 Therefore, we enable an app by removing file "disable-@app" and creating
You-Cheng Syu70e99ad2017-03-09 17:15:00 +0800217 file "enable-@app", and vice versa.
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800218 """
219 app_enable = os.path.join(self._usr_local_dest,
220 'factory', 'init', 'main.d', 'enable-' + app)
221 app_disable = os.path.join(self._usr_local_dest,
222 'factory', 'init', 'main.d', 'disable-' + app)
223 if enabled:
Yilin Yang71e39412019-09-24 09:26:46 +0800224 print('*** Enabling {app} ***'.format(app=app))
Youcheng Syuac391772017-04-20 09:08:58 +0000225 Spawn(['rm', '-f', app_disable], sudo=self._sudo, log=True,
226 check_call=True)
227 Spawn(['touch', app_enable], sudo=self._sudo, log=True, check_call=True)
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800228 else:
Yilin Yang71e39412019-09-24 09:26:46 +0800229 print('*** Disabling {app} ***'.format(app=app))
Youcheng Syuac391772017-04-20 09:08:58 +0000230 Spawn(['touch', app_disable], sudo=self._sudo, log=True, check_call=True)
231 Spawn(['rm', '-f', app_enable], sudo=self._sudo, log=True,
232 check_call=True)
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800233
234 def _EnableApps(self):
235 if not self._apps:
236 return
237
238 app_list = []
239 for app in self._apps:
240 if app[0] == '+':
241 app_list.append((app[1:], True))
242 elif app[0] == '-':
243 app_list.append((app[1:], False))
244 else:
245 raise ValueError(
246 'Use +{app} to enable and -{app} to disable'.format(app=app))
247
248 for app, enabled in app_list:
249 self._EnableApp(app, enabled)
250
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800251 def InstallFactorySubDir(self, sub_dirs):
252 """Install only the specified directories under factory folder."""
253
254 def _InstallOneSubDir(sub_dir_name):
255 sub_dir_dest = os.path.join(self._usr_local_dest, 'factory', sub_dir_name)
256 sub_dir_src = os.path.join(self._src, 'usr', 'local', 'factory',
257 sub_dir_name)
258 try:
Youcheng Syuac391772017-04-20 09:08:58 +0000259 Spawn(['mkdir', '-p', sub_dir_dest], sudo=True, log=True,
260 check_call=True)
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800261 except OSError as e:
Yilin Yang71e39412019-09-24 09:26:46 +0800262 print(str(e))
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800263 return
264
Youcheng Syuac391772017-04-20 09:08:58 +0000265 Spawn(['rsync', '-a', '--force', '-v',
266 sub_dir_src + '/', sub_dir_dest],
267 sudo=self._sudo, log=True, check_call=True)
268 Spawn(['chown', '-R', 'root', sub_dir_dest],
269 sudo=self._sudo, log=True, check_call=True)
270 Spawn(['chmod', '-R', 'go+rX', sub_dir_dest],
271 sudo=self._sudo, log=True, check_call=True)
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800272
273 for sub_dir_name in sub_dirs:
274 _InstallOneSubDir(sub_dir_name)
275
276 self._SetTagFile('factory', self._tag_file, not self._no_enable)
277 self._EnableApps()
278
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800279 def Install(self):
Yilin Yang71e39412019-09-24 09:26:46 +0800280 print('*** Installing factory toolkit...')
Mao Huangf75aa3e2016-11-24 11:44:17 +0800281
282 # --no-owner and --no-group will set owner/group to the current user/group
283 # running the command. This is important if we're running with sudo, so
284 # the destination will be changed to root/root instead of the user/group
285 # before sudo (doesn't matter if sudo is not present). --force is also
286 # necessary to allow goofy directory from prior toolkit installations to
287 # be overwritten by the goofy symlink.
Yilin Yang71e39412019-09-24 09:26:46 +0800288 print('*** %s -> %s' % (self._usr_local_src, self._usr_local_dest))
Youcheng Syuac391772017-04-20 09:08:58 +0000289 Spawn(['rsync', '-a', '--no-owner', '--no-group', '--chmod=ugo+rX',
290 '--force'] + SERVER_FILE_MASK + [self._usr_local_src + '/',
291 self._usr_local_dest],
292 sudo=self._sudo, log=True, check_output=True, cwd=self._usr_local_src)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800293
Yilin Yang71e39412019-09-24 09:26:46 +0800294 print('*** Ensure SSH keys file permission...')
Hung-Te Lineb7632b2016-07-29 15:38:34 +0800295 sshkeys_dir = os.path.join(self._usr_local_dest, 'factory/misc/sshkeys')
296 sshkeys = glob.glob(os.path.join(sshkeys_dir, '*'))
297 ssh_public_keys = glob.glob(os.path.join(sshkeys_dir, '*.pub'))
298 ssh_private_keys = list(set(sshkeys) - set(ssh_public_keys))
299 if ssh_private_keys:
Youcheng Syuac391772017-04-20 09:08:58 +0000300 Spawn(['chmod', '600'] + ssh_private_keys, log=True, check_call=True,
301 sudo=self._sudo)
Hung-Te Lineb7632b2016-07-29 15:38:34 +0800302
Yilin Yang71e39412019-09-24 09:26:46 +0800303 print('*** Installing symlinks...')
Jon Salz25590302014-07-11 16:07:20 +0800304 install_symlinks.InstallSymlinks(
305 '../factory/bin',
306 os.path.join(self._usr_local_dest, 'bin'),
307 install_symlinks.MODE_FULL,
308 sudo=self._sudo)
309
Vic Yang7039f422014-07-07 15:38:13 -0700310 self._SetTagFile('factory', self._tag_file, not self._no_enable)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800311
Peter Shih2f1f8c42017-06-15 15:05:55 +0800312 self._SetActiveTestList()
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800313 self._EnableApps()
Wei-Ning Huang5135b7e2015-07-03 17:31:15 +0800314
Yilin Yang71e39412019-09-24 09:26:46 +0800315 print('*** Installation completed.')
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800316
317
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800318@contextmanager
319def DummyContext(arg):
320 """A context manager that simply yields its argument."""
321 yield arg
322
323
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800324def PrintBuildInfo(src_root):
325 """Print build information."""
326 info_file = os.path.join(src_root, 'REPO_STATUS')
327 if not os.path.exists(info_file):
328 raise OSError('Build info file not found!')
Yilin Yang71e39412019-09-24 09:26:46 +0800329 print(file_utils.ReadFile(info_file))
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800330
331
Cheng Yueh1df18152021-03-31 18:17:37 +0800332def PackFactoryToolkit(src_root, output_path, initial_version, quiet=False):
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800333 """Packs the files containing this script into a factory toolkit."""
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +0800334 if initial_version is None:
335 complete_version = '%s repacked by %s@%s at %s\n' % (
336 file_utils.ReadFile(os.path.join(src_root, VERSION_PATH)),
337 getpass.getuser(), os.uname()[1], time.strftime('%Y-%m-%d %H:%M:%S'))
338 initial_version = complete_version.splitlines()[0]
339 else:
340 complete_version = initial_version + '\n'
341 modified_times = len(complete_version.splitlines()) - 1
342 if modified_times == 0:
343 modified_msg = ''
344 else:
345 modified_msg = ' (modified %d times)' % modified_times
Yilin Yang09312c52019-12-04 13:50:35 +0800346 with tempfile.NamedTemporaryFile('w') as help_header:
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +0800347 help_header.write(initial_version + '\n' +
348 HELP_HEADER + HELP_HEADER_MAKESELF)
Jon Salz4f3ade52014-02-20 17:55:09 +0800349 help_header.flush()
Wei-Ning Huangb723d7f2014-11-17 17:26:32 +0800350 cmd = [os.path.join(src_root, 'makeself.sh'), '--bzip2', '--nox11',
Jon Salz4f3ade52014-02-20 17:55:09 +0800351 '--help-header', help_header.name,
Meng-Huan Yuea9dd912019-08-07 17:45:17 +0800352 src_root, # archive_dir
353 output_path, # file_name
354 initial_version + modified_msg, # label
355 # startup script and args
356 # We have to explicitly execute python instead of directly execute
357 # INSTALLER_PATH because files under INSTALLER_PATH may not be
358 # executable.
Wei-Han Chen1efb9142019-10-03 17:42:01 +0800359 'env', 'PYTHONPATH=' + PYTHONPATH,
Yilin Yang19da6932019-12-10 13:39:28 +0800360 'python3', '-m', INSTALLER_MODULE, '--in-exe']
Cheng Yueh1df18152021-03-31 18:17:37 +0800361 Spawn(cmd, check_call=True, log=True, read_stdout=quiet, read_stderr=quiet)
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +0800362 with file_utils.TempDirectory() as tmp_dir:
363 version_path = os.path.join(tmp_dir, VERSION_PATH)
364 os.makedirs(os.path.dirname(version_path))
365 file_utils.WriteFile(version_path, complete_version)
You-Cheng Syuc0682732017-05-10 12:17:05 +0800366 Spawn([cmd[0], '--lsm', version_path, '--append', tmp_dir, output_path],
Cheng Yueh1df18152021-03-31 18:17:37 +0800367 check_call=True, log=True, read_stdout=quiet, read_stderr=quiet)
Yilin Yang71e39412019-09-24 09:26:46 +0800368 print('\n'
369 ' Factory toolkit generated at %s.\n'
370 '\n'
371 ' To install factory toolkit on a live device running a test image,\n'
372 ' copy this to the device and execute it as root.\n'
373 '\n'
374 ' Alternatively, the factory toolkit can be used to patch a test\n'
375 ' image. For more information, run:\n'
376 ' %s --help\n'
377 '\n' % (output_path, output_path))
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800378
379
Wei-Ning Huang4855e792015-06-11 15:33:39 +0800380def ExtractOverlord(src_root, output_dir):
381 output_dir = os.path.join(output_dir, 'overlord')
382 try:
383 os.makedirs(output_dir)
384 except OSError as e:
Yilin Yang71e39412019-09-24 09:26:46 +0800385 print(str(e))
Wei-Ning Huang4855e792015-06-11 15:33:39 +0800386 return
387
388 # Copy overlord binary and resource files
389 shutil.copyfile(os.path.join(src_root, 'usr/bin/overlordd'),
390 os.path.join(output_dir, 'overlordd'))
391 shutil.copytree(os.path.join(src_root, 'usr/share/overlord/app'),
392 os.path.join(output_dir, 'app'))
393
394 # Give overlordd execution permission
Peter Shihe6afab32018-09-11 17:16:48 +0800395 os.chmod(os.path.join(output_dir, 'overlordd'), 0o755)
Yilin Yang71e39412019-09-24 09:26:46 +0800396 print("Extracted overlord under '%s'" % output_dir)
Wei-Ning Huang4855e792015-06-11 15:33:39 +0800397
398
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800399def main():
Jon Salz4f3ade52014-02-20 17:55:09 +0800400 import logging
401 logging.basicConfig(level=logging.INFO)
402
403 # In order to determine which usage message to show, first determine
404 # whether we're in the self-extracting archive. Do this first
405 # because we need it to even parse the arguments.
406 if '--in-exe' in sys.argv:
407 sys.argv = [x for x in sys.argv if x != '--in-exe']
408 in_archive = True
409 else:
410 in_archive = False
411
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800412 parser = argparse.ArgumentParser(
Jon Salz4f3ade52014-02-20 17:55:09 +0800413 description=HELP_HEADER + HELP_HEADER_ADVANCED,
414 usage=('install_factory_toolkit.run -- [options]' if in_archive
415 else None),
416 formatter_class=argparse.RawDescriptionHelpFormatter)
Hung-Te Lin56b18402015-01-16 14:52:30 +0800417 parser.add_argument(
418 'dest', nargs='?', default='/',
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800419 help='A test image or the mount point of the stateful partition. '
420 "If omitted, install to live system, i.e. '/'.")
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800421 parser.add_argument('--no-enable', '-n', action='store_true',
Hung-Te Lin56b18402015-01-16 14:52:30 +0800422 help="Don't enable factory tests after installing")
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800423 parser.add_argument('--yes', '-y', action='store_true',
Hung-Te Lin56b18402015-01-16 14:52:30 +0800424 help="Don't ask for confirmation")
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800425 parser.add_argument('--build-info', action='store_true',
Hung-Te Lin56b18402015-01-16 14:52:30 +0800426 help='Print build information and exit')
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800427 parser.add_argument('--pack-into', metavar='NEW_TOOLKIT',
Hung-Te Lin56b18402015-01-16 14:52:30 +0800428 help='Pack the files into a new factory toolkit')
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800429 parser.add_argument('--repack', metavar='UNPACKED_TOOLKIT',
Hung-Te Lin56b18402015-01-16 14:52:30 +0800430 help='Repack from previously unpacked toolkit')
You-Cheng Syu53f4a0c2017-04-20 17:46:12 +0800431 parser.add_argument('--version', metavar='VERSION',
432 help='String to write into TOOLKIT_VERSION when packing')
Vic Yang7039f422014-07-07 15:38:13 -0700433
Vic Yang70fdae92015-02-17 19:21:08 -0800434 parser.add_argument('--non-cros', dest='non_cros',
435 action='store_true',
436 help='Install on non-ChromeOS host.')
437
Vic Yang423c2722014-09-24 16:05:06 +0800438
Rong Chang6d65fad2014-08-22 16:00:12 +0800439 parser.add_argument('--exe-path', dest='exe_path',
Hung-Te Lin56b18402015-01-16 14:52:30 +0800440 nargs='?', default=None,
441 help='Current self-extracting archive pathname')
Wei-Ning Huang4855e792015-06-11 15:33:39 +0800442 parser.add_argument('--extract-overlord', dest='extract_overlord',
443 metavar='OUTPUT_DIR', type=str, default=None,
444 help='Extract overlord from the toolkit')
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800445 parser.add_argument('--install-dirs', nargs='+', default=None,
446 help=('Install only the specified directories under '
447 'factory folder. Can be used with --apps to '
448 'enable / disable some apps. Defaults to install '
449 'all folders.'))
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800450 parser.add_argument('--apps', type=lambda s: s.split(','), default=None,
451 help=('Enable or disable some apps under '
452 'factory/init/main.d/. Use prefix "-" to disable, '
You-Cheng Syu70e99ad2017-03-09 17:15:00 +0800453 'prefix "+" to enable, and use "," to separate. '
Wei-Han Chene6fe3872016-06-30 14:29:06 +0800454 'For example: --apps="-goofy,+whale_servo"'))
Peter Shih2f1f8c42017-06-15 15:05:55 +0800455 parser.add_argument('--active-test-list', dest='active_test_list',
456 default=None,
457 help='Set the id of active test list for Goofy.')
Cheng Yueh1df18152021-03-31 18:17:37 +0800458 parser.add_argument('--quiet', action='store_true',
459 help='Do not output makeself.sh log when success.')
Vic Yang7039f422014-07-07 15:38:13 -0700460
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800461 args = parser.parse_args()
462
Peter Shihad166772017-05-31 11:36:17 +0800463 src_root = paths.FACTORY_DIR
Yilin Yangbf84d2e2020-05-13 10:34:46 +0800464 for unused_i in range(3):
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800465 src_root = os.path.dirname(src_root)
466
Wei-Ning Huang4855e792015-06-11 15:33:39 +0800467 if args.extract_overlord is not None:
468 ExtractOverlord(src_root, args.extract_overlord)
469 return
470
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800471 # --pack-into may be called directly so this must be done before changing
472 # working directory to OLDPWD.
473 if args.pack_into and args.repack is None:
Cheng Yueh1df18152021-03-31 18:17:37 +0800474 PackFactoryToolkit(src_root, args.pack_into, args.version, args.quiet)
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800475 return
476
Jon Salz4f3ade52014-02-20 17:55:09 +0800477 if not in_archive:
478 # If you're not in the self-extracting archive, you're not allowed to
479 # do anything except the above --pack-into call.
480 parser.error('Not running from install_factory_toolkit.run; '
481 'only --pack-into (without --repack) is allowed')
482
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800483 # Change to original working directory in case the user specifies
484 # a relative path.
485 # TODO: Use USER_PWD instead when makeself is upgraded
486 os.chdir(os.environ['OLDPWD'])
487
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800488 if args.repack:
489 if args.pack_into is None:
490 parser.error('Must specify --pack-into when using --repack.')
Wei-Han Chen1efb9142019-10-03 17:42:01 +0800491 env = dict(os.environ,
492 PYTHONPATH=os.path.join(args.repack, PYTHONPATH))
Cheng Yueh1df18152021-03-31 18:17:37 +0800493 cmd = ['python3', '-m', INSTALLER_MODULE, '--pack-into', args.pack_into]
494 if args.quiet:
495 cmd.append('--quiet')
496 Spawn(cmd, check_call=True, log=True, env=env)
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800497 return
498
499 if args.build_info:
500 PrintBuildInfo(src_root)
501 return
502
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800503 if not os.path.exists(args.dest):
504 parser.error('Destination %s does not exist!' % args.dest)
505
506 patch_test_image = os.path.isfile(args.dest)
507
Hung-Te Linf5f2d7f2016-01-08 17:12:46 +0800508 with (sys_utils.MountPartition(args.dest, 1, rw=True) if patch_test_image
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800509 else DummyContext(args.dest)) as dest:
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800510
Hung-Te Lin56b18402015-01-16 14:52:30 +0800511 installer = FactoryToolkitInstaller(
Wei-Ning Huang5135b7e2015-07-03 17:31:15 +0800512 src=src_root, dest=dest, no_enable=args.no_enable,
Hung-Te Linfc162e62017-09-21 00:45:04 +0800513 non_cros=args.non_cros, apps=args.apps,
514 active_test_list=args.active_test_list)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800515
Yilin Yang71e39412019-09-24 09:26:46 +0800516 print(installer.WarningMessage(args.dest if patch_test_image else None))
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800517
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800518 if not args.yes:
Yilin Yang8cc5dfb2019-10-22 15:58:53 +0800519 answer = input('*** Continue? [y/N] ')
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800520 if not answer or answer[0] not in 'yY':
521 sys.exit('Aborting.')
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800522
Wei-Han Chen7137dcf2016-08-03 15:43:22 +0800523 if args.install_dirs:
524 installer.InstallFactorySubDir(args.install_dirs)
525 else:
526 installer.Install()
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800527
528if __name__ == '__main__':
You-Cheng Syu70e99ad2017-03-09 17:15:00 +0800529 # makself interprets "LICENSE" environment variable string as license text and
Hung-Te Lin5a2a1c42016-11-10 12:43:40 +0800530 # will prompt user to accept before installation. For factory toolkit, we
531 # don't want any user interaction in installation and the license is already
532 # covered by ebuild or download platform like CPFE.
533 os.putenv('LICENSE', '')
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800534 main()