Example #1
0
def create_url_map():
    """Instantiate all WSGI Apps and put them into the URL-Map."""
    _api_app = CheckmkApiApp(
        __name__,
        specification_dir=openapi_spec_dir(),
    )
    # NOTE
    # The URL will always contain the most up to date major version number, so that clients
    # exploring the API (browsers, etc.) will have a structural stability guarantee. Within major
    # versions only additions of fields or endpoints are allowed, never field changes or removals.
    # If a new major version is created it should be ADDED here and not replace the older version.
    # NOTE: v0 means totally unstable until we hit v1.
    _api_app.add_api_blueprint(
        'checkmk.yaml',
        base_path='/%s/check_mk/api/v0/' % cmk.omd_site(),
        validate_responses=True,
    )

    wrapped_api_app = OverrideRequestMethod(_api_app)
    cmk_app = CheckmkApp()

    return Map([
        Submount('/<string:site>', [
            Submount("/check_mk", [
                Rule("/", endpoint=cmk_app),
                Rule("/dump.py", endpoint=dump_environ_app),
                Submount('/api', [
                    Rule("/", endpoint=wrapped_api_app),
                    Rule("/<path:path>", endpoint=wrapped_api_app),
                ]),
                Rule("/<string:script>", endpoint=cmk_app),
            ]),
        ])
    ])
Example #2
0
    def __init__(self, config):
        super(AggregationRawdataGenerator, self).__init__()
        self._config = config

        self._credentials = config["credentials"]
        if self._credentials == "automation":
            self._username = self._credentials

            secret_file_path = Path(
                cmk.utils.paths.var_dir
            ) / "web" / self._username / "automation.secret"

            with secret_file_path.open(encoding="utf-8") as f:
                self._secret = f.read()
        else:
            self._username, self._secret = self._credentials[1]

        site_config = config["site"]

        if site_config == "local":
            self._site_url = "http://localhost:%d/%s" % (
                cmk.utils.site.get_apache_port(), cmk.omd_site())
        else:
            self._site_url = site_config[1]

        self._errors = []
Example #3
0
def event_match_site(rule, context):
    if "match_site" not in rule:
        return

    required_site_ids = rule["match_site"]

    # Fallback to local site ID in case there is none in the context
    site_id = context.get("OMD_SITE", cmk.omd_site())

    if site_id not in required_site_ids:
        return "The site '%s' is not in the required sites list: %s" % \
                        (site_id, ",".join(required_site_ids))
Example #4
0
def search(user=None, token_info=None):
    return {
        "site": cmk.omd_site(),
        "group": request.environ.get('mod_wsgi.application_group', 'unknown'),
        "versions": {
            "apache": request.environ.get('apache.version', 'unknown'),
            "checkmk": cmk.omd_version(),
            "python": sys.version,
            'mod_wsgi': request.environ.get('mod_wsgi.version', 'unknown'),
            'wsgi': request.environ['wsgi.version'],
        },
        "edition": cmk.edition_short(),
        "demo": cmk.is_demo(),
    }
Example #5
0
def search(param):
    if request.args.get('fail'):
        raise Exception("This is an intentional failure.")
    return {
        "site": cmk.omd_site(),
        "group": request.environ.get('mod_wsgi.application_group', 'unknown'),
        "versions": {
            "apache": request.environ.get('apache.version', 'unknown'),
            "checkmk": cmk.omd_version(),
            "python": sys.version,
            'mod_wsgi': request.environ.get('mod_wsgi.version', 'unknown'),
            'wsgi': request.environ['wsgi.version'],
        },
        "edition": cmk.edition_short(),
        "demo": cmk.is_demo(),
    }
Example #6
0
def complete_raw_context(raw_context, with_dump):
    # type: (EventContext, bool) -> None
    """Extend the raw notification context

    This ensures that all raw contexts processed in the notification code has specific variables
    set. Add a few further helper variables that are useful in notification and alert plugins.

    Please not that this is not only executed on the source system. When notifications are
    forwarded to another site and the analysis is executed on that site, this function will be
    executed on the central site. So be sure not to overwrite site specific things.
    """

    raw_keys = list(raw_context)

    try:
        raw_context["WHAT"] = "SERVICE" if raw_context.get("SERVICEDESC") else "HOST"

        raw_context.setdefault("MONITORING_HOST", socket.gethostname())
        raw_context.setdefault("OMD_ROOT", cmk.utils.paths.omd_root)
        raw_context.setdefault("OMD_SITE", cmk.omd_site())

        # The Check_MK Micro Core sends the MICROTIME and no other time stamps. We add
        # a few Nagios-like variants in order to be compatible
        if "MICROTIME" in raw_context:
            microtime = int(raw_context["MICROTIME"])
            timestamp = float(microtime) / 1000000.0
            broken = time.localtime(timestamp)
            raw_context["DATE"] = time.strftime("%Y-%m-%d", broken)
            raw_context["SHORTDATETIME"] = time.strftime("%Y-%m-%d %H:%M:%S", broken)
            raw_context["LONGDATETIME"] = time.strftime("%a %b %d %H:%M:%S %Z %Y", broken)
        elif "MICROTIME" not in raw_context:
            # In case the microtime is not provided, e.g. when using Nagios, then set it here
            # from the current time. We could look for "LONGDATETIME" and calculate the timestamp
            # from that one, but we try to keep this simple here.
            raw_context["MICROTIME"] = "%d" % (time.time() * 1000000)

        url_host_view = 'view.py?view_name=hoststatus&host=%s&site=%s' % (raw_context['HOSTNAME'],
                                                                          raw_context['OMD_SITE'])
        raw_context['HOSTURL'] = '/check_mk/index.py?start_url=%s' % quote(url_host_view)

        if raw_context['WHAT'] == 'SERVICE':
            url_service_view = 'view.py?view_name=service&host=%s&service=%s&site=%s' % (
                raw_context['HOSTNAME'], raw_context['SERVICEDESC'], raw_context['OMD_SITE'])
            raw_context['SERVICEURL'] = '/check_mk/index.py?start_url=%s' % quote(url_service_view)

        # Relative Timestamps for several macros
        for macro in [
                'LASTHOSTSTATECHANGE', 'LASTSERVICESTATECHANGE', 'LASTHOSTUP', 'LASTSERVICEOK'
        ]:
            if macro in raw_context:
                raw_context[macro + '_REL'] = get_readable_rel_date(raw_context[macro])

        # Rule based notifications enabled? We might need to complete a few macros
        contact = raw_context.get("CONTACTNAME")
        if not contact or contact == "check-mk-notify":
            add_rulebased_macros(raw_context)

        # For custom notifications the number is set to 0 by the core (Nagios and CMC). We force at least
        # number 1 here, so that rules with conditions on numbers do not fail (the minimum is 1 here)
        for key in ["HOSTNOTIFICATIONNUMBER", "SERVICENOTIFICATIONNUMBER"]:
            if key in raw_context and raw_context[key] == "0":
                if with_dump:
                    logger.info("Setting %s for notification from '0' to '1'", key)
                raw_context[key] = "1"

        # Add the previous hard state. This is neccessary for notification rules that depend on certain transitions,
        # like OK -> WARN (but not CRIT -> WARN). The CMC sends PREVIOUSHOSTHARDSTATE and PREVIOUSSERVICEHARDSTATE.
        # Nagios does not have this information and we try to deduct this.
        if "PREVIOUSHOSTHARDSTATE" not in raw_context and "LASTHOSTSTATE" in raw_context:
            prev_state = raw_context["LASTHOSTSTATE"]
            # When the attempts are > 1 then the last state could be identical with
            # the current one, e.g. both critical. In that case we assume the
            # previous hard state to be OK.
            if prev_state == raw_context["HOSTSTATE"]:
                prev_state = "UP"
            elif "HOSTATTEMPT" not in raw_context or \
                ("HOSTATTEMPT" in raw_context and raw_context["HOSTATTEMPT"] != "1"):
                # Here We do not know. The transition might be OK -> WARN -> CRIT and
                # the initial OK is completely lost. We use the artificial state "?"
                # here, which matches all states and makes sure that when in doubt a
                # notification is being sent out. But when the new state is UP, then
                # we know that the previous state was a hard state (otherwise there
                # would not have been any notification)
                if raw_context["HOSTSTATE"] != "UP":
                    prev_state = "?"
                logger.info("Previous host hard state not known. Allowing all states.")
            raw_context["PREVIOUSHOSTHARDSTATE"] = prev_state

        # Same for services
        if raw_context["WHAT"] == "SERVICE" and "PREVIOUSSERVICEHARDSTATE" not in raw_context:
            prev_state = raw_context["LASTSERVICESTATE"]
            if prev_state == raw_context["SERVICESTATE"]:
                prev_state = "OK"
            elif "SERVICEATTEMPT" not in raw_context or \
                ("SERVICEATTEMPT" in raw_context and raw_context["SERVICEATTEMPT"] != "1"):
                if raw_context["SERVICESTATE"] != "OK":
                    prev_state = "?"
                logger.info("Previous service hard state not known. Allowing all states.")
            raw_context["PREVIOUSSERVICEHARDSTATE"] = prev_state

        # Add short variants for state names (at most 4 characters)
        for key, value in list(raw_context.items()):
            if key.endswith("STATE"):
                raw_context[key[:-5] + "SHORTSTATE"] = value[:4]

        if raw_context["WHAT"] == "SERVICE":
            raw_context['SERVICEFORURL'] = quote(raw_context['SERVICEDESC'])
        raw_context['HOSTFORURL'] = quote(raw_context['HOSTNAME'])

        convert_context_to_unicode(raw_context)

    except Exception as e:
        logger.info("Error on completing raw context: %s", e)

    if with_dump:
        log_context = "\n".join(
            sorted([
                "                    %s=%s" % (k, raw_context[k])
                for k in raw_context
                if k not in raw_keys
            ]))
        logger.info("Computed variables:\n%s", log_context)
Example #7
0
def url_prefix():
    # type: () -> str
    return "/%s/" % cmk.omd_site()
Example #8
0
def omd_site():
    # type: () -> SiteId
    return cmk.omd_site()
Example #9
0
def omd_site():
    # type: () -> SiteId
    return SiteId(bytes(cmk.omd_site()))
Example #10
0
def url_prefix():
    return "/%s/" % cmk.omd_site()
Example #11
0
def omd_site():
    return cmk.omd_site()