blob: e1be5e900bf2e44664e6d0495130be7ab7e1819a [file] [log] [blame]
Wei-Han Chene97d3532016-03-31 19:22:01 +08001# Copyright 2016 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Joel Kitching679a00b2016-08-03 11:42:58 +08005"""Transition to release state directly without reboot."""
Wei-Han Chene97d3532016-03-31 19:22:01 +08006
Wei-Han Chenbe1355a2016-04-24 19:31:03 +08007import json
Wei-Han Chene97d3532016-03-31 19:22:01 +08008import logging
Wei-Han Chene97d3532016-03-31 19:22:01 +08009import os
10import resource
11import shutil
12import signal
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080013import socket
Wei-Han Chene97d3532016-03-31 19:22:01 +080014import tempfile
15import textwrap
16import time
17
18import factory_common # pylint: disable=unused-import
19from cros.factory.gooftool import chroot
Wei-Han Chen0a3320e2016-04-23 01:32:07 +080020from cros.factory.gooftool.common import ExecFactoryPar
Shen-En Shih502b3102018-04-24 11:12:01 +080021from cros.factory.gooftool.common import Shell
Wei-Han Chen9adf9de2016-04-01 19:35:41 +080022from cros.factory.gooftool.common import Util
Wei-Han Chen0a3320e2016-04-23 01:32:07 +080023from cros.factory.test.env import paths
Wei-Han Chenb05699a2017-07-12 16:37:47 +080024from cros.factory.utils import file_utils
Wei-Han Chene97d3532016-03-31 19:22:01 +080025from cros.factory.utils import process_utils
26from cros.factory.utils import sync_utils
27from cros.factory.utils import sys_utils
28
29
Hung-Te Lina3195462016-10-14 15:48:29 +080030CUTOFF_SCRIPT_DIR = '/usr/local/factory/sh/cutoff'
Peter Shih18898302018-03-05 15:32:58 +080031"""Directory of scripts for device cut-off"""
Wei-Han Chen9adf9de2016-04-01 19:35:41 +080032
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080033WIPE_IN_TMPFS_LOG = 'wipe_in_tmpfs.log'
Wei-Han Chene97d3532016-03-31 19:22:01 +080034
Wei-Han Chenb05699a2017-07-12 16:37:47 +080035STATEFUL_PARTITION_PATH = '/mnt/stateful_partition/'
36
37WIPE_MARK_FILE = 'wipe_mark_file'
38
Hung-Te Lindd3425d2017-07-12 20:10:52 +080039CRX_CACHE_PAYLOAD_NAME = 'cros_payloads/release_image.crx_cache'
40CRX_CACHE_TAR_PATH = '/tmp/crx_cache.tar'
Wei-Han Chenb05699a2017-07-12 16:37:47 +080041
Peter Shihe6afab32018-09-11 17:16:48 +080042class WipeError(Exception):
Wei-Han Chenb05699a2017-07-12 16:37:47 +080043 """Failed to complete wiping."""
44
Joel Kitching679a00b2016-08-03 11:42:58 +080045
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080046def _CopyLogFileToStateDev(state_dev, logfile):
Wei-Han Chene97d3532016-03-31 19:22:01 +080047 with sys_utils.MountPartition(state_dev,
48 rw=True,
49 fstype='ext4') as mount_point:
50 shutil.copyfile(logfile,
51 os.path.join(mount_point, os.path.basename(logfile)))
52
53
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080054def _OnError(ip, port, token, state_dev, wipe_in_tmpfs_log=None,
55 wipe_init_log=None):
56 if wipe_in_tmpfs_log:
57 _CopyLogFileToStateDev(state_dev, wipe_in_tmpfs_log)
58 if wipe_init_log:
59 _CopyLogFileToStateDev(state_dev, wipe_init_log)
60 _InformStation(ip, port, token,
61 wipe_in_tmpfs_log=wipe_in_tmpfs_log,
62 wipe_init_log=wipe_init_log,
63 success=False)
64
65
Wei-Han Chene97d3532016-03-31 19:22:01 +080066def Daemonize(logfile=None):
67 """Starts a daemon process and terminates current process.
68
You-Cheng Syu461ec032017-03-06 15:56:58 +080069 A daemon process will be started, and continue executing the following codes.
Wei-Han Chene97d3532016-03-31 19:22:01 +080070 The original process that calls this function will be terminated.
71
72 Example::
73
74 def DaemonFunc():
75 Daemonize()
76 # the process calling DaemonFunc is terminated.
77 # the following codes will be executed in a daemon process
78 ...
79
80 If you would like to keep the original process alive, you could fork a child
81 process and let child process start the daemon.
82 """
83 # fork from parent process
84 if os.fork():
85 # stop parent process
86 os._exit(0) # pylint: disable=protected-access
87
88 # decouple from parent process
89 os.chdir('/')
90 os.umask(0)
91 os.setsid()
92
93 # fork again
94 if os.fork():
95 os._exit(0) # pylint: disable=protected-access
96
97 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
98 if maxfd == resource.RLIM_INFINITY:
99 maxfd = 1024
100
101 for fd in xrange(maxfd):
102 try:
103 os.close(fd)
104 except OSError:
105 pass
106
107 # Reopen fd 0 (stdin), 1 (stdout), 2 (stderr) to prevent errors from reading
108 # or writing to these files.
109 # Since we have closed all file descriptors, os.open should open a file with
110 # file descriptor equals to 0
111 os.open('/dev/null', os.O_RDWR)
112 if logfile is None:
113 os.dup2(0, 1) # stdout
114 os.dup2(0, 2) # stderr
115 else:
116 os.open(logfile, os.O_RDWR | os.O_CREAT)
117 os.dup2(1, 2) # stderr
118
119
120def ResetLog(logfile=None):
Peter Shih19a938f2018-02-26 14:26:16 +0800121 if logging.getLogger().handlers:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800122 for handler in logging.getLogger().handlers:
123 logging.getLogger().removeHandler(handler)
124 logging.basicConfig(filename=logfile, level=logging.NOTSET)
125
126
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800127def WipeInTmpFs(is_fast=None, shopfloor_url=None, station_ip=None,
Wei-Han Chenf3924112019-02-25 14:52:58 +0800128 station_port=None, wipe_finish_token=None,
129 keep_developer_mode_flag=False):
You-Cheng Syu461ec032017-03-06 15:56:58 +0800130 """prepare to wipe by pivot root to tmpfs and unmount stateful partition.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800131
132 Args:
133 is_fast: whether or not to apply fast wipe.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800134 shopfloor_url: for inform_shopfloor.sh
135 """
136
Shen-En Shih502b3102018-04-24 11:12:01 +0800137 def _CheckBug78323428():
138 # b/78323428: Check if dhcpcd is locking /var/run. If dhcpcd is locking
139 # /var/run, unmount will fail. Need CL:1021611 to use /run instead.
140 for pid in Shell('pgrep dhcpcd').stdout.splitlines():
141 lock_result = Shell('ls -al /proc/%s/fd | grep /var/run' % pid)
142 if lock_result.stdout:
143 raise WipeError('dhcpcd is still locking on /var/run. Please use a '
144 'newer ChromeOS image with CL:1021611 included. '
145 'Lock info: "%s"' % lock_result.stdout)
146 _CheckBug78323428()
147
Wei-Han Chene97d3532016-03-31 19:22:01 +0800148 Daemonize()
149
You-Cheng Syu461ec032017-03-06 15:56:58 +0800150 # Set the default umask.
Peter Shihe6afab32018-09-11 17:16:48 +0800151 os.umask(0o022)
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800152
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800153 logfile = os.path.join('/tmp', WIPE_IN_TMPFS_LOG)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800154 ResetLog(logfile)
155
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800156 factory_par = paths.GetFactoryPythonArchivePath()
Wei-Han Chene97d3532016-03-31 19:22:01 +0800157
158 new_root = tempfile.mkdtemp(prefix='tmpfs.')
159 binary_deps = [
160 'activate_date', 'backlight_tool', 'busybox', 'cgpt', 'cgpt.bin',
161 'clobber-log', 'clobber-state', 'coreutils', 'crossystem', 'dd',
162 'display_boot_message', 'dumpe2fs', 'ectool', 'flashrom', 'halt',
163 'initctl', 'mkfs.ext4', 'mktemp', 'mosys', 'mount', 'mount-encrypted',
164 'od', 'pango-view', 'pkill', 'pv', 'python', 'reboot', 'setterm', 'sh',
Cheng-Han Yang6f12dc42017-11-30 15:28:38 +0800165 'shutdown', 'stop', 'umount', 'vpd', 'curl', 'lsof', 'jq', '/sbin/frecon',
chuntsen421b6e22019-02-19 19:51:24 +0800166 'stressapptest', 'fuser']
Wei-Han Chene97d3532016-03-31 19:22:01 +0800167
168 etc_issue = textwrap.dedent("""
169 You are now in tmp file system created for in-place wiping.
170
171 For debugging wiping fails, see log files under
172 /tmp
173 /mnt/stateful_partition/unencrypted
174
175 The log file name should be
176 - wipe_in_tmpfs.log
177 - wipe_init.log
178
179 You can also run scripts under /usr/local/factory/sh for wiping process.
180 """)
181
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800182 util = Util()
183
184 root_disk = util.GetPrimaryDevicePath()
185 release_rootfs = util.GetReleaseRootPartitionPath()
186 state_dev = util.GetPrimaryDevicePath(1)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800187 wipe_args = 'factory' + (' fast' if is_fast else '')
188
189 logging.debug('state_dev: %s', state_dev)
190 logging.debug('factory_par: %s', factory_par)
191
192 old_root = 'old_root'
193
194 try:
195 with chroot.TmpChroot(
196 new_root,
197 file_dir_list=[
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800198 # Basic rootfs.
Wei-Ning Huang71f94e12016-07-17 23:21:41 +0800199 '/bin', '/etc', '/lib', '/lib64', '/root', '/sbin',
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800200 '/usr/sbin', '/usr/bin',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800201 # Factory related scripts.
202 factory_par,
203 '/usr/local/factory/sh',
Wei-Han Chen85ace052017-06-24 15:39:50 +0800204 # Factory config files
205 '/usr/local/factory/py/config',
Wei-Han Chene97d3532016-03-31 19:22:01 +0800206 '/usr/share/fonts/notocjk',
207 '/usr/share/cache/fontconfig',
208 '/usr/share/chromeos-assets/images',
209 '/usr/share/chromeos-assets/text/boot_messages',
210 '/usr/share/misc/chromeos-common.sh',
Cheng-Han Yang3c891b72018-09-20 16:16:02 +0800211 # lsb-factory is required for overriding cutoff configs
212 '/mnt/stateful_partition/dev_image/etc/lsb-factory',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800213 # File required for enable ssh connection.
214 '/mnt/stateful_partition/etc/ssh',
215 '/root/.ssh',
216 '/usr/share/chromeos-ssh-config',
217 # /var/empty is required by openssh server.
218 '/var/empty'],
Wei-Han Chene97d3532016-03-31 19:22:01 +0800219 binary_list=binary_deps, etc_issue=etc_issue).PivotRoot(old_root):
220 logging.debug(
221 'lsof: %s',
222 process_utils.SpawnOutput('lsof -p %d' % os.getpid(), shell=True))
223
Hung-Te Lin6ce54bd2017-06-27 16:20:36 +0800224 # Modify display_wipe_message so we have shells in VT2.
225 # --dev-mode provides shell with etc-issue.
226 # --enable-vt1 allows drawing escapes (OSC) on VT1 but it'll also display
227 # etc-issue and login prompt.
228 # For now we only want login prompts on VT2+.
229 process_utils.Spawn(['sed', '-i',
230 's/--no-login/--dev-mode/g;s/--enable-vt1//g',
231 '/usr/sbin/display_boot_message'],
232 call=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800233
234 # Restart gooftool under new root. Since current gooftool might be using
235 # some resource under stateful partition, restarting gooftool ensures that
236 # everything new gooftool is using comes from tmpfs and we can safely
237 # unmount stateful partition.
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800238 args = []
239 if wipe_args:
240 args += ['--wipe_args', wipe_args]
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800241 if shopfloor_url:
242 args += ['--shopfloor_url', shopfloor_url]
243 if station_ip:
244 args += ['--station_ip', station_ip]
245 if station_port:
246 args += ['--station_port', station_port]
247 if wipe_finish_token:
248 args += ['--wipe_finish_token', wipe_finish_token]
249 args += ['--state_dev', state_dev]
250 args += ['--release_rootfs', release_rootfs]
251 args += ['--root_disk', root_disk]
252 args += ['--old_root', old_root]
Wei-Han Chenf3924112019-02-25 14:52:58 +0800253 if keep_developer_mode_flag:
254 args += ['--keep_developer_mode_flag_after_clobber_state']
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800255
256 ExecFactoryPar('gooftool', 'wipe_init', *args)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800257 raise WipeError('Should not reach here')
Hung-Te Linc8174b52017-06-02 11:11:45 +0800258 except Exception:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800259 logging.exception('wipe_in_place failed')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800260 _OnError(station_ip, station_port, wipe_finish_token, state_dev,
261 wipe_in_tmpfs_log=logfile, wipe_init_log=None)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800262 raise
263
264
265def _StopAllUpstartJobs(exclude_list=None):
266 logging.debug('stopping upstart jobs')
267
268 # Try three times to stop running services because some service will respawn
269 # one time after being stopped, e.g. shill_respawn. Two times should be enough
270 # to stop shill. Adding one more try for safety.
271
272 if exclude_list is None:
273 exclude_list = []
274
275 for unused_tries in xrange(3):
276 service_list = process_utils.SpawnOutput(['initctl', 'list']).splitlines()
277 service_list = [
278 line.split()[0] for line in service_list if 'start/running' in line]
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800279 logging.info('Going to stop: services: %r', service_list)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800280 for service in service_list:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800281 if service in exclude_list or service.startswith('console-'):
Wei-Han Chene97d3532016-03-31 19:22:01 +0800282 continue
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800283 process_utils.Spawn(['stop', service], call=True, log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800284
285
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800286def _UnmountStatefulPartition(root, state_dev):
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800287 logging.debug('Unmount stateful partition.')
Wei-Han Chene97d3532016-03-31 19:22:01 +0800288
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800289 # Expected stateful partition mount point.
290 state_dir = os.path.join(root, STATEFUL_PARTITION_PATH.strip(os.path.sep))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800291
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800292 # Touch a mark file so we can check if the stateful partition is wiped
293 # successfully.
294 file_utils.WriteFile(os.path.join(state_dir, WIPE_MARK_FILE), '')
295
296 # Backup extension cache (crx_cache) if available (will be restored after
297 # wiping by clobber-state).
298 crx_cache_path = os.path.join(state_dir, CRX_CACHE_PAYLOAD_NAME)
299 if os.path.exists(crx_cache_path):
300 shutil.copyfile(crx_cache_path, CRX_CACHE_TAR_PATH)
301
302 # Find mount points on stateful partition.
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800303 mount_output = process_utils.SpawnOutput(['mount'], log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800304
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800305 mount_point_list = []
306 for line in mount_output.splitlines():
307 fields = line.split()
308 if fields[0] == state_dev:
309 mount_point_list.append(fields[2])
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800310 logging.debug('stateful partitions mounted on: %s', mount_point_list)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800311
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800312 def _ListProcOpening(path_list):
313 lsof_cmd = ['lsof', '-t'] + path_list
Wei-Han Chene97d3532016-03-31 19:22:01 +0800314 return [int(line)
315 for line in process_utils.SpawnOutput(lsof_cmd).splitlines()]
316
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800317 def _ListMinijail():
318 # Not sure why, but if we use 'minijail0', then we can't find processes that
319 # starts with /sbin/minijail0.
320 list_cmd = ['pgrep', 'minijail']
321 return [int(line)
322 for line in process_utils.SpawnOutput(list_cmd).splitlines()]
323
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800324 # Find processes that are using stateful partitions.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800325 proc_list = _ListProcOpening(mount_point_list)
326
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800327 if os.getpid() in proc_list:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800328 logging.error('wipe_init itself is using stateful partition')
329 logging.error(
330 'lsof: %s',
331 process_utils.SpawnOutput('lsof -p %d' % os.getpid(), shell=True))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800332 raise WipeError('wipe_init itself is using stateful partition')
Wei-Han Chene97d3532016-03-31 19:22:01 +0800333
334 def _KillOpeningBySignal(sig):
chuntsen421b6e22019-02-19 19:51:24 +0800335 for mount_point in mount_point_list:
336 cmd = ['fuser', '-k', '-%d' % sig, '-m', mount_point]
337 process_utils.Spawn(cmd, call=True, log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800338 proc_list = _ListProcOpening(mount_point_list)
339 if not proc_list:
340 return True # we are done
341 for pid in proc_list:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800342 try:
343 os.kill(pid, sig)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800344 except Exception:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800345 logging.exception('killing process %d failed', pid)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800346 return False # need to check again
347
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800348 # Try to kill processes using stateful partition gracefully.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800349 sync_utils.Retry(10, 0.1, None, _KillOpeningBySignal, signal.SIGTERM)
350 sync_utils.Retry(10, 0.1, None, _KillOpeningBySignal, signal.SIGKILL)
351
352 proc_list = _ListProcOpening(mount_point_list)
353 assert not proc_list, "processes using stateful partition: %s" % proc_list
354
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800355 def _Unmount(mount_point, critical):
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800356 logging.info('try to unmount %s', mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800357 for unused_i in xrange(10):
358 output = process_utils.Spawn(['umount', '-n', '-R', mount_point],
359 read_stderr=True, log=True).stderr_data
360 # some mount points need to be unmounted multiple times.
361 if (output.endswith(': not mounted\n') or
362 output.endswith(': not found\n')):
363 return
364 time.sleep(0.5)
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800365 logging.error('failed to unmount %s', mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800366 if critical:
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800367 raise WipeError('Unmounting %s is critical. Stop.' % mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800368
Wei-Han Chene97d3532016-03-31 19:22:01 +0800369 if os.path.exists(os.path.join(root, 'dev', 'mapper', 'encstateful')):
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800370
371 # minijail will make encstateful busy, but usually we can't just kill them.
372 # Need to list the processes and solve each-by-each.
373 proc_list = _ListMinijail()
374 assert not proc_list, "processes still using minijail: %s" % proc_list
375
You-Cheng Syuf0990462016-09-07 14:56:19 +0800376 # Doing what 'mount-encrypted umount' should do.
377 for mount_point in mount_point_list:
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800378 _Unmount(mount_point, False)
379 _Unmount(os.path.join(root, 'var'), True)
Jeffy Chend5b08e12017-03-06 10:22:59 +0800380 process_utils.Spawn(['dmsetup', 'remove', 'encstateful',
381 '--noudevrules', '--noudevsync'], check_call=True)
You-Cheng Syuf0990462016-09-07 14:56:19 +0800382 process_utils.Spawn(['losetup', '-D'], check_call=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800383
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800384 # Try to unmount all known mount points.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800385 for mount_point in mount_point_list:
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800386 _Unmount(mount_point, True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800387 process_utils.Spawn(['sync'], call=True)
388
You-Cheng Syuf0990462016-09-07 14:56:19 +0800389 # Check if the stateful partition is unmounted successfully.
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800390 if _IsStateDevMounted(state_dev):
391 raise WipeError('Failed to unmount stateful_partition')
392
393
394def _IsStateDevMounted(state_dev):
395 try:
396 output = process_utils.CheckOutput(['df', state_dev])
397 return output.splitlines()[-1].split()[0] == state_dev
398 except Exception:
399 return False
You-Cheng Syuf0990462016-09-07 14:56:19 +0800400
Wei-Han Chene97d3532016-03-31 19:22:01 +0800401
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800402def _InformStation(ip, port, token, wipe_init_log=None,
403 wipe_in_tmpfs_log=None, success=True):
404 if not ip:
405 return
406 port = int(port)
407
408 logging.debug('inform station %s:%d', ip, port)
409
410 try:
411 sync_utils.WaitFor(
Peter Shih14458732018-02-26 14:40:15 +0800412 lambda: process_utils.Spawn(['ping', '-w1', '-c1', ip],
413 call=True).returncode == 0,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800414 timeout_secs=180, poll_interval=1)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800415 except Exception:
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800416 logging.exception('cannot get network connection...')
417 else:
418 sock = socket.socket()
419 sock.connect((ip, port))
420
421 response = dict(token=token, success=success)
422
423 if wipe_init_log:
424 with open(wipe_init_log) as f:
425 response['wipe_init_log'] = f.read()
426
427 if wipe_in_tmpfs_log:
428 with open(wipe_in_tmpfs_log) as f:
429 response['wipe_in_tmpfs_log'] = f.read()
430
431 sock.sendall(json.dumps(response) + '\n')
432 sock.close()
433
434
Wei-Han Chenf3924112019-02-25 14:52:58 +0800435def _WipeStateDev(release_rootfs, root_disk, wipe_args, state_dev,
436 keep_developer_mode_flag):
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800437 clobber_state_env = os.environ.copy()
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800438 clobber_state_env.update(ROOT_DEV=release_rootfs,
Earl Oueeb289d2016-11-04 14:36:40 +0800439 ROOT_DISK=root_disk)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800440 logging.debug('clobber-state: root_dev=%s, root_disk=%s',
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800441 release_rootfs, root_disk)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800442 process_utils.Spawn(
443 ['clobber-state', wipe_args], env=clobber_state_env, check_call=True)
444
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800445 logging.info('Checking if stateful partition is mounted...')
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800446 # Check if the stateful partition is wiped.
447 if not _IsStateDevMounted(state_dev):
448 process_utils.Spawn(['mount', state_dev, STATEFUL_PARTITION_PATH],
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800449 check_call=True, log=True)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800450
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800451 logging.info('Checking wipe mark file %s...', WIPE_MARK_FILE)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800452 if os.path.exists(
453 os.path.join(STATEFUL_PARTITION_PATH, WIPE_MARK_FILE)):
454 raise WipeError(WIPE_MARK_FILE + ' still exists')
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800455
456 # Restore CRX cache.
457 logging.info('Checking CRX cache %s...', CRX_CACHE_TAR_PATH)
458 if os.path.exists(CRX_CACHE_TAR_PATH):
459 process_utils.Spawn(['tar', '-xpvf', CRX_CACHE_TAR_PATH, '-C',
460 STATEFUL_PARTITION_PATH], check_call=True, log=True)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800461
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800462 try:
Wei-Han Chenf3924112019-02-25 14:52:58 +0800463 if not keep_developer_mode_flag:
464 # Remove developer flag, which is created by clobber-state after wiping.
465 os.unlink(os.path.join(STATEFUL_PARTITION_PATH, '.developer_mode'))
466 # Otherwise we don't care.
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800467 except OSError:
468 pass
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800469
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800470 process_utils.Spawn(['umount', STATEFUL_PARTITION_PATH], call=True)
471 # Make sure that everything is synced.
472 process_utils.Spawn(['sync'], call=True)
473 time.sleep(3)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800474
Joel Kitching679a00b2016-08-03 11:42:58 +0800475
Earl Ou564a7872016-10-05 10:22:00 +0800476def EnableReleasePartition(release_rootfs):
477 """Enables a release image partition on disk."""
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800478 logging.debug('enable release partition: %s', release_rootfs)
479 Util().EnableReleasePartition(release_rootfs)
Earl Ou564a7872016-10-05 10:22:00 +0800480 logging.debug('Device will boot from %s after reboot.', release_rootfs)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800481
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800482
483def _InformShopfloor(shopfloor_url):
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800484 if shopfloor_url:
485 logging.debug('inform shopfloor %s', shopfloor_url)
Hung-Te Lina3195462016-10-14 15:48:29 +0800486 proc = process_utils.Spawn(
Yilun Lindbb8af72018-01-31 16:01:17 +0800487 [
488 os.path.join(CUTOFF_SCRIPT_DIR, 'inform_shopfloor.sh'),
489 shopfloor_url, 'factory_wipe'
490 ],
491 read_stdout=True,
492 read_stderr=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800493 logging.debug('stdout: %s', proc.stdout_data)
494 logging.debug('stderr: %s', proc.stderr_data)
Yilun Lindbb8af72018-01-31 16:01:17 +0800495 if proc.returncode != 0:
Peter Shihbf6f22b2018-02-26 14:05:28 +0800496 raise RuntimeError('InformShopfloor failed.')
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800497
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800498
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800499def _Cutoff():
500 logging.debug('cutoff')
Hung-Te Lina3195462016-10-14 15:48:29 +0800501 cutoff_script = os.path.join(CUTOFF_SCRIPT_DIR, 'cutoff.sh')
You-Cheng Syue6844172017-11-28 16:39:32 +0800502 process_utils.Spawn([cutoff_script], check_call=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800503
504
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800505def WipeInit(wipe_args, shopfloor_url, state_dev, release_rootfs,
Wei-Han Chenf3924112019-02-25 14:52:58 +0800506 root_disk, old_root, station_ip, station_port, finish_token,
507 keep_developer_mode_flag):
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800508 Daemonize()
Wei-Han Chene97d3532016-03-31 19:22:01 +0800509 logfile = '/tmp/wipe_init.log'
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800510 wipe_in_tmpfs_log = os.path.join(old_root, 'tmp', WIPE_IN_TMPFS_LOG)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800511 ResetLog(logfile)
512
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800513 logging.debug('wipe_args: %s', wipe_args)
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800514 logging.debug('shopfloor_url: %s', shopfloor_url)
515 logging.debug('state_dev: %s', state_dev)
516 logging.debug('release_rootfs: %s', release_rootfs)
517 logging.debug('root_disk: %s', root_disk)
518 logging.debug('old_root: %s', old_root)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800519
Wei-Han Chene97d3532016-03-31 19:22:01 +0800520 try:
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800521 _StopAllUpstartJobs(exclude_list=[
522 # Milestone marker that use to determine the running of other services.
523 'boot-services',
524 'system-services',
525 'failsafe',
526 # Keep dbus to make sure we can shutdown the device.
527 'dbus',
528 # Keep shill for connecting to shopfloor or stations.
529 'shill',
530 # Keep openssh-server for debugging purpose.
531 'openssh-server',
532 # sslh is a service in ARC++ for muxing between ssh and adb.
533 'sslh'
Peter Shihe6afab32018-09-11 17:16:48 +0800534 ])
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800535 _UnmountStatefulPartition(old_root, state_dev)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800536
Hung-Te Lina3195462016-10-14 15:48:29 +0800537 process_utils.Spawn(
538 [os.path.join(CUTOFF_SCRIPT_DIR, 'display_wipe_message.sh'), 'wipe'],
539 call=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800540
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800541 try:
Wei-Han Chenf3924112019-02-25 14:52:58 +0800542 _WipeStateDev(release_rootfs, root_disk, wipe_args, state_dev,
543 keep_developer_mode_flag)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800544 except Exception:
545 process_utils.Spawn(
546 [os.path.join(CUTOFF_SCRIPT_DIR, 'display_wipe_message.sh'),
547 'wipe_failed'], call=True)
548 raise
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800549
Earl Ou564a7872016-10-05 10:22:00 +0800550 EnableReleasePartition(release_rootfs)
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800551
552 _InformShopfloor(shopfloor_url)
553
554 _InformStation(station_ip, station_port, finish_token,
555 wipe_init_log=logfile,
556 wipe_in_tmpfs_log=wipe_in_tmpfs_log,
557 success=True)
558
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800559 _Cutoff()
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800560
561 # should not reach here
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800562 logging.info('Going to sleep forever!')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800563 time.sleep(1e8)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800564 except Exception:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800565 logging.exception('wipe_init failed')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800566 _OnError(station_ip, station_port, finish_token, state_dev,
567 wipe_in_tmpfs_log=wipe_in_tmpfs_log, wipe_init_log=logfile)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800568 raise