0df037d8536a4e47254189e042ce9def44199426
[bottlenecks.git] / vstf / vstf / agent / env / basic / commandline.py
1 import subprocess
2 import threading
3 import logging
4 from vstf.common import constants
5
6 LOG = logging.getLogger(__name__)
7
8
9 class CommandLine(object):
10     def __init__(self):
11         super(CommandLine, self).__init__()
12         self.proc = None
13         self.is_timeout = False
14
15     def __kill_proc(self):
16         self.is_timeout = True
17         self.proc.kill()
18
19     def execute(self, cmd, timeout=constants.TIMEOUT, shell=False):
20         """this func call subprocess.Popen(),
21         here setup a timer to deal with timeout.
22         :param cmd: cmd list like ['ls', 'home']
23         :param timeout: for timer count for timeout
24         :return: (ret, output) the output (stdout+'\n'+stderr)
25         """
26         # reset the timeout flag
27         self.is_timeout = False
28         self.proc = subprocess.Popen(cmd,
29                                      stdout=subprocess.PIPE,
30                                      stderr=subprocess.PIPE,
31                                      shell=shell)
32
33         timer = threading.Timer(timeout, self.__kill_proc, [])
34         timer.start()
35         stdout, stderr = self.proc.communicate()
36         timer.cancel()
37
38         if self.proc.returncode or self.is_timeout:
39             if self.is_timeout:
40                 LOG.error("run cmd<%(cmd)s> timeout", {"cmd": cmd})
41             ret = False
42             output = "".join([stderr, stdout])
43         else:
44             ret = True
45             output = stdout
46         return ret, output