blob: 589e2f579d8b0bd0cc7b725439984cd391de3a62 [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
Shun-Hsing Oub5724832016-07-21 11:45:58 +080010import re
Wei-Han Chene97d3532016-03-31 19:22:01 +080011import resource
12import shutil
13import signal
Wei-Han Chenbe1355a2016-04-24 19:31:03 +080014import socket
Wei-Han Chene97d3532016-03-31 19:22:01 +080015import tempfile
16import textwrap
17import time
18
19import factory_common # pylint: disable=unused-import
20from cros.factory.gooftool import chroot
Wei-Han Chen0a3320e2016-04-23 01:32:07 +080021from cros.factory.gooftool.common import ExecFactoryPar
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
42class WipeError(StandardError):
43 """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,
128 station_port=None, wipe_finish_token=None):
You-Cheng Syu461ec032017-03-06 15:56:58 +0800129 """prepare to wipe by pivot root to tmpfs and unmount stateful partition.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800130
131 Args:
132 is_fast: whether or not to apply fast wipe.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800133 shopfloor_url: for inform_shopfloor.sh
134 """
135
Wei-Han Chene97d3532016-03-31 19:22:01 +0800136 Daemonize()
137
You-Cheng Syu461ec032017-03-06 15:56:58 +0800138 # Set the default umask.
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800139 os.umask(0022)
140
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800141 logfile = os.path.join('/tmp', WIPE_IN_TMPFS_LOG)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800142 ResetLog(logfile)
143
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800144 factory_par = paths.GetFactoryPythonArchivePath()
Wei-Han Chene97d3532016-03-31 19:22:01 +0800145
146 new_root = tempfile.mkdtemp(prefix='tmpfs.')
147 binary_deps = [
148 'activate_date', 'backlight_tool', 'busybox', 'cgpt', 'cgpt.bin',
149 'clobber-log', 'clobber-state', 'coreutils', 'crossystem', 'dd',
150 'display_boot_message', 'dumpe2fs', 'ectool', 'flashrom', 'halt',
151 'initctl', 'mkfs.ext4', 'mktemp', 'mosys', 'mount', 'mount-encrypted',
152 'od', 'pango-view', 'pkill', 'pv', 'python', 'reboot', 'setterm', 'sh',
Cheng-Han Yang6f12dc42017-11-30 15:28:38 +0800153 'shutdown', 'stop', 'umount', 'vpd', 'curl', 'lsof', 'jq', '/sbin/frecon',
154 'stressapptest']
Wei-Han Chene97d3532016-03-31 19:22:01 +0800155
156 etc_issue = textwrap.dedent("""
157 You are now in tmp file system created for in-place wiping.
158
159 For debugging wiping fails, see log files under
160 /tmp
161 /mnt/stateful_partition/unencrypted
162
163 The log file name should be
164 - wipe_in_tmpfs.log
165 - wipe_init.log
166
167 You can also run scripts under /usr/local/factory/sh for wiping process.
168 """)
169
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800170 util = Util()
171
172 root_disk = util.GetPrimaryDevicePath()
173 release_rootfs = util.GetReleaseRootPartitionPath()
174 state_dev = util.GetPrimaryDevicePath(1)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800175 wipe_args = 'factory' + (' fast' if is_fast else '')
176
177 logging.debug('state_dev: %s', state_dev)
178 logging.debug('factory_par: %s', factory_par)
179
180 old_root = 'old_root'
181
182 try:
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800183 # pango load library module dynamically. Therefore we need to query it
184 # first.
185 pango_query_output = process_utils.SpawnOutput(
186 ['pango-querymodules', '--system'])
187 m = re.search(r'^# ModulesPath = (.+)$', pango_query_output, re.M)
188 assert m != None, 'Failed to find pango module path.'
189 pango_module = m.group(1)
190
Wei-Han Chene97d3532016-03-31 19:22:01 +0800191 with chroot.TmpChroot(
192 new_root,
193 file_dir_list=[
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800194 # Basic rootfs.
Wei-Ning Huang71f94e12016-07-17 23:21:41 +0800195 '/bin', '/etc', '/lib', '/lib64', '/root', '/sbin',
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800196 '/usr/sbin', '/usr/bin',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800197 # Factory related scripts.
198 factory_par,
199 '/usr/local/factory/sh',
Wei-Han Chen85ace052017-06-24 15:39:50 +0800200 # Factory config files
201 '/usr/local/factory/py/config',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800202 # Fonts and assets required for showing message.
203 pango_module,
Wei-Han Chene97d3532016-03-31 19:22:01 +0800204 '/usr/share/fonts/notocjk',
205 '/usr/share/cache/fontconfig',
206 '/usr/share/chromeos-assets/images',
207 '/usr/share/chromeos-assets/text/boot_messages',
208 '/usr/share/misc/chromeos-common.sh',
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800209 # File required for enable ssh connection.
210 '/mnt/stateful_partition/etc/ssh',
211 '/root/.ssh',
212 '/usr/share/chromeos-ssh-config',
213 # /var/empty is required by openssh server.
214 '/var/empty'],
Wei-Han Chene97d3532016-03-31 19:22:01 +0800215 binary_list=binary_deps, etc_issue=etc_issue).PivotRoot(old_root):
216 logging.debug(
217 'lsof: %s',
218 process_utils.SpawnOutput('lsof -p %d' % os.getpid(), shell=True))
219
Hung-Te Lin6ce54bd2017-06-27 16:20:36 +0800220 # Modify display_wipe_message so we have shells in VT2.
221 # --dev-mode provides shell with etc-issue.
222 # --enable-vt1 allows drawing escapes (OSC) on VT1 but it'll also display
223 # etc-issue and login prompt.
224 # For now we only want login prompts on VT2+.
225 process_utils.Spawn(['sed', '-i',
226 's/--no-login/--dev-mode/g;s/--enable-vt1//g',
227 '/usr/sbin/display_boot_message'],
228 call=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800229
230 # Restart gooftool under new root. Since current gooftool might be using
231 # some resource under stateful partition, restarting gooftool ensures that
232 # everything new gooftool is using comes from tmpfs and we can safely
233 # unmount stateful partition.
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800234 args = []
235 if wipe_args:
236 args += ['--wipe_args', wipe_args]
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800237 if shopfloor_url:
238 args += ['--shopfloor_url', shopfloor_url]
239 if station_ip:
240 args += ['--station_ip', station_ip]
241 if station_port:
242 args += ['--station_port', station_port]
243 if wipe_finish_token:
244 args += ['--wipe_finish_token', wipe_finish_token]
245 args += ['--state_dev', state_dev]
246 args += ['--release_rootfs', release_rootfs]
247 args += ['--root_disk', root_disk]
248 args += ['--old_root', old_root]
249
250 ExecFactoryPar('gooftool', 'wipe_init', *args)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800251 raise WipeError('Should not reach here')
Hung-Te Linc8174b52017-06-02 11:11:45 +0800252 except Exception:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800253 logging.exception('wipe_in_place failed')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800254 _OnError(station_ip, station_port, wipe_finish_token, state_dev,
255 wipe_in_tmpfs_log=logfile, wipe_init_log=None)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800256 raise
257
258
259def _StopAllUpstartJobs(exclude_list=None):
260 logging.debug('stopping upstart jobs')
261
262 # Try three times to stop running services because some service will respawn
263 # one time after being stopped, e.g. shill_respawn. Two times should be enough
264 # to stop shill. Adding one more try for safety.
265
266 if exclude_list is None:
267 exclude_list = []
268
269 for unused_tries in xrange(3):
270 service_list = process_utils.SpawnOutput(['initctl', 'list']).splitlines()
271 service_list = [
272 line.split()[0] for line in service_list if 'start/running' in line]
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800273 logging.info('Going to stop: services: %r', service_list)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800274 for service in service_list:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800275 if service in exclude_list or service.startswith('console-'):
Wei-Han Chene97d3532016-03-31 19:22:01 +0800276 continue
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800277 process_utils.Spawn(['stop', service], call=True, log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800278
279
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800280def _UnmountStatefulPartition(root, state_dev):
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800281 logging.debug('Unmount stateful partition.')
Wei-Han Chene97d3532016-03-31 19:22:01 +0800282
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800283 # Expected stateful partition mount point.
284 state_dir = os.path.join(root, STATEFUL_PARTITION_PATH.strip(os.path.sep))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800285
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800286 # Touch a mark file so we can check if the stateful partition is wiped
287 # successfully.
288 file_utils.WriteFile(os.path.join(state_dir, WIPE_MARK_FILE), '')
289
290 # Backup extension cache (crx_cache) if available (will be restored after
291 # wiping by clobber-state).
292 crx_cache_path = os.path.join(state_dir, CRX_CACHE_PAYLOAD_NAME)
293 if os.path.exists(crx_cache_path):
294 shutil.copyfile(crx_cache_path, CRX_CACHE_TAR_PATH)
295
296 # Find mount points on stateful partition.
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800297 mount_output = process_utils.SpawnOutput(['mount'], log=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800298
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800299 mount_point_list = []
300 for line in mount_output.splitlines():
301 fields = line.split()
302 if fields[0] == state_dev:
303 mount_point_list.append(fields[2])
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800304 logging.debug('stateful partitions mounted on: %s', mount_point_list)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800305
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800306 def _ListProcOpening(path_list):
307 lsof_cmd = ['lsof', '-t'] + path_list
Wei-Han Chene97d3532016-03-31 19:22:01 +0800308 return [int(line)
309 for line in process_utils.SpawnOutput(lsof_cmd).splitlines()]
310
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800311 def _ListMinijail():
312 # Not sure why, but if we use 'minijail0', then we can't find processes that
313 # starts with /sbin/minijail0.
314 list_cmd = ['pgrep', 'minijail']
315 return [int(line)
316 for line in process_utils.SpawnOutput(list_cmd).splitlines()]
317
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800318 # Find processes that are using stateful partitions.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800319 proc_list = _ListProcOpening(mount_point_list)
320
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800321 if os.getpid() in proc_list:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800322 logging.error('wipe_init itself is using stateful partition')
323 logging.error(
324 'lsof: %s',
325 process_utils.SpawnOutput('lsof -p %d' % os.getpid(), shell=True))
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800326 raise WipeError('wipe_init itself is using stateful partition')
Wei-Han Chene97d3532016-03-31 19:22:01 +0800327
328 def _KillOpeningBySignal(sig):
329 proc_list = _ListProcOpening(mount_point_list)
330 if not proc_list:
331 return True # we are done
332 for pid in proc_list:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800333 try:
334 os.kill(pid, sig)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800335 except Exception:
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800336 logging.exception('killing process %d failed', pid)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800337 return False # need to check again
338
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800339 # Try to kill processes using stateful partition gracefully.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800340 sync_utils.Retry(10, 0.1, None, _KillOpeningBySignal, signal.SIGTERM)
341 sync_utils.Retry(10, 0.1, None, _KillOpeningBySignal, signal.SIGKILL)
342
343 proc_list = _ListProcOpening(mount_point_list)
344 assert not proc_list, "processes using stateful partition: %s" % proc_list
345
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800346 def _Unmount(mount_point, critical):
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800347 logging.info('try to unmount %s', mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800348 for unused_i in xrange(10):
349 output = process_utils.Spawn(['umount', '-n', '-R', mount_point],
350 read_stderr=True, log=True).stderr_data
351 # some mount points need to be unmounted multiple times.
352 if (output.endswith(': not mounted\n') or
353 output.endswith(': not found\n')):
354 return
355 time.sleep(0.5)
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800356 logging.error('failed to unmount %s', mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800357 if critical:
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800358 raise WipeError('Unmounting %s is critical. Stop.' % mount_point)
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800359
Wei-Han Chene97d3532016-03-31 19:22:01 +0800360 if os.path.exists(os.path.join(root, 'dev', 'mapper', 'encstateful')):
Hung-Te Lin09226ef2017-01-11 18:00:19 +0800361
362 # minijail will make encstateful busy, but usually we can't just kill them.
363 # Need to list the processes and solve each-by-each.
364 proc_list = _ListMinijail()
365 assert not proc_list, "processes still using minijail: %s" % proc_list
366
You-Cheng Syuf0990462016-09-07 14:56:19 +0800367 # Doing what 'mount-encrypted umount' should do.
368 for mount_point in mount_point_list:
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800369 _Unmount(mount_point, False)
370 _Unmount(os.path.join(root, 'var'), True)
Jeffy Chend5b08e12017-03-06 10:22:59 +0800371 process_utils.Spawn(['dmsetup', 'remove', 'encstateful',
372 '--noudevrules', '--noudevsync'], check_call=True)
You-Cheng Syuf0990462016-09-07 14:56:19 +0800373 process_utils.Spawn(['losetup', '-D'], check_call=True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800374
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800375 # Try to unmount all known mount points.
Wei-Han Chene97d3532016-03-31 19:22:01 +0800376 for mount_point in mount_point_list:
You-Cheng Syu2ea26dd2016-12-06 20:50:05 +0800377 _Unmount(mount_point, True)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800378 process_utils.Spawn(['sync'], call=True)
379
You-Cheng Syuf0990462016-09-07 14:56:19 +0800380 # Check if the stateful partition is unmounted successfully.
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800381 if _IsStateDevMounted(state_dev):
382 raise WipeError('Failed to unmount stateful_partition')
383
384
385def _IsStateDevMounted(state_dev):
386 try:
387 output = process_utils.CheckOutput(['df', state_dev])
388 return output.splitlines()[-1].split()[0] == state_dev
389 except Exception:
390 return False
You-Cheng Syuf0990462016-09-07 14:56:19 +0800391
Wei-Han Chene97d3532016-03-31 19:22:01 +0800392
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800393def _InformStation(ip, port, token, wipe_init_log=None,
394 wipe_in_tmpfs_log=None, success=True):
395 if not ip:
396 return
397 port = int(port)
398
399 logging.debug('inform station %s:%d', ip, port)
400
401 try:
402 sync_utils.WaitFor(
Peter Shih14458732018-02-26 14:40:15 +0800403 lambda: process_utils.Spawn(['ping', '-w1', '-c1', ip],
404 call=True).returncode == 0,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800405 timeout_secs=180, poll_interval=1)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800406 except Exception:
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800407 logging.exception('cannot get network connection...')
408 else:
409 sock = socket.socket()
410 sock.connect((ip, port))
411
412 response = dict(token=token, success=success)
413
414 if wipe_init_log:
415 with open(wipe_init_log) as f:
416 response['wipe_init_log'] = f.read()
417
418 if wipe_in_tmpfs_log:
419 with open(wipe_in_tmpfs_log) as f:
420 response['wipe_in_tmpfs_log'] = f.read()
421
422 sock.sendall(json.dumps(response) + '\n')
423 sock.close()
424
425
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800426def _WipeStateDev(release_rootfs, root_disk, wipe_args, state_dev):
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800427 clobber_state_env = os.environ.copy()
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800428 clobber_state_env.update(ROOT_DEV=release_rootfs,
Earl Oueeb289d2016-11-04 14:36:40 +0800429 ROOT_DISK=root_disk)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800430 logging.debug('clobber-state: root_dev=%s, root_disk=%s',
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800431 release_rootfs, root_disk)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800432 process_utils.Spawn(
433 ['clobber-state', wipe_args], env=clobber_state_env, check_call=True)
434
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800435 logging.info('Checking if stateful partition is mounted...')
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800436 # Check if the stateful partition is wiped.
437 if not _IsStateDevMounted(state_dev):
438 process_utils.Spawn(['mount', state_dev, STATEFUL_PARTITION_PATH],
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800439 check_call=True, log=True)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800440
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800441 logging.info('Checking wipe mark file %s...', WIPE_MARK_FILE)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800442 if os.path.exists(
443 os.path.join(STATEFUL_PARTITION_PATH, WIPE_MARK_FILE)):
444 raise WipeError(WIPE_MARK_FILE + ' still exists')
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800445
446 # Restore CRX cache.
447 logging.info('Checking CRX cache %s...', CRX_CACHE_TAR_PATH)
448 if os.path.exists(CRX_CACHE_TAR_PATH):
449 process_utils.Spawn(['tar', '-xpvf', CRX_CACHE_TAR_PATH, '-C',
450 STATEFUL_PARTITION_PATH], check_call=True, log=True)
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800451
452 # Remove developer flag, which is created by clobber-state after wiping.
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800453 try:
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800454 # TODO(hungte) Unlink or create developer flag according to gooftool
455 # execution results.
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800456 os.unlink(os.path.join(STATEFUL_PARTITION_PATH, '.developer_mode'))
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800457 except OSError:
458 pass
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800459
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800460 process_utils.Spawn(['umount', STATEFUL_PARTITION_PATH], call=True)
461 # Make sure that everything is synced.
462 process_utils.Spawn(['sync'], call=True)
463 time.sleep(3)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800464
Joel Kitching679a00b2016-08-03 11:42:58 +0800465
Earl Ou564a7872016-10-05 10:22:00 +0800466def EnableReleasePartition(release_rootfs):
467 """Enables a release image partition on disk."""
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800468 logging.debug('enable release partition: %s', release_rootfs)
469 Util().EnableReleasePartition(release_rootfs)
Earl Ou564a7872016-10-05 10:22:00 +0800470 logging.debug('Device will boot from %s after reboot.', release_rootfs)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800471
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800472
473def _InformShopfloor(shopfloor_url):
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800474 if shopfloor_url:
475 logging.debug('inform shopfloor %s', shopfloor_url)
Hung-Te Lina3195462016-10-14 15:48:29 +0800476 proc = process_utils.Spawn(
Yilun Lindbb8af72018-01-31 16:01:17 +0800477 [
478 os.path.join(CUTOFF_SCRIPT_DIR, 'inform_shopfloor.sh'),
479 shopfloor_url, 'factory_wipe'
480 ],
481 read_stdout=True,
482 read_stderr=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800483 logging.debug('stdout: %s', proc.stdout_data)
484 logging.debug('stderr: %s', proc.stderr_data)
Yilun Lindbb8af72018-01-31 16:01:17 +0800485 if proc.returncode != 0:
Peter Shihbf6f22b2018-02-26 14:05:28 +0800486 raise RuntimeError('InformShopfloor failed.')
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800487
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800488
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800489def _Cutoff():
490 logging.debug('cutoff')
Hung-Te Lina3195462016-10-14 15:48:29 +0800491 cutoff_script = os.path.join(CUTOFF_SCRIPT_DIR, 'cutoff.sh')
You-Cheng Syue6844172017-11-28 16:39:32 +0800492 process_utils.Spawn([cutoff_script], check_call=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800493
494
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800495def WipeInit(wipe_args, shopfloor_url, state_dev, release_rootfs,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800496 root_disk, old_root, station_ip, station_port, finish_token):
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800497 Daemonize()
Wei-Han Chene97d3532016-03-31 19:22:01 +0800498 logfile = '/tmp/wipe_init.log'
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800499 wipe_in_tmpfs_log = os.path.join(old_root, 'tmp', WIPE_IN_TMPFS_LOG)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800500 ResetLog(logfile)
501
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800502 logging.debug('wipe_args: %s', wipe_args)
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800503 logging.debug('shopfloor_url: %s', shopfloor_url)
504 logging.debug('state_dev: %s', state_dev)
505 logging.debug('release_rootfs: %s', release_rootfs)
506 logging.debug('root_disk: %s', root_disk)
507 logging.debug('old_root: %s', old_root)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800508
Wei-Han Chene97d3532016-03-31 19:22:01 +0800509 try:
Shun-Hsing Oub5724832016-07-21 11:45:58 +0800510 _StopAllUpstartJobs(exclude_list=[
511 # Milestone marker that use to determine the running of other services.
512 'boot-services',
513 'system-services',
514 'failsafe',
515 # Keep dbus to make sure we can shutdown the device.
516 'dbus',
517 # Keep shill for connecting to shopfloor or stations.
518 'shill',
519 # Keep openssh-server for debugging purpose.
520 'openssh-server',
521 # sslh is a service in ARC++ for muxing between ssh and adb.
522 'sslh'
523 ])
Wei-Han Chenc8f24562016-04-23 19:42:42 +0800524 _UnmountStatefulPartition(old_root, state_dev)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800525
Hung-Te Lina3195462016-10-14 15:48:29 +0800526 process_utils.Spawn(
527 [os.path.join(CUTOFF_SCRIPT_DIR, 'display_wipe_message.sh'), 'wipe'],
528 call=True)
Wei-Han Chen9adf9de2016-04-01 19:35:41 +0800529
Wei-Han Chenb05699a2017-07-12 16:37:47 +0800530 try:
531 _WipeStateDev(release_rootfs, root_disk, wipe_args, state_dev)
532 except Exception:
533 process_utils.Spawn(
534 [os.path.join(CUTOFF_SCRIPT_DIR, 'display_wipe_message.sh'),
535 'wipe_failed'], call=True)
536 raise
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800537
Earl Ou564a7872016-10-05 10:22:00 +0800538 EnableReleasePartition(release_rootfs)
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800539
540 _InformShopfloor(shopfloor_url)
541
542 _InformStation(station_ip, station_port, finish_token,
543 wipe_init_log=logfile,
544 wipe_in_tmpfs_log=wipe_in_tmpfs_log,
545 success=True)
546
Hung-Te Lin7b27f0c2016-10-18 18:41:29 +0800547 _Cutoff()
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800548
549 # should not reach here
Hung-Te Lindd3425d2017-07-12 20:10:52 +0800550 logging.info('Going to sleep forever!')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800551 time.sleep(1e8)
Hung-Te Linc8174b52017-06-02 11:11:45 +0800552 except Exception:
Wei-Han Chene97d3532016-03-31 19:22:01 +0800553 logging.exception('wipe_init failed')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800554 _OnError(station_ip, station_port, finish_token, state_dev,
555 wipe_in_tmpfs_log=wipe_in_tmpfs_log, wipe_init_log=logfile)
Wei-Han Chene97d3532016-03-31 19:22:01 +0800556 raise