• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lint as: python2, python3
2"""
3Sets up a subprocess to run any generic command in the background every
4few seconds (by default the interval is 60 secs)
5"""
6
7from __future__ import absolute_import
8from __future__ import division
9from __future__ import print_function
10
11import time, os, subprocess
12from six.moves import zip
13
14from autotest_lib.client.bin import profiler
15from autotest_lib.client.common_lib import utils, error
16
17class cmdprofile(profiler.profiler):
18    version = 2
19    supports_reboot = True
20
21
22    def initialize(self, cmds=['ps'], interval=60, outputfile='cmdprofile',
23                   outputfiles=None):
24
25        # do some basic sanity checking on the parameters
26        if not outputfiles and not outputfile:
27            raise error.TestError(
28                'cmdprofile cannot run if neither outputfile nor outputfile '
29                'is specified')
30        elif outputfiles and len(outputfiles) != len(cmds):
31            raise error.TestError(
32                'cmdprofile paramter outputfiles has length %d and cmds has '
33                'length %d, but both lists must have the same length' %
34                (len(outputfiles), len(cmds)))
35
36        self.interval = interval
37        self.cmds = cmds
38        if outputfiles:
39            # outputfiles overrides outputfile
40            self.outputfiles = outputfiles
41        else:
42            self.outputfiles = [outputfile] * len(cmds)
43
44
45    def start(self, test):
46        self.pid = os.fork()
47        if self.pid:  # parent
48            return
49        else:  # child
50            while True:
51                for cmd, outputfile in zip(self.cmds, self.outputfiles):
52                    logfile = open(os.path.join(test.profdir, outputfile), 'a')
53                    utils.run(cmd, stdout_tee=logfile, stderr_tee=logfile)
54                    logfile.write('\n')
55                    logfile.close()
56                time.sleep(self.interval)
57
58
59    def stop(self, test):
60        utils.nuke_pid(self.pid)
61