Skip to content
Permalink
Browse files

subprocess.Popen -> cmk.utils.cmk_subprocess.Popen (3)

Change-Id: I821fc91ea577c75e4dbf1ec808cb7f08a7c1c270
  • Loading branch information
si-23 committed Nov 18, 2019
1 parent 5e365a5 commit 7631b1dc891183ae3793c59ebc739d9b0b34cf70
@@ -170,14 +170,20 @@ def init_auth():
if auth_mode == 'kerberos':
from requests_kerberos import HTTPKerberosAuth # type: ignore

from subprocess import Popen, PIPE
kinit = Popen(["kinit", username], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, errors = kinit.communicate("%s\n" % password)
import cmk.utils.cmk_subprocess as subprocess
kinit = subprocess.Popen(
["kinit", username],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
stdout, stderr = kinit.communicate(input=("%s\n" % password).decode("utf-8"))
kinit.wait()
if kinit.returncode or errors:
if kinit.returncode or stderr:
sys.stderr.write("Error getting Kerberos Ticket:\n")
sys.stderr.write("stdout: %s\nstderr: %s\nrc: %s" %
(output, errors, kinit.returncode))
msg = "stdout: %s\nstderr: %s\nrc: %s" % (stdout, stderr, kinit.returncode)
sys.stderr.write(msg.encode("utf-8"))
sys.exit(1)

auth_obj = HTTPKerberosAuth(principal=username)
@@ -25,7 +25,6 @@
# Boston, MA 02110-1301 USA.

import os
import subprocess
import time

import six
@@ -34,7 +33,7 @@
import cmk.utils.debug
import cmk.utils.defines
from cmk.utils.log import VERBOSE
from cmk.utils.encoding import make_utf8
import cmk.utils.cmk_subprocess as subprocess
import livestatus

#.
@@ -176,21 +175,24 @@ def _send_email(config, to, subject, body, logger):
if config["debug_rules"]:
logger.info(" Executing: %s" % " ".join(command_utf8))

p = subprocess.Popen(command_utf8,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
p = subprocess.Popen(
command_utf8,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
encoding="utf-8",
)
# FIXME: This may lock on too large buffer. We should move all "mail sending" code
# to a general place and fix this for all our components (notification plugins,
# notify.py, this one, ...)
stdout_txt, stderr_txt = p.communicate(body.encode("utf-8"))
stdout, stderr = p.communicate(input=body)
exitcode = p.returncode

logger.info(' Exitcode: %d' % exitcode)
if exitcode != 0:
logger.info(" Error: Failed to send the mail.")
for line in (stdout_txt + stderr_txt).splitlines():
for line in (stdout + stderr).splitlines():
logger.info(" Output: %s" % line.rstrip())
return False

@@ -216,11 +218,12 @@ def _execute_script(event_columns, body, event, logger):
stderr=subprocess.STDOUT,
close_fds=True,
env=script_env,
encoding="utf-8",
)
output = p.communicate(body.encode('utf-8'))[0]
stdout, _stderr = p.communicate(input=body)
logger.info(' Exit code: %d' % p.returncode)
if output:
logger.info(' Output: \'%s\'' % output)
if stdout:
logger.info(' Output: \'%s\'' % stdout)


def _get_event_tags(event_columns, event):
@@ -288,20 +291,23 @@ def do_notify(event_server, logger, event, username=None, is_cancelling=False):
return

# Send notification context via stdin.
context_string = make_utf8("".join([
context_string = "".join([
"%s=%s\n" % (varname, value.replace("\n", "\\n"))
for (varname, value) in context.iteritems()
]))

p = subprocess.Popen(["cmk", "--notify", "stdin"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True)
response = p.communicate(input=context_string)[0]
])

p = subprocess.Popen(
["cmk", "--notify", "stdin"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
encoding="utf-8",
)
stdout, _stderr = p.communicate(input=context_string)
status = p.returncode
if status:
logger.error("Error notifying via Check_MK: %s" % response.strip())
logger.error("Error notifying via Check_MK: %s" % stdout.strip())
else:
logger.info("Successfully forwarded notification for event %d to Check_MK" % event["id"])

@@ -26,10 +26,10 @@

import os
import time
import subprocess
from typing import Dict, Any # pylint: disable=unused-import

import cmk.utils.store as store
import cmk.utils.cmk_subprocess as subprocess

import cmk.gui.pages
import cmk.gui.utils as utils
@@ -379,21 +379,24 @@ def notify_mail(user_id, msg):
_('No UTF-8 encoding found in your locale -a! Please provide C.UTF-8 encoding.'))

try:
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
close_fds=True)
p = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
close_fds=True,
encoding="utf-8",
)
except OSError as e:
raise MKInternalError(
_('Mail could not be delivered. '
'Failed to execute command "%s": %s') % (" ".join(command), e))

output = p.communicate(body.encode("utf-8"))[0]
stdout, _stderr = p.communicate(input=body)
exitcode = p.returncode
if exitcode != 0:
raise MKInternalError(
_('Mail could not be delivered. Exit code of command is %r. '
'Output is: %s') % (exitcode, output))
'Output is: %s') % (exitcode, stdout))
else:
return True
@@ -29,13 +29,12 @@
import os
import re
import signal
import subprocess
import traceback
from pathlib2 import Path

import cmk
import cmk.utils.store as store
from cmk.utils.encoding import make_utf8
import cmk.utils.cmk_subprocess as subprocess

import cmk.gui.hooks as hooks
import cmk.gui.config as config
@@ -361,12 +360,15 @@ def activate(self):

self._logger.debug("Executing \"omd config change\"")
self._logger.debug(" Commands: %r" % config_change_commands)
p = subprocess.Popen(["omd", "config", "change"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
close_fds=True)
stdout = p.communicate(make_utf8("\n".join(config_change_commands)))[0]
p = subprocess.Popen(
["omd", "config", "change"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
close_fds=True,
encoding="utf-8",
)
stdout, _stderr = p.communicate(input="\n".join(config_change_commands))
self._logger.debug(" Exit code: %d" % p.returncode)
self._logger.debug(" Output: %r" % stdout)
if p.returncode != 0:
@@ -25,7 +25,6 @@

import os
import re
import subprocess
import sys
from html import escape as html_escape # type: ignore
from typing import ( # pylint: disable=unused-import
@@ -35,6 +34,7 @@

from cmk.utils.notify import find_wato_folder
import cmk.utils.password_store
import cmk.utils.cmk_subprocess as subprocess


def collect_context():
@@ -168,11 +168,14 @@ def send_mail_sendmail(m, target, from_address):
cmd += ["-i", target.encode("utf-8")]

try:
p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
p = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
)
except OSError:
raise Exception("Failed to send the mail: /usr/sbin/sendmail is missing")

p.communicate(m.as_string())
p.communicate(input=m.as_string())
if p.returncode != 0:
raise Exception("sendmail returned with exit code: %d" % p.returncode)

@@ -28,7 +28,6 @@
import errno
import glob
import os
import subprocess
import sys
import time
import shutil
@@ -43,6 +42,7 @@
from cmk.utils.labels import DiscoveredHostLabelsStore
from cmk.utils.exceptions import MKGeneralException
from cmk.utils.encoding import convert_to_unicode
import cmk.utils.cmk_subprocess as subprocess

import cmk_base.utils
import cmk_base.config as config
@@ -549,12 +549,14 @@ def _rename_host_in_core_history_files(self, file_paths, oldname, newname):
handled_files = []

command = ["sed", "-ri", "--file=/dev/fd/0"]
p = subprocess.Popen(command + file_paths,
stdin=subprocess.PIPE,
stdout=open(os.devnull, "w"),
stderr=subprocess.STDOUT,
close_fds=True)
p.communicate(sed_commands)
p = subprocess.Popen(
command + file_paths,
stdin=subprocess.PIPE,
stdout=open(os.devnull, "w"),
stderr=subprocess.STDOUT,
close_fds=True,
)
p.communicate(input=sed_commands)
# TODO: error handling?

handled_files += file_paths
@@ -31,6 +31,7 @@
import abc
import logging
import sys
from typing import Text # pylint: disable=unused-import
import six

import cmk.utils.log # TODO: Remove this!
@@ -42,7 +43,10 @@
import cmk.utils.store as store
import cmk.utils.tty as tty
from cmk.utils.exceptions import MKGeneralException, MKTerminate, MKTimeout
from cmk.utils.encoding import convert_to_unicode
from cmk.utils.encoding import (
convert_to_unicode,
ensure_bytestr,
)

import cmk_base.utils
import cmk_base.agent_simulator
@@ -269,7 +273,8 @@ def _from_cache_file(self, raw_data):
return raw_data

def _to_cache_file(self, raw_data):
return raw_data
# type: (Text) -> bytes
return ensure_bytestr(raw_data)

@abc.abstractmethod
def _convert_to_sections(self, raw_data):
@@ -26,12 +26,13 @@

import os
import signal
import subprocess
import collections
from pathlib2 import Path

import cmk.utils.paths
from cmk.utils.exceptions import MKTimeout
import cmk.utils.cmk_subprocess as subprocess
from cmk.utils.encoding import ensure_unicode

import cmk_base.config as config
import cmk_base.core_config as core_config
@@ -75,7 +76,9 @@ def _get_agent_info_program(self, commandline, command_stdin):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=os.setsid,
close_fds=True)
close_fds=True,
encoding="utf-8",
)
else:
# We can not create a separate process group when running Nagios
# Upon reaching the service_check_timeout Nagios only kills the process
@@ -86,9 +89,16 @@ def _get_agent_info_program(self, commandline, command_stdin):
stdin=subprocess.PIPE if command_stdin else open(os.devnull),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
stdout, stderr = p.communicate(input=command_stdin)
close_fds=True,
encoding="utf-8",
)

if command_stdin:
stdout, stderr = p.communicate(input=ensure_unicode(command_stdin))
else:
stdout, stderr = p.communicate()
exitstatus = p.returncode

except MKTimeout:
# On timeout exception try to stop the process to prevent child process "leakage"
if p:

0 comments on commit 7631b1d

Please sign in to comment.
You can’t perform that action at this time.