blob: 368bb486fdd289fc02be0c317ec08a6f2bd479f9 [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
Yilin Yange6639682019-10-03 12:49:21 +080018from six.moves import xrange
19
Wei-Han Chene97d3532016-03-31 19:22:01 +080020import factory_common # pylint: disable=unused-import
21from cros.factory.gooftool import chroot
Wei-Han Chen0a3320e2016-04-23 01:32:07 +080022from cros.factory.gooftool.common import ExecFactoryPar
Shen-En Shih502b3102018-04-24 11:12:01 +080023from cros.factory.gooftool.common import Shell
Wei-Han Chen9adf9de2016-04-01 19:35:41 +080024from cros.factory.gooftool.common import Util
Wei-Han Chen0a3320e2016-04-23 01:32:07 +080025from cros.factory.test.env import paths
Wei-Han Chenb05699a2017-07-12 16:37:47 +080026from cros.factory.utils import file_utils
Wei-Han Chene97d3532016-03-31 19:22:01 +080027from cros.factory.utils import process_utils
28from cros.factory.utils import sync_utils
29from cros.factory.utils import sys_utils
30
31
Hung-Te Lina3195462016-10-14 15:48:29 +080032CUTOFF_SCRIPT_DIR = '/usr/local/factory/sh/cutoff'
Peter Shih18898302018-03-05 15:32:58 +080033"""Directory of scripts for device cut-off"""
Wei-Han Chen9adf9de2016-04-01 19:35:41 +080034
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080035WIPE_IN_TMPFS_LOG = 'wipe_in_tmpfs.log'
Wei-Han Chene97d3532016-03-31 19:22:01 +080036
Wei-Han Chenb05699a2017-07-12 16:37:47 +080037STATEFUL_PARTITION_PATH = '/mnt/stateful_partition/'
38
39WIPE_MARK_FILE = 'wipe_mark_file'
40
Cheng Yuehe84775f2020-02-12 14:03:35 +080041CRX_CACHE_PAYLOAD_NAME = 'dev_image/opt/cros_payloads/release_image.crx_cache'
Hung-Te Lindd3425d2017-07-12 20:10:52 +080042CRX_CACHE_TAR_PATH = '/tmp/crx_cache.tar'
Wei-Han Chenb05699a2017-07-12 16:37:47 +080043
Peter Shihe6afab32018-09-11 17:16:48 +080044class WipeError(Exception):
Wei-Han Chenb05699a2017-07-12 16:37:47 +080045 """Failed to complete wiping."""
46
Joel Kitching679a00b2016-08-03 11:42:58 +080047
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080048def _CopyLogFileToStateDev(state_dev, logfile):
Wei-Han Chene97d3532016-03-31 19:22:01 +080049 with sys_utils.MountPartition(state_dev,
50 rw=True,
51 fstype='ext4') as mount_point:
52 shutil.copyfile(logfile,
53 os.path.join(mount_point, os.path.basename(logfile)))
54
55
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080056def _OnError(ip, port, token, state_dev, wipe_in_tmpfs_log=None,
57 wipe_init_log=None):
58 if wipe_in_tmpfs_log:
59 _CopyLogFileToStateDev(state_dev, wipe_in_tmpfs_log)
60 if wipe_init_log:
61 _CopyLogFileToStateDev(state_dev, wipe_init_log)
62 _InformStation(ip, port, token,
63 wipe_in_tmpfs_log=wipe_in_tmpfs_log,
64 wipe_init_log=wipe_init_log,
65 success=False)
66
67
Wei-Han Chene97d3532016-03-31 19:22:01 +080068def Daemonize(logfile=None):
69 """Starts a daemon process and terminates current process.
70
You-Cheng Syu461ec032017-03-06 15:56:58 +080071 A daemon process will be started, and continue executing the following codes.
Wei-Han Chene97d3532016-03-31 19:22:01 +080072 The original process that calls this function will be terminated.
73
74 Example::
75
76 def DaemonFunc():
77 Daemonize()
78 # the process calling DaemonFunc is terminated.
79 # the following codes will be executed in a daemon process
80 ...
81
82 If you would like to keep the original process alive, you could fork a child
83 process and let child process start the daemon.
84 """
85 # fork from parent process
86 if os.fork():
87 # stop parent process
88 os._exit(0) # pylint: disable=protected-access
89
90 # decouple from parent process
91 os.chdir('/')
92 os.umask(0)
93 os.setsid()
94
95 # fork again
96 if os.fork():
97 os._exit(0) # pylint: disable=protected-access
98
99 maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
100 if maxfd == resource.RLIM_INFINITY:
101 maxfd = 1024
102
103 for fd in xrange(maxfd):
104 try:
105 os.close(fd)
106 except OSError:
107 pass
108
109 # Reopen fd 0 (stdin), 1 (stdout), 2 (stderr) to prevent errors from reading
110 # or writing to these files.
111 # Since we have closed all file descriptors, os.open should open a file with
112 # file descriptor equals to 0
113 os.open('/dev/null', os.O_RDWR)
114 if logfile is None:
115 os.dup2(0, 1) # stdout
116 os.dup2(0, 2) # stderr
117 else:
118 os.open(logfile, os.O_RDWR | os.O_CREAT)
119 os.dup2(1, 2) # stderr
120
121
122def ResetLog(logfile=None):
Peter Shih19a938f2018-02-26 14:26:16 +0800123 if logging.getLogger().handlers:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800124 for handler in logging.getLogger().handlers:
125 logging.getLogger().removeHandler(handler)
126 logging.basicConfig(filename=logfile, level=logging.NOTSET)
127
128
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800129def WipeInTmpFs(is_fast=None, shopfloor_url=None, station_ip=None,
Wei-Han Chenf3924112019-02-25 14:52:58 +0800130 station_port=None, wipe_finish_token=None,
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800131 keep_developer_mode_flag=False, test_umount=False):
You-Cheng Syu461ec032017-03-06 15:56:58 +0800132 """prepare to wipe by pivot root to tmpfs and unmount stateful partition.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800133
134 Args:
135 is_fast: whether or not to apply fast wipe.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800136 shopfloor_url: for inform_shopfloor.sh
137 """
138
Shen-En Shih502b3102018-04-24 11:12:01 +0800139 def _CheckBug78323428():
140 # b/78323428: Check if dhcpcd is locking /var/run. If dhcpcd is locking
141 # /var/run, unmount will fail. Need CL:1021611 to use /run instead.
142 for pid in Shell('pgrep dhcpcd').stdout.splitlines():
143 lock_result = Shell('ls -al /proc/%s/fd | grep /var/run' % pid)
144 if lock_result.stdout:
145 raise WipeError('dhcpcd is still locking on /var/run. Please use a '
146 'newer ChromeOS image with CL:1021611 included. '
147 'Lock info: "%s"' % lock_result.stdout)
148 _CheckBug78323428()
149
Wei-Han Chene97d3532016-03-31 19:22:01 +0800150 Daemonize()
151
You-Cheng Syu461ec032017-03-06 15:56:58 +0800152 # Set the default umask.
Peter Shihe6afab32018-09-11 17:16:48 +0800153 os.umask(0o022)
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800154
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800155 logfile = os.path.join('/tmp', WIPE_IN_TMPFS_LOG)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800156 ResetLog(logfile)
157
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800158 factory_par = paths.GetFactoryPythonArchivePath()
Wei-Han Chene97d3532016-03-31 19:22:01 +0800159
160 new_root = tempfile.mkdtemp(prefix='tmpfs.')
161 binary_deps = [
162 'activate_date', 'backlight_tool', 'busybox', 'cgpt', 'cgpt.bin',
163 'clobber-log', 'clobber-state', 'coreutils', 'crossystem', 'dd',
164 'display_boot_message', 'dumpe2fs', 'ectool', 'flashrom', 'halt',
165 'initctl', 'mkfs.ext4', 'mktemp', 'mosys', 'mount', 'mount-encrypted',
166 'od', 'pango-view', 'pkill', 'pv', 'python', 'reboot', 'setterm', 'sh',
Cheng-Han Yang6f12dc42017-11-30 15:28:38 +0800167 'shutdown', 'stop', 'umount', 'vpd', 'curl', 'lsof', 'jq', '/sbin/frecon',
chuntsen421b6e22019-02-19 19:51:24 +0800168 'stressapptest', 'fuser']
Wei-Han Chene97d3532016-03-31 19:22:01 +0800169
170 etc_issue = textwrap.dedent("""
171 You are now in tmp file system created for in-place wiping.
172
173 For debugging wiping fails, see log files under
174 /tmp
175 /mnt/stateful_partition/unencrypted
176
177 The log file name should be
178 - wipe_in_tmpfs.log
179 - wipe_init.log
180
181 You can also run scripts under /usr/local/factory/sh for wiping process.
182 """)
183
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800184 util = Util()
185
186 root_disk = util.GetPrimaryDevicePath()
187 release_rootfs = util.GetReleaseRootPartitionPath()
188 state_dev = util.GetPrimaryDevicePath(1)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800189 wipe_args = 'factory' + (' fast' if is_fast else '')
190
191 logging.debug('state_dev: %s', state_dev)
192 logging.debug('factory_par: %s', factory_par)
193
194 old_root = 'old_root'
195
196 try:
197 with chroot.TmpChroot(
198 new_root,
199 file_dir_list=[
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800200 # Basic rootfs.
Wei-Ning Huang71f94e12016-07-17 23:21:41 +0800201 '/bin', '/etc', '/lib', '/lib64', '/root', '/sbin',
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800202 '/usr/sbin', '/usr/bin',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800203 # Factory related scripts.
204 factory_par,
205 '/usr/local/factory/sh',
Wei-Han Chen85ace052017-06-24 15:39:50 +0800206 # Factory config files
207 '/usr/local/factory/py/config',
Wei-Han Chene97d3532016-03-31 19:22:01 +0800208 '/usr/share/fonts/notocjk',
209 '/usr/share/cache/fontconfig',
210 '/usr/share/chromeos-assets/images',
211 '/usr/share/chromeos-assets/text/boot_messages',
212 '/usr/share/misc/chromeos-common.sh',
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]
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800249 if test_umount:
250 args += ['--test_umount']
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800251 args += ['--state_dev', state_dev]
252 args += ['--release_rootfs', release_rootfs]
253 args += ['--root_disk', root_disk]
254 args += ['--old_root', old_root]
Wei-Han Chenf3924112019-02-25 14:52:58 +0800255 if keep_developer_mode_flag:
256 args += ['--keep_developer_mode_flag_after_clobber_state']
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800257
258 ExecFactoryPar('gooftool', 'wipe_init', *args)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800259 raise WipeError('Should not reach here')
Hung-Te Linc8174b52017-06-02 11:11:45 +0800260 except Exception:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800261 logging.exception('wipe_in_place failed')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800262 _OnError(station_ip, station_port, wipe_finish_token, state_dev,
263 wipe_in_tmpfs_log=logfile, wipe_init_log=None)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800264 raise
265
266
267def _StopAllUpstartJobs(exclude_list=None):
268 logging.debug('stopping upstart jobs')
269
270 # Try three times to stop running services because some service will respawn
271 # one time after being stopped, e.g. shill_respawn. Two times should be enough
272 # to stop shill. Adding one more try for safety.
273
274 if exclude_list is None:
275 exclude_list = []
276
277 for unused_tries in xrange(3):
278 service_list = process_utils.SpawnOutput(['initctl', 'list']).splitlines()
279 service_list = [
280 line.split()[0] for line in service_list if 'start/running' in line]
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800281 logging.info('Going to stop: services: %r', service_list)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800282 for service in service_list:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800283 if service in exclude_list or service.startswith('console-'):
Wei-Han Chene97d3532016-03-31 19:22:01 +0800284 continue
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800285 process_utils.Spawn(['stop', service], call=True, log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800286
287
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800288def _UnmountStatefulPartition(root, state_dev):
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800289 logging.debug('Unmount stateful partition.')
Wei-Han Chene97d3532016-03-31 19:22:01 +0800290
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800291 # Expected stateful partition mount point.
292 state_dir = os.path.join(root, STATEFUL_PARTITION_PATH.strip(os.path.sep))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800293
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800294 # Touch a mark file so we can check if the stateful partition is wiped
295 # successfully.
296 file_utils.WriteFile(os.path.join(state_dir, WIPE_MARK_FILE), '')
297
298 # Backup extension cache (crx_cache) if available (will be restored after
299 # wiping by clobber-state).
300 crx_cache_path = os.path.join(state_dir, CRX_CACHE_PAYLOAD_NAME)
301 if os.path.exists(crx_cache_path):
302 shutil.copyfile(crx_cache_path, CRX_CACHE_TAR_PATH)
303
304 # Find mount points on stateful partition.
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800305 mount_output = process_utils.SpawnOutput(['mount'], log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800306
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800307 mount_point_list = []
308 for line in mount_output.splitlines():
309 fields = line.split()
310 if fields[0] == state_dev:
311 mount_point_list.append(fields[2])
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800312 logging.debug('stateful partitions mounted on: %s', mount_point_list)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800313
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800314 def _ListProcOpening(path_list):
315 lsof_cmd = ['lsof', '-t'] + path_list
Wei-Han Chene97d3532016-03-31 19:22:01 +0800316 return [int(line)
317 for line in process_utils.SpawnOutput(lsof_cmd).splitlines()]
318
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800319 def _ListMinijail():
320 # Not sure why, but if we use 'minijail0', then we can't find processes that
321 # starts with /sbin/minijail0.
322 list_cmd = ['pgrep', 'minijail']
323 return [int(line)
324 for line in process_utils.SpawnOutput(list_cmd).splitlines()]
325
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800326 # Find processes that are using stateful partitions.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800327 proc_list = _ListProcOpening(mount_point_list)
328
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800329 if os.getpid() in proc_list:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800330 logging.error('wipe_init itself is using stateful partition')
331 logging.error(
332 'lsof: %s',
333 process_utils.SpawnOutput('lsof -p %d' % os.getpid(), shell=True))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800334 raise WipeError('wipe_init itself is using stateful partition')
Wei-Han Chene97d3532016-03-31 19:22:01 +0800335
336 def _KillOpeningBySignal(sig):
chuntsen421b6e22019-02-19 19:51:24 +0800337 for mount_point in mount_point_list:
338 cmd = ['fuser', '-k', '-%d' % sig, '-m', mount_point]
Meng-Huan Yu98f78232020-02-19 17:40:54 +0800339 process_utils.Spawn(cmd, log_stderr_on_error=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800340 proc_list = _ListProcOpening(mount_point_list)
341 if not proc_list:
342 return True # we are done
343 for pid in proc_list:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800344 try:
345 os.kill(pid, sig)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800346 except Exception:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800347 logging.exception('killing process %d failed', pid)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800348 return False # need to check again
349
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800350 # Try to kill processes using stateful partition gracefully.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800351 sync_utils.Retry(10, 0.1, None, _KillOpeningBySignal, signal.SIGTERM)
352 sync_utils.Retry(10, 0.1, None, _KillOpeningBySignal, signal.SIGKILL)
353
354 proc_list = _ListProcOpening(mount_point_list)
355 assert not proc_list, "processes using stateful partition: %s" % proc_list
356
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800357 def _Unmount(mount_point, critical):
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800358 logging.info('try to unmount %s', mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800359 for unused_i in xrange(10):
360 output = process_utils.Spawn(['umount', '-n', '-R', mount_point],
Meng-Huan Yu98f78232020-02-19 17:40:54 +0800361 log_stderr_on_error=True).stderr_data
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800362 # some mount points need to be unmounted multiple times.
363 if (output.endswith(': not mounted\n') or
364 output.endswith(': not found\n')):
365 return
366 time.sleep(0.5)
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800367 logging.error('failed to unmount %s', mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800368 if critical:
Meng-Huan Yu98f78232020-02-19 17:40:54 +0800369 logging.debug(
370 'lsof +f -- %s: %s',
371 mount_point,
372 process_utils.SpawnOutput(['lsof', '+f', '--', mount_point]))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800373 raise WipeError('Unmounting %s is critical. Stop.' % mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800374
Wei-Han Chene97d3532016-03-31 19:22:01 +0800375 if os.path.exists(os.path.join(root, 'dev', 'mapper', 'encstateful')):
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800376
377 # minijail will make encstateful busy, but usually we can't just kill them.
378 # Need to list the processes and solve each-by-each.
379 proc_list = _ListMinijail()
380 assert not proc_list, "processes still using minijail: %s" % proc_list
381
You-Cheng Syuf0990462016-09-07 14:56:19 +0800382 # Doing what 'mount-encrypted umount' should do.
383 for mount_point in mount_point_list:
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800384 _Unmount(mount_point, False)
385 _Unmount(os.path.join(root, 'var'), True)
Jeffy Chend5b08e12017-03-06 10:22:59 +0800386 process_utils.Spawn(['dmsetup', 'remove', 'encstateful',
387 '--noudevrules', '--noudevsync'], check_call=True)
You-Cheng Syuf0990462016-09-07 14:56:19 +0800388 process_utils.Spawn(['losetup', '-D'], check_call=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800389
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800390 # Try to unmount all known mount points.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800391 for mount_point in mount_point_list:
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800392 _Unmount(mount_point, True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800393 process_utils.Spawn(['sync'], call=True)
394
You-Cheng Syuf0990462016-09-07 14:56:19 +0800395 # Check if the stateful partition is unmounted successfully.
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800396 if _IsStateDevMounted(state_dev):
397 raise WipeError('Failed to unmount stateful_partition')
398
399
400def _IsStateDevMounted(state_dev):
401 try:
402 output = process_utils.CheckOutput(['df', state_dev])
403 return output.splitlines()[-1].split()[0] == state_dev
404 except Exception:
405 return False
You-Cheng Syuf0990462016-09-07 14:56:19 +0800406
Wei-Han Chene97d3532016-03-31 19:22:01 +0800407
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800408def _InformStation(ip, port, token, wipe_init_log=None,
409 wipe_in_tmpfs_log=None, success=True):
410 if not ip:
411 return
412 port = int(port)
413
414 logging.debug('inform station %s:%d', ip, port)
415
416 try:
417 sync_utils.WaitFor(
Peter Shih14458732018-02-26 14:40:15 +0800418 lambda: process_utils.Spawn(['ping', '-w1', '-c1', ip],
419 call=True).returncode == 0,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800420 timeout_secs=180, poll_interval=1)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800421 except Exception:
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800422 logging.exception('cannot get network connection...')
423 else:
424 sock = socket.socket()
425 sock.connect((ip, port))
426
427 response = dict(token=token, success=success)
428
429 if wipe_init_log:
430 with open(wipe_init_log) as f:
431 response['wipe_init_log'] = f.read()
432
433 if wipe_in_tmpfs_log:
434 with open(wipe_in_tmpfs_log) as f:
435 response['wipe_in_tmpfs_log'] = f.read()
436
437 sock.sendall(json.dumps(response) + '\n')
438 sock.close()
439
440
Wei-Han Chenf3924112019-02-25 14:52:58 +0800441def _WipeStateDev(release_rootfs, root_disk, wipe_args, state_dev,
442 keep_developer_mode_flag):
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800443 clobber_state_env = os.environ.copy()
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800444 clobber_state_env.update(ROOT_DEV=release_rootfs,
Earl Oueeb289d2016-11-04 14:36:40 +0800445 ROOT_DISK=root_disk)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800446 logging.debug('clobber-state: root_dev=%s, root_disk=%s',
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800447 release_rootfs, root_disk)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800448 process_utils.Spawn(
449 ['clobber-state', wipe_args], env=clobber_state_env, check_call=True)
450
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800451 logging.info('Checking if stateful partition is mounted...')
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800452 # Check if the stateful partition is wiped.
453 if not _IsStateDevMounted(state_dev):
454 process_utils.Spawn(['mount', state_dev, STATEFUL_PARTITION_PATH],
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800455 check_call=True, log=True)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800456
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800457 logging.info('Checking wipe mark file %s...', WIPE_MARK_FILE)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800458 if os.path.exists(
459 os.path.join(STATEFUL_PARTITION_PATH, WIPE_MARK_FILE)):
460 raise WipeError(WIPE_MARK_FILE + ' still exists')
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800461
462 # Restore CRX cache.
463 logging.info('Checking CRX cache %s...', CRX_CACHE_TAR_PATH)
464 if os.path.exists(CRX_CACHE_TAR_PATH):
465 process_utils.Spawn(['tar', '-xpvf', CRX_CACHE_TAR_PATH, '-C',
466 STATEFUL_PARTITION_PATH], check_call=True, log=True)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800467
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800468 try:
Wei-Han Chenf3924112019-02-25 14:52:58 +0800469 if not keep_developer_mode_flag:
470 # Remove developer flag, which is created by clobber-state after wiping.
471 os.unlink(os.path.join(STATEFUL_PARTITION_PATH, '.developer_mode'))
472 # Otherwise we don't care.
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800473 except OSError:
474 pass
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800475
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800476 process_utils.Spawn(['umount', STATEFUL_PARTITION_PATH], call=True)
477 # Make sure that everything is synced.
478 process_utils.Spawn(['sync'], call=True)
479 time.sleep(3)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800480
Joel Kitching679a00b2016-08-03 11:42:58 +0800481
Earl Ou564a7872016-10-05 10:22:00 +0800482def EnableReleasePartition(release_rootfs):
483 """Enables a release image partition on disk."""
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800484 logging.debug('enable release partition: %s', release_rootfs)
485 Util().EnableReleasePartition(release_rootfs)
Earl Ou564a7872016-10-05 10:22:00 +0800486 logging.debug('Device will boot from %s after reboot.', release_rootfs)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800487
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800488
489def _InformShopfloor(shopfloor_url):
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800490 if shopfloor_url:
491 logging.debug('inform shopfloor %s', shopfloor_url)
Hung-Te Lina3195462016-10-14 15:48:29 +0800492 proc = process_utils.Spawn(
Yilun Lindbb8af72018-01-31 16:01:17 +0800493 [
494 os.path.join(CUTOFF_SCRIPT_DIR, 'inform_shopfloor.sh'),
495 shopfloor_url, 'factory_wipe'
496 ],
497 read_stdout=True,
498 read_stderr=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800499 logging.debug('stdout: %s', proc.stdout_data)
500 logging.debug('stderr: %s', proc.stderr_data)
Yilun Lindbb8af72018-01-31 16:01:17 +0800501 if proc.returncode != 0:
Peter Shihbf6f22b2018-02-26 14:05:28 +0800502 raise RuntimeError('InformShopfloor failed.')
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800503
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800504
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800505def _Cutoff():
506 logging.debug('cutoff')
Hung-Te Lina3195462016-10-14 15:48:29 +0800507 cutoff_script = os.path.join(CUTOFF_SCRIPT_DIR, 'cutoff.sh')
You-Cheng Syue6844172017-11-28 16:39:32 +0800508 process_utils.Spawn([cutoff_script], check_call=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800509
510
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800511def WipeInit(wipe_args, shopfloor_url, state_dev, release_rootfs,
Wei-Han Chenf3924112019-02-25 14:52:58 +0800512 root_disk, old_root, station_ip, station_port, finish_token,
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800513 keep_developer_mode_flag, test_umount):
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800514 Daemonize()
Wei-Han Chene97d3532016-03-31 19:22:01 +0800515 logfile = '/tmp/wipe_init.log'
516 ResetLog(logfile)
Meng-Huan Yu7e530ce2019-12-23 17:35:57 +0800517 wipe_in_tmpfs_log = os.path.join(old_root, 'tmp', WIPE_IN_TMPFS_LOG)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800518
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800519 logging.debug('wipe_args: %s', wipe_args)
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800520 logging.debug('shopfloor_url: %s', shopfloor_url)
521 logging.debug('state_dev: %s', state_dev)
522 logging.debug('release_rootfs: %s', release_rootfs)
523 logging.debug('root_disk: %s', root_disk)
524 logging.debug('old_root: %s', old_root)
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800525 logging.debug('test_umount: %s', test_umount)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800526
Wei-Han Chene97d3532016-03-31 19:22:01 +0800527 try:
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800528 _StopAllUpstartJobs(exclude_list=[
529 # Milestone marker that use to determine the running of other services.
530 'boot-services',
531 'system-services',
532 'failsafe',
533 # Keep dbus to make sure we can shutdown the device.
534 'dbus',
535 # Keep shill for connecting to shopfloor or stations.
536 'shill',
cyuehefe3cf92020-01-07 12:01:22 +0800537 # Keep wpasupplicant since shopfloor may connect over WiFi.
538 'wpasupplicant',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800539 # Keep openssh-server for debugging purpose.
540 'openssh-server',
541 # sslh is a service in ARC++ for muxing between ssh and adb.
542 'sslh'
Peter Shihe6afab32018-09-11 17:16:48 +0800543 ])
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800544 _UnmountStatefulPartition(old_root, state_dev)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800545
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800546 # When testing, stop the wiping process with no error. In normal
547 # process, this function will run forever until reboot.
548 if test_umount:
549 logging.info('Finished unmount, stop wiping process because test_umount '
550 'is set.')
551 return
552
Meng-Huan Yua97e44b2020-02-14 17:07:36 +0800553 # The following code could not be executed when factory is not installed
554 # due to lacking of CUTOFF_SCRIPT_DIR.
555 process_utils.Spawn(
556 [os.path.join(CUTOFF_SCRIPT_DIR, 'display_wipe_message.sh'), 'wipe'],
557 call=True)
558
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800559 try:
Wei-Han Chenf3924112019-02-25 14:52:58 +0800560 _WipeStateDev(release_rootfs, root_disk, wipe_args, state_dev,
561 keep_developer_mode_flag)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800562 except Exception:
563 process_utils.Spawn(
564 [os.path.join(CUTOFF_SCRIPT_DIR, 'display_wipe_message.sh'),
565 'wipe_failed'], call=True)
566 raise
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800567
Earl Ou564a7872016-10-05 10:22:00 +0800568 EnableReleasePartition(release_rootfs)
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800569
570 _InformShopfloor(shopfloor_url)
571
572 _InformStation(station_ip, station_port, finish_token,
573 wipe_init_log=logfile,
574 wipe_in_tmpfs_log=wipe_in_tmpfs_log,
575 success=True)
576
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800577 _Cutoff()
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800578
579 # should not reach here
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800580 logging.info('Going to sleep forever!')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800581 time.sleep(1e8)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800582 except Exception:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800583 logging.exception('wipe_init failed')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800584 _OnError(station_ip, station_port, finish_token, state_dev,
585 wipe_in_tmpfs_log=wipe_in_tmpfs_log, wipe_init_log=logfile)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800586 raise