blob: bab679d3c44d119c8a2810ecebe11e3b3ccd9555 [file] [log] [blame]
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +08001#!/usr/bin/python -Bu
2#
3# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""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
14
15import argparse
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080016from contextlib import contextmanager
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080017import os
Jon Salz4f3ade52014-02-20 17:55:09 +080018import re
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080019import sys
Jon Salz4f3ade52014-02-20 17:55:09 +080020import tempfile
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080021
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080022import factory_common # pylint: disable=W0611
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080023from cros.factory.test import factory
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080024from cros.factory.tools.mount_partition import MountPartition
25from cros.factory.utils.process_utils import Spawn
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080026
27
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +080028INSTALLER_PATH = 'usr/local/factory/py/toolkit/installer.py'
29
Jon Salz4f3ade52014-02-20 17:55:09 +080030# Short and sweet help header for the executable generated by makeself.
31HELP_HEADER = """
32Installs the factory toolkit, transforming a test image into a factory test
33image. You can:
34
35- Install the factory toolkit on a CrOS device that is running a test
36 image. To do this, copy install_factory_toolkit.run to the device and
37 run it. The factory tests will then come up on the next boot.
38
39 rsync -a install_factory_toolkit.run crosdevice:/tmp
40 ssh crosdevice '/tmp/install_factory_toolkit.run && sync && reboot'
41
42- Modify a test image, turning it into a factory test image. When you
43 use the image on a device, the factory tests will come up.
44
45 install_factory_toolkit.run chromiumos_test_image.bin
46"""
47
48HELP_HEADER_ADVANCED = """
49- (advanced) Modify a mounted stateful partition, turning it into a factory
50 test image. This is equivalent to the previous command:
51
52 mount_partition -rw chromiumos_test_image.bin 1 /mnt/stateful
53 install_factory_toolkit.run /mnt/stateful
54 umount /mnt/stateful
55
56- (advanced) Unpack the factory toolkit, modify a file, and then repack it.
57
58 # Unpack but don't actually install
59 install_factory_toolkit.run --target /tmp/toolkit --noexec
60 # Edit some files in /tmp/toolkit
61 emacs /tmp/toolkit/whatever
62 # Repack
63 install_factory_toolkit.run -- --repack /tmp/toolkit \\
64 --pack-into /path/to/new/install_factory_toolkit.run
65"""
66
67# The makeself-generated header comes next. This is a little confusing,
68# so explain.
69HELP_HEADER_MAKESELF = """
70For complete usage information and advanced operations, run
71"install_factory_toolkit.run -- --help" (note the extra "--").
72
73Following is the help message from makeself, which was used to create
74this self-extracting archive.
75
76-----
77"""
78
79
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080080class FactoryToolkitInstaller():
81 """Factory toolkit installer.
82
83 Args:
84 src: Source path containing usr/ and var/.
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080085 dest: Installation destination path. Set this to the mount point of the
86 stateful partition if patching a test image.
87 no_enable: True to not install the tag file.
88 system_root: The path to the root of the file system. This must be left
89 as its default value except for unit testing.
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +080090 """
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080091
Jon Salzb7e44262014-05-07 15:53:37 +080092 # Whether to sudo when rsyncing; set to False for testing.
93 _sudo = True
94
Vic Yang7039f422014-07-07 15:38:13 -070095 def __init__(self, src, dest, no_enable, enable_host,
96 enable_device, system_root='/'):
Jon Salz4f3ade52014-02-20 17:55:09 +080097 self._src = src
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +080098 self._system_root = system_root
99 if dest == self._system_root:
100 self._usr_local_dest = os.path.join(dest, 'usr', 'local')
101 self._var_dest = os.path.join(dest, 'var')
Jon Salz4f3ade52014-02-20 17:55:09 +0800102
103 # Make sure we're on a CrOS device.
104 lsb_release = self._ReadLSBRelease()
105 is_cros = (
106 lsb_release and
107 re.match('^CHROMEOS_RELEASE', lsb_release, re.MULTILINE) is not None)
108
109 if not is_cros:
110 sys.stderr.write(
111 "ERROR: You're not on a CrOS device (/etc/lsb-release does not\n"
112 "contain CHROMEOS_RELEASE), so you must specify a test image or a\n"
113 "mounted stateful partition on which to install the factory\n"
114 "toolkit. Please run\n"
115 "\n"
116 " install_factory_toolkit.run -- --help\n"
117 "\n"
118 "for help.\n")
119 sys.exit(1)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800120 if os.getuid() != 0:
Jon Salz4f3ade52014-02-20 17:55:09 +0800121 raise Exception('You must be root to install the factory toolkit on a '
122 'CrOS device.')
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800123 else:
124 self._usr_local_dest = os.path.join(dest, 'dev_image')
125 self._var_dest = os.path.join(dest, 'var_overlay')
126 if (not os.path.exists(self._usr_local_dest) or
127 not os.path.exists(self._var_dest)):
128 raise Exception(
129 'The destination path %s is not a stateful partition!' % dest)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800130
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800131 self._dest = dest
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800132 self._usr_local_src = os.path.join(src, 'usr', 'local')
133 self._var_src = os.path.join(src, 'var')
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800134 self._no_enable = no_enable
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800135 self._tag_file = os.path.join(self._usr_local_dest, 'factory', 'enabled')
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800136
Vic Yang7039f422014-07-07 15:38:13 -0700137 self._enable_host = enable_host
138 self._host_tag_file = os.path.join(self._var_dest, 'factory',
139 'state', 'run_goofy_host')
140
141 self._enable_device = enable_device
142 self._device_tag_file = os.path.join(self._var_dest, 'factory',
143 'state', 'run_goofy_device')
144
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800145 if (not os.path.exists(self._usr_local_src) or
146 not os.path.exists(self._var_src)):
147 raise Exception(
148 'This installer must be run from within the factory toolkit!')
149
Jon Salz4f3ade52014-02-20 17:55:09 +0800150 @staticmethod
151 def _ReadLSBRelease():
152 """Returns the contents of /etc/lsb-release, or None if it does not
153 exist."""
154 if os.path.exists('/etc/lsb-release'):
155 with open('/etc/lsb-release') as f:
156 return f.read()
157 return None
158
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800159 def WarningMessage(self, target_test_image=None):
Jon Salz4f3ade52014-02-20 17:55:09 +0800160 with open(os.path.join(self._src, 'VERSION')) as f:
161 ret = f.read()
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800162 if target_test_image:
Jon Salz4f3ade52014-02-20 17:55:09 +0800163 ret += (
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800164 '\n'
165 '\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800166 '*** You are about to patch the factory toolkit into:\n'
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800167 '*** %s\n'
168 '***' % target_test_image)
169 else:
Jon Salz4f3ade52014-02-20 17:55:09 +0800170 ret += (
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800171 '\n'
172 '\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800173 '*** You are about to install the factory toolkit to:\n'
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800174 '*** %s\n'
175 '***' % self._dest)
176 if self._dest == self._system_root:
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800177 if self._no_enable:
178 ret += ('\n'
179 '*** Factory tests will be disabled after this process is done, but\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800180 '*** you can enable them by creating the factory enabled tag:\n'
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800181 '*** %s\n'
182 '***' % self._tag_file)
183 else:
184 ret += ('\n'
185 '*** After this process is done, your device will start factory\n'
186 '*** tests on the next reboot.\n'
187 '***\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800188 '*** Factory tests can be disabled by deleting the factory enabled\n'
189 '*** tag:\n'
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800190 '*** %s\n'
191 '***' % self._tag_file)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800192 return ret
193
Vic Yang7039f422014-07-07 15:38:13 -0700194 def _SetTagFile(self, name, path, enabled):
195 """Install or remove a tag file."""
196 if enabled:
197 print '*** Installing %s enabled tag...' % name
198 Spawn(['touch', path], sudo=True, log=True, check_call=True)
199 else:
200 print '*** Removing %s enabled tag...' % name
201 Spawn(['rm', '-f', path], sudo=True, log=True, check_call=True)
202
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800203 def Install(self):
204 print '*** Installing factory toolkit...'
Jon Salzb7e44262014-05-07 15:53:37 +0800205 for src, dest in ((self._usr_local_src, self._usr_local_dest),
206 (self._var_src, self._var_dest)):
207 # Change the source directory to root, and add group/world read
208 # permissions. This is necessary because when the toolkit was
209 # unpacked, the user may not have been root so the permessions
210 # may be hosed. This is skipped for testing.
Peter Ammon5ac58422014-06-09 14:45:50 -0700211 # --force is necessary to allow goofy directory from prior
212 # toolkit installations to be overwritten by the goofy symlink.
Ricky Liang5e95be22014-07-09 12:52:07 +0800213 try:
214 if self._sudo:
215 Spawn(['chown', '-R', 'root', src],
216 sudo=True, log=True, check_call=True)
217 Spawn(['chmod', '-R', 'go+rX', src],
218 sudo=True, log=True, check_call=True)
219 print '*** %s -> %s' % (src, dest)
220 Spawn(['rsync', '-a', '--force', src + '/', dest],
221 sudo=self._sudo, log=True, check_output=True)
222 finally:
223 # Need to change the source directory back to the original user, or the
224 # script in makeself will fail to remove the temporary source directory.
225 if self._sudo:
226 myuser = os.environ.get('USER')
227 Spawn(['chown', '-R', myuser, src],
228 sudo=True, log=True, check_call=True)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800229
Vic Yang7039f422014-07-07 15:38:13 -0700230 self._SetTagFile('factory', self._tag_file, not self._no_enable)
231 self._SetTagFile('host', self._host_tag_file, self._enable_host)
232 self._SetTagFile('device', self._device_tag_file, self._enable_device)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800233
234 print '*** Installation completed.'
235
236
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800237@contextmanager
238def DummyContext(arg):
239 """A context manager that simply yields its argument."""
240 yield arg
241
242
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800243def PrintBuildInfo(src_root):
244 """Print build information."""
245 info_file = os.path.join(src_root, 'REPO_STATUS')
246 if not os.path.exists(info_file):
247 raise OSError('Build info file not found!')
248 with open(info_file, 'r') as f:
249 print f.read()
250
251
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800252def PackFactoryToolkit(src_root, output_path):
253 """Packs the files containing this script into a factory toolkit."""
254 with open(os.path.join(src_root, 'VERSION'), 'r') as f:
255 version = f.read().strip()
Jon Salz4f3ade52014-02-20 17:55:09 +0800256 with tempfile.NamedTemporaryFile() as help_header:
257 help_header.write(version + "\n" + HELP_HEADER + HELP_HEADER_MAKESELF)
258 help_header.flush()
259 Spawn([os.path.join(src_root, 'makeself.sh'), '--bzip2', '--nox11',
260 '--help-header', help_header.name,
261 src_root, output_path, version, INSTALLER_PATH, '--in-exe'],
262 check_call=True, log=True)
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800263 print ('\n'
264 ' Factory toolkit generated at %s.\n'
265 '\n'
266 ' To install factory toolkit on a live device running a test image,\n'
267 ' copy this to the device and execute it as root.\n'
268 '\n'
269 ' Alternatively, the factory toolkit can be used to patch a test\n'
270 ' image. For more information, run:\n'
Jon Salz4f3ade52014-02-20 17:55:09 +0800271 ' %s --help\n'
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800272 '\n' % (output_path, output_path))
273
274
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800275def main():
Jon Salz4f3ade52014-02-20 17:55:09 +0800276 import logging
277 logging.basicConfig(level=logging.INFO)
278
279 # In order to determine which usage message to show, first determine
280 # whether we're in the self-extracting archive. Do this first
281 # because we need it to even parse the arguments.
282 if '--in-exe' in sys.argv:
283 sys.argv = [x for x in sys.argv if x != '--in-exe']
284 in_archive = True
285 else:
286 in_archive = False
287
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800288 parser = argparse.ArgumentParser(
Jon Salz4f3ade52014-02-20 17:55:09 +0800289 description=HELP_HEADER + HELP_HEADER_ADVANCED,
290 usage=('install_factory_toolkit.run -- [options]' if in_archive
291 else None),
292 formatter_class=argparse.RawDescriptionHelpFormatter)
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800293 parser.add_argument('dest', nargs='?', default='/',
294 help='A test image or the mount point of the stateful partition. '
295 "If omitted, install to live system, i.e. '/'.")
Vic (Chun-Ju) Yang7cc3e672014-01-20 14:06:39 +0800296 parser.add_argument('--no-enable', '-n', action='store_true',
297 help="Don't enable factory tests after installing")
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800298 parser.add_argument('--yes', '-y', action='store_true',
299 help="Don't ask for confirmation")
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800300 parser.add_argument('--build-info', action='store_true',
301 help="Print build information and exit")
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800302 parser.add_argument('--pack-into', metavar='NEW_TOOLKIT',
303 help="Pack the files into a new factory toolkit")
304 parser.add_argument('--repack', metavar='UNPACKED_TOOLKIT',
305 help="Repack from previously unpacked toolkit")
Vic Yang7039f422014-07-07 15:38:13 -0700306
307 parser.add_argument('--enable-host', dest='enable_host',
308 action='store_true',
309 help="Run goofy host on startup")
310 parser.add_argument('--no-enable-host', dest='enable_host',
311 action='store_false', help=argparse.SUPPRESS)
312 parser.set_defaults(enable_host=True)
313
314 parser.add_argument('--enable-device', dest='enable_device',
315 action='store_true',
316 help="Run goofy_device on startup")
317 parser.add_argument('--no-enable-device', dest='enable_device',
318 action='store_false', help=argparse.SUPPRESS)
319 parser.set_defaults(enable_device=False)
320
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800321 args = parser.parse_args()
322
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800323 src_root = factory.FACTORY_PATH
324 for _ in xrange(3):
325 src_root = os.path.dirname(src_root)
326
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800327 # --pack-into may be called directly so this must be done before changing
328 # working directory to OLDPWD.
329 if args.pack_into and args.repack is None:
330 PackFactoryToolkit(src_root, args.pack_into)
Vic (Chun-Ju) Yang98b4fbc2014-02-18 19:32:32 +0800331 return
332
Jon Salz4f3ade52014-02-20 17:55:09 +0800333 if not in_archive:
334 # If you're not in the self-extracting archive, you're not allowed to
335 # do anything except the above --pack-into call.
336 parser.error('Not running from install_factory_toolkit.run; '
337 'only --pack-into (without --repack) is allowed')
338
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800339 # Change to original working directory in case the user specifies
340 # a relative path.
341 # TODO: Use USER_PWD instead when makeself is upgraded
342 os.chdir(os.environ['OLDPWD'])
343
Vic (Chun-Ju) Yangb7388f72014-02-19 15:22:58 +0800344 if args.repack:
345 if args.pack_into is None:
346 parser.error('Must specify --pack-into when using --repack.')
347 Spawn([os.path.join(args.repack, INSTALLER_PATH),
348 '--pack-into', args.pack_into], check_call=True, log=True)
349 return
350
351 if args.build_info:
352 PrintBuildInfo(src_root)
353 return
354
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800355 if not os.path.exists(args.dest):
356 parser.error('Destination %s does not exist!' % args.dest)
357
358 patch_test_image = os.path.isfile(args.dest)
359
360 with (MountPartition(args.dest, 1, rw=True) if patch_test_image
361 else DummyContext(args.dest)) as dest:
Vic Yang7039f422014-07-07 15:38:13 -0700362 installer = FactoryToolkitInstaller(
363 src_root, dest, args.no_enable, args.enable_host, args.enable_device)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800364
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800365 print installer.WarningMessage(args.dest if patch_test_image else None)
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800366
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800367 if not args.yes:
368 answer = raw_input('*** Continue? [y/N] ')
369 if not answer or answer[0] not in 'yY':
370 sys.exit('Aborting.')
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800371
Vic (Chun-Ju) Yang469592b2014-02-18 19:15:41 +0800372 installer.Install()
Vic (Chun-Ju) Yang296871a2014-01-13 12:05:18 +0800373
374if __name__ == '__main__':
375 main()