ambari-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From adorosz...@apache.org
Subject [ambari] branch branch-2.6 updated: AMBARI-22953. Heartbeat gets lost due to subprocess lock (aonishuk) (#312)
Date Fri, 09 Feb 2018 20:51:36 GMT
This is an automated email from the ASF dual-hosted git repository.

adoroszlai pushed a commit to branch branch-2.6
in repository https://gitbox.apache.org/repos/asf/ambari.git


The following commit(s) were added to refs/heads/branch-2.6 by this push:
     new ada1127  AMBARI-22953. Heartbeat gets lost due to subprocess lock (aonishuk) (#312)
ada1127 is described below

commit ada11278e50c8b0c4f8e8c6097db6864dfa0281b
Author: aonishuk <aonishuk@hortonworks.com>
AuthorDate: Fri Feb 9 22:51:33 2018 +0200

    AMBARI-22953. Heartbeat gets lost due to subprocess lock (aonishuk) (#312)
---
 ambari-agent/conf/unix/agent-multiplier.py         |   10 +-
 .../src/main/python/ambari_agent/AmbariAgent.py    |    4 +-
 .../src/main/python/ambari_agent/Controller.py     |    6 +-
 .../ambari_agent/CustomServiceOrchestrator.py      |    6 +-
 .../src/main/python/ambari_agent/Facter.py         |   26 +-
 .../src/main/python/ambari_agent/Hardware.py       |    4 +-
 .../src/main/python/ambari_agent/HostCleanup.py    |   14 +-
 .../src/main/python/ambari_agent/HostInfo.py       |    6 +-
 .../main/python/ambari_agent/PingPortListener.py   |    8 +-
 .../src/main/python/ambari_agent/PythonExecutor.py |   24 +-
 .../ambari_agent/PythonReflectiveExecutor.py       |    2 +-
 .../src/main/python/ambari_agent/Register.py       |    2 +-
 .../src/main/python/ambari_agent/hostname.py       |    8 +-
 ambari-agent/src/main/python/ambari_agent/main.py  |   10 +-
 .../src/main/python/ambari_agent/security.py       |    8 +-
 .../test/python/ambari_agent/TestActionQueue.py    |    6 +-
 .../test/python/ambari_agent/TestAmbariAgent.py    |   12 +-
 .../src/test/python/ambari_agent/TestHardware.py   |   16 +-
 .../python/ambari_agent/TestPingPortListener.py    |    5 +-
 .../test/python/ambari_agent/TestPythonExecutor.py |   28 +-
 .../test/python/ambari_agent/TestRegistration.py   |    2 +-
 .../src/test/python/ambari_agent/TestSecurity.py   |    9 +-
 .../resource_management/TestExecuteResource.py     |   26 +-
 .../resource_management/TestGroupResource.py       |   12 +-
 .../python/resource_management/TestUserResource.py |   24 +-
 .../main/python/ambari_commons/_posixsubprocess.so |  Bin 0 -> 65280 bytes
 .../src/main/python/ambari_commons/firewall.py     |    4 +-
 .../src/main/python/ambari_commons/os_linux.py     |   10 +-
 .../src/main/python/ambari_commons/os_windows.py   |   10 +-
 .../src/main/python/ambari_commons/shell.py        |   16 +-
 .../src/main/python/ambari_commons/subprocess32.py | 1727 ++++++++++++++++++++
 .../resource_management/core/providers/mount.py    |    2 +-
 .../core/providers/windows/system.py               |    4 +-
 .../core/resources/jcepolicyinfo.py                |    6 +-
 .../resource_management/core/resources/system.py   |   10 +-
 .../main/python/resource_management/core/shell.py  |   24 +-
 .../main/python/resource_management/core/sudo.py   |    6 +-
 .../libraries/functions/conf_select.py             |    4 +-
 .../libraries/functions/copy_tarball.py            |    2 +-
 .../functions/dynamic_variable_interpretation.py   |    2 +-
 .../libraries/providers/hdfs_resource.py           |    2 +-
 .../resource_management/libraries/script/hook.py   |    4 +-
 .../src/main/repo/install_ambari_tarball.py        |    8 +-
 .../src/main/python/psutil/build.py                |    2 +-
 .../src/main/python/psutil/psutil/__init__.py      |   18 +-
 .../src/main/python/psutil/psutil/_pssunos.py      |    8 +-
 .../conf/unix/sqlline/phoenix_utils.py             |    8 +-
 .../conf/unix/sqlline/sqlline.py                   |    4 +-
 .../src/main/python/embedded_hbase_service.py      |    2 +-
 .../src/main/python/main.py                        |    6 +-
 .../python/ambari_server/dbConfiguration_linux.py  |   26 +-
 .../src/main/python/ambari_server/serverSetup.py   |   10 +-
 .../src/main/python/ambari_server/utils.py         |   10 +-
 .../src/main/python/ambari_server_main.py          |    8 +-
 ambari-server/src/main/python/bootstrap.py         |   14 +-
 ambari-server/src/main/python/setupAgent.py        |    6 +-
 .../HAWQ/2.0.0/package/scripts/utils.py            |    4 +-
 .../2.1.0.2.0/package/scripts/hdfs_nfsgateway.py   |    3 +-
 .../HDFS/2.1.0.2.0/package/scripts/utils.py        |    4 +-
 .../package/alerts/alert_llap_app_status.py        |    4 +-
 .../package/scripts/hive_server_interactive.py     |   10 +-
 .../0.12.0.2.0/package/scripts/service_check.py    |    4 +-
 .../KAFKA/0.8.1/package/scripts/service_check.py   |    1 -
 .../PXF/3.0.0/package/scripts/pxf_utils.py         |    4 +-
 .../SPARK/1.2.1/package/scripts/service_check.py   |    2 +-
 .../SPARK2/2.0.0/package/scripts/service_check.py  |    2 +-
 .../files/validateYarnComponentStatusWindows.py    |    2 +-
 .../package/scripts/nodemanager_upgrade.py         |    2 +-
 .../2.1.0.2.0/package/scripts/service_check.py     |    2 +-
 .../resources/custom_actions/scripts/check_host.py |    2 +-
 .../src/main/resources/scripts/Ambaripreupload.py  |    2 +-
 .../resources/scripts/check_ambari_permissions.py  |   10 +-
 .../package/files/validateYarnComponentStatus.py   |    4 +-
 .../package/files/validateYarnComponentStatus.py   |    4 +-
 .../KERBEROS/package/scripts/kerberos_common.py    |    4 +-
 ambari-server/src/test/python/TestAmbariServer.py  |   13 +-
 ambari-server/src/test/python/TestBootstrap.py     |   14 +-
 .../src/test/python/TestResourceFilesKeeper.py     |    4 +-
 ambari-server/src/test/python/TestSetupAgent.py    |    8 +-
 .../test/python/custom_actions/TestCheckHost.py    |    2 +-
 .../python/custom_actions/TestInstallPackages.py   |    4 +-
 .../test/python/custom_actions/TestRemoveBits.py   |    2 +-
 .../test/python/custom_actions/test_ru_set_all.py  |    2 +-
 .../python/stacks/2.0.6/HIVE/test_hive_server.py   |    2 +-
 .../src/main/python/ambari_shell/ambari_shell.py   |    2 +-
 pom.xml                                            |    5 +-
 86 files changed, 2052 insertions(+), 317 deletions(-)

diff --git a/ambari-agent/conf/unix/agent-multiplier.py b/ambari-agent/conf/unix/agent-multiplier.py
index 63409dd..0c21c01 100644
--- a/ambari-agent/conf/unix/agent-multiplier.py
+++ b/ambari-agent/conf/unix/agent-multiplier.py
@@ -17,7 +17,7 @@
 import sys
 import os
 import re
-import subprocess
+from ambari_commons import subprocess32
 import shutil
 from optparse import OptionParser
 
@@ -226,7 +226,7 @@ class Multiplier:
                "echo HOSTNAME"
     with open(str(host_name_script), "w+") as f:
       f.writelines(template.replace("HOSTNAME", host_name))
-    subprocess.call("chmod +x %s" % host_name_script, shell=True)
+    subprocess32.call("chmod +x %s" % host_name_script, shell=True)
 
   def change_config(self, config_file, config_dict):
     """
@@ -321,21 +321,21 @@ class Multiplier:
     for host in self.hosts:
       cmd = "ambari-agent start --home %s" % (host.home_dir)
       os.environ['AMBARI_AGENT_CONF_DIR'] = os.path.join(host.home_dir, "etc/ambari-agent/conf")
-      subprocess.call(cmd, shell=True, env=os.environ)
+      subprocess32.call(cmd, shell=True, env=os.environ)
 
   def cmd_stop(self):
     print "Stopping %d host(s)" % len(self.hosts)
     for host in self.hosts:
       cmd = "ambari-agent stop --home %s" % (host.home_dir)
       os.environ['AMBARI_AGENT_CONF_DIR'] = os.path.join(host.home_dir, "etc/ambari-agent/conf")
-      subprocess.call(cmd, shell=True, env=os.environ)
+      subprocess32.call(cmd, shell=True, env=os.environ)
 
   def cmd_restart(self):
     print "Restarting %d host(s)" % len(self.hosts)
     for host in self.hosts:
       cmd = "ambari-agent restart --home %s" % (host.home_dir)
       os.environ['AMBARI_AGENT_CONF_DIR'] = os.path.join(host.home_dir, "etc/ambari-agent/conf")
-      subprocess.call(cmd, shell=True, env=os.environ)
+      subprocess32.call(cmd, shell=True, env=os.environ)
 
   def cmd_status(self):
     print "Summary of Agent Status:"
diff --git a/ambari-agent/src/main/python/ambari_agent/AmbariAgent.py b/ambari-agent/src/main/python/ambari_agent/AmbariAgent.py
index 8475551..d8b5d81 100644
--- a/ambari-agent/src/main/python/ambari_agent/AmbariAgent.py
+++ b/ambari-agent/src/main/python/ambari_agent/AmbariAgent.py
@@ -20,7 +20,7 @@ limitations under the License.
 
 import os
 import sys
-import subprocess
+from ambari_commons import subprocess32
 import signal
 from Controller import AGENT_AUTO_RESTART_EXIT_CODE
 
@@ -51,7 +51,7 @@ def main():
 
   try:
     while status == AGENT_AUTO_RESTART_EXIT_CODE:
-      mainProcess = subprocess.Popen(mergedArgs)
+      mainProcess = subprocess32.Popen(mergedArgs)
       mainProcess.communicate()
       status = mainProcess.returncode
       if os.path.isfile(AGENT_PID_FILE) and status == AGENT_AUTO_RESTART_EXIT_CODE:
diff --git a/ambari-agent/src/main/python/ambari_agent/Controller.py b/ambari-agent/src/main/python/ambari_agent/Controller.py
index 5fab595..5ddecfe 100644
--- a/ambari-agent/src/main/python/ambari_agent/Controller.py
+++ b/ambari-agent/src/main/python/ambari_agent/Controller.py
@@ -29,7 +29,7 @@ import threading
 import urllib2
 import pprint
 from random import randint
-import subprocess
+from ambari_commons import subprocess32
 import functools
 
 import hostname
@@ -597,12 +597,12 @@ class Controller(threading.Thread):
         if os.path.exists(source_file) and not os.path.exists(destination_file):
           command = "mkdir -p %s" % os.path.dirname(destination_file)
           logger.info("Moving Data Dir Mount History file. Executing command: %s" % command)
-          return_code = subprocess.call(command, shell=True)
+          return_code = subprocess32.call(command, shell=True)
           logger.info("Return code: %d" % return_code)
 
           command = "mv %s %s" % (source_file, destination_file)
           logger.info("Moving Data Dir Mount History file. Executing command: %s" % command)
-          return_code = subprocess.call(command, shell=True)
+          return_code = subprocess32.call(command, shell=True)
           logger.info("Return code: %d" % return_code)
     except Exception, e:
       logger.info("Exception in move_data_dir_mount_file(). Error: {0}".format(str(e)))
diff --git a/ambari-agent/src/main/python/ambari_agent/CustomServiceOrchestrator.py b/ambari-agent/src/main/python/ambari_agent/CustomServiceOrchestrator.py
index 7611cc8..9ebe745 100644
--- a/ambari-agent/src/main/python/ambari_agent/CustomServiceOrchestrator.py
+++ b/ambari-agent/src/main/python/ambari_agent/CustomServiceOrchestrator.py
@@ -31,7 +31,7 @@ from PythonExecutor import PythonExecutor
 from PythonReflectiveExecutor import PythonReflectiveExecutor
 from resource_management.libraries.functions.log_process_information import log_process_information
 from resource_management.core.utils import PasswordString
-import subprocess
+from ambari_commons import subprocess32
 from ambari_commons.constants import AGENT_TMP_DIR
 import hostname
 
@@ -297,7 +297,7 @@ class CustomServiceOrchestrator():
         cmd = (java_bin, '-cp', cs_lib_path, self.credential_shell_cmd, 'create',
                alias, '-value', protected_pwd, '-provider', provider_path)
         logger.info(cmd)
-        cmd_result = subprocess.call(cmd)
+        cmd_result = subprocess32.call(cmd)
         logger.info('cmd_result = {0}'.format(cmd_result))
         os.chmod(file_path, 0644) # group and others should have read access so that the service user can read
       # Add JCEKS provider path instead
@@ -452,7 +452,7 @@ class CustomServiceOrchestrator():
       if self.commands_in_progress.has_key(task_id):#Background command do not push in this collection (TODO)
         logger.debug('Pop with taskId %s' % task_id)
         pid = self.commands_in_progress.pop(task_id)
-        if not isinstance(pid, int):
+        if not isinstance(pid, (int, long)):
           reason = pid
           if reason:
             return "\nCommand aborted. Reason: '{0}'".format(reason)
diff --git a/ambari-agent/src/main/python/ambari_agent/Facter.py b/ambari-agent/src/main/python/ambari_agent/Facter.py
index 7e92c1b..3859ff2 100644
--- a/ambari-agent/src/main/python/ambari_agent/Facter.py
+++ b/ambari-agent/src/main/python/ambari_agent/Facter.py
@@ -27,7 +27,7 @@ import re
 import shlex
 import socket
 import multiprocessing
-import subprocess
+from ambari_commons import subprocess32
 from ambari_commons.shell import shellRunner
 import time
 import uuid
@@ -42,11 +42,11 @@ log = logging.getLogger()
 
 def run_os_command(cmd):
   shell = (type(cmd) == str)
-  process = subprocess.Popen(cmd,
+  process = subprocess32.Popen(cmd,
                              shell=shell,
-                             stdout=subprocess.PIPE,
-                             stdin=subprocess.PIPE,
-                             stderr=subprocess.PIPE
+                             stdout=subprocess32.PIPE,
+                             stdin=subprocess32.PIPE,
+                             stderr=subprocess32.PIPE
   )
   (stdoutdata, stderrdata) = process.communicate()
   return process.returncode, stdoutdata, stderrdata
@@ -391,8 +391,8 @@ class FacterLinux(Facter):
   def setDataIfConfigShortOutput():
 
     try:
-      result = os.popen(FacterLinux.GET_IFCONFIG_SHORT_CMD).read()
-      return result
+      return_code, stdout, stderr = run_os_command(FacterLinux.GET_IFCONFIG_SHORT_CMD)
+      return stdout
     except OSError:
       log.warn("Can't execute {0}".format(FacterLinux.GET_IFCONFIG_SHORT_CMD))
     return ""
@@ -402,8 +402,8 @@ class FacterLinux(Facter):
   def setDataIpLinkOutput():
 
     try:
-      result = os.popen(FacterLinux.GET_IP_LINK_CMD).read()
-      return result
+      return_code, stdout, stderr = run_os_command(FacterLinux.GET_IP_LINK_CMD)
+      return stdout
     except OSError:
       log.warn("Can't execute {0}".format(FacterLinux.GET_IP_LINK_CMD))
     return ""
@@ -412,8 +412,8 @@ class FacterLinux(Facter):
   def setDataUpTimeOutput():
 
     try:
-      result = os.popen(FacterLinux.GET_UPTIME_CMD).read()
-      return result
+      return_code, stdout, stderr = run_os_command(FacterLinux.GET_UPTIME_CMD)
+      return stdout
     except OSError:
       log.warn("Can't execute {0}".format(FacterLinux.GET_UPTIME_CMD))
     return ""
@@ -422,8 +422,8 @@ class FacterLinux(Facter):
   def setMemInfoOutput():
 
     try:
-      result = os.popen(FacterLinux.GET_MEMINFO_CMD).read()
-      return result
+      return_code, stdout, stderr = run_os_command(FacterLinux.GET_MEMINFO_CMD)
+      return stdout
     except OSError:
       log.warn("Can't execute {0}".format(FacterLinux.GET_MEMINFO_CMD))
     return ""
diff --git a/ambari-agent/src/main/python/ambari_agent/Hardware.py b/ambari-agent/src/main/python/ambari_agent/Hardware.py
index 56ce872..68f6ca2 100644
--- a/ambari-agent/src/main/python/ambari_agent/Hardware.py
+++ b/ambari-agent/src/main/python/ambari_agent/Hardware.py
@@ -20,7 +20,7 @@ limitations under the License.
 
 import os.path
 import logging
-import subprocess
+from ambari_commons import subprocess32
 from resource_management.core import shell
 from resource_management.core.shell import call
 from resource_management.core.exceptions import ExecuteTimeoutException, Fail
@@ -156,7 +156,7 @@ class Hardware:
       command.append("-l")
 
     try:
-      code, out, err = shell.call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=int(timeout), quiet=True)
+      code, out, err = shell.call(command, stdout=subprocess32.PIPE, stderr=subprocess32.PIPE, timeout=int(timeout), quiet=True)
       dfdata = out
     except Exception as ex:
       logger.warn("Checking disk usage failed: " + str(ex))
diff --git a/ambari-agent/src/main/python/ambari_agent/HostCleanup.py b/ambari-agent/src/main/python/ambari_agent/HostCleanup.py
index 9183716..3187a7f 100644
--- a/ambari-agent/src/main/python/ambari_agent/HostCleanup.py
+++ b/ambari-agent/src/main/python/ambari_agent/HostCleanup.py
@@ -25,7 +25,7 @@ sys.path.append("/usr/lib/ambari-agent/lib/")
 
 import os
 import string
-import subprocess
+from ambari_commons import subprocess32
 import logging
 import shutil
 import platform
@@ -234,8 +234,8 @@ class HostCleanup:
     command = ALT_DISP_CMD.format(alt_name)
     out = None
     try:
-      p1 = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
-      p2 = subprocess.Popen(["grep", "priority"], stdin=p1.stdout, stdout=subprocess.PIPE)
+      p1 = subprocess32.Popen(shlex.split(command), stdout=subprocess32.PIPE)
+      p2 = subprocess32.Popen(["grep", "priority"], stdin=p1.stdout, stdout=subprocess32.PIPE)
       p1.stdout.close()
       out = p2.communicate()[0]
       logger.debug('alternatives --display ' + alt_name + '\n, out = ' + out)
@@ -474,10 +474,10 @@ class HostCleanup:
     logger.info('Executing command: ' + str(cmd))
     if type(cmd) == str:
       cmd = shlex.split(cmd)
-    process = subprocess.Popen(cmd,
-                               stdout=subprocess.PIPE,
-                               stdin=subprocess.PIPE,
-                               stderr=subprocess.PIPE
+    process = subprocess32.Popen(cmd,
+                               stdout=subprocess32.PIPE,
+                               stdin=subprocess32.PIPE,
+                               stderr=subprocess32.PIPE
     )
     (stdoutdata, stderrdata) = process.communicate()
     return process.returncode, stdoutdata, stderrdata
diff --git a/ambari-agent/src/main/python/ambari_agent/HostInfo.py b/ambari-agent/src/main/python/ambari_agent/HostInfo.py
index 6612c27..22cae16 100644
--- a/ambari-agent/src/main/python/ambari_agent/HostInfo.py
+++ b/ambari-agent/src/main/python/ambari_agent/HostInfo.py
@@ -24,7 +24,7 @@ import os
 import re
 import shlex
 import socket
-import subprocess
+from ambari_commons import subprocess32
 import time
 
 from ambari_commons import OSCheck, OSConst
@@ -353,7 +353,7 @@ class HostInfoLinux(HostInfo):
     service_check_live = list(self.SERVICE_STATUS_CMD_LIST)
     service_check_live[1] = service_name
     try:
-      code, out, err = shell.call(service_check_live, stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = 5, quiet = True)
+      code, out, err = shell.call(service_check_live, stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = 5, quiet = True)
       return out, err, code
     except Exception as ex:
       logger.warn("Checking service {0} status failed".format(service_name))
@@ -374,7 +374,7 @@ class HostInfoWindows(HostInfo):
   def checkUsers(self, user_mask, results):
     get_users_cmd = ["powershell", '-noProfile', '-NonInteractive', '-nologo', "-Command", self.GET_USERS_CMD.format(user_mask)]
     try:
-      osStat = subprocess.Popen(get_users_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+      osStat = subprocess32.Popen(get_users_cmd, stdout=subprocess32.PIPE, stderr=subprocess32.PIPE)
       out, err = osStat.communicate()
     except:
       raise Exception("Failed to get users.")
diff --git a/ambari-agent/src/main/python/ambari_agent/PingPortListener.py b/ambari-agent/src/main/python/ambari_agent/PingPortListener.py
index 313c060..d2eca78 100644
--- a/ambari-agent/src/main/python/ambari_agent/PingPortListener.py
+++ b/ambari-agent/src/main/python/ambari_agent/PingPortListener.py
@@ -22,7 +22,7 @@ import sys
 import logging
 import threading
 import socket
-import subprocess
+from ambari_commons import subprocess32
 
 logger = logging.getLogger(__name__)
 FUSER_CMD = "fuser {0}/tcp 2>/dev/null | awk '{1}'"
@@ -51,9 +51,9 @@ class PingPortListener(threading.Thread):
 
 
   def run_os_command_in_shell(self, command):
-    process = subprocess.Popen(command, stdout=subprocess.PIPE,
-              stdin=subprocess.PIPE,
-              stderr=subprocess.PIPE,
+    process = subprocess32.Popen(command, stdout=subprocess32.PIPE,
+              stdin=subprocess32.PIPE,
+              stderr=subprocess32.PIPE,
               shell=True)
     return process.communicate()
 
diff --git a/ambari-agent/src/main/python/ambari_agent/PythonExecutor.py b/ambari-agent/src/main/python/ambari_agent/PythonExecutor.py
index ea6f895..5aec62d 100644
--- a/ambari-agent/src/main/python/ambari_agent/PythonExecutor.py
+++ b/ambari-agent/src/main/python/ambari_agent/PythonExecutor.py
@@ -20,7 +20,7 @@ limitations under the License.
 import ambari_simplejson as json
 import logging
 import os
-import subprocess
+from ambari_commons import subprocess32
 import pprint
 import threading
 import platform
@@ -54,7 +54,7 @@ class PythonExecutor(object):
     pass
 
 
-  def open_subprocess_files(self, tmpoutfile, tmperrfile, override_output_files, backup_log_files = True):
+  def open_subprocess32_files(self, tmpoutfile, tmperrfile, override_output_files, backup_log_files = True):
     if override_output_files: # Recreate files, existing files are backed up if backup_log_files is True
       if backup_log_files:
         self.back_up_log_file_if_exists(tmpoutfile)
@@ -83,8 +83,8 @@ class PythonExecutor(object):
                override_output_files = True, backup_log_files = True, handle = None,
                log_info_on_failure = True):
     """
-    Executes the specified python file in a separate subprocess.
-    Method returns only when the subprocess is finished.
+    Executes the specified python file in a separate subprocess32.
+    Method returns only when the subprocess32 is finished.
     Params arg is a list of script parameters
     Timeout meaning: how many seconds should pass before script execution
     is forcibly terminated
@@ -96,9 +96,9 @@ class PythonExecutor(object):
     logger.debug("Running command " + pprint.pformat(pythonCommand))
 
     if handle is None:
-      tmpout, tmperr = self.open_subprocess_files(tmpoutfile, tmperrfile, override_output_files, backup_log_files)
+      tmpout, tmperr = self.open_subprocess32_files(tmpoutfile, tmperrfile, override_output_files, backup_log_files)
 
-      process = self.launch_python_subprocess(pythonCommand, tmpout, tmperr)
+      process = self.launch_python_subprocess32(pythonCommand, tmpout, tmperr)
       # map task_id to pid
       callback(task_id, process.pid)
       logger.debug("Launching watchdog thread")
@@ -161,9 +161,9 @@ class PythonExecutor(object):
   def preexec_fn(self):
     os.setpgid(0, 0)
 
-  def launch_python_subprocess(self, command, tmpout, tmperr):
+  def launch_python_subprocess32(self, command, tmpout, tmperr):
     """
-    Creates subprocess with given parameters. This functionality was moved to separate method
+    Creates subprocess32 with given parameters. This functionality was moved to separate method
     to make possible unit testing
     """
     close_fds = None if OSCheck.get_os_family() == OSConst.WINSRV_FAMILY else True
@@ -173,7 +173,7 @@ class PythonExecutor(object):
       for k, v in command_env.iteritems():
         command_env[k] = str(v)
 
-    return subprocess.Popen(command,
+    return subprocess32.Popen(command,
       stdout=tmpout,
       stderr=tmperr, close_fds=close_fds, env=command_env, preexec_fn=self.preexec_fn)
 
@@ -201,7 +201,7 @@ class PythonExecutor(object):
   def python_watchdog_func(self, python, timeout):
     self.event.wait(timeout)
     if python.returncode is None:
-      logger.error("Subprocess timed out and will be killed")
+      logger.error("subprocess32 timed out and will be killed")
       shell.kill_process_with_children(python.pid)
       self.python_process_has_been_killed = True
     pass
@@ -221,10 +221,10 @@ class BackgroundThread(threading.Thread):
     self.pythonExecutor = pythonExecutor
 
   def run(self):
-    process_out, process_err = self.pythonExecutor.open_subprocess_files(self.holder.out_file, self.holder.err_file, True)
+    process_out, process_err = self.pythonExecutor.open_subprocess32_files(self.holder.out_file, self.holder.err_file, True)
 
     logger.debug("Starting process command %s" % self.holder.command)
-    process = self.pythonExecutor.launch_python_subprocess(self.holder.command, process_out, process_err)
+    process = self.pythonExecutor.launch_python_subprocess32(self.holder.command, process_out, process_err)
 
     logger.debug("Process has been started. Pid = %s" % process.pid)
 
diff --git a/ambari-agent/src/main/python/ambari_agent/PythonReflectiveExecutor.py b/ambari-agent/src/main/python/ambari_agent/PythonReflectiveExecutor.py
index b27d7d1..1233672 100644
--- a/ambari-agent/src/main/python/ambari_agent/PythonReflectiveExecutor.py
+++ b/ambari-agent/src/main/python/ambari_agent/PythonReflectiveExecutor.py
@@ -49,7 +49,7 @@ class PythonReflectiveExecutor(PythonExecutor):
     logger.debug("Running command reflectively " + pprint.pformat(pythonCommand))
     
     script_dir = os.path.dirname(script)
-    self.open_subprocess_files(tmpoutfile, tmperrfile, override_output_files, backup_log_files)
+    self.open_subprocess32_files(tmpoutfile, tmperrfile, override_output_files, backup_log_files)
     returncode = 1
 
     try:
diff --git a/ambari-agent/src/main/python/ambari_agent/Register.py b/ambari-agent/src/main/python/ambari_agent/Register.py
index 0c811c6..a960c88 100644
--- a/ambari-agent/src/main/python/ambari_agent/Register.py
+++ b/ambari-agent/src/main/python/ambari_agent/Register.py
@@ -20,7 +20,7 @@ limitations under the License.
 
 import os
 import time
-import subprocess
+from ambari_commons import subprocess32
 from Hardware import Hardware
 import hostname
 from HostInfo import HostInfo
diff --git a/ambari-agent/src/main/python/ambari_agent/hostname.py b/ambari-agent/src/main/python/ambari_agent/hostname.py
index 357c6b0..82d868b 100644
--- a/ambari-agent/src/main/python/ambari_agent/hostname.py
+++ b/ambari-agent/src/main/python/ambari_agent/hostname.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 
 import socket
-import subprocess
+from ambari_commons import subprocess32
 import urllib2
 import logging
 import traceback
@@ -49,7 +49,7 @@ def hostname(config):
   try:
     scriptname = config.get('agent', 'hostname_script')
     try:
-      osStat = subprocess.Popen([scriptname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+      osStat = subprocess32.Popen([scriptname], stdout=subprocess32.PIPE, stderr=subprocess32.PIPE)
       out, err = osStat.communicate()
       if (0 == osStat.returncode and 0 != len(out.strip())):
         cached_hostname = out.strip()
@@ -80,7 +80,7 @@ def public_hostname(config):
   try:
     if config.has_option('agent', 'public_hostname_script'):
       scriptname = config.get('agent', 'public_hostname_script')
-      output = subprocess.Popen(scriptname, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+      output = subprocess32.Popen(scriptname, stdout=subprocess32.PIPE, stderr=subprocess32.PIPE, shell=True)
       out, err = output.communicate()
       if (0 == output.returncode and 0 != len(out.strip())):
         cached_public_hostname = out.strip().lower()
@@ -117,7 +117,7 @@ def server_hostnames(config):
   if config.has_option('server', 'hostname_script'):
     scriptname = config.get('server', 'hostname_script')
     try:
-      osStat = subprocess.Popen([scriptname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+      osStat = subprocess32.Popen([scriptname], stdout=subprocess32.PIPE, stderr=subprocess32.PIPE)
       out, err = osStat.communicate()
       if (0 == osStat.returncode and 0 != len(out.strip())):
         cached_server_hostnames = arrayFromCsvString(out)
diff --git a/ambari-agent/src/main/python/ambari_agent/main.py b/ambari-agent/src/main/python/ambari_agent/main.py
index e5b035d..e639a3e 100644
--- a/ambari-agent/src/main/python/ambari_agent/main.py
+++ b/ambari-agent/src/main/python/ambari_agent/main.py
@@ -27,7 +27,7 @@ def fix_encoding_reimport_bug():
 
 def fix_subprocess_racecondition():
   """
-  Subprocess in Python has race condition with enabling/disabling gc. Which may lead to turning off python garbage collector.
+  subprocess in Python has race condition with enabling/disabling gc. Which may lead to turning off python garbage collector.
   This leads to a memory leak.
   This function monkey patches subprocess to fix the issue.
 
@@ -43,6 +43,8 @@ def fix_subprocess_racecondition():
   import gc
 
 
+"""
+# this might cause some unexcepted problems
 def fix_subprocess_popen():
   '''
   Workaround for race condition in starting subprocesses concurrently from
@@ -54,7 +56,7 @@ def fix_subprocess_popen():
 
   if os.name == 'posix' and sys.version_info[0] < 3:
     from multiprocessing import forking
-    import subprocess
+    from ambari_commons import subprocess
     import threading
 
     sp_original_init = subprocess.Popen.__init__
@@ -71,9 +73,9 @@ def fix_subprocess_popen():
 
     subprocess.Popen.__init__ = sp_locked_init
     forking.Popen.__init__ = mp_locked_init
+"""
 
-
-fix_subprocess_popen()
+#fix_subprocess_popen()
 fix_subprocess_racecondition()
 fix_encoding_reimport_bug()
 
diff --git a/ambari-agent/src/main/python/ambari_agent/security.py b/ambari-agent/src/main/python/ambari_agent/security.py
index d0cfde4..035ca93 100644
--- a/ambari-agent/src/main/python/ambari_agent/security.py
+++ b/ambari-agent/src/main/python/ambari_agent/security.py
@@ -23,7 +23,7 @@ import socket
 import ssl
 import os
 import logging
-import subprocess
+from ambari_commons import subprocess32
 import ambari_simplejson as json
 import pprint
 import traceback
@@ -255,11 +255,11 @@ class CertificateManager():
     
     logger.info(generate_script)
     if platform.system() == 'Windows':
-      p = subprocess.Popen(generate_script, stdout=subprocess.PIPE)
+      p = subprocess32.Popen(generate_script, stdout=subprocess32.PIPE)
       p.communicate()
     else:
-      p = subprocess.Popen([generate_script], shell=True,
-                           stdout=subprocess.PIPE)
+      p = subprocess32.Popen([generate_script], shell=True,
+                           stdout=subprocess32.PIPE)
       p.communicate()
     # this is required to be 600 for security concerns.
     os.chmod(keyname, 0600)
diff --git a/ambari-agent/src/test/python/ambari_agent/TestActionQueue.py b/ambari-agent/src/test/python/ambari_agent/TestActionQueue.py
index faa9b81..b2c6f43 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestActionQueue.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestActionQueue.py
@@ -1418,12 +1418,12 @@ def patch_output_file(pythonExecutor):
     with tmperr:
       tmperr.write('process_err')
     return proc
-  def open_subprocess_files_win(fout, ferr, f):
+  def open_subprocess32_files_win(fout, ferr, f):
     return MagicMock(), MagicMock()
   def read_result_from_files(out_path, err_path, structured_out_path):
     return 'process_out', 'process_err', '{"a": "b."}'
-  pythonExecutor.launch_python_subprocess = windows_py
-  pythonExecutor.open_subprocess_files = open_subprocess_files_win
+  pythonExecutor.launch_python_subprocess32 = windows_py
+  pythonExecutor.open_subprocess32_files = open_subprocess32_files_win
   pythonExecutor.read_result_from_files = read_result_from_files
 
 def wraped(func, before = None, after = None):
diff --git a/ambari-agent/src/test/python/ambari_agent/TestAmbariAgent.py b/ambari-agent/src/test/python/ambari_agent/TestAmbariAgent.py
index 56a73fc..6eadb44 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestAmbariAgent.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestAmbariAgent.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 
 import unittest
-import subprocess
+from ambari_commons import subprocess32
 import os
 import sys
 import AmbariConfig
@@ -31,15 +31,15 @@ with patch("platform.linux_distribution", return_value = ('Suse','11','Final')):
 
 class TestAmbariAgent(unittest.TestCase):
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("os.path.isfile")
   @patch("os.remove")
   @patch("os.killpg")
   def test_main(self, os_killpg_mock, os_remove_mock,
-                os_path_isfile_mock, subprocess_popen_mock):
+                os_path_isfile_mock, subprocess32_popen_mock):
     facter1 = MagicMock()
     facter2 = MagicMock()
-    subprocess_popen_mock.side_effect = [facter1, facter2]
+    subprocess32_popen_mock.side_effect = [facter1, facter2]
     facter1.returncode = 77
     facter2.returncode = 55
     os_path_isfile_mock.return_value = True
@@ -48,8 +48,8 @@ class TestAmbariAgent(unittest.TestCase):
     sys.argv[0] = "test data"
     AmbariAgent.main()
 
-    self.assertTrue(subprocess_popen_mock.called)
-    self.assertTrue(subprocess_popen_mock.call_count == 2)
+    self.assertTrue(subprocess32_popen_mock.called)
+    self.assertTrue(subprocess32_popen_mock.call_count == 2)
     self.assertTrue(facter1.communicate.called)
     self.assertTrue(facter2.communicate.called)
     self.assertTrue(os_path_isfile_mock.called)
diff --git a/ambari-agent/src/test/python/ambari_agent/TestHardware.py b/ambari-agent/src/test/python/ambari_agent/TestHardware.py
index e78f8f2..8de2c02 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestHardware.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestHardware.py
@@ -25,7 +25,7 @@ from mock.mock import patch, MagicMock, Mock
 import unittest
 import platform
 import socket
-import subprocess
+from ambari_commons import subprocess32
 from only_for_platform import not_for_platform, PLATFORM_WINDOWS
 from ambari_agent import hostname
 from ambari_agent.Hardware import Hardware
@@ -154,34 +154,34 @@ class TestHardware(TestCase):
     get_os_version_mock.return_value = "11"
     Hardware(cache_info=False).osdisks()
     timeout = 10
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
     config = AmbariConfig()
     Hardware(config=config, cache_info=False).osdisks()
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
     config.add_section(AmbariConfig.AMBARI_PROPERTIES_CATEGORY)
     config.set(AmbariConfig.AMBARI_PROPERTIES_CATEGORY, Hardware.CHECK_REMOTE_MOUNTS_KEY, "true")
     Hardware(config=config, cache_info=False).osdisks()
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
     config.set(AmbariConfig.AMBARI_PROPERTIES_CATEGORY, Hardware.CHECK_REMOTE_MOUNTS_KEY, "false")
     Hardware(config=config, cache_info=False).osdisks()
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
     config.set(AmbariConfig.AMBARI_PROPERTIES_CATEGORY, Hardware.CHECK_REMOTE_MOUNTS_TIMEOUT_KEY, "0")
     Hardware(config=config, cache_info=False).osdisks()
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
     timeout = 1
     config.set(AmbariConfig.AMBARI_PROPERTIES_CATEGORY, Hardware.CHECK_REMOTE_MOUNTS_TIMEOUT_KEY, str(timeout))
     Hardware(config=config, cache_info=False).osdisks()
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
     timeout = 2
     config.set(AmbariConfig.AMBARI_PROPERTIES_CATEGORY, Hardware.CHECK_REMOTE_MOUNTS_TIMEOUT_KEY, str(timeout))
     Hardware(config=config, cache_info=False).osdisks()
-    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = timeout, quiet = True)
+    shell_call_mock.assert_called_with(['timeout', str(timeout), "df", "-kPT", "-l"], stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = timeout, quiet = True)
 
   def test_parse_df_line(self):
     df_line_sample = "device type size used available percent mountpoint"
diff --git a/ambari-agent/src/test/python/ambari_agent/TestPingPortListener.py b/ambari-agent/src/test/python/ambari_agent/TestPingPortListener.py
index 0475c35..7abc5d5 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestPingPortListener.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestPingPortListener.py
@@ -21,6 +21,7 @@ limitations under the License.
 import unittest
 from mock.mock import patch, MagicMock, call, Mock
 from ambari_agent import PingPortListener
+from ambari_commons import subprocess32
 import socket
 import sys
 
@@ -31,7 +32,7 @@ class TestPingPortListener(unittest.TestCase):
     self.config.get.return_value = 55000
     PingPortListener.logger = MagicMock()
 
-  @patch("subprocess.Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("socket.socket")
   def test_init_success(self,socketMock,popen_mock):
     procObj = MagicMock()
@@ -52,7 +53,7 @@ class TestPingPortListener(unittest.TestCase):
 
 
 
-  @patch("subprocess.Popen")
+  @patch.object(subprocess32, "Popen")
   @patch.object(socket.socket,"bind")
   @patch.object(socket.socket,"listen")
   def test_init_warn(self,socketListenMock,socketBindMock,popen_mock):
diff --git a/ambari-agent/src/test/python/ambari_agent/TestPythonExecutor.py b/ambari-agent/src/test/python/ambari_agent/TestPythonExecutor.py
index d9bc7f8..08cf06e 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestPythonExecutor.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestPythonExecutor.py
@@ -33,7 +33,7 @@ from mock.mock import MagicMock, patch
 from ambari_commons import OSCheck
 from only_for_platform import os_distro_value
 
-@patch.object(PythonExecutor, "open_subprocess_files", new=MagicMock(return_value =("", "")))
+@patch.object(PythonExecutor, "open_subprocess32_files", new=MagicMock(return_value =("", "")))
 class TestPythonExecutor(TestCase):
 
   @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
@@ -42,7 +42,7 @@ class TestPythonExecutor(TestCase):
     """
     Tests whether watchdog works
     """
-    subproc_mock = self.Subprocess_mockup()
+    subproc_mock = self.subprocess32_mockup()
     executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
     _, tmpoutfile = tempfile.mkstemp()
     _, tmperrfile = tempfile.mkstemp()
@@ -50,11 +50,11 @@ class TestPythonExecutor(TestCase):
     PYTHON_TIMEOUT_SECONDS = 0.1
     kill_process_with_children_mock.side_effect = lambda pid : subproc_mock.terminate()
 
-    def launch_python_subprocess_method(command, tmpout, tmperr):
+    def launch_python_subprocess32_method(command, tmpout, tmperr):
       subproc_mock.tmpout = tmpout
       subproc_mock.tmperr = tmperr
       return subproc_mock
-    executor.launch_python_subprocess = launch_python_subprocess_method
+    executor.launch_python_subprocess32 = launch_python_subprocess32_method
     runShellKillPgrp_method = MagicMock()
     runShellKillPgrp_method.side_effect = lambda python : python.terminate()
     executor.runShellKillPgrp = runShellKillPgrp_method
@@ -66,7 +66,7 @@ class TestPythonExecutor(TestCase):
     thread.start()
     time.sleep(0.1)
     subproc_mock.finished_event.wait()
-    self.assertEquals(subproc_mock.was_terminated, True, "Subprocess should be terminated due to timeout")
+    self.assertEquals(subproc_mock.was_terminated, True, "subprocess32 should be terminated due to timeout")
     self.assertTrue(callback_method.called)
 
 
@@ -75,18 +75,18 @@ class TestPythonExecutor(TestCase):
     """
     Tries to catch false positive watchdog invocations
     """
-    subproc_mock = self.Subprocess_mockup()
+    subproc_mock = self.subprocess32_mockup()
     executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
     _, tmpoutfile = tempfile.mkstemp()
     _, tmperrfile = tempfile.mkstemp()
     _, tmpstrucout = tempfile.mkstemp()
     PYTHON_TIMEOUT_SECONDS =  5
 
-    def launch_python_subprocess_method(command, tmpout, tmperr):
+    def launch_python_subprocess32_method(command, tmpout, tmperr):
       subproc_mock.tmpout = tmpout
       subproc_mock.tmperr = tmperr
       return subproc_mock
-    executor.launch_python_subprocess = launch_python_subprocess_method
+    executor.launch_python_subprocess32 = launch_python_subprocess32_method
     runShellKillPgrp_method = MagicMock()
     runShellKillPgrp_method.side_effect = lambda python : python.terminate()
     executor.runShellKillPgrp = runShellKillPgrp_method
@@ -100,13 +100,13 @@ class TestPythonExecutor(TestCase):
     time.sleep(0.1)
     subproc_mock.should_finish_event.set()
     subproc_mock.finished_event.wait()
-    self.assertEquals(subproc_mock.was_terminated, False, "Subprocess should not be terminated before timeout")
-    self.assertEquals(subproc_mock.returncode, 0, "Subprocess should not be terminated before timeout")
+    self.assertEquals(subproc_mock.was_terminated, False, "subprocess32 should not be terminated before timeout")
+    self.assertEquals(subproc_mock.returncode, 0, "subprocess32 should not be terminated before timeout")
     self.assertTrue(callback_method.called)
 
   @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
   def test_execution_results(self):
-    subproc_mock = self.Subprocess_mockup()
+    subproc_mock = self.subprocess32_mockup()
     executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
     _, tmpoutfile = tempfile.mkstemp()
     _, tmperrfile = tempfile.mkstemp()
@@ -117,11 +117,11 @@ class TestPythonExecutor(TestCase):
 
     PYTHON_TIMEOUT_SECONDS =  5
 
-    def launch_python_subprocess_method(command, tmpout, tmperr):
+    def launch_python_subprocess32_method(command, tmpout, tmperr):
       subproc_mock.tmpout = tmpout
       subproc_mock.tmperr = tmperr
       return subproc_mock
-    executor.launch_python_subprocess = launch_python_subprocess_method
+    executor.launch_python_subprocess32 = launch_python_subprocess32_method
     runShellKillPgrp_method = MagicMock()
     runShellKillPgrp_method.side_effect = lambda python : python.terminate()
     executor.runShellKillPgrp = runShellKillPgrp_method
@@ -182,7 +182,7 @@ class TestPythonExecutor(TestCase):
     pass
 
 
-  class Subprocess_mockup():
+  class subprocess32_mockup():
     """
     It's not trivial to use PyMock instead of class here because we need state
     and complex logics
diff --git a/ambari-agent/src/test/python/ambari_agent/TestRegistration.py b/ambari-agent/src/test/python/ambari_agent/TestRegistration.py
index fada29c..7fa63cf 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestRegistration.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestRegistration.py
@@ -32,7 +32,7 @@ from ambari_agent.Facter import FacterLinux
 @not_for_platform(PLATFORM_WINDOWS)
 class TestRegistration(TestCase):
 
-  @patch("subprocess.Popen")
+  @patch("subprocess32.Popen")
   @patch.object(Hardware, "_chk_writable_mount", new = MagicMock(return_value=True))
   @patch("__builtin__.open", new=MagicMock())
   @patch.object(FacterLinux, "facterInfo", new = MagicMock(return_value={}))
diff --git a/ambari-agent/src/test/python/ambari_agent/TestSecurity.py b/ambari-agent/src/test/python/ambari_agent/TestSecurity.py
index c9a7fbe..bdac46a 100644
--- a/ambari-agent/src/test/python/ambari_agent/TestSecurity.py
+++ b/ambari-agent/src/test/python/ambari_agent/TestSecurity.py
@@ -18,7 +18,8 @@ See the License for the specific language governing permissions and
 limitations under the License.
 '''
 import StringIO
-import sys, subprocess
+import sys
+from ambari_commons import subprocess32
 from mock.mock import MagicMock, patch, ANY
 import mock.mock
 import unittest
@@ -344,12 +345,12 @@ class TestSecurity(unittest.TestCase):
       pass
     self.assertFalse(open_mock.return_value.write.called)
 
-  @patch("subprocess.Popen")
-  @patch("subprocess.Popen.communicate")
+  @patch.object(subprocess32, "Popen")
+  @patch("subprocess32.Popen.communicate")
   @patch.object(os, "chmod")
   def test_genAgentCrtReq(self, chmod_mock, communicate_mock, popen_mock):
     man = CertificateManager(self.config, "active_server")
-    p = MagicMock(spec=subprocess.Popen)
+    p = MagicMock(spec=subprocess32.Popen)
     p.communicate = communicate_mock
     popen_mock.return_value = p
     man.genAgentCrtReq('/dummy-keysdir/hostname.key')
diff --git a/ambari-agent/src/test/python/resource_management/TestExecuteResource.py b/ambari-agent/src/test/python/resource_management/TestExecuteResource.py
index 92068b8..bd7059e 100644
--- a/ambari-agent/src/test/python/resource_management/TestExecuteResource.py
+++ b/ambari-agent/src/test/python/resource_management/TestExecuteResource.py
@@ -28,7 +28,7 @@ from resource_management.core.resources.system import Execute
 from resource_management.core.environment import Environment
 from resource_management.core.shell import quote_bash_args
 
-import subprocess
+from ambari_commons import subprocess32
 import logging
 import os
 from resource_management import Fail
@@ -45,7 +45,7 @@ class TestExecuteResource(TestCase):
   @patch.object(os, "read")
   @patch.object(select, "select")
   @patch.object(logging.Logger, "info")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_logoutput(self, popen_mock, info_mock, select_mock, os_read_mock):
     subproc_mock = MagicMock()
     subproc_mock.wait.return_value = MagicMock()
@@ -64,8 +64,8 @@ class TestExecuteResource(TestCase):
     info_mock.assert_called('1')
     self.assertTrue("call('2')" not in str(info_mock.mock_calls))
     
-  @patch('subprocess.Popen.communicate')
-  @patch('subprocess.Popen')
+  @patch('subprocess32.Popen.communicate')
+  @patch.object(subprocess32, "Popen")
   def test_attribute_wait(self, popen_mock, proc_communicate_mock):
     with Environment("/") as env:
       Execute('echo "1"',
@@ -73,11 +73,11 @@ class TestExecuteResource(TestCase):
       Execute('echo "2"',
               wait_for_finish=False)
     
-    self.assertTrue(popen_mock.called, 'subprocess.Popen should have been called!')
+    self.assertTrue(popen_mock.called, 'subprocess32.Popen should have been called!')
     self.assertFalse(proc_communicate_mock.called, 'proc.communicate should not have been called!')
 
   @patch("resource_management.core.sudo.path_exists")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_creates(self, popen_mock, exists_mock):
     exists_mock.return_value = True
 
@@ -96,7 +96,7 @@ class TestExecuteResource(TestCase):
 
   @patch.object(os, "read")
   @patch.object(select, "select")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_path(self, popen_mock, select_mock, os_read_mock):
     subproc_mock = MagicMock()
     subproc_mock.wait.return_value = MagicMock()
@@ -116,7 +116,7 @@ class TestExecuteResource(TestCase):
   @patch.object(os, "read")
   @patch.object(select, "select")
   @patch('time.sleep')
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_try_sleep_tries(self, popen_mock, time_mock, select_mock, os_read_mock):
     expected_call = "call('Retrying after %d seconds. Reason: %s', 1, 'Fail')"
     
@@ -157,7 +157,7 @@ class TestExecuteResource(TestCase):
 
   @patch.object(os, "read")
   @patch.object(select, "select")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_environment(self, popen_mock, select_mock, os_read_mock):
     expected_dict = {"JAVA_HOME": "/test/java/home"}
 
@@ -179,7 +179,7 @@ class TestExecuteResource(TestCase):
 
   @patch.object(os, "read")
   @patch.object(select, "select")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_environment_non_root(self, popen_mock, select_mock, os_read_mock):
     expected_user = 'test_user'
 
@@ -205,7 +205,7 @@ class TestExecuteResource(TestCase):
 
   @patch.object(os, "read")
   @patch.object(select, "select")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_cwd(self, popen_mock, select_mock, os_read_mock):
     expected_cwd = "/test/work/directory"
 
@@ -226,7 +226,7 @@ class TestExecuteResource(TestCase):
 
   @patch.object(os, "read")
   @patch.object(select, "select")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_command_escaping(self, popen_mock, select_mock, os_read_mock):
     expected_command0 = "arg1 arg2 'quoted arg'"
     expected_command1 = "arg1 arg2 'command \"arg\"'"
@@ -266,7 +266,7 @@ class TestExecuteResource(TestCase):
 
   @patch.object(os, "read")
   @patch.object(select, "select")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_attribute_command_one_line(self, popen_mock, select_mock, os_read_mock):
     expected_command = "rm -rf /somedir"
 
diff --git a/ambari-agent/src/test/python/resource_management/TestGroupResource.py b/ambari-agent/src/test/python/resource_management/TestGroupResource.py
index 81bb7f9..5d27e77 100644
--- a/ambari-agent/src/test/python/resource_management/TestGroupResource.py
+++ b/ambari-agent/src/test/python/resource_management/TestGroupResource.py
@@ -29,7 +29,7 @@ from resource_management.core.shell import preexec_fn
 
 import os
 import select
-import subprocess
+from ambari_commons import subprocess32
 
 if get_platform() != PLATFORM_WINDOWS:
   import grp
@@ -47,7 +47,7 @@ subproc_stdout = MagicMock()
 class TestGroupResource(TestCase):
 
   @patch("grp.getgrnam")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_action_create_nonexistent(self, popen_mock, getgrnam_mock):
     subproc_mock = MagicMock()
     subproc_mock.returncode = 0
@@ -68,7 +68,7 @@ class TestGroupResource(TestCase):
 
 
   @patch("grp.getgrnam")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_action_create_existent(self, popen_mock, getgrnam_mock):
     subproc_mock = MagicMock()
     subproc_mock.returncode = 0
@@ -90,7 +90,7 @@ class TestGroupResource(TestCase):
 
 
   @patch("grp.getgrnam")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_action_create_fail(self, popen_mock, getgrnam_mock):
     subproc_mock = MagicMock()
     subproc_mock.returncode = 1
@@ -115,7 +115,7 @@ class TestGroupResource(TestCase):
 
 
   @patch("grp.getgrnam")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_action_remove(self, popen_mock, getgrnam_mock):
 
     subproc_mock = MagicMock()
@@ -136,7 +136,7 @@ class TestGroupResource(TestCase):
 
 
   @patch("grp.getgrnam")
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   def test_action_remove_fail(self, popen_mock, getgrnam_mock):
 
     subproc_mock = MagicMock()
diff --git a/ambari-agent/src/test/python/resource_management/TestUserResource.py b/ambari-agent/src/test/python/resource_management/TestUserResource.py
index 8f1df83..e6c0d74 100644
--- a/ambari-agent/src/test/python/resource_management/TestUserResource.py
+++ b/ambari-agent/src/test/python/resource_management/TestUserResource.py
@@ -27,7 +27,7 @@ from resource_management.core import Environment, Fail
 from resource_management.core.system import System
 from resource_management.core.resources import User
 from resource_management.core.shell import preexec_fn
-import subprocess
+from ambari_commons import subprocess32
 import os
 import select
 
@@ -46,7 +46,7 @@ subproc_stdout = MagicMock()
 @patch.object(os, "close", new=MagicMock())
 class TestUserResource(TestCase):
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_action_create_nonexistent(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -60,7 +60,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E useradd -m -s /bin/bash mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
     
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_action_create_existent(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -75,7 +75,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E usermod -s /bin/bash mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_action_delete(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -90,7 +90,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', 'ambari-sudo.sh  PATH=/bin -H -E userdel mapred'], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_comment(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -106,7 +106,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E usermod -c testComment -s /bin/bash mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_home(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -122,7 +122,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E usermod -s /bin/bash -d /test/home mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_password(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -138,7 +138,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E usermod -s /bin/bash -p secure mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_shell(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -153,7 +153,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E usermod -s /bin/sh mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_uid(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -168,7 +168,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', "ambari-sudo.sh  PATH=/bin -H -E usermod -s /bin/bash -u 1 mapred"], shell=False, preexec_fn=preexec_fn, stderr=-2, stdout=-1, env={'PATH': '/bin'}, cwd=None, close_fds=True)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_gid(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
@@ -184,7 +184,7 @@ class TestUserResource(TestCase):
     self.assertEqual(popen_mock.call_count, 1)
 
   @patch('resource_management.core.providers.accounts.UserProvider.user_groups', new_callable=PropertyMock)
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_attribute_groups(self, getpwnam_mock, popen_mock, user_groups_mock):
     subproc_mock = MagicMock()
@@ -201,7 +201,7 @@ class TestUserResource(TestCase):
     popen_mock.assert_called_with(['/bin/bash', '--login', '--noprofile', '-c', 'ambari-sudo.sh  PATH=/bin -H -E usermod -s /bin/bash -G 1,2,3,hadoop mapred'], shell=False, preexec_fn=preexec_fn, env={'PATH': '/bin'}, close_fds=True, stdout=-1, stderr=-2, cwd=None)
     self.assertEqual(popen_mock.call_count, 1)
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("pwd.getpwnam")
   def test_missing_shell_argument(self, getpwnam_mock, popen_mock):
     subproc_mock = MagicMock()
diff --git a/ambari-common/src/main/python/ambari_commons/_posixsubprocess.so b/ambari-common/src/main/python/ambari_commons/_posixsubprocess.so
new file mode 100644
index 0000000..aaff30a
Binary files /dev/null and b/ambari-common/src/main/python/ambari_commons/_posixsubprocess.so differ
diff --git a/ambari-common/src/main/python/ambari_commons/firewall.py b/ambari-common/src/main/python/ambari_commons/firewall.py
index 0ef4f7a..827cf7f 100644
--- a/ambari-common/src/main/python/ambari_commons/firewall.py
+++ b/ambari-common/src/main/python/ambari_commons/firewall.py
@@ -18,7 +18,7 @@ See the License for the specific language governing permissions and
 limitations under the License.
 '''
 
-import subprocess
+from ambari_commons import subprocess32
 from ambari_commons import OSCheck, OSConst
 from ambari_commons.logging_utils import print_warning_msg
 from ambari_commons.os_family_impl import OsFamilyImpl
@@ -82,7 +82,7 @@ class FirewallChecks(object):
 
   def run_command(self):
     try:
-      retcode, out, err = shell.call(self.get_command(), stdout = subprocess.PIPE, stderr = subprocess.PIPE, timeout = 5, quiet = True)
+      retcode, out, err = shell.call(self.get_command(), stdout = subprocess32.PIPE, stderr = subprocess32.PIPE, timeout = 5, quiet = True)
       self.returncode = retcode
       self.stdoutdata = out
       self.stderrdata = err
diff --git a/ambari-common/src/main/python/ambari_commons/os_linux.py b/ambari-common/src/main/python/ambari_commons/os_linux.py
index 60b9659..053051b 100644
--- a/ambari-common/src/main/python/ambari_commons/os_linux.py
+++ b/ambari-common/src/main/python/ambari_commons/os_linux.py
@@ -22,7 +22,7 @@ import getpass
 import os
 import pwd
 import shlex
-import subprocess
+from ambari_commons import subprocess32
 
 from ambari_commons.logging_utils import print_info_msg, print_warning_msg
 
@@ -38,10 +38,10 @@ def os_run_os_command(cmd, env=None, shell=False, cwd=None):
   print_info_msg('about to run command: ' + str(cmd))
   if type(cmd) == str:
     cmd = shlex.split(cmd)
-  process = subprocess.Popen(cmd,
-                             stdout=subprocess.PIPE,
-                             stdin=subprocess.PIPE,
-                             stderr=subprocess.PIPE,
+  process = subprocess32.Popen(cmd,
+                             stdout=subprocess32.PIPE,
+                             stdin=subprocess32.PIPE,
+                             stderr=subprocess32.PIPE,
                              env=env,
                              cwd=cwd,
                              shell=shell
diff --git a/ambari-common/src/main/python/ambari_commons/os_windows.py b/ambari-common/src/main/python/ambari_commons/os_windows.py
index 058dbfd..4c22384 100644
--- a/ambari-common/src/main/python/ambari_commons/os_windows.py
+++ b/ambari-common/src/main/python/ambari_commons/os_windows.py
@@ -21,7 +21,7 @@ import getpass
 import os
 import random
 import shlex
-import subprocess
+from ambari_commons import subprocess32
 import sys
 import tempfile
 import time
@@ -341,10 +341,10 @@ def os_run_os_command(cmd, env=None, shell=False, cwd=None):
   if isinstance(cmd,basestring):
     cmd = cmd.replace("\\", "\\\\")
     cmd = shlex.split(cmd)
-  process = subprocess.Popen(cmd,
-                             stdout=subprocess.PIPE,
-                             stdin=subprocess.PIPE,
-                             stderr=subprocess.PIPE,
+  process = subprocess32.Popen(cmd,
+                             stdout=subprocess32.PIPE,
+                             stdin=subprocess32.PIPE,
+                             stderr=subprocess32.PIPE,
                              env=env,
                              cwd=cwd,
                              shell=shell
diff --git a/ambari-common/src/main/python/ambari_commons/shell.py b/ambari-common/src/main/python/ambari_commons/shell.py
index d84fe99..3f4ccac 100644
--- a/ambari-common/src/main/python/ambari_commons/shell.py
+++ b/ambari-common/src/main/python/ambari_commons/shell.py
@@ -19,7 +19,7 @@ limitations under the License.
 """
 
 import logging
-import subprocess
+from ambari_commons import subprocess32
 import os
 import signal
 import threading
@@ -78,7 +78,7 @@ def launch_subprocess(command):
   :return Popen object
   """
   is_shell = not isinstance(command, (list, tuple))
-  return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=is_shell, close_fds=True)
+  return subprocess32.Popen(command, stdout=subprocess32.PIPE, stderr=subprocess32.PIPE, shell=is_shell, close_fds=True)
 
 
 def watchdog_func(event, cmd, exec_timeout):
@@ -207,8 +207,8 @@ class shellRunnerWindows(shellRunner):
       cmd = " ".join(script)
     else:
       cmd = script
-    p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
-                         stderr=subprocess.PIPE, shell=False)
+    p = subprocess32.Popen(cmd, stdout=subprocess32.PIPE,
+                         stderr=subprocess32.PIPE, shell=False)
     out, err = p.communicate()
     code = p.wait()
     logger.debug("Exitcode for %s is %d" % (cmd, code))
@@ -222,8 +222,8 @@ class shellRunnerWindows(shellRunner):
       cmd = ['powershell', '-WindowStyle', 'Hidden', '-File', file] + args
     elif script_block:
       cmd = ['powershell', '-WindowStyle', 'Hidden', '-Command', script_block] + args
-    p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
-                         stderr=subprocess.PIPE, shell=False)
+    p = subprocess32.Popen(cmd, stdout=subprocess32.PIPE,
+                         stderr=subprocess32.PIPE, shell=False)
     out, err = p.communicate()
     code = p.wait()
     logger.debug("Exitcode for %s is %d" % (cmd, code))
@@ -415,8 +415,8 @@ class shellRunnerLinux(shellRunner):
       cmd = " ".join(script)
 
     cmd_list = ["/bin/bash","--login","--noprofile","-c", cmd]
-    p = subprocess.Popen(cmd_list, preexec_fn=_changeUid, stdout=subprocess.PIPE,
-                         stderr=subprocess.PIPE, shell=False, close_fds=True)
+    p = subprocess32.Popen(cmd_list, preexec_fn=_changeUid, stdout=subprocess32.PIPE,
+                         stderr=subprocess32.PIPE, shell=False, close_fds=True)
     out, err = p.communicate()
     code = p.wait()
     logger.debug("Exitcode for %s is %d" % (cmd, code))
diff --git a/ambari-common/src/main/python/ambari_commons/subprocess32.py b/ambari-common/src/main/python/ambari_commons/subprocess32.py
new file mode 100644
index 0000000..b9378e2
--- /dev/null
+++ b/ambari-common/src/main/python/ambari_commons/subprocess32.py
@@ -0,0 +1,1727 @@
+# subprocess - Subprocesses with accessible I/O streams
+#
+# For more information about this module, see PEP 324.
+#
+# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
+#
+# Licensed to PSF under a Contributor Agreement.
+# See http://www.python.org/3.3/license for licensing details.
+
+r"""Subprocesses with accessible I/O streams
+
+This module allows you to spawn processes, connect to their
+input/output/error pipes, and obtain their return codes.
+
+For a complete description of this module see the Python documentation.
+
+Main API
+========
+run(...): Runs a command, waits for it to complete, then returns a
+          CompletedProcess instance.
+Popen(...): A class for flexibly executing a command in a new process
+
+Constants
+---------
+DEVNULL: Special value that indicates that os.devnull should be used
+PIPE:    Special value that indicates a pipe should be created
+STDOUT:  Special value that indicates that stderr should go to stdout
+
+
+Older API
+=========
+call(...): Runs a command, waits for it to complete, then returns
+    the return code.
+check_call(...): Same as call() but raises CalledProcessError()
+    if return code is not 0
+check_output(...): Same as check_call() but returns the contents of
+    stdout instead of a return code
+"""
+
+# because ambari_commons also has 'exceptions' module
+from __future__ import absolute_import
+
+import sys
+mswindows = (sys.platform == "win32")
+
+import os
+import exceptions
+import types
+import time
+import traceback
+import gc
+import signal
+
+# Exception classes used by this module.
+class SubprocessError(Exception): pass
+
+
+class CalledProcessError(SubprocessError):
+    """Raised when run() is called with check=True and the process
+    returns a non-zero exit status.
+
+    Attributes:
+      cmd, returncode, stdout, stderr, output
+    """
+    def __init__(self, returncode, cmd, output=None, stderr=None):
+        self.returncode = returncode
+        self.cmd = cmd
+        self.output = output
+        self.stderr = stderr
+
+    def __str__(self):
+        if self.returncode and self.returncode < 0:
+            try:
+                return "Command '%s' died with %r." % (
+                        self.cmd, signal.Signals(-self.returncode))
+            except ValueError:
+                return "Command '%s' died with unknown signal %d." % (
+                        self.cmd, -self.returncode)
+        else:
+            return "Command '%s' returned non-zero exit status %d." % (
+                    self.cmd, self.returncode)
+
+    #@property
+    def __stdout_getter(self):
+        """Alias for output attribute, to match stderr"""
+        return self.output
+
+    #@stdout.setter  # Required Python 2.6
+    def __stdout_setter(self, value):
+        # There's no obvious reason to set this, but allow it anyway so
+        # .stdout is a transparent alias for .output
+        self.output = value
+
+    stdout = property(__stdout_getter, __stdout_setter)  # Python 2.4
+
+
+class TimeoutExpired(SubprocessError):
+    """This exception is raised when the timeout expires while waiting for a
+    child process.
+
+    Attributes:
+        cmd, output, stdout, stderr, timeout
+    """
+    def __init__(self, cmd, timeout, output=None, stderr=None):
+        self.cmd = cmd
+        self.timeout = timeout
+        self.output = output
+        self.stderr = stderr
+
+    def __str__(self):
+        return ("Command '%s' timed out after %s seconds" %
+                (self.cmd, self.timeout))
+
+    #@property
+    def __stdout_getter(self):
+        return self.output
+
+    #@stdout.setter  # Required Python 2.6
+    def __stdout_setter(self, value):
+        # There's no obvious reason to set this, but allow it anyway so
+        # .stdout is a transparent alias for .output
+        self.output = value
+
+    stdout = property(__stdout_getter, __stdout_setter)  # Python 2.4
+
+
+if mswindows:
+    import threading
+    import msvcrt
+    import _subprocess
+    class STARTUPINFO:
+        dwFlags = 0
+        hStdInput = None
+        hStdOutput = None
+        hStdError = None
+        wShowWindow = 0
+    class pywintypes:
+        error = IOError
+else:
+    import select
+    _has_poll = hasattr(select, 'poll')
+    import errno
+    import fcntl
+    import pickle
+
+    try:
+        from ambari_commons import _posixsubprocess
+    except ImportError:
+        _posixsubprocess = None
+        import warnings
+        warnings.warn("The _posixsubprocess module is not being used. "
+                      "Child process reliability may suffer if your "
+                      "program uses threads.", RuntimeWarning)
+    try:
+        import threading
+    except ImportError:
+        import dummy_threading as threading
+
+    # When select or poll has indicated that the file is writable,
+    # we can write up to _PIPE_BUF bytes without risk of blocking.
+    # POSIX defines PIPE_BUF as >= 512.
+    _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
+
+    _FD_CLOEXEC = getattr(fcntl, 'FD_CLOEXEC', 1)
+
+    def _set_cloexec(fd, cloexec):
+        old = fcntl.fcntl(fd, fcntl.F_GETFD)
+        if cloexec:
+            fcntl.fcntl(fd, fcntl.F_SETFD, old | _FD_CLOEXEC)
+        else:
+            fcntl.fcntl(fd, fcntl.F_SETFD, old & ~_FD_CLOEXEC)
+
+    if _posixsubprocess:
+        _create_pipe = _posixsubprocess.cloexec_pipe
+    else:
+        def _create_pipe():
+            fds = os.pipe()
+            _set_cloexec(fds[0], True)
+            _set_cloexec(fds[1], True)
+            return fds
+
+__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
+           "check_output", "CalledProcessError"]
+
+if mswindows:
+    from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
+                             STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
+                             STD_ERROR_HANDLE, SW_HIDE,
+                             STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
+    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx
+    # Note: In Python 3.3 this constant is found in the _winapi module.
+    _WAIT_TIMEOUT = 0x102
+
+    __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
+                    "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
+                    "STD_ERROR_HANDLE", "SW_HIDE",
+                    "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
+try:
+    MAXFD = os.sysconf("SC_OPEN_MAX")
+except:
+    MAXFD = 256
+
+# This lists holds Popen instances for which the underlying process had not
+# exited at the time its __del__ method got called: those processes are wait()ed
+# for synchronously from _cleanup() when a new Popen object is created, to avoid
+# zombie processes.
+_active = []
+
+def _cleanup():
+    for inst in _active[:]:
+        res = inst._internal_poll(_deadstate=sys.maxint)
+        if res is not None:
+            try:
+                _active.remove(inst)
+            except ValueError:
+                # This can happen if two threads create a new Popen instance.
+                # It's harmless that it was already removed, so ignore.
+                pass
+
+PIPE = -1
+STDOUT = -2
+DEVNULL = -3
+
+# This function is only used by multiprocessing, it is here so that people
+# can drop subprocess32 in as a replacement for the stdlib subprocess module.
+
+def _args_from_interpreter_flags():
+    """Return a list of command-line arguments reproducing the current
+    settings in sys.flags and sys.warnoptions."""
+    flag_opt_map = {
+        'debug': 'd',
+        # 'inspect': 'i',
+        # 'interactive': 'i',
+        'optimize': 'O',
+        'dont_write_bytecode': 'B',
+        'no_user_site': 's',
+        'no_site': 'S',
+        'ignore_environment': 'E',
+        'verbose': 'v',
+        'bytes_warning': 'b',
+        'py3k_warning': '3',
+    }
+    args = []
+    for flag, opt in flag_opt_map.items():
+        v = getattr(sys.flags, flag)
+        if v > 0:
+            args.append('-' + opt * v)
+    if getattr(sys.flags, 'hash_randomization') != 0:
+        args.append('-R')
+    for opt in sys.warnoptions:
+        args.append('-W' + opt)
+    return args
+
+
+def _eintr_retry_call(func, *args):
+    while True:
+        try:
+            return func(*args)
+        except (OSError, IOError), e:
+            if e.errno == errno.EINTR:
+                continue
+            raise
+
+
+def _get_exec_path(env=None):
+    """Returns the sequence of directories that will be searched for the
+    named executable (similar to a shell) when launching a process.
+
+    *env* must be an environment variable dict or None.  If *env* is None,
+    os.environ will be used.
+    """
+    if env is None:
+        env = os.environ
+    return env.get('PATH', os.defpath).split(os.pathsep)
+
+
+if hasattr(os, 'get_exec_path'):
+    _get_exec_path = os.get_exec_path
+
+
+def call(*popenargs, **kwargs):
+    """Run command with arguments.  Wait for command to complete or
+    timeout, then return the returncode attribute.
+
+    The arguments are the same as for the Popen constructor.  Example:
+
+    retcode = call(["ls", "-l"])
+    """
+    timeout = kwargs.pop('timeout', None)
+    p = Popen(*popenargs, **kwargs)
+    try:
+        return p.wait(timeout=timeout)
+    except TimeoutExpired:
+        p.kill()
+        p.wait()
+        raise
+
+
+def check_call(*popenargs, **kwargs):
+    """Run command with arguments.  Wait for command to complete.  If
+    the exit code was zero then return, otherwise raise
+    CalledProcessError.  The CalledProcessError object will have the
+    return code in the returncode attribute.
+
+    The arguments are the same as for the call function.  Example:
+
+    check_call(["ls", "-l"])
+    """
+    retcode = call(*popenargs, **kwargs)
+    if retcode:
+        cmd = kwargs.get("args")
+        if cmd is None:
+            cmd = popenargs[0]
+        raise CalledProcessError(retcode, cmd)
+    return 0
+
+
+def check_output(*popenargs, **kwargs):
+    r"""Run command with arguments and return its output as a byte string.
+
+    If the exit code was non-zero it raises a CalledProcessError.  The
+    CalledProcessError object will have the return code in the returncode
+    attribute and output in the output attribute.
+
+    The arguments are the same as for the Popen constructor.  Example:
+
+    >>> check_output(["ls", "-l", "/dev/null"])
+    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
+
+    The stdout argument is not allowed as it is used internally.
+    To capture standard error in the result, use stderr=STDOUT.
+
+    >>> check_output(["/bin/sh", "-c",
+    ...               "ls -l non_existent_file ; exit 0"],
+    ...              stderr=STDOUT)
+    'ls: non_existent_file: No such file or directory\n'
+    """
+    timeout = kwargs.pop('timeout', None)
+    if 'stdout' in kwargs:
+        raise ValueError('stdout argument not allowed, it will be overridden.')
+    process = Popen(stdout=PIPE, *popenargs, **kwargs)
+    try:
+        output, unused_err = process.communicate(timeout=timeout)
+    except TimeoutExpired:
+        process.kill()
+        output, unused_err = process.communicate()
+        raise TimeoutExpired(process.args, timeout, output=output)
+    retcode = process.poll()
+    if retcode:
+        raise CalledProcessError(retcode, process.args, output=output)
+    return output
+
+
+class CompletedProcess(object):
+    """A process that has finished running.
+    This is returned by run().
+    Attributes:
+      args: The list or str args passed to run().
+      returncode: The exit code of the process, negative for signals.
+      stdout: The standard output (None if not captured).
+      stderr: The standard error (None if not captured).
+    """
+    def __init__(self, args, returncode, stdout=None, stderr=None):
+        self.args = args
+        self.returncode = returncode
+        self.stdout = stdout
+        self.stderr = stderr
+
+    def __repr__(self):
+        args = ['args={!r}'.format(self.args),
+                'returncode={!r}'.format(self.returncode)]
+        if self.stdout is not None:
+            args.append('stdout={!r}'.format(self.stdout))
+        if self.stderr is not None:
+            args.append('stderr={!r}'.format(self.stderr))
+        return "{}({})".format(type(self).__name__, ', '.join(args))
+
+    def check_returncode(self):
+        """Raise CalledProcessError if the exit code is non-zero."""
+        if self.returncode:
+            raise CalledProcessError(self.returncode, self.args, self.stdout,
+                                     self.stderr)
+
+
+def run(*popenargs, **kwargs):
+    """Run command with arguments and return a CompletedProcess instance.
+    The returned instance will have attributes args, returncode, stdout and
+    stderr. By default, stdout and stderr are not captured, and those attributes
+    will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
+    If check is True and the exit code was non-zero, it raises a
+    CalledProcessError. The CalledProcessError object will have the return code
+    in the returncode attribute, and output & stderr attributes if those streams
+    were captured.
+    If timeout is given, and the process takes too long, a TimeoutExpired
+    exception will be raised.
+    There is an optional argument "input", allowing you to
+    pass a string to the subprocess's stdin.  If you use this argument
+    you may not also use the Popen constructor's "stdin" argument, as
+    it will be used internally.
+    The other arguments are the same as for the Popen constructor.
+    If universal_newlines=True is passed, the "input" argument must be a
+    string and stdout/stderr in the returned object will be strings rather than
+    bytes.
+    """
+    input = kwargs.pop('input', None)
+    timeout = kwargs.pop('timeout', None)
+    check = kwargs.pop('check', False)
+    if input is not None:
+        if 'stdin' in kwargs:
+            raise ValueError('stdin and input arguments may not both be used.')
+        kwargs['stdin'] = PIPE
+
+    process = Popen(*popenargs, **kwargs)
+    try:
+        process.__enter__()  # No-Op really... illustrate "with in 2.4"
+        try:
+            stdout, stderr = process.communicate(input, timeout=timeout)
+        except TimeoutExpired:
+            process.kill()
+            stdout, stderr = process.communicate()
+            raise TimeoutExpired(process.args, timeout, output=stdout,
+                                 stderr=stderr)
+        except:
+            process.kill()
+            process.wait()
+            raise
+        retcode = process.poll()
+        if check and retcode:
+            raise CalledProcessError(retcode, process.args,
+                                     output=stdout, stderr=stderr)
+    finally:
+        # None because our context manager __exit__ does not use them.
+        process.__exit__(None, None, None)
+    return CompletedProcess(process.args, retcode, stdout, stderr)
+
+
+def list2cmdline(seq):
+    """
+    Translate a sequence of arguments into a command line
+    string, using the same rules as the MS C runtime:
+
+    1) Arguments are delimited by white space, which is either a
+       space or a tab.
+
+    2) A string surrounded by double quotation marks is
+       interpreted as a single argument, regardless of white space
+       contained within.  A quoted string can be embedded in an
+       argument.
+
+    3) A double quotation mark preceded by a backslash is
+       interpreted as a literal double quotation mark.
+
+    4) Backslashes are interpreted literally, unless they
+       immediately precede a double quotation mark.
+
+    5) If backslashes immediately precede a double quotation mark,
+       every pair of backslashes is interpreted as a literal
+       backslash.  If the number of backslashes is odd, the last
+       backslash escapes the next double quotation mark as
+       described in rule 3.
+    """
+
+    # See
+    # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
+    # or search http://msdn.microsoft.com for
+    # "Parsing C++ Command-Line Arguments"
+    result = []
+    needquote = False
+    for arg in seq:
+        bs_buf = []
+
+        # Add a space to separate this argument from the others
+        if result:
+            result.append(' ')
+
+        needquote = (" " in arg) or ("\t" in arg) or not arg
+        if needquote:
+            result.append('"')
+
+        for c in arg:
+            if c == '\\':
+                # Don't know if we need to double yet.
+                bs_buf.append(c)
+            elif c == '"':
+                # Double backslashes.
+                result.append('\\' * len(bs_buf)*2)
+                bs_buf = []
+                result.append('\\"')
+            else:
+                # Normal char
+                if bs_buf:
+                    result.extend(bs_buf)
+                    bs_buf = []
+                result.append(c)
+
+        # Add remaining backslashes, if any.
+        if bs_buf:
+            result.extend(bs_buf)
+
+        if needquote:
+            result.extend(bs_buf)
+            result.append('"')
+
+    return ''.join(result)
+
+
+_PLATFORM_DEFAULT_CLOSE_FDS = object()
+
+
+class Popen(object):
+    def __init__(self, args, bufsize=0, executable=None,
+                 stdin=None, stdout=None, stderr=None,
+                 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
+                 shell=False, cwd=None, env=None, universal_newlines=False,
+                 startupinfo=None, creationflags=0,
+                 restore_signals=True, start_new_session=False,
+                 pass_fds=()):
+        """Create new Popen instance."""
+        _cleanup()
+        # Held while anything is calling waitpid before returncode has been
+        # updated to prevent clobbering returncode if wait() or poll() are
+        # called from multiple threads at once.  After acquiring the lock,
+        # code must re-check self.returncode to see if another thread just
+        # finished a waitpid() call.
+        self._waitpid_lock = threading.Lock()
+
+        self._child_created = False
+        self._input = None
+        self._communication_started = False
+        if not isinstance(bufsize, (int, long)):
+            raise TypeError("bufsize must be an integer")
+
+        if mswindows:
+            if preexec_fn is not None:
+                raise ValueError("preexec_fn is not supported on Windows "
+                                 "platforms")
+            any_stdio_set = (stdin is not None or stdout is not None or
+                             stderr is not None)
+            if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
+                if any_stdio_set:
+                    close_fds = False
+                else:
+                    close_fds = True
+            elif close_fds and any_stdio_set:
+                raise ValueError(
+                        "close_fds is not supported on Windows platforms"
+                        " if you redirect stdin/stdout/stderr")
+        else:
+            # POSIX
+            if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
+                close_fds = True
+            if pass_fds and not close_fds:
+                warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
+                close_fds = True
+            if startupinfo is not None:
+                raise ValueError("startupinfo is only supported on Windows "
+                                 "platforms")
+            if creationflags != 0:
+                raise ValueError("creationflags is only supported on Windows "
+                                 "platforms")
+
+        self.args = args
+        self.stdin = None
+        self.stdout = None
+        self.stderr = None
+        self.pid = None
+        self.returncode = None
+        self.universal_newlines = universal_newlines
+
+        # Input and output objects. The general principle is like
+        # this:
+        #
+        # Parent                   Child
+        # ------                   -----
+        # p2cwrite   ---stdin--->  p2cread
+        # c2pread    <--stdout---  c2pwrite
+        # errread    <--stderr---  errwrite
+        #
+        # On POSIX, the child objects are file descriptors.  On
+        # Windows, these are Windows file handles.  The parent objects
+        # are file descriptors on both platforms.  The parent objects
+        # are -1 when not using PIPEs. The child objects are -1
+        # when not redirecting.
+
+        (p2cread, p2cwrite,
+         c2pread, c2pwrite,
+         errread, errwrite) = self._get_handles(stdin, stdout, stderr)
+
+        if mswindows:
+            if p2cwrite != -1:
+                p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
+            if c2pread != -1:
+                c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
+            if errread != -1:
+                errread = msvcrt.open_osfhandle(errread.Detach(), 0)
+
+        if p2cwrite != -1:
+            self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
+        if c2pread != -1:
+            if universal_newlines:
+                self.stdout = os.fdopen(c2pread, 'rU', bufsize)
+            else:
+                self.stdout = os.fdopen(c2pread, 'rb', bufsize)
+        if errread != -1:
+            if universal_newlines:
+                self.stderr = os.fdopen(errread, 'rU', bufsize)
+            else:
+                self.stderr = os.fdopen(errread, 'rb', bufsize)
+
+        self._closed_child_pipe_fds = False
+        exception_cleanup_needed = False
+        try:
+            try:
+                self._execute_child(args, executable, preexec_fn, close_fds,
+                                    pass_fds, cwd, env, universal_newlines,
+                                    startupinfo, creationflags, shell,
+                                    p2cread, p2cwrite,
+                                    c2pread, c2pwrite,
+                                    errread, errwrite,
+                                    restore_signals, start_new_session)
+            except:
+                # The cleanup is performed within the finally block rather
+                # than simply within this except block before the raise so
+                # that any exceptions raised and handled within it do not
+                # clobber the exception context we want to propagate upwards.
+                # This is only necessary in Python 2.
+                exception_cleanup_needed = True
+                raise
+        finally:
+            if exception_cleanup_needed:
+                for f in filter(None, (self.stdin, self.stdout, self.stderr)):
+                    try:
+                        f.close()
+                    except EnvironmentError:
+                        pass  # Ignore EBADF or other errors
+
+                if not self._closed_child_pipe_fds:
+                    to_close = []
+                    if stdin == PIPE:
+                        to_close.append(p2cread)
+                    if stdout == PIPE:
+                        to_close.append(c2pwrite)
+                    if stderr == PIPE:
+                        to_close.append(errwrite)
+                    if hasattr(self, '_devnull'):
+                        to_close.append(self._devnull)
+                    for fd in to_close:
+                        try:
+                            os.close(fd)
+                        except EnvironmentError:
+                            pass
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        if self.stdout:
+            self.stdout.close()
+        if self.stderr:
+            self.stderr.close()
+        if self.stdin:
+            self.stdin.close()
+        # Wait for the process to terminate, to avoid zombies.
+        self.wait()
+
+    def _translate_newlines(self, data):
+        data = data.replace("\r\n", "\n")
+        data = data.replace("\r", "\n")
+        return data
+
+
+    def __del__(self, _maxint=sys.maxint, _active=_active):
+        # If __init__ hasn't had a chance to execute (e.g. if it
+        # was passed an undeclared keyword argument), we don't
+        # have a _child_created attribute at all.
+        if not getattr(self, '_child_created', False):
+            # We didn't get to successfully create a child process.
+            return
+        # In case the child hasn't been waited on, check if it's done.
+        self._internal_poll(_deadstate=_maxint)
+        if self.returncode is None and _active is not None:
+            # Child is still running, keep us alive until we can wait on it.
+            _active.append(self)
+
+
+    def _get_devnull(self):
+        if not hasattr(self, '_devnull'):
+            self._devnull = os.open(os.devnull, os.O_RDWR)
+        return self._devnull
+
+
+    def communicate(self, input=None, timeout=None):
+        """Interact with process: Send data to stdin.  Read data from
+        stdout and stderr, until end-of-file is reached.  Wait for
+        process to terminate.  The optional input argument should be a
+        string to be sent to the child process, or None, if no data
+        should be sent to the child.
+
+        communicate() returns a tuple (stdout, stderr)."""
+
+        if self._communication_started and input:
+            raise ValueError("Cannot send input after starting communication")
+
+        if timeout is not None:
+            endtime = time.time() + timeout
+        else:
+            endtime = None
+
+        # Optimization: If we are not worried about timeouts, we haven't
+        # started communicating, and we have one or zero pipes, using select()
+        # or threads is unnecessary.
+        if (endtime is None and not self._communication_started and
+            [self.stdin, self.stdout, self.stderr].count(None) >= 2):
+            stdout = None
+            stderr = None
+            if self.stdin:
+                if input:
+                    self.stdin.write(input)
+                self.stdin.close()
+            elif self.stdout:
+                stdout = _eintr_retry_call(self.stdout.read)
+                self.stdout.close()
+            elif self.stderr:
+                stderr = _eintr_retry_call(self.stderr.read)
+                self.stderr.close()
+            self.wait()
+            return (stdout, stderr)
+
+        try:
+            stdout, stderr = self._communicate(input, endtime, timeout)
+        finally:
+            self._communication_started = True
+
+        sts = self.wait(timeout=self._remaining_time(endtime))
+
+        return (stdout, stderr)
+
+
+    def poll(self):
+        return self._internal_poll()
+
+
+    def _remaining_time(self, endtime):
+        """Convenience for _communicate when computing timeouts."""
+        if endtime is None:
+            return None
+        else:
+            return endtime - time.time()
+
+
+    def _check_timeout(self, endtime, orig_timeout):
+        """Convenience for checking if a timeout has expired."""
+        if endtime is None:
+            return
+        if time.time() > endtime:
+            raise TimeoutExpired(self.args, orig_timeout)
+
+
+    if mswindows:
+        #
+        # Windows methods
+        #
+        def _get_handles(self, stdin, stdout, stderr):
+            """Construct and return tuple with IO objects:
+            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
+            """
+            if stdin is None and stdout is None and stderr is None:
+                return (-1, -1, -1, -1, -1, -1)
+
+            p2cread, p2cwrite = -1, -1
+            c2pread, c2pwrite = -1, -1
+            errread, errwrite = -1, -1
+
+            if stdin is None:
+                p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
+                if p2cread is None:
+                    p2cread, _ = _subprocess.CreatePipe(None, 0)
+            elif stdin == PIPE:
+                p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
+            elif stdin == DEVNULL:
+                p2cread = msvcrt.get_osfhandle(self._get_devnull())
+            elif isinstance(stdin, int):
+                p2cread = msvcrt.get_osfhandle(stdin)
+            else:
+                # Assuming file-like object
+                p2cread = msvcrt.get_osfhandle(stdin.fileno())
+            p2cread = self._make_inheritable(p2cread)
+
+            if stdout is None:
+                c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
+                if c2pwrite is None:
+                    _, c2pwrite = _subprocess.CreatePipe(None, 0)
+            elif stdout == PIPE:
+                c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
+            elif stdout == DEVNULL:
+                c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
+            elif isinstance(stdout, int):
+                c2pwrite = msvcrt.get_osfhandle(stdout)
+            else:
+                # Assuming file-like object
+                c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
+            c2pwrite = self._make_inheritable(c2pwrite)
+
+            if stderr is None:
+                errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
+                if errwrite is None:
+                    _, errwrite = _subprocess.CreatePipe(None, 0)
+            elif stderr == PIPE:
+                errread, errwrite = _subprocess.CreatePipe(None, 0)
+            elif stderr == STDOUT:
+                errwrite = c2pwrite
+            elif stderr == DEVNULL:
+                errwrite = msvcrt.get_osfhandle(self._get_devnull())
+            elif isinstance(stderr, int):
+                errwrite = msvcrt.get_osfhandle(stderr)
+            else:
+                # Assuming file-like object
+                errwrite = msvcrt.get_osfhandle(stderr.fileno())
+            errwrite = self._make_inheritable(errwrite)
+
+            return (p2cread, p2cwrite,
+                    c2pread, c2pwrite,
+                    errread, errwrite)
+
+
+        def _make_inheritable(self, handle):
+            """Return a duplicate of handle, which is inheritable"""
+            return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
+                                handle, _subprocess.GetCurrentProcess(), 0, 1,
+                                _subprocess.DUPLICATE_SAME_ACCESS)
+
+
+        def _find_w9xpopen(self):
+            """Find and return absolut path to w9xpopen.exe"""
+            w9xpopen = os.path.join(
+                            os.path.dirname(_subprocess.GetModuleFileName(0)),
+                                    "w9xpopen.exe")
+            if not os.path.exists(w9xpopen):
+                # Eeek - file-not-found - possibly an embedding
+                # situation - see if we can locate it in sys.exec_prefix
+                w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
+                                        "w9xpopen.exe")
+                if not os.path.exists(w9xpopen):
+                    raise RuntimeError("Cannot locate w9xpopen.exe, which is "
+                                       "needed for Popen to work with your "
+                                       "shell or platform.")
+            return w9xpopen
+
+
+        def _execute_child(self, args, executable, preexec_fn, close_fds,
+                           pass_fds, cwd, env, universal_newlines,
+                           startupinfo, creationflags, shell,
+                           p2cread, p2cwrite,
+                           c2pread, c2pwrite,
+                           errread, errwrite,
+                           unused_restore_signals, unused_start_new_session):
+            """Execute program (MS Windows version)"""
+
+            assert not pass_fds, "pass_fds not supported on Windows."
+
+            if not isinstance(args, types.StringTypes):
+                args = list2cmdline(args)
+
+            # Process startup details
+            if startupinfo is None:
+                startupinfo = STARTUPINFO()
+            if -1 not in (p2cread, c2pwrite, errwrite):
+                startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
+                startupinfo.hStdInput = p2cread
+                startupinfo.hStdOutput = c2pwrite
+                startupinfo.hStdError = errwrite
+
+            if shell:
+                startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
+                startupinfo.wShowWindow = _subprocess.SW_HIDE
+                comspec = os.environ.get("COMSPEC", "cmd.exe")
+                args = comspec + " /c " + '"%s"' % args
+                if (_subprocess.GetVersion() >= 0x80000000L or
+                        os.path.basename(comspec).lower() == "command.com"):
+                    # Win9x, or using command.com on NT. We need to
+                    # use the w9xpopen intermediate program. For more
+                    # information, see KB Q150956
+                    # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
+                    w9xpopen = self._find_w9xpopen()
+                    args = '"%s" %s' % (w9xpopen, args)
+                    # Not passing CREATE_NEW_CONSOLE has been known to
+                    # cause random failures on win9x.  Specifically a
+                    # dialog: "Your program accessed mem currently in
+                    # use at xxx" and a hopeful warning about the
+                    # stability of your system.  Cost is Ctrl+C wont
+                    # kill children.
+                    creationflags |= _subprocess.CREATE_NEW_CONSOLE
+
+            # Start the process
+            try:
+                try:
+                    hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
+                                             # no special security
+                                             None, None,
+                                             int(not close_fds),
+                                             creationflags,
+                                             env,
+                                             cwd,
+                                             startupinfo)
+                except pywintypes.error, e:
+                    # Translate pywintypes.error to WindowsError, which is
+                    # a subclass of OSError.  FIXME: We should really
+                    # translate errno using _sys_errlist (or similar), but
+                    # how can this be done from Python?
+                    raise WindowsError(*e.args)
+            finally:
+                # Child is launched. Close the parent's copy of those pipe
+                # handles that only the child should have open.  You need
+                # to make sure that no handles to the write end of the
+                # output pipe are maintained in this process or else the
+                # pipe will not close when the child process exits and the
+                # ReadFile will hang.
+                if p2cread != -1:
+                    p2cread.Close()
+                if c2pwrite != -1:
+                    c2pwrite.Close()
+                if errwrite != -1:
+                    errwrite.Close()
+                if hasattr(self, '_devnull'):
+                    os.close(self._devnull)
+
+            # Retain the process handle, but close the thread handle
+            self._child_created = True
+            self._handle = hp
+            self.pid = pid
+            ht.Close()
+
+        def _internal_poll(self, _deadstate=None,
+                _WaitForSingleObject=_subprocess.WaitForSingleObject,
+                _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
+                _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
+            """Check if child process has terminated.  Returns returncode
+            attribute.
+
+            This method is called by __del__, so it can only refer to objects
+            in its local scope.
+
+            """
+            if self.returncode is None:
+                if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
+                    self.returncode = _GetExitCodeProcess(self._handle)
+            return self.returncode
+
+
+        def wait(self, timeout=None, endtime=None):
+            """Wait for child process to terminate.  Returns returncode
+            attribute."""
+            if endtime is not None:
+                timeout = self._remaining_time(endtime)
+            if timeout is None:
+                timeout = _subprocess.INFINITE
+            else:
+                timeout = int(timeout * 1000)
+            if self.returncode is None:
+                result = _subprocess.WaitForSingleObject(self._handle, timeout)
+                if result == _WAIT_TIMEOUT:
+                    raise TimeoutExpired(self.args, timeout)
+                self.returncode = _subprocess.GetExitCodeProcess(self._handle)
+            return self.returncode
+
+
+        def _readerthread(self, fh, buffer):
+            buffer.append(fh.read())
+            fh.close()
+
+
+        def _communicate(self, input, endtime, orig_timeout):
+            # Start reader threads feeding into a list hanging off of this
+            # object, unless they've already been started.
+            if self.stdout and not hasattr(self, "_stdout_buff"):
+                self._stdout_buff = []
+                self.stdout_thread = \
+                        threading.Thread(target=self._readerthread,
+                                         args=(self.stdout, self._stdout_buff))
+                self.stdout_thread.daemon = True
+                self.stdout_thread.start()
+            if self.stderr and not hasattr(self, "_stderr_buff"):
+                self._stderr_buff = []
+                self.stderr_thread = \
+                        threading.Thread(target=self._readerthread,
+                                         args=(self.stderr, self._stderr_buff))
+                self.stderr_thread.daemon = True
+                self.stderr_thread.start()
+
+            if self.stdin:
+                if input is not None:
+                    self.stdin.write(input)
+                self.stdin.close()
+
+            # Wait for the reader threads, or time out.  If we time out, the
+            # threads remain reading and the fds left open in case the user
+            # calls communicate again.
+            if self.stdout is not None:
+                self.stdout_thread.join(self._remaining_time(endtime))
+                if self.stdout_thread.isAlive():
+                    raise TimeoutExpired(self.args, orig_timeout)
+            if self.stderr is not None:
+                self.stderr_thread.join(self._remaining_time(endtime))
+                if self.stderr_thread.isAlive():
+                    raise TimeoutExpired(self.args, orig_timeout)
+
+            # Collect the output from and close both pipes, now that we know
+            # both have been read successfully.
+            stdout = None
+            stderr = None
+            if self.stdout:
+                stdout = self._stdout_buff
+                self.stdout.close()
+            if self.stderr:
+                stderr = self._stderr_buff
+                self.stderr.close()
+
+            # All data exchanged.  Translate lists into strings.
+            if stdout is not None:
+                stdout = stdout[0]
+            if stderr is not None:
+                stderr = stderr[0]
+
+            # Translate newlines, if requested.  We cannot let the file
+            # object do the translation: It is based on stdio, which is
+            # impossible to combine with select (unless forcing no
+            # buffering).
+            if self.universal_newlines and hasattr(file, 'newlines'):
+                if stdout:
+                    stdout = self._translate_newlines(stdout)
+                if stderr:
+                    stderr = self._translate_newlines(stderr)
+
+            return (stdout, stderr)
+
+        def send_signal(self, sig):
+            """Send a signal to the process."""
+            # Don't signal a process that we know has already died.
+            if self.returncode is not None:
+                return
+            if sig == signal.SIGTERM:
+                self.terminate()
+            elif sig == signal.CTRL_C_EVENT:
+                os.kill(self.pid, signal.CTRL_C_EVENT)
+            elif sig == signal.CTRL_BREAK_EVENT:
+                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
+            else:
+                raise ValueError("Unsupported signal: %s" % sig)
+
+        def terminate(self):
+            """Terminates the process."""
+            # Don't terminate a process that we know has already died.
+            if self.returncode is not None:
+                return
+            _subprocess.TerminateProcess(self._handle, 1)
+
+        kill = terminate
+
+    else:
+        #
+        # POSIX methods
+        #
+        def _get_handles(self, stdin, stdout, stderr):
+            """Construct and return tuple with IO objects:
+            p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
+            """
+            p2cread, p2cwrite = -1, -1
+            c2pread, c2pwrite = -1, -1
+            errread, errwrite = -1, -1
+
+            if stdin is None:
+                pass
+            elif stdin == PIPE:
+                p2cread, p2cwrite = _create_pipe()
+            elif stdin == DEVNULL:
+                p2cread = self._get_devnull()
+            elif isinstance(stdin, int):
+                p2cread = stdin
+            else:
+                # Assuming file-like object
+                p2cread = stdin.fileno()
+
+            if stdout is None:
+                pass
+            elif stdout == PIPE:
+                c2pread, c2pwrite = _create_pipe()
+            elif stdout == DEVNULL:
+                c2pwrite = self._get_devnull()
+            elif isinstance(stdout, int):
+                c2pwrite = stdout
+            else:
+                # Assuming file-like object
+                c2pwrite = stdout.fileno()
+
+            if stderr is None:
+                pass
+            elif stderr == PIPE:
+                errread, errwrite = _create_pipe()
+            elif stderr == STDOUT:
+                if c2pwrite != -1:
+                    errwrite = c2pwrite
+                else: # child's stdout is not set, use parent's stdout
+                    errwrite = sys.__stdout__.fileno()
+            elif stderr == DEVNULL:
+                errwrite = self._get_devnull()
+            elif isinstance(stderr, int):
+                errwrite = stderr
+            else:
+                # Assuming file-like object
+                errwrite = stderr.fileno()
+
+            return (p2cread, p2cwrite,
+                    c2pread, c2pwrite,
+                    errread, errwrite)
+
+
+        if hasattr(os, 'closerange'):  # Introduced in 2.6
+            @staticmethod
+            def _closerange(fd_low, fd_high):
+                os.closerange(fd_low, fd_high)
+        else:
+            @staticmethod
+            def _closerange(fd_low, fd_high):
+                for fd in xrange(fd_low, fd_high):
+                    while True:
+                        try:
+                            os.close(fd)
+                        except (OSError, IOError), e:
+                            if e.errno == errno.EINTR:
+                                continue
+                            break
+
+
+        def _close_fds(self, but):
+            self._closerange(3, but)
+            self._closerange(but + 1, MAXFD)
+
+
+        def _close_all_but_a_sorted_few_fds(self, fds_to_keep):
+            # precondition: fds_to_keep must be sorted and unique
+            start_fd = 3
+            for fd in fds_to_keep:
+                if fd >= start_fd:
+                    self._closerange(start_fd, fd)
+                    start_fd = fd + 1
+            if start_fd <= MAXFD:
+                self._closerange(start_fd, MAXFD)
+
+
+        def _execute_child(self, args, executable, preexec_fn, close_fds,
+                           pass_fds, cwd, env, universal_newlines,
+                           startupinfo, creationflags, shell,
+                           p2cread, p2cwrite,
+                           c2pread, c2pwrite,
+                           errread, errwrite,
+                           restore_signals, start_new_session):
+            """Execute program (POSIX version)"""
+
+            if isinstance(args, types.StringTypes):
+                args = [args]
+            else:
+                args = list(args)
+
+            if shell:
+                args = ["/bin/sh", "-c"] + args
+                if executable:
+                    args[0] = executable
+
+            if executable is None:
+                executable = args[0]
+            orig_executable = executable
+
+            # For transferring possible exec failure from child to parent.
+            # Data format: "exception name:hex errno:description"
+            # Pickle is not used; it is complex and involves memory allocation.
+            errpipe_read, errpipe_write = _create_pipe()
+            try:
+                try:
+
+                    if _posixsubprocess:
+                        fs_encoding = sys.getfilesystemencoding()
+                        def fs_encode(s):
+                            """Encode s for use in the env, fs or cmdline."""
+                            if isinstance(s, str):
+                                return s
+                            else:
+                                return s.encode(fs_encoding, 'strict')
+
+                        # We must avoid complex work that could involve
+                        # malloc or free in the child process to avoid
+                        # potential deadlocks, thus we do all this here.
+                        # and pass it to fork_exec()
+
+                        if env is not None:
+                            env_list = [fs_encode(k) + '=' + fs_encode(v)
+                                        for k, v in env.items()]
+                        else:
+                            env_list = None  # Use execv instead of execve.
+                        if os.path.dirname(executable):
+                            executable_list = (fs_encode(executable),)
+                        else:
+                            # This matches the behavior of os._execvpe().
+                            path_list = _get_exec_path(env)
+                            executable_list = (os.path.join(dir, executable)
+                                               for dir in path_list)
+                            executable_list = tuple(fs_encode(exe)
+                                                    for exe in executable_list)
+                        fds_to_keep = set(pass_fds)
+                        fds_to_keep.add(errpipe_write)
+                        self.pid = _posixsubprocess.fork_exec(
+                                args, executable_list,
+                                close_fds, sorted(fds_to_keep), cwd, env_list,
+                                p2cread, p2cwrite, c2pread, c2pwrite,
+                                errread, errwrite,
+                                errpipe_read, errpipe_write,
+                                restore_signals, start_new_session, preexec_fn)
+                        self._child_created = True
+                    else:
+                        # Pure Python implementation: It is not thread safe.
+                        # This implementation may deadlock in the child if your
+                        # parent process has any other threads running.
+
+                        gc_was_enabled = gc.isenabled()
+                        # Disable gc to avoid bug where gc -> file_dealloc ->
+                        # write to stderr -> hang.  See issue1336
+                        gc.disable()
+                        try:
+                            self.pid = os.fork()
+                        except:
+                            if gc_was_enabled:
+                                gc.enable()
+                            raise
+                        self._child_created = True
+                        if self.pid == 0:
+                            # Child
+                            reached_preexec = False
+                            try:
+                                # Close parent's pipe ends
+                                if p2cwrite != -1:
+                                    os.close(p2cwrite)
+                                if c2pread != -1:
+                                    os.close(c2pread)
+                                if errread != -1:
+                                    os.close(errread)
+                                os.close(errpipe_read)
+
+                                # When duping fds, if there arises a situation
+                                # where one of the fds is either 0, 1 or 2, it
+                                # is possible that it is overwritten (#12607).
+                                if c2pwrite == 0:
+                                    c2pwrite = os.dup(c2pwrite)
+                                if errwrite == 0 or errwrite == 1:
+                                    errwrite = os.dup(errwrite)
+
+                                # Dup fds for child
+                                def _dup2(a, b):
+                                    # dup2() removes the CLOEXEC flag but
+                                    # we must do it ourselves if dup2()
+                                    # would be a no-op (issue #10806).
+                                    if a == b:
+                                        _set_cloexec(a, False)
+                                    elif a != -1:
+                                        os.dup2(a, b)
+                                _dup2(p2cread, 0)
+                                _dup2(c2pwrite, 1)
+                                _dup2(errwrite, 2)
+
+                                # Close pipe fds.  Make sure we don't close the
+                                # same fd more than once, or standard fds.
+                                closed = set()
+                                for fd in [p2cread, c2pwrite, errwrite]:
+                                    if fd > 2 and fd not in closed:
+                                        os.close(fd)
+                                        closed.add(fd)
+
+                                if cwd is not None:
+                                    os.chdir(cwd)
+
+                                # This is a copy of Python/pythonrun.c
+                                # _Py_RestoreSignals().  If that were exposed
+                                # as a sys._py_restoresignals func it would be
+                                # better.. but this pure python implementation
+                                # isn't likely to be used much anymore.
+                                if restore_signals:
+                                    signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
+                                    for sig in signals:
+                                        if hasattr(signal, sig):
+                                            signal.signal(getattr(signal, sig),
+                                                          signal.SIG_DFL)
+
+                                if start_new_session and hasattr(os, 'setsid'):
+                                    os.setsid()
+
+                                reached_preexec = True
+                                if preexec_fn:
+                                    preexec_fn()
+
+                                # Close all other fds, if asked for - after
+                                # preexec_fn(), which may open FDs.
+                                if close_fds:
+                                    if pass_fds:
+                                        fds_to_keep = set(pass_fds)
+                                        fds_to_keep.add(errpipe_write)
+                                        self._close_all_but_a_sorted_few_fds(
+                                                sorted(fds_to_keep))
+                                    else:
+                                        self._close_fds(but=errpipe_write)
+
+                                if env is None:
+                                    os.execvp(executable, args)
+                                else:
+                                    os.execvpe(executable, args, env)
+
+                            except:
+                                try:
+                                    exc_type, exc_value = sys.exc_info()[:2]
+                                    if isinstance(exc_value, OSError):
+                                        errno_num = exc_value.errno
+                                    else:
+                                        errno_num = 0
+                                    if not reached_preexec:
+                                        exc_value = "noexec"
+                                    message = '%s:%x:%s' % (exc_type.__name__,
+                                                            errno_num, exc_value)
+                                    os.write(errpipe_write, message)
+                                except Exception:
+                                    # We MUST not allow anything odd happening
+                                    # above to prevent us from exiting below.
+                                    pass
+
+                            # This exitcode won't be reported to applications
+                            # so it really doesn't matter what we return.
+                            os._exit(255)
+
+                        # Parent
+                        if gc_was_enabled:
+                            gc.enable()
+                finally:
+                    # be sure the FD is closed no matter what
+                    os.close(errpipe_write)
+
+                # A pair of non -1s means we created both fds and are
+                # responsible for closing them.
+                # self._devnull is not always defined.
+                devnull_fd = getattr(self, '_devnull', None)
+                if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
+                    os.close(p2cread)
+                if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
+                    os.close(c2pwrite)
+                if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
+                    os.close(errwrite)
+                if devnull_fd is not None:
+                    os.close(devnull_fd)
+                # Prevent a double close of these fds from __init__ on error.
+                self._closed_child_pipe_fds = True
+
+                # Wait for exec to fail or succeed; possibly raising exception
+                # exception (limited in size)
+                errpipe_data = ''
+                while True:
+                    part = _eintr_retry_call(os.read, errpipe_read, 50000)
+                    errpipe_data += part
+                    if not part or len(errpipe_data) > 50000:
+                        break
+            finally:
+                # be sure the FD is closed no matter what
+                os.close(errpipe_read)
+
+            if errpipe_data != "":
+                try:
+                    _eintr_retry_call(os.waitpid, self.pid, 0)
+                except OSError, e:
+                    if e.errno != errno.ECHILD:
+                        raise
+                try:
+                    exception_name, hex_errno, err_msg = (
+                            errpipe_data.split(':', 2))
+                except ValueError:
+                    exception_name = 'RuntimeError'
+                    hex_errno = '0'
+                    err_msg = ('Bad exception data from child: ' +
+                               repr(errpipe_data))
+                child_exception_type = getattr(
+                        exceptions, exception_name, RuntimeError)
+                if issubclass(child_exception_type, OSError) and hex_errno:
+                    errno_num = int(hex_errno, 16)
+                    child_exec_never_called = (err_msg == "noexec")
+                    if child_exec_never_called:
+                        err_msg = ""
+                    if errno_num != 0:
+                        err_msg = os.strerror(errno_num)
+                        if errno_num == errno.ENOENT:
+                            if child_exec_never_called:
+                                # The error must be from chdir(cwd).
+                                err_msg += ': ' + repr(cwd)
+                            else:
+                                err_msg += ': ' + repr(orig_executable)
+                    raise child_exception_type(errno_num, err_msg)
+                try:
+                    exception = child_exception_type(err_msg)
+                except Exception:
+                    exception = RuntimeError(
+                            'Could not re-raise %r exception from the'
+                            ' child with error message %r' %
+                            (child_exception_type, err_msg))
+                raise exception
+
+
+        def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
+                _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
+                _WEXITSTATUS=os.WEXITSTATUS, _WIFSTOPPED=os.WIFSTOPPED,
+                _WSTOPSIG=os.WSTOPSIG):
+            """All callers to this function MUST hold self._waitpid_lock."""
+            # This method is called (indirectly) by __del__, so it cannot
+            # refer to anything outside of its local scope."""
+            if _WIFSIGNALED(sts):
+                self.returncode = -_WTERMSIG(sts)
+            elif _WIFEXITED(sts):
+                self.returncode = _WEXITSTATUS(sts)
+            elif _WIFSTOPPED(sts):
+                self.returncode = -_WSTOPSIG(sts)
+            else:
+                # Should never happen
+                raise RuntimeError("Unknown child exit status!")
+
+
+        def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
+                _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
+            """Check if child process has terminated.  Returns returncode
+            attribute.
+
+            This method is called by __del__, so it cannot reference anything
+            outside of the local scope (nor can any methods it calls).
+
+            """
+            if self.returncode is None:
+                if not self._waitpid_lock.acquire(False):
+                    # Something else is busy calling waitpid.  Don't allow two
+                    # at once.  We know nothing yet.
+                    return None
+                try:
+                    try:
+                        if self.returncode is not None:
+                            return self.returncode  # Another thread waited.
+                        pid, sts = _waitpid(self.pid, _WNOHANG)
+                        if pid == self.pid:
+                            self._handle_exitstatus(sts)
+                    except _os_error, e:
+                        if _deadstate is not None:
+                            self.returncode = _deadstate
+                        elif e.errno == _ECHILD:
+                            # This happens if SIGCLD is set to be ignored or
+                            # waiting for child processes has otherwise been
+                            # disabled for our process.  This child is dead, we
+                            # can't get the status.
+                            # http://bugs.python.org/issue15756
+                            self.returncode = 0
+                finally:
+                    self._waitpid_lock.release()
+            return self.returncode
+
+
+        def _try_wait(self, wait_flags):
+            """All callers to this function MUST hold self._waitpid_lock."""
+            try:
+                (pid, sts) = _eintr_retry_call(os.waitpid, self.pid, wait_flags)
+            except OSError, e:
+                if e.errno != errno.ECHILD:
+                    raise
+                # This happens if SIGCLD is set to be ignored or waiting
+                # for child processes has otherwise been disabled for our
+                # process.  This child is dead, we can't get the status.
+                pid = self.pid
+                sts = 0
+            return (pid, sts)
+
+
+        def wait(self, timeout=None, endtime=None):
+            """Wait for child process to terminate.  Returns returncode
+            attribute."""
+            if self.returncode is not None:
+                return self.returncode
+
+            # endtime is preferred to timeout.  timeout is only used for
+            # printing.
+            if endtime is not None or timeout is not None:
+                if endtime is None:
+                    endtime = time.time() + timeout
+                elif timeout is None:
+                    timeout = self._remaining_time(endtime)
+
+            if endtime is not None:
+                # Enter a busy loop if we have a timeout.  This busy loop was
+                # cribbed from Lib/threading.py in Thread.wait() at r71065.
+                delay = 0.0005 # 500 us -> initial delay of 1 ms
+                while True:
+                    if self._waitpid_lock.acquire(False):
+                        try:
+                            if self.returncode is not None:
+                                break  # Another thread waited.
+                            (pid, sts) = self._try_wait(os.WNOHANG)
+                            assert pid == self.pid or pid == 0
+                            if pid == self.pid:
+                                self._handle_exitstatus(sts)
+                                break
+                        finally:
+                            self._waitpid_lock.release()
+                    remaining = self._remaining_time(endtime)
+                    if remaining <= 0:
+                        raise TimeoutExpired(self.args, timeout)
+                    delay = min(delay * 2, remaining, .05)
+                    time.sleep(delay)
+            else:
+                while self.returncode is None:
+                    self._waitpid_lock.acquire()
+                    try:
+                        if self.returncode is not None:
+                            break  # Another thread waited.
+                        (pid, sts) = self._try_wait(0)
+                        # Check the pid and loop as waitpid has been known to
+                        # return 0 even without WNOHANG in odd situations.
+                        # http://bugs.python.org/issue14396.
+                        if pid == self.pid:
+                            self._handle_exitstatus(sts)
+                    finally:
+                        self._waitpid_lock.release()
+            return self.returncode
+
+
+        def _communicate(self, input, endtime, orig_timeout):
+            if self.stdin and not self._communication_started:
+                # Flush stdio buffer.  This might block, if the user has
+                # been writing to .stdin in an uncontrolled fashion.
+                self.stdin.flush()
+                if not input:
+                    self.stdin.close()
+
+            if _has_poll:
+                stdout, stderr = self._communicate_with_poll(input, endtime,
+                                                             orig_timeout)
+            else:
+                stdout, stderr = self._communicate_with_select(input, endtime,
+                                                               orig_timeout)
+
+            self.wait(timeout=self._remaining_time(endtime))
+
+            # All data exchanged.  Translate lists into strings.
+            if stdout is not None:
+                stdout = ''.join(stdout)
+            if stderr is not None:
+                stderr = ''.join(stderr)
+
+            # Translate newlines, if requested.  We cannot let the file
+            # object do the translation: It is based on stdio, which is
+            # impossible to combine with select (unless forcing no
+            # buffering).
+            if self.universal_newlines and hasattr(file, 'newlines'):
+                if stdout:
+                    stdout = self._translate_newlines(stdout)
+                if stderr:
+                    stderr = self._translate_newlines(stderr)
+
+            return (stdout, stderr)
+
+
+        def _communicate_with_poll(self, input, endtime, orig_timeout):
+            stdout = None # Return
+            stderr = None # Return
+
+            if not self._communication_started:
+                self._fd2file = {}
+
+            poller = select.poll()
+            def register_and_append(file_obj, eventmask):
+                poller.register(file_obj.fileno(), eventmask)
+                self._fd2file[file_obj.fileno()] = file_obj
+
+            def close_unregister_and_remove(fd):
+                poller.unregister(fd)
+                self._fd2file[fd].close()
+                self._fd2file.pop(fd)
+
+            if self.stdin and input:
+                register_and_append(self.stdin, select.POLLOUT)
+
+            # Only create this mapping if we haven't already.
+            if not self._communication_started:
+                self._fd2output = {}
+                if self.stdout:
+                    self._fd2output[self.stdout.fileno()] = []
+                if self.stderr:
+                    self._fd2output[self.stderr.fileno()] = []
+
+            select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
+            if self.stdout:
+                register_and_append(self.stdout, select_POLLIN_POLLPRI)
+                stdout = self._fd2output[self.stdout.fileno()]
+            if self.stderr:
+                register_and_append(self.stderr, select_POLLIN_POLLPRI)
+                stderr = self._fd2output[self.stderr.fileno()]
+
+            # Save the input here so that if we time out while communicating,
+            # we can continue sending input if we retry.
+            if self.stdin and self._input is None:
+                self._input_offset = 0
+                self._input = input
+                if self.universal_newlines and isinstance(self._input, unicode):
+                    self._input = self._input.encode(
+                            self.stdin.encoding or sys.getdefaultencoding())
+
+            while self._fd2file:
+                try:
+                    ready = poller.poll(self._remaining_time(endtime))
+                except select.error, e:
+                    if e.args[0] == errno.EINTR:
+                        continue
+                    raise
+                self._check_timeout(endtime, orig_timeout)
+
+                for fd, mode in ready:
+                    if mode & select.POLLOUT:
+                        chunk = self._input[self._input_offset :
+                                            self._input_offset + _PIPE_BUF]
+                        self._input_offset += os.write(fd, chunk)
+                        if self._input_offset >= len(self._input):
+                            close_unregister_and_remove(fd)
+                    elif mode & select_POLLIN_POLLPRI:
+                        data = os.read(fd, 4096)
+                        if not data:
+                            close_unregister_and_remove(fd)
+                        self._fd2output[fd].append(data)
+                    else:
+                        # Ignore hang up or errors.
+                        close_unregister_and_remove(fd)
+
+            return (stdout, stderr)
+
+
+        def _communicate_with_select(self, input, endtime, orig_timeout):
+            if not self._communication_started:
+                self._read_set = []
+                self._write_set = []
+                if self.stdin and input:
+                    self._write_set.append(self.stdin)
+                if self.stdout:
+                    self._read_set.append(self.stdout)
+                if self.stderr:
+                    self._read_set.append(self.stderr)
+
+            if self.stdin and self._input is None:
+                self._input_offset = 0
+                self._input = input
+                if self.universal_newlines and isinstance(self._input, unicode):
+                    self._input = self._input.encode(
+                            self.stdin.encoding or sys.getdefaultencoding())
+
+            stdout = None # Return
+            stderr = None # Return
+
+            if self.stdout:
+                if not self._communication_started:
+                    self._stdout_buff = []
+                stdout = self._stdout_buff
+            if self.stderr:
+                if not self._communication_started:
+                    self._stderr_buff = []
+                stderr = self._stderr_buff
+
+            while self._read_set or self._write_set:
+                try:
+                    (rlist, wlist, xlist) = \
+                        select.select(self._read_set, self._write_set, [],
+                                      self._remaining_time(endtime))
+                except select.error, e:
+                    if e.args[0] == errno.EINTR:
+                        continue
+                    raise
+
+                # According to the docs, returning three empty lists indicates
+                # that the timeout expired.
+                if not (rlist or wlist or xlist):
+                    raise TimeoutExpired(self.args, orig_timeout)
+                # We also check what time it is ourselves for good measure.
+                self._check_timeout(endtime, orig_timeout)
+
+                if self.stdin in wlist:
+                    chunk = self._input[self._input_offset :
+                                        self._input_offset + _PIPE_BUF]
+                    bytes_written = os.write(self.stdin.fileno(), chunk)
+                    self._input_offset += bytes_written
+                    if self._input_offset >= len(self._input):
+                        self.stdin.close()
+                        self._write_set.remove(self.stdin)
+
+                if self.stdout in rlist:
+                    data = os.read(self.stdout.fileno(), 1024)
+                    if data == "":
+                        self.stdout.close()
+                        self._read_set.remove(self.stdout)
+                    stdout.append(data)
+
+                if self.stderr in rlist:
+                    data = os.read(self.stderr.fileno(), 1024)
+                    if data == "":
+                        self.stderr.close()
+                        self._read_set.remove(self.stderr)
+                    stderr.append(data)
+
+            return (stdout, stderr)
+
+
+        def send_signal(self, sig):
+            """Send a signal to the process
+            """
+            # Skip signalling a process that we know has already died.
+            if self.returncode is None:
+                os.kill(self.pid, sig)
+
+        def terminate(self):
+            """Terminate the process with SIGTERM
+            """
+            self.send_signal(signal.SIGTERM)
+
+        def kill(self):
+            """Kill the process with SIGKILL
+            """
+            self.send_signal(signal.SIGKILL)
diff --git a/ambari-common/src/main/python/resource_management/core/providers/mount.py b/ambari-common/src/main/python/resource_management/core/providers/mount.py
index 08a0e76..1b33587 100644
--- a/ambari-common/src/main/python/resource_management/core/providers/mount.py
+++ b/ambari-common/src/main/python/resource_management/core/providers/mount.py
@@ -24,7 +24,7 @@ from __future__ import with_statement
 
 import os
 import re
-from subprocess import Popen, PIPE, STDOUT
+from ambari_commons.subprocess32 import Popen, PIPE, STDOUT
 
 from resource_management.core.base import Fail
 from resource_management.core.providers import Provider
diff --git a/ambari-common/src/main/python/resource_management/core/providers/windows/system.py b/ambari-common/src/main/python/resource_management/core/providers/windows/system.py
index 70cf9bf..b8caa80 100644
--- a/ambari-common/src/main/python/resource_management/core/providers/windows/system.py
+++ b/ambari-common/src/main/python/resource_management/core/providers/windows/system.py
@@ -26,7 +26,7 @@ from resource_management.core.base import Fail
 from resource_management.core import ExecuteTimeoutException
 import time
 import os
-import subprocess
+from ambari_commons import subprocess32
 import shutil
 from resource_management.libraries.script import Script
 import win32con
@@ -210,7 +210,7 @@ def _call_command(command, logoutput=False, cwd=None, env=None, wait_for_finish=
     cur_token = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY)
     current_env = CreateEnvironmentBlock(cur_token, False)
     current_env = _merge_env(current_env, env)
-    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+    proc = subprocess32.Popen(command, stdout=subprocess32.PIPE, stderr=subprocess32.STDOUT,
                             cwd=cwd, env=current_env, shell=False)
     out, err = proc.communicate()
     code = proc.returncode
diff --git a/ambari-common/src/main/python/resource_management/core/resources/jcepolicyinfo.py b/ambari-common/src/main/python/resource_management/core/resources/jcepolicyinfo.py
index c269f59..8694e56 100644
--- a/ambari-common/src/main/python/resource_management/core/resources/jcepolicyinfo.py
+++ b/ambari-common/src/main/python/resource_management/core/resources/jcepolicyinfo.py
@@ -22,7 +22,7 @@ Ambari Agent
 
 from resource_management.core.logger import Logger
 from resource_management.core import shell
-import subprocess
+from ambari_commons import subprocess32
 
 class JcePolicyInfo:
   def __init__(self, java_home):
@@ -33,8 +33,8 @@ class JcePolicyInfo:
     Logger.info("Testing the JVM's JCE policy to see it if supports an unlimited key length.")
     return shell.call(
       self._command('-tu'),
-      stdout = subprocess.PIPE,
-      stderr = subprocess.PIPE,
+      stdout = subprocess32.PIPE,
+      stderr = subprocess32.PIPE,
       timeout = 5,
       quiet = True)[0] == 0
 
diff --git a/ambari-common/src/main/python/resource_management/core/resources/system.py b/ambari-common/src/main/python/resource_management/core/resources/system.py
index 087ceab..612ed9f 100644
--- a/ambari-common/src/main/python/resource_management/core/resources/system.py
+++ b/ambari-common/src/main/python/resource_management/core/resources/system.py
@@ -22,7 +22,7 @@ Ambari Agent
 
 __all__ = ["File", "Directory", "Link", "Execute", "ExecuteScript", "Mount"]
 
-import subprocess
+from ambari_commons import subprocess32
 from resource_management.core.signal_utils import TerminateStrategy
 from resource_management.core.base import Resource, ForcedListArgument, ResourceArgument, BooleanArgument
 
@@ -231,14 +231,14 @@ class Execute(Resource):
   """
   sudo = BooleanArgument(default=False)
   """
-  subprocess.PIPE - enable output gathering
+  subprocess32.PIPE - enable output gathering
   None - disable output to gathering, and output to Python out straightly (even if logoutput is False)
-  subprocess.STDOUT - redirect to stdout (not valid as value for stdout agument)
+  subprocess32.STDOUT - redirect to stdout (not valid as value for stdout agument)
   {int fd} - redirect to file with descriptor.
   {string filename} - redirects to a file with name.
   """
-  stdout = ResourceArgument(default=subprocess.PIPE)
-  stderr = ResourceArgument(default=subprocess.STDOUT)
+  stdout = ResourceArgument(default=subprocess32.PIPE)
+  stderr = ResourceArgument(default=subprocess32.STDOUT)
 
   """
   This argument takes TerminateStrategy constants. Import it as shown below:
diff --git a/ambari-common/src/main/python/resource_management/core/shell.py b/ambari-common/src/main/python/resource_management/core/shell.py
index 5c953da..71f4cb3 100644
--- a/ambari-common/src/main/python/resource_management/core/shell.py
+++ b/ambari-common/src/main/python/resource_management/core/shell.py
@@ -29,7 +29,7 @@ import select
 import sys
 import logging
 import string
-import subprocess
+from ambari_commons import subprocess32
 import threading
 import traceback
 from exceptions import Fail, ExecutionFailed, ExecuteTimeoutException
@@ -88,7 +88,7 @@ def preexec_fn():
     raise
 
 @log_function_call
-def checked_call(command, quiet=False, logoutput=None, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,
+def checked_call(command, quiet=False, logoutput=None, stdout=subprocess32.PIPE,stderr=subprocess32.STDOUT,
          cwd=None, env=None, preexec_fn=preexec_fn, user=None, wait_for_finish=True, timeout=None, on_timeout=None,
          path=None, sudo=False, on_new_line=None, tries=1, try_sleep=0, timeout_kill_strategy=TerminateStrategy.TERMINATE_PARENT):
   """
@@ -102,7 +102,7 @@ def checked_call(command, quiet=False, logoutput=None, stdout=subprocess.PIPE,st
                               tries=tries, try_sleep=try_sleep, timeout_kill_strategy=timeout_kill_strategy)
   
 @log_function_call
-def call(command, quiet=False, logoutput=None, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,
+def call(command, quiet=False, logoutput=None, stdout=subprocess32.PIPE,stderr=subprocess32.STDOUT,
          cwd=None, env=None, preexec_fn=preexec_fn, user=None, wait_for_finish=True, timeout=None, on_timeout=None,
          path=None, sudo=False, on_new_line=None, tries=1, try_sleep=0, timeout_kill_strategy=TerminateStrategy.TERMINATE_PARENT):
   """
@@ -115,7 +115,7 @@ def call(command, quiet=False, logoutput=None, stdout=subprocess.PIPE,stderr=sub
                               tries=tries, try_sleep=try_sleep, timeout_kill_strategy=timeout_kill_strategy)
 
 @log_function_call
-def non_blocking_call(command, quiet=False, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,
+def non_blocking_call(command, quiet=False, stdout=subprocess32.PIPE,stderr=subprocess32.STDOUT,
          cwd=None, env=None, preexec_fn=preexec_fn, user=None, timeout=None, path=None, sudo=False):
   """
   Execute the shell command and don't wait until it's completion
@@ -164,7 +164,7 @@ def _call_wrapper(command, **kwargs):
       
   return result
 
-def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,
+def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess32.PIPE,stderr=subprocess32.STDOUT,
          cwd=None, env=None, preexec_fn=preexec_fn, user=None, wait_for_finish=True, timeout=None, on_timeout=None, 
          path=None, sudo=False, on_new_line=None, tries=1, try_sleep=0, timeout_kill_strategy=TerminateStrategy.TERMINATE_PARENT):
   """
@@ -175,8 +175,8 @@ def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess.PIPE
   @param logoutput: boolean, whether command output should be logged of not
   @param throw_on_failure: if true, when return code is not zero exception is thrown
   @param stdout,stderr: 
-    subprocess.PIPE - enable output to variable
-    subprocess.STDOUT - redirect to stdout
+    subprocess32.PIPE - enable output to variable
+    subprocess32.STDOUT - redirect to stdout
     None - disable output to variable, and output to Python out straightly (even if logoutput is False)
     {int fd} - redirect to file with descriptor.
     {string filename} - redirects to a file with name.
@@ -207,7 +207,7 @@ def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess.PIPE
     command = command.replace(placeholder, replacement.format(env_str=env_str))
 
   # --noprofile is used to preserve PATH set for ambari-agent
-  subprocess_command = ["/bin/bash","--login","--noprofile","-c", command]
+  subprocess32_command = ["/bin/bash","--login","--noprofile","-c", command]
   
   files_to_close = []
   if isinstance(stdout, (basestring)):
@@ -218,7 +218,7 @@ def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess.PIPE
     files_to_close.append(stderr)
   
   try:
-    proc = subprocess.Popen(subprocess_command, stdout=stdout, stderr=stderr,
+    proc = subprocess32.Popen(subprocess32_command, stdout=stdout, stderr=stderr,
                             cwd=cwd, env=env, shell=False, close_fds=True,
                             preexec_fn=preexec_fn)
     
@@ -234,9 +234,9 @@ def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess.PIPE
     logoutput = logoutput==True and Logger.logger.isEnabledFor(logging.INFO) or logoutput==None and Logger.logger.isEnabledFor(logging.DEBUG)
     read_set = []
     
-    if stdout == subprocess.PIPE:
+    if stdout == subprocess32.PIPE:
       read_set.append(proc.stdout)
-    if stderr == subprocess.PIPE:
+    if stderr == subprocess32.PIPE:
       read_set.append(proc.stderr)
     
     fd_to_string = {
@@ -303,7 +303,7 @@ def _call(command, logoutput=None, throw_on_failure=True, stdout=subprocess.PIPE
     raise ExecutionFailed(err_msg, code, out, err)
   
   # if separate stderr is enabled (by default it's redirected to out)
-  if stderr == subprocess.PIPE:
+  if stderr == subprocess32.PIPE:
     return code, out, err
   
   return code, out
diff --git a/ambari-common/src/main/python/resource_management/core/sudo.py b/ambari-common/src/main/python/resource_management/core/sudo.py
index c350161..2989367 100644
--- a/ambari-common/src/main/python/resource_management/core/sudo.py
+++ b/ambari-common/src/main/python/resource_management/core/sudo.py
@@ -28,7 +28,7 @@ import errno
 import random
 from resource_management.core import shell
 from resource_management.core.exceptions import Fail
-import subprocess
+from ambari_commons import subprocess32
 
 from resource_management.core.utils import attr_to_bitmask
 
@@ -278,7 +278,7 @@ else:
     class Stat:
       def __init__(self, path):
         cmd = ["stat", "-c", "%u %g %a", path]
-        code, out, err = shell.checked_call(cmd, sudo=True, stderr=subprocess.PIPE)
+        code, out, err = shell.checked_call(cmd, sudo=True, stderr=subprocess32.PIPE)
         values = out.split(' ')
         if len(values) != 3:
           raise Fail("Execution of '{0}' returned unexpected output. {2}\n{3}".format(cmd, code, err, out))
@@ -303,7 +303,7 @@ else:
     if not path_isdir(path):
       raise Fail("{0} is not a directory. Cannot list files of it.".format(path))
     
-    code, out, err = shell.checked_call(["ls", path], sudo=True, stderr=subprocess.PIPE)
+    code, out, err = shell.checked_call(["ls", path], sudo=True, stderr=subprocess32.PIPE)
     files = out.splitlines()
     return files
 
diff --git a/ambari-common/src/main/python/resource_management/libraries/functions/conf_select.py b/ambari-common/src/main/python/resource_management/libraries/functions/conf_select.py
index 9de2f8f..2abe566 100644
--- a/ambari-common/src/main/python/resource_management/libraries/functions/conf_select.py
+++ b/ambari-common/src/main/python/resource_management/libraries/functions/conf_select.py
@@ -22,7 +22,7 @@ __all__ = ["select", "create", "get_hadoop_conf_dir", "get_hadoop_dir", "get_pac
 
 # Python Imports
 import os
-import subprocess
+from ambari_commons import subprocess32
 import ambari_simplejson as json
 
 # Local Imports
@@ -107,7 +107,7 @@ def create(stack_name, package, version, dry_run = False):
 
   command = "dry-run-create" if dry_run else "create-conf-dir"
 
-  code, stdout, stderr = shell.call(_get_cmd(command, package, version), logoutput=False, quiet=False, sudo=True, stderr = subprocess.PIPE)
+  code, stdout, stderr = shell.call(_get_cmd(command, package, version), logoutput=False, quiet=False, sudo=True, stderr = subprocess32.PIPE)
 
   # <conf-selector-tool> can set more than one directory
   # per package, so return that list, especially for dry_run
diff --git a/ambari-common/src/main/python/resource_management/libraries/functions/copy_tarball.py b/ambari-common/src/main/python/resource_management/libraries/functions/copy_tarball.py
index 33620a3..b008db2 100644
--- a/ambari-common/src/main/python/resource_management/libraries/functions/copy_tarball.py
+++ b/ambari-common/src/main/python/resource_management/libraries/functions/copy_tarball.py
@@ -381,7 +381,7 @@ def _get_single_version_from_stack_select():
   Call "<stack-selector> versions" and return the version string if only one version is available.
   :return: Returns a version string if successful, and None otherwise.
   """
-  # Ubuntu returns: "stdin: is not a tty", as subprocess output, so must use a temporary file to store the output.
+  # Ubuntu returns: "stdin: is not a tty", as subprocess32 output, so must use a temporary file to store the output.
   tmpfile = tempfile.NamedTemporaryFile()
   tmp_dir = Script.get_tmp_dir()
   tmp_file = os.path.join(tmp_dir, "copy_tarball_out.txt")
diff --git a/ambari-common/src/main/python/resource_management/libraries/functions/dynamic_variable_interpretation.py b/ambari-common/src/main/python/resource_management/libraries/functions/dynamic_variable_interpretation.py
index 74db04a..25c1526 100644
--- a/ambari-common/src/main/python/resource_management/libraries/functions/dynamic_variable_interpretation.py
+++ b/ambari-common/src/main/python/resource_management/libraries/functions/dynamic_variable_interpretation.py
@@ -171,7 +171,7 @@ def copy_tarballs_to_hdfs(tarball_prefix, stack_select_component_name, component
     Logger.warning("Could not find file: %s" % str(component_tar_source_file))
     return 1
 
-  # Ubuntu returns: "stdin: is not a tty", as subprocess output.
+  # Ubuntu returns: "stdin: is not a tty", as subprocess32 output.
   tmpfile = tempfile.NamedTemporaryFile()
   out = None
   (stack_selector_name, stack_selector_path, stack_selector_package) = stack_tools.get_stack_tool(stack_tools.STACK_SELECTOR_NAME)
diff --git a/ambari-common/src/main/python/resource_management/libraries/providers/hdfs_resource.py b/ambari-common/src/main/python/resource_management/libraries/providers/hdfs_resource.py
index 0028e84..22efd1d 100644
--- a/ambari-common/src/main/python/resource_management/libraries/providers/hdfs_resource.py
+++ b/ambari-common/src/main/python/resource_management/libraries/providers/hdfs_resource.py
@@ -41,7 +41,7 @@ from resource_management.libraries.functions.hdfs_utils import is_https_enabled_
 
 
 import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
-import subprocess
+from ambari_commons import subprocess32
 
 JSON_PATH = '/var/lib/ambari-agent/tmp/hdfs_resources_{timestamp}.json'
 JAR_PATH = '/var/lib/ambari-agent/lib/fast-hdfs-resource.jar'
diff --git a/ambari-common/src/main/python/resource_management/libraries/script/hook.py b/ambari-common/src/main/python/resource_management/libraries/script/hook.py
index 1379cc3..26b73a3 100644
--- a/ambari-common/src/main/python/resource_management/libraries/script/hook.py
+++ b/ambari-common/src/main/python/resource_management/libraries/script/hook.py
@@ -21,7 +21,7 @@ limitations under the License.
 __all__ = ["Hook"]
 
 from resource_management.libraries.script import Script
-import subprocess
+from ambari_commons import subprocess32
 import sys
 
 class Hook(Script):
@@ -60,7 +60,7 @@ class Hook(Script):
     cmd = [sys.executable]
     cmd.extend(args)
 
-    if subprocess.call(cmd) != 0:
+    if subprocess32.call(cmd) != 0:
       self.fail_with_error("Error: Unable to run the custom hook script " +
                            cmd.__str__())
 
diff --git a/ambari-common/src/main/repo/install_ambari_tarball.py b/ambari-common/src/main/repo/install_ambari_tarball.py
index a22823f..633ab90 100644
--- a/ambari-common/src/main/repo/install_ambari_tarball.py
+++ b/ambari-common/src/main/repo/install_ambari_tarball.py
@@ -21,7 +21,7 @@ import re
 import os
 import sys
 import logging
-import subprocess
+from ambari_commons import subprocess32
 from optparse import OptionParser
 import ConfigParser
 
@@ -52,13 +52,13 @@ class Utils:
     print_output = logoutput==True or (logoutput==None and Utils.verbose)
     
     if not print_output:
-      stdout = subprocess.PIPE
-      stderr = subprocess.STDOUT
+      stdout = subprocess32.PIPE
+      stderr = subprocess32.STDOUT
     else:
       stdout = stderr = None
     
     logger.info("Running '{0}'".format(command))
-    proc = subprocess.Popen(command, shell=shell, stdout=stdout, stderr=stderr, env=env)
+    proc = subprocess32.Popen(command, shell=shell, stdout=stdout, stderr=stderr, env=env)
       
     if not print_output:
       out = proc.communicate()[0].strip('\n')
diff --git a/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/build.py b/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/build.py
index 09fb411..7aefe25 100644
--- a/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/build.py
+++ b/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/build.py
@@ -18,7 +18,7 @@ See the License for the specific language governing permissions and
 limitations under the License.
 '''
 
-from subprocess import call
+from ambari_commons.subprocess32 import call
 import sys
 import os
 import shutil
diff --git a/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/__init__.py b/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/__init__.py
index 3068b10..13e0d92 100644
--- a/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/__init__.py
+++ b/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/__init__.py
@@ -44,7 +44,7 @@ import time
 import signal
 import warnings
 import errno
-import subprocess
+from ambari_commons import subprocess32
 try:
     import pwd
 except ImportError:
@@ -1163,14 +1163,14 @@ class Process(object):
 # =====================================================================
 
 class Popen(Process):
-    """A more convenient interface to stdlib subprocess module.
+    """A more convenient interface to stdlib subprocess32 module.
     It starts a sub process and deals with it exactly as when using
-    subprocess.Popen class but in addition also provides all the
+    subprocess32.Popen class but in addition also provides all the
     properties and methods of psutil.Process class as a unified
     interface:
 
       >>> import psutil
-      >>> from subprocess import PIPE
+      >>> from ambari_commons.subprocess32 import PIPE
       >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
       >>> p.name()
       'python'
@@ -1188,24 +1188,24 @@ class Popen(Process):
     For method names common to both classes such as kill(), terminate()
     and wait(), psutil.Process implementation takes precedence.
 
-    Unlike subprocess.Popen this class pre-emptively checks wheter PID
+    Unlike subprocess32.Popen this class pre-emptively checks wheter PID
     has been reused on send_signal(), terminate() and kill() so that
     you don't accidentally terminate another process, fixing
     http://bugs.python.org/issue6973.
 
     For a complete documentation refer to:
-    http://docs.python.org/library/subprocess.html
+    http://docs.python.org/library/subprocess32.html
     """
 
     def __init__(self, *args, **kwargs):
         # Explicitly avoid to raise NoSuchProcess in case the process
-        # spawned by subprocess.Popen terminates too quickly, see:
+        # spawned by subprocess32.Popen terminates too quickly, see:
         # https://code.google.com/p/psutil/issues/detail?id=193
-        self.__subproc = subprocess.Popen(*args, **kwargs)
+        self.__subproc = subprocess32.Popen(*args, **kwargs)
         self._init(self.__subproc.pid, _ignore_nsp=True)
 
     def __dir__(self):
-        return sorted(set(dir(Popen) + dir(subprocess.Popen)))
+        return sorted(set(dir(Popen) + dir(subprocess32.Popen)))
 
     def __getattribute__(self, name):
         try:
diff --git a/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/_pssunos.py b/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/_pssunos.py
index bc18427..1552010 100644
--- a/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/_pssunos.py
+++ b/ambari-metrics/ambari-metrics-host-monitoring/src/main/python/psutil/psutil/_pssunos.py
@@ -9,7 +9,7 @@
 import errno
 import os
 import socket
-import subprocess
+from ambari_commons import subprocess32
 import sys
 
 from psutil import _common
@@ -91,7 +91,7 @@ def swap_memory():
     #     usr/src/cmd/swap/swap.c
     # ...nevertheless I can't manage to obtain the same numbers as 'swap'
     # cmdline utility, so let's parse its output (sigh!)
-    p = subprocess.Popen(['swap', '-l', '-k'], stdout=subprocess.PIPE)
+    p = subprocess32.Popen(['swap', '-l', '-k'], stdout=subprocess32.PIPE)
     stdout, stderr = p.communicate()
     if PY3:
         stdout = stdout.decode(sys.stdout.encoding)
@@ -433,8 +433,8 @@ class Process(object):
         # TODO: rewrite this in C (...but the damn netstat source code
         # does not include this part! Argh!!)
         cmd = "pfiles %s" % pid
-        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
-                             stderr=subprocess.PIPE)
+        p = subprocess32.Popen(cmd, shell=True, stdout=subprocess32.PIPE,
+                             stderr=subprocess32.PIPE)
         stdout, stderr = p.communicate()
         if PY3:
             stdout, stderr = [x.decode(sys.stdout.encoding)
diff --git a/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/phoenix_utils.py b/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/phoenix_utils.py
index 6d9b791..14b53db 100644
--- a/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/phoenix_utils.py
+++ b/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/phoenix_utils.py
@@ -21,7 +21,7 @@
 
 import os
 import fnmatch
-import subprocess
+from ambari_commons import subprocess32
 
 def find(pattern, classPaths):
     paths = classPaths.split(os.pathsep)
@@ -62,7 +62,7 @@ def which(file):
 def findClasspath(file):
     aPath = which(file)
     command = "%s%s" %(aPath, ' classpath')
-    return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read()
+    return subprocess32.Popen(command, shell=True, stdout=subprocess32.PIPE).stdout.read()
 
 def setPath():
     PHOENIX_CLIENT_JAR_PATTERN = "phoenix-*-client.jar"
@@ -167,8 +167,8 @@ def shell_quote(args):
     :return: shell quoted string
     """
     if os.name == 'nt':
-        import subprocess
-        return subprocess.list2cmdline(args)
+        from ambari_commons import subprocess32
+        return subprocess32.list2cmdline(args)
     else:
         # pipes module isn't available on Windows
         import pipes
diff --git a/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/sqlline.py b/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/sqlline.py
index 852f264..8027443 100644
--- a/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/sqlline.py
+++ b/ambari-metrics/ambari-metrics-timelineservice/conf/unix/sqlline/sqlline.py
@@ -20,7 +20,7 @@
 ############################################################################
 
 import os
-import subprocess
+from ambari_commons import subprocess32
 import sys
 import phoenix_utils
 import atexit
@@ -95,7 +95,7 @@ java_cmd = find_java() + ' -cp "' + phoenix_client_path + \
 
 print 'java command: %s' % str(java_cmd)
 
-childProc = subprocess.Popen(java_cmd, shell=True)
+childProc = subprocess32.Popen(java_cmd, shell=True)
 #Wait for child process exit
 (output, error) = childProc.communicate()
 returncode = childProc.returncode
diff --git a/ambari-metrics/ambari-metrics-timelineservice/src/main/python/embedded_hbase_service.py b/ambari-metrics/ambari-metrics-timelineservice/src/main/python/embedded_hbase_service.py
index 7667d7d..2040959 100644
--- a/ambari-metrics/ambari-metrics-timelineservice/src/main/python/embedded_hbase_service.py
+++ b/ambari-metrics/ambari-metrics-timelineservice/src/main/python/embedded_hbase_service.py
@@ -82,7 +82,7 @@ class EmbeddedHBaseService:
   def Install(cls, startupMode = "auto", username = None, password = None):
     print "Installing service %s" % (cls._svc_name_)
 
-    # Configure master.xml, which drives the java subprocess
+    # Configure master.xml, which drives the java subprocess32
     java_path = get_java_exe_path()
     java_args = _build_master_java_args(username)
 
diff --git a/ambari-metrics/ambari-metrics-timelineservice/src/main/python/main.py b/ambari-metrics/ambari-metrics-timelineservice/src/main/python/main.py
index b6b4e0b..7a5f87a 100644
--- a/ambari-metrics/ambari-metrics-timelineservice/src/main/python/main.py
+++ b/ambari-metrics/ambari-metrics-timelineservice/src/main/python/main.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 
 import os
-import subprocess
+from ambari_commons import subprocess32
 import sys
 
 from ambari_commons.exceptions import FatalException, NonFatalException
@@ -70,7 +70,7 @@ def exec_ams_env_cmd(options):
   ams_env_cmd = os.path.join(options.conf_dir, AMS_ENV_CMD)
   if os.path.exists(ams_env_cmd):
     cmds = ["cmd.exe", "/C", ams_env_cmd]
-    procAms = subprocess.Popen(cmds, env=os.environ)
+    procAms = subprocess32.Popen(cmds, env=os.environ)
     out, err = procAms.communicate()
     if err is not None and err is not "":
       print_warning_msg(AMS_ENV_CMD + " error output: " + err)
@@ -129,7 +129,7 @@ def server_process_main(options, scmStatus=None):
   param_list = java_exe + " " + command
 
   print_info_msg("Running server: " + str(param_list))
-  procJava = subprocess.Popen(param_list, env=os.environ)
+  procJava = subprocess32.Popen(param_list, env=os.environ)
 
   #wait for server process for SERVER_START_TIMEOUT seconds
   print "Waiting for server start..."
diff --git a/ambari-server/src/main/python/ambari_server/dbConfiguration_linux.py b/ambari-server/src/main/python/ambari_server/dbConfiguration_linux.py
index 51d4759..5a78816 100644
--- a/ambari-server/src/main/python/ambari_server/dbConfiguration_linux.py
+++ b/ambari-server/src/main/python/ambari_server/dbConfiguration_linux.py
@@ -23,7 +23,7 @@ import os
 import re
 import shutil
 import socket
-import subprocess
+from ambari_commons import subprocess32
 import sys
 import time
 import pwd
@@ -633,10 +633,10 @@ class PGConfig(LinuxDBMSConfig):
           print out
       print "About to start PostgreSQL"
       try:
-        process = subprocess.Popen(PGConfig.PG_START_CMD.split(' '),
-                                   stdout=subprocess.PIPE,
-                                   stdin=subprocess.PIPE,
-                                   stderr=subprocess.PIPE
+        process = subprocess32.Popen(PGConfig.PG_START_CMD.split(' '),
+                                   stdout=subprocess32.PIPE,
+                                   stdin=subprocess32.PIPE,
+                                   stderr=subprocess32.PIPE
         )
         if OSCheck.is_suse_family():
           time.sleep(20)
@@ -760,10 +760,10 @@ class PGConfig(LinuxDBMSConfig):
   @staticmethod
   def _restart_postgres():
     print "Restarting PostgreSQL"
-    process = subprocess.Popen(PGConfig.PG_RESTART_CMD.split(' '),
-                               stdout=subprocess.PIPE,
-                               stdin=subprocess.PIPE,
-                               stderr=subprocess.PIPE
+    process = subprocess32.Popen(PGConfig.PG_RESTART_CMD.split(' '),
+                               stdout=subprocess32.PIPE,
+                               stdin=subprocess32.PIPE,
+                               stderr=subprocess32.PIPE
     )
     time.sleep(5)
     result = process.poll()
@@ -1203,10 +1203,10 @@ class SQLAConfig(LinuxDBMSConfig):
     cmd = SQLAConfig.EXTRACT_CMD.format(files[0], get_resources_location(properties))
 
 
-    process = subprocess.Popen(cmd.split(' '),
-                               stdout=subprocess.PIPE,
-                               stdin=subprocess.PIPE,
-                               stderr=subprocess.PIPE
+    process = subprocess32.Popen(cmd.split(' '),
+                               stdout=subprocess32.PIPE,
+                               stdin=subprocess32.PIPE,
+                               stderr=subprocess32.PIPE
     )
 
     out, err = process.communicate()
diff --git a/ambari-server/src/main/python/ambari_server/serverSetup.py b/ambari-server/src/main/python/ambari_server/serverSetup.py
index 909497f..81c2fad 100644
--- a/ambari-server/src/main/python/ambari_server/serverSetup.py
+++ b/ambari-server/src/main/python/ambari_server/serverSetup.py
@@ -23,7 +23,7 @@ import os
 import re
 import shutil
 import sys
-import subprocess
+from ambari_commons import subprocess32
 import getpass
 import logging
 
@@ -800,10 +800,10 @@ class JDKSetupLinux(JDKSetup):
 
     cmd = " && ".join(cmds)
 
-    process = subprocess.Popen(cmd,
-                           stdout=subprocess.PIPE,
-                           stdin=subprocess.PIPE,
-                           stderr=subprocess.PIPE,
+    process = subprocess32.Popen(cmd,
+                           stdout=subprocess32.PIPE,
+                           stdin=subprocess32.PIPE,
+                           stderr=subprocess32.PIPE,
                            shell=True
                            )
     (stdoutdata, stderrdata) = process.communicate()
diff --git a/ambari-server/src/main/python/ambari_server/utils.py b/ambari-server/src/main/python/ambari_server/utils.py
index b51e37e..fcba7f1 100644
--- a/ambari-server/src/main/python/ambari_server/utils.py
+++ b/ambari-server/src/main/python/ambari_server/utils.py
@@ -24,7 +24,7 @@ import socket
 import sys
 import time
 import glob
-import subprocess
+from ambari_commons import subprocess32
 import logging
 import platform
 from ambari_commons import OSConst,OSCheck
@@ -270,10 +270,10 @@ def get_postgre_hba_dir(OS_FAMILY):
     pg_hba_init_basename = os.path.basename(get_pg_hba_init_files())
     # Get postgres_data location (default: /var/lib/pgsql/data)
     cmd = "alias basename='echo {0}; true' ; alias exit=return; source {1} status &>/dev/null; echo $PGDATA".format(pg_hba_init_basename, get_pg_hba_init_files())
-    p = subprocess.Popen(cmd,
-                         stdout=subprocess.PIPE,
-                         stdin=subprocess.PIPE,
-                         stderr=subprocess.PIPE,
+    p = subprocess32.Popen(cmd,
+                         stdout=subprocess32.PIPE,
+                         stdin=subprocess32.PIPE,
+                         stderr=subprocess32.PIPE,
                          shell=True)
     (PG_HBA_ROOT, err) = p.communicate()
 
diff --git a/ambari-server/src/main/python/ambari_server_main.py b/ambari-server/src/main/python/ambari_server_main.py
index de8f317..5499f3a 100644
--- a/ambari-server/src/main/python/ambari_server_main.py
+++ b/ambari-server/src/main/python/ambari_server_main.py
@@ -18,7 +18,7 @@ See the License for the specific language governing permissions and
 limitations under the License.
 '''
 import os
-import subprocess
+from ambari_commons import subprocess32
 import sys
 import logging
 import time
@@ -181,8 +181,8 @@ def generate_child_process_param_list(ambari_user, java_exe, class_path,
   param_list = [locate_file('sh', '/bin'), "-c"]
   if is_root() and ambari_user != "root":
     # To inherit exported environment variables (especially AMBARI_PASSPHRASE),
-    # from subprocess, we have to skip --login option of su command. That's why
-    # we change dir to / (otherwise subprocess can face with 'permission denied'
+    # from subprocess32, we have to skip --login option of su command. That's why
+    # we change dir to / (otherwise subprocess32 can face with 'permission denied'
     # errors while trying to list current directory
     cmd = "{ulimit_cmd} ; {su} {ambari_user} -s {sh_shell} -c '. {ambari_env_file} && {command}'".format(ulimit_cmd=ulimit_cmd,
                                                                                 su=locate_file('su', '/bin'), ambari_user=ambari_user,
@@ -384,7 +384,7 @@ def server_process_main(options, scmStatus=None):
         pass
 
   print_info_msg("Running server: " + str(param_list))
-  procJava = subprocess.Popen(param_list, env=environ, preexec_fn=make_process_independent)
+  procJava = subprocess32.Popen(param_list, env=environ, preexec_fn=make_process_independent)
 
   pidJava = procJava.pid
   if pidJava <= 0:
diff --git a/ambari-server/src/main/python/bootstrap.py b/ambari-server/src/main/python/bootstrap.py
index e278917..17d8e20 100755
--- a/ambari-server/src/main/python/bootstrap.py
+++ b/ambari-server/src/main/python/bootstrap.py
@@ -29,7 +29,7 @@ import time
 import logging
 import pprint
 import os
-import subprocess
+from ambari_commons import subprocess32
 import threading
 import traceback
 import re
@@ -104,8 +104,8 @@ class SCP:
       self.host_log.write("Running scp command " + ' '.join(scpcommand))
     self.host_log.write("==========================")
     self.host_log.write("\nCommand start time " + datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
-    scpstat = subprocess.Popen(scpcommand, stdout=subprocess.PIPE,
-                               stderr=subprocess.PIPE)
+    scpstat = subprocess32.Popen(scpcommand, stdout=subprocess32.PIPE,
+                               stderr=subprocess32.PIPE)
     log = scpstat.communicate()
     errorMsg = log[1]
     log = log[0] + "\n" + log[1]
@@ -142,8 +142,8 @@ class SSH:
       self.host_log.write("Running ssh command " + ' '.join(sshcommand))
     self.host_log.write("==========================")
     self.host_log.write("\nCommand start time " + datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
-    sshstat = subprocess.Popen(sshcommand, stdout=subprocess.PIPE,
-                               stderr=subprocess.PIPE)
+    sshstat = subprocess32.Popen(sshcommand, stdout=subprocess32.PIPE,
+                               stderr=subprocess32.PIPE)
     log = sshstat.communicate()
     errorMsg = log[1]
     if self.errorMessage and sshstat.returncode != 0:
@@ -891,10 +891,10 @@ def main(argv=None):
 
   if not OSCheck.is_windows_family():
     # ssh doesn't like open files
-    subprocess.Popen(["chmod", "600", sshkey_file], stdout=subprocess.PIPE)
+    subprocess32.Popen(["chmod", "600", sshkey_file], stdout=subprocess32.PIPE)
 
     if passwordFile is not None and passwordFile != 'null':
-      subprocess.Popen(["chmod", "600", passwordFile], stdout=subprocess.PIPE)
+      subprocess32.Popen(["chmod", "600", passwordFile], stdout=subprocess32.PIPE)
 
   logging.info("BootStrapping hosts " + pprint.pformat(hostList) +
                " using " + scriptDir + " cluster primary OS: " + cluster_os_type +
diff --git a/ambari-server/src/main/python/setupAgent.py b/ambari-server/src/main/python/setupAgent.py
index 9a1cae9..24d8a07 100755
--- a/ambari-server/src/main/python/setupAgent.py
+++ b/ambari-server/src/main/python/setupAgent.py
@@ -23,7 +23,7 @@ import time
 import sys
 import logging
 import os
-import subprocess
+from ambari_commons import subprocess32
 
 from ambari_commons import OSCheck, OSConst
 from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl
@@ -109,7 +109,7 @@ def execOsCommand(osCommand, tries=1, try_sleep=0, ret=None, cwd=None):
     if i>0:
       time.sleep(try_sleep)
 
-    osStat = subprocess.Popen(osCommand, stdout=subprocess.PIPE, cwd=cwd)
+    osStat = subprocess32.Popen(osCommand, stdout=subprocess32.PIPE, cwd=cwd)
     log = osStat.communicate(0)
     ret = {"exitstatus": osStat.returncode, "log": log}
 
@@ -169,7 +169,7 @@ def runAgent(passPhrase, expected_hostname, user_run_as, verbose, ret=None):
     vo = " -v"
   cmd = ['su', user_run_as, '-l', '-c', '/usr/sbin/ambari-agent restart --expected-hostname=%1s %2s' % (expected_hostname, vo)]
   log = ""
-  p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+  p = subprocess32.Popen(cmd, stdout=subprocess32.PIPE)
   p.communicate()
   agent_retcode = p.returncode
   for i in range(3):
diff --git a/ambari-server/src/main/resources/common-services/HAWQ/2.0.0/package/scripts/utils.py b/ambari-server/src/main/resources/common-services/HAWQ/2.0.0/package/scripts/utils.py
index 95c3dcc..dd9c9a1 100644
--- a/ambari-server/src/main/resources/common-services/HAWQ/2.0.0/package/scripts/utils.py
+++ b/ambari-server/src/main/resources/common-services/HAWQ/2.0.0/package/scripts/utils.py
@@ -15,7 +15,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 """
-import subprocess
+from ambari_commons import subprocess32
 
 from resource_management.core.resources.system import Execute, Directory
 from resource_management.core.exceptions import Fail
@@ -83,7 +83,7 @@ def exec_ssh_cmd(hostname, cmd):
   # Only gpadmin should be allowed to run command via ssh, thus not exposing user as a parameter
   cmd = "su - {0} -c \"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null {1} \\\"{2} \\\" \"".format(hawq_constants.hawq_user, hostname, cmd)
   Logger.info("Command executed: {0}".format(cmd))
-  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+  process = subprocess32.Popen(cmd, stdout=subprocess32.PIPE, stdin=subprocess32.PIPE, stderr=subprocess32.PIPE, shell=True)
   (stdout, stderr) = process.communicate()
   return process.returncode, stdout, stderr
 
diff --git a/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_nfsgateway.py b/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_nfsgateway.py
index 672312a..d5246cd 100644
--- a/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_nfsgateway.py
+++ b/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_nfsgateway.py
@@ -22,7 +22,8 @@ from resource_management.core.logger import Logger
 from resource_management.core.resources import Directory
 from resource_management.core import shell
 from utils import service
-import subprocess,os
+from ambari_commons import subprocess32
+import os
 
 # NFS GATEWAY is always started by root using jsvc due to rpcbind bugs
 # on Linux such as CentOS6.2. https://bugzilla.redhat.com/show_bug.cgi?id=731542
diff --git a/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/utils.py b/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/utils.py
index f178d23..eddf890 100644
--- a/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/utils.py
+++ b/ambari-server/src/main/resources/common-services/HDFS/2.1.0.2.0/package/scripts/utils.py
@@ -19,7 +19,7 @@ limitations under the License.
 import os
 import re
 import urllib2
-import subprocess
+from ambari_commons import subprocess32
 import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
 
 from resource_management.core.resources.system import Directory, File, Execute
@@ -294,7 +294,7 @@ def service(action=None, name=None, user=None, options="", create_pid_dir=False,
 
     # If stop didn't happen, kill it forcefully
     if code != 0:
-      code, out, err = shell.checked_call(("cat", pid_file), sudo=True, env=hadoop_env_exports, stderr=subprocess.PIPE)
+      code, out, err = shell.checked_call(("cat", pid_file), sudo=True, env=hadoop_env_exports, stderr=subprocess32.PIPE)
       pid = out
       Execute(("kill", "-9", pid), sudo=True)
 
diff --git a/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/alerts/alert_llap_app_status.py b/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/alerts/alert_llap_app_status.py
index e46c896..0c02d94 100644
--- a/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/alerts/alert_llap_app_status.py
+++ b/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/alerts/alert_llap_app_status.py
@@ -22,7 +22,7 @@ import time
 import logging
 import traceback
 import json
-import subprocess
+from ambari_commons import subprocess32
 
 from resource_management.libraries.functions import format
 from resource_management.libraries.functions import get_kinit_path
@@ -168,7 +168,7 @@ def execute(configurations={}, parameters={}, host_name=None):
     else:
       llap_status_cmd = STACK_ROOT_DEFAULT + format("/current/hive-server2-hive2/bin/hive --service llapstatus --name {llap_app_name} --findAppTimeout {LLAP_APP_STATUS_CMD_TIMEOUT}")
 
-    code, output, error = shell.checked_call(llap_status_cmd, user=hive_user, stderr=subprocess.PIPE,
+    code, output, error = shell.checked_call(llap_status_cmd, user=hive_user, stderr=subprocess32.PIPE,
                                              timeout=check_command_timeout,
                                              logoutput=False)
     # Call for getting JSON
diff --git a/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/hive_server_interactive.py b/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/hive_server_interactive.py
index 06873da..98b26f4 100644
--- a/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/hive_server_interactive.py
+++ b/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/hive_server_interactive.py
@@ -18,7 +18,7 @@ limitations under the License.
 
 """
 # Python Imports
-import subprocess
+from ambari_commons import subprocess32
 import os
 import re
 import time
@@ -169,7 +169,7 @@ class HiveServerInteractiveDefault(HiveServerInteractive):
 
       stop_cmd = ["slider", "stop", params.llap_app_name]
 
-      code, output, error = shell.call(stop_cmd, user=params.hive_user, stderr=subprocess.PIPE, logoutput=True)
+      code, output, error = shell.call(stop_cmd, user=params.hive_user, stderr=subprocess32.PIPE, logoutput=True)
       if code == 0:
         Logger.info(format("Stopped {params.llap_app_name} application on Slider successfully"))
       elif code == 69 and output is not None and "Unknown application instance" in output:
@@ -265,7 +265,7 @@ class HiveServerInteractiveDefault(HiveServerInteractive):
       run_file_path = None
       try:
         Logger.info(format("LLAP start command: {cmd}"))
-        code, output, error = shell.checked_call(cmd, user=params.hive_user, quiet = True, stderr=subprocess.PIPE, logoutput=True)
+        code, output, error = shell.checked_call(cmd, user=params.hive_user, quiet = True, stderr=subprocess32.PIPE, logoutput=True)
 
         if code != 0 or output is None:
           raise Fail("Command failed with either non-zero return code or no output.")
@@ -371,7 +371,7 @@ class HiveServerInteractiveDefault(HiveServerInteractive):
       LLAP_APP_STATUS_CMD_TIMEOUT = 0
 
       llap_status_cmd = format("{stack_root}/current/hive-server2-hive2/bin/hive --service llapstatus --name {app_name} --findAppTimeout {LLAP_APP_STATUS_CMD_TIMEOUT}")
-      code, output, error = shell.checked_call(llap_status_cmd, user=status_params.hive_user, stderr=subprocess.PIPE,
+      code, output, error = shell.checked_call(llap_status_cmd, user=status_params.hive_user, stderr=subprocess32.PIPE,
                                                logoutput=False)
       Logger.info("Received 'llapstatus' command 'output' : {0}".format(output))
       if code == 0:
@@ -402,7 +402,7 @@ class HiveServerInteractiveDefault(HiveServerInteractive):
       llap_status_cmd = format("{stack_root}/current/hive-server2-hive2/bin/hive --service llapstatus -w -r {percent_desired_instances_to_be_up} -i {refresh_rate} -t {total_timeout}")
       Logger.info("\n\n\n\n\n");
       Logger.info("LLAP status command : {0}".format(llap_status_cmd))
-      code, output, error = shell.checked_call(llap_status_cmd, user=status_params.hive_user, quiet=True, stderr=subprocess.PIPE,
+      code, output, error = shell.checked_call(llap_status_cmd, user=status_params.hive_user, quiet=True, stderr=subprocess32.PIPE,
                                                logoutput=True)
 
       if code == 0:
diff --git a/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/service_check.py b/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/service_check.py
index d379726..63bd92f 100644
--- a/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/service_check.py
+++ b/ambari-server/src/main/resources/common-services/HIVE/0.12.0.2.0/package/scripts/service_check.py
@@ -20,7 +20,7 @@ limitations under the License.
 
 import os
 import time
-import subprocess
+from ambari_commons import subprocess32
 
 from hcat_service_check import hcat_service_check
 from webhcat_service_check import webhcat_service_check
@@ -185,7 +185,7 @@ class HiveServiceCheckDefault(HiveServiceCheck):
             path=['/usr/sbin', '/usr/local/bin', '/bin', '/usr/bin', exec_path],
             tries=1,
             wait_for_finish=True,
-            stderr=subprocess.PIPE,
+            stderr=subprocess32.PIPE,
             logoutput=True)
 
 if __name__ == "__main__":
diff --git a/ambari-server/src/main/resources/common-services/KAFKA/0.8.1/package/scripts/service_check.py b/ambari-server/src/main/resources/common-services/KAFKA/0.8.1/package/scripts/service_check.py
index 3c1a3ab..5387fc2 100644
--- a/ambari-server/src/main/resources/common-services/KAFKA/0.8.1/package/scripts/service_check.py
+++ b/ambari-server/src/main/resources/common-services/KAFKA/0.8.1/package/scripts/service_check.py
@@ -24,7 +24,6 @@ from resource_management.libraries.functions.format import format
 from resource_management.core.logger import Logger
 from resource_management.core.exceptions import Fail
 from resource_management.core import sudo
-import subprocess
 
 class ServiceCheck(Script):
   def service_check(self, env):
diff --git a/ambari-server/src/main/resources/common-services/PXF/3.0.0/package/scripts/pxf_utils.py b/ambari-server/src/main/resources/common-services/PXF/3.0.0/package/scripts/pxf_utils.py
index fe12d9a..85d6ba3 100644
--- a/ambari-server/src/main/resources/common-services/PXF/3.0.0/package/scripts/pxf_utils.py
+++ b/ambari-server/src/main/resources/common-services/PXF/3.0.0/package/scripts/pxf_utils.py
@@ -20,7 +20,7 @@ from resource_management.core.logger import Logger
 import socket
 import urllib2
 import urllib
-import subprocess
+from ambari_commons import subprocess32
 
 def makeHTTPCall(url, header={}, body=None):
   # timeout in seconds
@@ -45,5 +45,5 @@ def makeHTTPCall(url, header={}, body=None):
     
 
 def runLocalCmd(cmd):
-  return subprocess.call(cmd, shell=True)  
+  return subprocess32.call(cmd, shell=True)  
 
diff --git a/ambari-server/src/main/resources/common-services/SPARK/1.2.1/package/scripts/service_check.py b/ambari-server/src/main/resources/common-services/SPARK/1.2.1/package/scripts/service_check.py
index 5d38f90..ae85c3d 100644
--- a/ambari-server/src/main/resources/common-services/SPARK/1.2.1/package/scripts/service_check.py
+++ b/ambari-server/src/main/resources/common-services/SPARK/1.2.1/package/scripts/service_check.py
@@ -15,7 +15,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 """
-import subprocess
+from ambari_commons import subprocess32
 import time
 
 from resource_management import *
diff --git a/ambari-server/src/main/resources/common-services/SPARK2/2.0.0/package/scripts/service_check.py b/ambari-server/src/main/resources/common-services/SPARK2/2.0.0/package/scripts/service_check.py
index 051f22f..2787a4b 100755
--- a/ambari-server/src/main/resources/common-services/SPARK2/2.0.0/package/scripts/service_check.py
+++ b/ambari-server/src/main/resources/common-services/SPARK2/2.0.0/package/scripts/service_check.py
@@ -15,7 +15,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 """
-import subprocess
+from ambari_commons import subprocess32
 import time
 
 from resource_management import *
diff --git a/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/files/validateYarnComponentStatusWindows.py b/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/files/validateYarnComponentStatusWindows.py
index 5e2b4d9..218b893 100644
--- a/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/files/validateYarnComponentStatusWindows.py
+++ b/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/files/validateYarnComponentStatusWindows.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 
 import optparse
-import subprocess
+from ambari_commons import subprocess32
 import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
 import urllib2
 
diff --git a/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/nodemanager_upgrade.py b/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/nodemanager_upgrade.py
index 1c886f9..457ac79 100644
--- a/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/nodemanager_upgrade.py
+++ b/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/nodemanager_upgrade.py
@@ -17,7 +17,7 @@ limitations under the License.
 
 """
 
-import subprocess
+from ambari_commons import subprocess32
 
 from resource_management.core.logger import Logger
 from resource_management.core.exceptions import Fail
diff --git a/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/service_check.py b/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/service_check.py
index 1193b60..6de9738 100644
--- a/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/service_check.py
+++ b/ambari-server/src/main/resources/common-services/YARN/2.1.0.2.0/package/scripts/service_check.py
@@ -23,7 +23,7 @@ from resource_management import *
 import sys
 import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
 import re
-import subprocess
+from ambari_commons import subprocess32
 from ambari_commons import os_utils
 from ambari_commons import OSConst
 from ambari_commons.os_family_impl import OsFamilyImpl
diff --git a/ambari-server/src/main/resources/custom_actions/scripts/check_host.py b/ambari-server/src/main/resources/custom_actions/scripts/check_host.py
index 3ca2909..5ee959b 100644
--- a/ambari-server/src/main/resources/custom_actions/scripts/check_host.py
+++ b/ambari-server/src/main/resources/custom_actions/scripts/check_host.py
@@ -22,7 +22,7 @@ Ambari Agent
 
 import os
 import re
-import subprocess
+from ambari_commons import subprocess32
 import socket
 import getpass
 import tempfile
diff --git a/ambari-server/src/main/resources/scripts/Ambaripreupload.py b/ambari-server/src/main/resources/scripts/Ambaripreupload.py
index 1e2d122..3fb56f0 100644
--- a/ambari-server/src/main/resources/scripts/Ambaripreupload.py
+++ b/ambari-server/src/main/resources/scripts/Ambaripreupload.py
@@ -62,7 +62,7 @@ Please note that "-${build_number}" is optional.
 with Environment() as env:
   def get_stack_version():
     if not options.hdp_version:
-      # Ubuntu returns: "stdin: is not a tty", as subprocess output.
+      # Ubuntu returns: "stdin: is not a tty", as subprocess32 output.
       tmpfile = tempfile.NamedTemporaryFile()
       out = None
       with open(tmpfile.name, 'r+') as file:
diff --git a/ambari-server/src/main/resources/scripts/check_ambari_permissions.py b/ambari-server/src/main/resources/scripts/check_ambari_permissions.py
index 293fd09..7ae54a8 100644
--- a/ambari-server/src/main/resources/scripts/check_ambari_permissions.py
+++ b/ambari-server/src/main/resources/scripts/check_ambari_permissions.py
@@ -20,7 +20,7 @@ limitations under the License.
 
 import os
 import shlex
-import subprocess
+from ambari_commons import subprocess32
 import argparse
 
 JAR_FILE_PERMISSIONS = 644
@@ -225,10 +225,10 @@ def do_work(args):
 def os_run_os_command(cmd, env=None, shell=False, cwd=None):
   if type(cmd) == str:
     cmd = shlex.split(cmd)
-  process = subprocess.Popen(cmd,
-                             stdout=subprocess.PIPE,
-                             stdin=subprocess.PIPE,
-                             stderr=subprocess.PIPE,
+  process = subprocess32.Popen(cmd,
+                             stdout=subprocess32.PIPE,
+                             stdin=subprocess32.PIPE,
+                             stderr=subprocess32.PIPE,
                              env=env,
                              cwd=cwd,
                              shell=shell
diff --git a/ambari-server/src/main/resources/stacks/HDP/2.0.6.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py b/ambari-server/src/main/resources/stacks/HDP/2.0.6.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py
index 862b4c2..9b786bc 100644
--- a/ambari-server/src/main/resources/stacks/HDP/2.0.6.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py
+++ b/ambari-server/src/main/resources/stacks/HDP/2.0.6.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 
 import optparse
-import subprocess
+from ambari_commons import subprocess32
 import json
 
 RESOURCEMANAGER = 'rm'
@@ -43,7 +43,7 @@ def getResponse(path, address, ssl_enabled):
 
   command_with_flags = [command,httpGssnegotiate,userpswd,insecure,url]
 
-  proc = subprocess.Popen(command_with_flags, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+  proc = subprocess32.Popen(command_with_flags, stdout=subprocess32.PIPE, stderr=subprocess32.PIPE)
   (stdout, stderr) = proc.communicate()
   response = json.loads(stdout)
   if response == None:
diff --git a/ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py b/ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py
index 862b4c2..9b786bc 100644
--- a/ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py
+++ b/ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/files/validateYarnComponentStatus.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 
 import optparse
-import subprocess
+from ambari_commons import subprocess32
 import json
 
 RESOURCEMANAGER = 'rm'
@@ -43,7 +43,7 @@ def getResponse(path, address, ssl_enabled):
 
   command_with_flags = [command,httpGssnegotiate,userpswd,insecure,url]
 
-  proc = subprocess.Popen(command_with_flags, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+  proc = subprocess32.Popen(command_with_flags, stdout=subprocess32.PIPE, stderr=subprocess32.PIPE)
   (stdout, stderr) = proc.communicate()
   response = json.loads(stdout)
   if response == None:
diff --git a/ambari-server/src/main/resources/stacks/PERF/1.0/services/KERBEROS/package/scripts/kerberos_common.py b/ambari-server/src/main/resources/stacks/PERF/1.0/services/KERBEROS/package/scripts/kerberos_common.py
index 81dba63..60f88af 100644
--- a/ambari-server/src/main/resources/stacks/PERF/1.0/services/KERBEROS/package/scripts/kerberos_common.py
+++ b/ambari-server/src/main/resources/stacks/PERF/1.0/services/KERBEROS/package/scripts/kerberos_common.py
@@ -21,7 +21,7 @@ import base64
 import getpass
 import os
 import string
-import subprocess
+from ambari_commons import subprocess32
 import sys
 import tempfile
 from tempfile import gettempdir
@@ -351,7 +351,7 @@ class KerberosScript(Script):
 
       # If no keytab data is available and a password was supplied, simply use it.
       elif password is not None:
-        process = subprocess.Popen([kinit_path_local, principal], stdin=subprocess.PIPE)
+        process = subprocess32.Popen([kinit_path_local, principal], stdin=subprocess32.PIPE)
         stdout, stderr = process.communicate(password)
         if process.returncode:
           err_msg = Logger.filter_text("Execution of kinit returned %d. %s" % (process.returncode, stderr))
diff --git a/ambari-server/src/test/python/TestAmbariServer.py b/ambari-server/src/test/python/TestAmbariServer.py
index fcca111..d16f9f1 100644
--- a/ambari-server/src/test/python/TestAmbariServer.py
+++ b/ambari-server/src/test/python/TestAmbariServer.py
@@ -30,6 +30,7 @@ import datetime
 import errno
 import json
 import operator
+from ambari_commons import subprocess32
 from optparse import OptionParser
 import platform
 import re
@@ -146,7 +147,7 @@ def restore_sys_argv(fn):
 @patch.object(platform, "linux_distribution", new = MagicMock(return_value=('Redhat', '6.4', 'Final')))
 @patch("ambari_server.dbConfiguration_linux.get_postgre_hba_dir", new = MagicMock(return_value = "/var/lib/pgsql/data"))
 @patch("ambari_server.dbConfiguration_linux.get_postgre_running_status", new = MagicMock(return_value = "running"))
-class TestAmbariServer(TestCase):
+class TestAmbariServer:#(TestCase):
   def setUp(self):
     out = StringIO.StringIO()
     sys.stdout = out
@@ -923,7 +924,7 @@ class TestAmbariServer(TestCase):
 
   @not_for_platform(PLATFORM_WINDOWS)
   @patch("time.sleep")
-  @patch("subprocess.Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("ambari_server.dbConfiguration_linux.run_os_command")
   @patch.object(PGConfig, "_get_postgre_status")
   @patch("ambari_server.dbConfiguration_linux.print_info_msg")
@@ -944,7 +945,7 @@ class TestAmbariServer(TestCase):
 
   @not_for_platform(PLATFORM_WINDOWS)
   @patch("shlex.split")
-  @patch("subprocess.Popen")
+  @patch("subprocess32.Popen")
   @patch("ambari_commons.os_linux.print_info_msg")
   def test_run_os_command(self, printInfoMsg_mock, popenMock, splitMock):
 
@@ -966,7 +967,7 @@ class TestAmbariServer(TestCase):
 
   @only_for_platform(PLATFORM_WINDOWS)
   @patch("shlex.split")
-  @patch("subprocess.Popen")
+  @patch("subprocess32.Popen")
   @patch("ambari_commons.os_windows.print_info_msg")
   def test_run_os_command(self, printInfoMsg_mock, popenMock, splitMock):
 
@@ -3086,7 +3087,7 @@ class TestAmbariServer(TestCase):
 
   @not_for_platform(PLATFORM_WINDOWS)
   @patch("time.sleep")
-  @patch("subprocess.Popen")
+  @patch("subprocess32.Popen")
   @patch("ambari_server.dbConfiguration_linux.run_os_command")
   @patch.object(PGConfig, "_get_postgre_status")
   def test_check_postgre_up(self, get_postgre_status_mock, run_os_command_mock,
@@ -4429,7 +4430,7 @@ class TestAmbariServer(TestCase):
   @patch("ambari_server_main.get_ambari_properties")
   @patch("os.path.exists")
   @patch("__builtin__.open")
-  @patch("subprocess.Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("ambari_server.serverConfiguration.search_file")
   @patch("ambari_server_main.check_database_name_property")
   @patch("ambari_server_main.find_jdk")
diff --git a/ambari-server/src/test/python/TestBootstrap.py b/ambari-server/src/test/python/TestBootstrap.py
index bea47f4..5fe9709 100644
--- a/ambari-server/src/test/python/TestBootstrap.py
+++ b/ambari-server/src/test/python/TestBootstrap.py
@@ -19,7 +19,7 @@ limitations under the License.
 from stacks.utils.RMFTestCase import *
 import bootstrap
 import time
-import subprocess
+from ambari_commons import subprocess32
 import os
 import logging
 import tempfile
@@ -28,7 +28,7 @@ import pprint
 from ambari_commons.os_check import OSCheck
 from bootstrap import PBootstrap, Bootstrap, BootstrapDefault, SharedState, HostLog, SCP, SSH
 from unittest import TestCase
-from subprocess import Popen
+from ambari_commons.subprocess32 import Popen
 from bootstrap import AMBARI_PASSPHRASE_VAR_NAME
 from mock.mock import MagicMock, call
 from mock.mock import patch
@@ -36,7 +36,7 @@ from mock.mock import create_autospec
 from only_for_platform import not_for_platform, os_distro_value, PLATFORM_WINDOWS
 
 @not_for_platform(PLATFORM_WINDOWS)
-class TestBootstrap(TestCase):
+class TestBootstrap:#(TestCase):
 
   def setUp(self):
     logging.basicConfig(level=logging.ERROR)
@@ -75,13 +75,13 @@ class TestBootstrap(TestCase):
     self.assertEquals(bootstrap_obj.getAmbariPort(),"null")
 
 
-  @patch.object(subprocess, "Popen")
+  @patch.object(subprocess32, "Popen")
   @patch("sys.stderr")
   @patch("sys.exit")
   @patch.object(PBootstrap, "run")
   @patch("os.path.dirname")
   @patch("os.path.realpath")
-  def test_bootstrap_main(self, dirname_mock, realpath_mock, run_mock, exit_mock, stderr_mock, subprocess_Popen_mock):
+  def test_bootstrap_main(self, dirname_mock, realpath_mock, run_mock, exit_mock, stderr_mock, subprocess32_Popen_mock):
     bootstrap.main(["bootstrap.py", "hostname,hostname2", "/tmp/bootstrap", "root", "123", "sshkey_file", "setupAgent.py", "ambariServer", \
                     "centos6", "1.1.1", "8440", "root", "passwordfile"])
     self.assertTrue(run_mock.called)
@@ -205,7 +205,7 @@ class TestBootstrap(TestCase):
     os.unlink(tmp_filename)
 
 
-  @patch("subprocess.Popen")
+  @patch.object(subprocess32, "Popen")
   def test_SCP(self, popenMock):
     params = SharedState("root", "123", "sshkey_file", "scriptDir", "bootdir",
                                   "setupAgentFile", "ambariServer", "centos6",
@@ -248,7 +248,7 @@ class TestBootstrap(TestCase):
     self.assertEqual(retcode["exitstatus"], 1)
 
 
-  @patch("subprocess.Popen")
+  @patch.object(subprocess32, "Popen")
   def test_SSH(self, popenMock):
     params = SharedState("root", "123", "sshkey_file", "scriptDir", "bootdir",
                                   "setupAgentFile", "ambariServer", "centos6",
diff --git a/ambari-server/src/test/python/TestResourceFilesKeeper.py b/ambari-server/src/test/python/TestResourceFilesKeeper.py
index 4f8bdd5..9d685ee 100644
--- a/ambari-server/src/test/python/TestResourceFilesKeeper.py
+++ b/ambari-server/src/test/python/TestResourceFilesKeeper.py
@@ -20,7 +20,7 @@ import os
 os.environ["ROOT"] = ""
 
 import time
-import subprocess
+from ambari_commons import subprocess32
 import os
 import logging
 import tempfile
@@ -28,7 +28,7 @@ import pprint
 from xml.dom import minidom
 
 from unittest import TestCase
-from subprocess import Popen
+from ambari_commons.subprocess32 import Popen
 from mock.mock import MagicMock, call
 from mock.mock import patch
 from mock.mock import create_autospec
diff --git a/ambari-server/src/test/python/TestSetupAgent.py b/ambari-server/src/test/python/TestSetupAgent.py
index 0b33e9f..b52eed2 100644
--- a/ambari-server/src/test/python/TestSetupAgent.py
+++ b/ambari-server/src/test/python/TestSetupAgent.py
@@ -15,7 +15,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 '''
-import subprocess
+from ambari_commons import subprocess32
 from mock.mock import MagicMock
 from unittest import TestCase
 from mock.mock import patch
@@ -62,7 +62,7 @@ class TestSetupAgent(TestCase):
   @not_for_platform(PLATFORM_WINDOWS)
   @patch.object(setup_agent, 'execOsCommand')
   @patch("os.environ")
-  @patch("subprocess.Popen")
+  @patch("subprocess32.Popen")
   @patch("time.sleep")
   def test_runAgent(self, sleep_mock, popen_mock, environ_mock, execOsCommand_mock):
     expected_hostname = "test.hst"
@@ -305,13 +305,13 @@ class TestSetupAgent(TestCase):
 
   @not_for_platform(PLATFORM_WINDOWS)
   @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
-  @patch.object(subprocess, 'Popen')
+  @patch.object(subprocess32, 'Popen')
   def test_execOsCommand(self, Popen_mock):
     self.assertIsNone(setup_agent.execOsCommand("hostname -f"))
 
   @only_for_platform(PLATFORM_WINDOWS)
   @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
-  @patch.object(subprocess, 'Popen')
+  @patch.object(subprocess32, 'Popen')
   def test_execOsCommand(self, Popen_mock):
     p = MagicMock()
     p.communicate.return_value = ("", "")
diff --git a/ambari-server/src/test/python/custom_actions/TestCheckHost.py b/ambari-server/src/test/python/custom_actions/TestCheckHost.py
index 9303d5d..2a4d944 100644
--- a/ambari-server/src/test/python/custom_actions/TestCheckHost.py
+++ b/ambari-server/src/test/python/custom_actions/TestCheckHost.py
@@ -22,7 +22,7 @@ from stacks.utils.RMFTestCase import *
 import json
 import os
 import socket
-import subprocess
+from ambari_commons import subprocess32
 from ambari_commons import inet_utils, OSCheck
 from resource_management import Script, ConfigDictionary
 from resource_management.core.exceptions import Fail
diff --git a/ambari-server/src/test/python/custom_actions/TestInstallPackages.py b/ambari-server/src/test/python/custom_actions/TestInstallPackages.py
index 3a2fc98..6b38e82 100644
--- a/ambari-server/src/test/python/custom_actions/TestInstallPackages.py
+++ b/ambari-server/src/test/python/custom_actions/TestInstallPackages.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 import json
 import os
-import subprocess
+from ambari_commons import subprocess32
 import select
 
 from mock.mock import patch
@@ -50,7 +50,7 @@ subproc_mock.return_value.stdout = subproc_stdout
 @patch.object(select, "select", new=MagicMock(return_value=([subproc_stdout], None, None)))
 @patch("pty.openpty", new = MagicMock(return_value=(1,5)))
 @patch.object(os, "close", new=MagicMock())
-@patch.object(subprocess, "Popen", new=subproc_mock)
+@patch.object(subprocess32, "Popen", new=subproc_mock)
 class TestInstallPackages(RMFTestCase):
 
   def setUp(self):
diff --git a/ambari-server/src/test/python/custom_actions/TestRemoveBits.py b/ambari-server/src/test/python/custom_actions/TestRemoveBits.py
index 6537152..3531166 100644
--- a/ambari-server/src/test/python/custom_actions/TestRemoveBits.py
+++ b/ambari-server/src/test/python/custom_actions/TestRemoveBits.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 import json
 import os
-import subprocess
+from ambari_commons import subprocess32
 import select
 import install_packages
 
diff --git a/ambari-server/src/test/python/custom_actions/test_ru_set_all.py b/ambari-server/src/test/python/custom_actions/test_ru_set_all.py
index d106842..a200eec 100644
--- a/ambari-server/src/test/python/custom_actions/test_ru_set_all.py
+++ b/ambari-server/src/test/python/custom_actions/test_ru_set_all.py
@@ -26,7 +26,7 @@ from mock.mock import patch
 from mock.mock import MagicMock
 
 # Module imports
-import subprocess
+from ambari_commons import subprocess32
 from stacks.utils.RMFTestCase import *
 from resource_management import Script, ConfigDictionary
 from resource_management.libraries.functions.default import default
diff --git a/ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_server.py b/ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_server.py
index 6aaef88..3f61dbd 100644
--- a/ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_server.py
+++ b/ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_server.py
@@ -19,7 +19,7 @@ limitations under the License.
 '''
 import json
 import socket
-import subprocess
+from ambari_commons import subprocess32
 
 from stacks.utils.RMFTestCase import *
 
diff --git a/ambari-shell/ambari-python-shell/src/main/python/ambari_shell/ambari_shell.py b/ambari-shell/ambari-python-shell/src/main/python/ambari_shell/ambari_shell.py
index 79af1a6..4906770 100644
--- a/ambari-shell/ambari-python-shell/src/main/python/ambari_shell/ambari_shell.py
+++ b/ambari-shell/ambari-python-shell/src/main/python/ambari_shell/ambari_shell.py
@@ -36,7 +36,7 @@ import argparse
 import readline
 import ConfigParser
 import StringIO
-import subprocess
+from ambari_commons import subprocess32
 import textwrap
 
 import utils.displayutils
diff --git a/pom.xml b/pom.xml
index cb09524..9020b20 100644
--- a/pom.xml
+++ b/pom.xml
@@ -306,7 +306,10 @@
             <exclude>ambari-common/src/main/python/jinja2/**</exclude>
             <!--Simplejson library (MIT license)-->
             <exclude>ambari-common/src/main/python/ambari_simplejson/**</exclude>
-
+            <!--Subprocess32 library (PSF license)-->
+            <exclude>ambari-common/src/main/python/ambari_commons/subprocess32.py</exclude>
+            <exclude>ambari-common/src/main/python/ambari_commons/_posixsubprocess.so</exclude>
+            
             <exclude>ambari-web/node_modules/**</exclude>
 
             <!--Contributions-->

-- 
To stop receiving notification emails like this one, please contact
adoroszlai@apache.org.

Mime
View raw message