JIRA: BOTTLENECKS-29
[bottlenecks.git] / vstf / vstf / agent / env / basic / commandline.py
1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import subprocess
11 import threading
12 import logging
13 from vstf.common import constants
14
15 LOG = logging.getLogger(__name__)
16
17
18 class CommandLine(object):
19     def __init__(self):
20         super(CommandLine, self).__init__()
21         self.proc = None
22         self.is_timeout = False
23
24     def __kill_proc(self):
25         self.is_timeout = True
26         self.proc.kill()
27
28     def execute(self, cmd, timeout=constants.TIMEOUT, shell=False):
29         """this func call subprocess.Popen(),
30         here setup a timer to deal with timeout.
31         :param cmd: cmd list like ['ls', 'home']
32         :param timeout: for timer count for timeout
33         :return: (ret, output) the output (stdout+'\n'+stderr)
34         """
35         # reset the timeout flag
36         self.is_timeout = False
37         self.proc = subprocess.Popen(cmd,
38                                      stdout=subprocess.PIPE,
39                                      stderr=subprocess.PIPE,
40                                      shell=shell)
41
42         timer = threading.Timer(timeout, self.__kill_proc, [])
43         timer.start()
44         stdout, stderr = self.proc.communicate()
45         timer.cancel()
46
47         if self.proc.returncode or self.is_timeout:
48             if self.is_timeout:
49                 LOG.error("run cmd<%(cmd)s> timeout", {"cmd": cmd})
50             ret = False
51             output = "".join([stderr, stdout])
52         else:
53             ret = True
54             output = stdout
55         return ret, output