1# Copyright (c) 2014 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
5from autotest_lib.client.common_lib import error
6from autotest_lib.server import test
7
8import logging
9
10
11POWERWASH_COUNT = '/mnt/stateful_partition/unencrypted/preserve/powerwash_count'
12
13POWERWASH_MARKER_FILE = '/mnt/stateful_partition/factory_install_reset'
14
15POWERWASH_COMMAND = 'safe fast keepimg'
16
17STATEFUL_MARKER_FILE = '/mnt/stateful_partition/platform_Powerwash_flag'
18
19
20class platform_Powerwash(test.test):
21    """Powerwash a device."""
22    version = 1
23
24    def run_once(self, host):
25        self._host = host
26
27        count_before = self._powerwash_count()
28
29        # We create a file on the stateful partition to test if it is deleted
30        # during the powerwash.
31        self._host.run('echo car > %s' % STATEFUL_MARKER_FILE)
32
33        logging.debug('Signaling powerwash on the device.')
34        self._mark_powerwash()
35        self._host.reboot()
36
37        # Check if the marker file still exists on the stateful partition.
38        # The powerwash cycle should remove it.
39        marker = self._host.run('[ -e %s ]' % STATEFUL_MARKER_FILE,
40                                ignore_status=True, ignore_timeout=True)
41
42        # If "[ -e file ]" finishes with status 0, the file is present.
43        if marker is None or marker.exit_status == 0:
44            raise error.TestFail("Powerwash cycle didn't remove the marker "
45                                 "file on the stateful partition.")
46
47        # Check the powerwash counter before and after the powerwash to verify
48        # it was incremented. This file should be preserved by the powerwash.
49        count_after = self._powerwash_count()
50        if count_after != count_before + 1:
51            raise error.TestFail("Powerwash count didn't increase after "
52                                 "powerwash cycle.")
53
54
55    def _mark_powerwash(self, command=None):
56        """Creates the Powerwash marker file on the host with the given command.
57
58        @param command: The text to include on the marker file, *not* including
59                        the '\n' at the end.
60        """
61        if command is None:
62            command = POWERWASH_COMMAND
63        self._host.run("echo '%s' > %s" % (command, POWERWASH_MARKER_FILE))
64
65
66    def _powerwash_count(self):
67        """Return the powerwash count from the DUT."""
68        count = self._host.run('cat %s' % POWERWASH_COUNT,
69                               ignore_status=True).stdout.strip()
70        logging.debug('Powerwash count is: %r', count)
71        if count:
72            return int(count)
73        return 0
74