1# Copyright (c) 2010 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
5
6import os, random, subprocess, time
7import commands, logging, random, time
8from autotest_lib.client.bin import utils, test
9from autotest_lib.client.common_lib import error
10from autotest_lib.client.cros import rtc, sys_power
11
12
13MIN_SLEEP_INTERVAL = 5
14MIN_WORK_INTERVAL = 30
15START_FILE = '/tmp/power_state_cycle_begin'
16STOP_FILE = '/tmp/power_state_cycle_end'
17
18class platform_SuspendStress(test.test):
19    version = 1
20    def initialize(self):
21        random.seed() # System time is fine.
22        if os.path.exists(STOP_FILE):
23            logging.warning('removing existing stop file %s' % STOP_FILE)
24            os.unlink(STOP_FILE)
25
26
27    def suspend_and_resume(self, seconds=MIN_SLEEP_INTERVAL):
28        """Suspends for N seconds."""
29        sleep_seconds = min(seconds, MIN_SLEEP_INTERVAL)
30        suspend_time = rtc.get_seconds()
31        sys_power.do_suspend(sleep_seconds)
32        logging.debug('and we\'re back... %ds elapsed.',
33                      rtc.get_seconds() - suspend_time)
34
35
36    def power_state_cycle(self, timeout=None):
37        try:
38            while not os.path.exists(STOP_FILE):
39                if timeout and time.mktime(time.localtime()) > timeout:
40                    raise error.TestFail('didn\'t find %s before timeout.' %
41                                         STOP_FILE)
42                self.suspend_and_resume(random.randint(MIN_SLEEP_INTERVAL, 15))
43                time.sleep(random.randint(MIN_WORK_INTERVAL,
44                                          MIN_WORK_INTERVAL+5))
45        finally:
46            # Ensure we disable the RTC alarm, leaving the original state
47            rtc.set_wake_alarm(0)
48
49
50    def run_once(self, auto_start=False, runtime=None):
51        if auto_start:
52            open(START_FILE, 'w').close()
53        utils.poll_for_condition(lambda: os.path.exists(START_FILE),
54                                 error.TestFail('startup not triggered.'),
55                                 timeout=30, sleep_interval=1)
56        logging.debug('Found %s, starting power state cycle.' % START_FILE)
57        if runtime:
58            runtime = time.mktime(time.localtime()) + runtime
59        os.unlink(START_FILE)
60        self.power_state_cycle(runtime)
61