1"""top prints out CPU stats"""
2
3import os, subprocess, signal
4import logging
5from autotest_lib.client.bin import profiler
6
7
8class top(profiler.profiler):
9    """
10    Starts top on the DUT and polls every 5 seconds. Any processes with a
11    %cpu of zero will be stripped from the output.
12    """
13
14    version = 1
15
16    SCRIPT = "top -b -c -w 200 -d 5 -o '%CPU' -H | " \
17             "awk '$1 ~ /[0-9]+/ && $9 == '0.0' {next} {print}'"
18
19    def start(self, test):
20        self._output = open(os.path.join(test.profdir, "top"), "wb")
21
22        logging.debug("Starting top")
23
24        # Log the start time so a complete datetime can be computed later
25        subprocess.call(["date", "-Iseconds"], stdout=self._output)
26
27        self._process = subprocess.Popen(
28                self.SCRIPT,
29                stderr=self._output,
30                stdout=self._output,
31                shell=True,
32                # We need to start a process group so we can kill the script's
33                # children.
34                preexec_fn=os.setpgrp,
35                close_fds=True)
36
37    def stop(self, test):
38        logging.debug("Stopping top")
39
40        # Kill the whole process group so top and awk die
41        os.killpg(self._process.pid, signal.SIGTERM)
42
43        self._process.wait()
44
45        logging.debug("Stopped top")
46
47        self._output.close()
48
49    def report(self, test):
50        pass
51