示例#1
0
def check_mk_local_automation(command, args=None, indata="", stdin_data=None, timeout=None):
    if args is None:
        args = []

    auto_logger = logger.getChild("automations")

    if timeout:
        args = ["--timeout", "%d" % timeout] + args

    cmd = ['check_mk', '--automation', command, '--'] + args
    if command in ['restart', 'reload']:
        call_hook_pre_activate_changes()

    cmd = [make_utf8(a) for a in cmd]
    try:
        # This debug output makes problems when doing bulk inventory, because
        # it garbles the non-HTML response output
        # if config.debug:
        #     html.write("<div class=message>Running <tt>%s</tt></div>\n" % subprocess.list2cmdline(cmd))
        auto_logger.info("RUN: %s" % subprocess.list2cmdline(cmd))
        p = subprocess.Popen(cmd,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=True)
    except Exception as e:
        raise _local_automation_failure(command=command, cmdline=cmd, exc=e)

    if stdin_data is not None:
        auto_logger.info("STDIN: %r" % stdin_data)
        p.stdin.write(stdin_data)
    else:
        auto_logger.info("STDIN: %r" % indata)
        p.stdin.write(repr(indata))

    p.stdin.close()
    outdata = p.stdout.read()
    exitcode = p.wait()
    auto_logger.info("FINISHED: %d" % exitcode)
    auto_logger.debug("OUTPUT: %r" % outdata)
    errdata = p.stderr.read()
    if errdata:
        auto_logger.warning("'%s' returned '%s'" % (" ".join(cmd), errdata))
    if exitcode != 0:
        auto_logger.error("Error running %r (exit code %d)" %
                          (subprocess.list2cmdline(cmd), exitcode))
        raise _local_automation_failure(command=command,
                                        cmdline=cmd,
                                        code=exitcode,
                                        out=outdata,
                                        err=errdata)

    # On successful "restart" command execute the activate changes hook
    if command in ['restart', 'reload']:
        call_hook_activate_changes()

    try:
        return ast.literal_eval(outdata)
    except SyntaxError as e:
        raise _local_automation_failure(command=command, cmdline=cmd, out=outdata, exc=e)
示例#2
0
 def myworker():
     # type: () -> None
     log = logger.getChild("SnapshotWorker(%d)" % os.getpid())
     try:
         self._generate_snapshot(*args, **kwargs)
     except Exception:
         log.error("Error in subprocess")
         log.error(traceback.format_exc())
示例#3
0
 def myworker():
     # type: () -> None
     log = logger.getChild("SnapshotWorker(%d)" % os.getpid())
     try:
         self._generate_snapshot(snapshot_work_dir, target_filepath, generic_components,
                                 custom_components, reuse_identical_snapshots)
     except Exception:
         log.error("Error in subprocess")
         log.error(traceback.format_exc())
示例#4
0
    def __init__(self, work_dir, args, kwargs):
        # type: (str, Tuple, Dict) -> None
        multiprocessing.Process.__init__(self,
                                         target=self._generate_snapshot,
                                         args=args,
                                         kwargs=kwargs)
        SnapshotCreationBase.__init__(self, work_dir)

        self.daemon = True
        self._logger = logger.getChild("SnapshotWorker(%d)" % os.getpid())
示例#5
0
    def __init__(self, activation_work_dir: str) -> None:
        super().__init__()
        self._logger = logger.getChild("SnapshotCreationBase")
        self._multitar_workdir = os.path.join(activation_work_dir, "multitar_workdir")
        self._rsync_target_dir = os.path.join(self._multitar_workdir, "synced_files")
        self._tarfile_dir = os.path.join(self._multitar_workdir, "subtars")

        self._available_snapshots: Dict[Tuple[str, ...], str] = {}

        # Debugging stuff
        self._statistics_rsync: List[str] = []
        self._statistics_tar: Dict[str, List[str]] = {}
示例#6
0
    def __init__(self, work_dir):
        super(SnapshotCreationBase, self).__init__()
        self._logger = logger.getChild("SnapshotCreationBase")
        self._work_dir = work_dir
        self._multitar_workdir = os.path.join(self._work_dir, "multitar_workdir")
        self._rsync_target_dir = os.path.join(self._multitar_workdir, "synced_files")
        self._tarfile_dir = os.path.join(self._multitar_workdir, "subtars")

        self._available_snapshots = {}

        # Debugging stuff
        self._statistics = {"rsync": [], "tar": {}}
示例#7
0
    def __init__(self, work_dir):
        # type: (str) -> None
        super(SnapshotCreationBase, self).__init__()
        self._logger = logger.getChild("SnapshotCreationBase")
        self._work_dir = work_dir
        self._multitar_workdir = os.path.join(self._work_dir, "multitar_workdir")
        self._rsync_target_dir = os.path.join(self._multitar_workdir, "synced_files")
        self._tarfile_dir = os.path.join(self._multitar_workdir, "subtars")

        self._available_snapshots = {}  # type: Dict[Tuple[str, ...], str]

        # Debugging stuff
        self._statistics_rsync = []  # type: List[Text]
        self._statistics_tar = {}  # type: Dict[str, List[str]]
 def __init__(self):
     super(ModeAnalyzeConfig, self).__init__()
     self._logger = logger.getChild("analyze-config")
     self._acks = self._load_acknowledgements()
示例#9
0
import cmk.gui.utils as utils
from cmk.gui.log import logger
import cmk.gui.i18n
import cmk.gui.mobile
from cmk.gui.http import Request
from cmk.gui.pages import page_registry, Page
from cmk.gui.i18n import _
from cmk.gui.globals import html, local, request as global_request
from cmk.gui.htmllib import HTML
from cmk.gui.breadcrumb import Breadcrumb

from cmk.gui.exceptions import HTTPRedirect, MKInternalError, MKAuthException, MKUserError, FinalizeRequest

from cmk.gui.utils.urls import makeuri

auth_logger = logger.getChild("auth")


@contextlib.contextmanager
def authenticate(request: Request) -> Iterator[bool]:
    """Perform the user authentication

    This is called by index.py to ensure user
    authentication and initialization of the user related data structures.

    Initialize the user session with the mod_python provided request object.
    The user may have configured (basic) authentication by the web server. In
    case a user is provided, we trust that user and assume it as authenticated.

    Otherwise we check / ask for the cookie authentication or eventually the
    automation secret authentication."""
示例#10
0
import cmk.gui.gui_background_job as gui_background_job
import cmk.gui.hooks as hooks
import cmk.gui.utils.escaping as escaping
from cmk.gui.background_job import BackgroundProcessInterface
from cmk.gui.exceptions import MKGeneralException, MKUserError
from cmk.gui.globals import config, request
from cmk.gui.i18n import _
from cmk.gui.log import logger
from cmk.gui.sites import get_site_config, site_is_local
from cmk.gui.utils.urls import urlencode_vars
from cmk.gui.watolib.automation_commands import automation_command_registry, AutomationCommand
from cmk.gui.watolib.sites import SiteManagementFactory
from cmk.gui.watolib.utils import mk_repr
from cmk.gui.watolib.wato_background_job import WatoBackgroundJob

auto_logger = logger.getChild("automations")

# Disable python warnings in background job output or logs like "Unverified
# HTTPS request is being made". We warn the user using analyze configuration.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class MKAutomationException(MKGeneralException):
    pass


def check_mk_automation(siteid: SiteId,
                        command: str,
                        args: Optional[Sequence[str]] = None,
                        indata: Any = "",
                        stdin_data: Optional[str] = None,
示例#11
0
 def __init__(self, work_dir):
     super(SnapshotWorkerSubprocess, self).__init__(work_dir)
     self._logger = logger.getChild("SnapshotWorker(%d)" % os.getpid())
示例#12
0
 def __init__(self):
     super(ConfigDomainOMD, self).__init__()
     self._logger = logger.getChild("config.omd")
示例#13
0
 def __init__(self):
     super().__init__()
     self._logger = logger.getChild("config.omd")
示例#14
0
 def __init__(self) -> None:
     super().__init__()
     self._logger: logging.Logger = logger.getChild("config.omd")
示例#15
0
 def __init__(self) -> None:
     super().__init__()
     self._logger = logger.getChild("analyze-config")
     self._acks = self._load_acknowledgements()