Exemplo n.º 1
0
 def activate(self):
     if getattr(config, "mkeventd_enabled", False):
         mkeventd.execute_command("RELOAD", site=omd_site())
         log_audit("mkeventd-activate",
                   _("Activated changes of event console configuration"))
         if hooks.registered('mkeventd-activate-changes'):
             hooks.call("mkeventd-activate-changes")
Exemplo n.º 2
0
def _create_nagvis_backends(sites_config):
    cfg = [
        "; MANAGED BY CHECK_MK WATO - Last Update: %s" %
        time.strftime("%Y-%m-%d %H:%M:%S"),
    ]
    for site_id, site in sites_config.items():
        if site == omd_site():
            continue  # skip local site, backend already added by omd

        socket = _encode_socket_for_nagvis(site_id, site)

        cfg += [
            "",
            "[backend_%s]" % site_id,
            'backendtype="mklivestatus"',
            'socket="%s"' % socket,
        ]

        if site.get("status_host"):
            cfg.append('statushost="%s"' % ":".join(site["status_host"]))

        if site["proxy"] is None and is_livestatus_encrypted(site):
            address_spec = site["socket"][1]
            tls_settings = address_spec["tls"][1]
            cfg.append("verify_tls_peer=%d" % tls_settings["verify"])
            cfg.append("verify_tls_ca_path=%s" %
                       ConfigDomainCACertificates.trusted_cas_file)

    store.save_text_to_file(
        "%s/etc/nagvis/conf.d/cmk_backends.ini.php" % cmk.utils.paths.omd_root,
        "\n".join(cfg))
Exemplo n.º 3
0
    def _automation_push_profile(self):
        site_id = request.var("siteid")
        if not site_id:
            raise MKGeneralException(_("Missing variable siteid"))

        user_id = request.var("user_id")
        if not user_id:
            raise MKGeneralException(_("Missing variable user_id"))

        our_id = omd_site()

        if our_id is not None and our_id != site_id:
            raise MKGeneralException(
                _("Site ID mismatch. Our ID is '%s', but you are saying we are '%s'."
                  ) % (our_id, site_id))

        profile = request.var("profile")
        if not profile:
            raise MKGeneralException(
                _("Invalid call: The profile is missing."))

        users = userdb.load_users(lock=True)
        users[UserId(user_id)] = watolib.mk_eval(profile)
        userdb.save_users(users)

        return True
Exemplo n.º 4
0
    def delete_site(cls, site_id):
        # TODO: Clean this up
        from cmk.gui.watolib.hosts_and_folders import Folder
        all_sites = cls.load_sites()
        if site_id not in all_sites:
            raise MKUserError(
                None,
                _("Unable to delete unknown site id: %s") % site_id)

        # Make sure that site is not being used by hosts and folders
        if site_id in Folder.root_folder().all_site_ids():
            search_url = makeactionuri(request, transactions, [
                ("host_search_change_site", "on"),
                ("host_search_site", site_id),
                ("host_search", "1"),
                ("folder", ""),
                ("mode", "search"),
                ("filled_in", "edit_host"),
            ])
            raise MKUserError(
                None,
                _("You cannot delete this connection. It has folders/hosts "
                  "assigned to it. You can use the <a href=\"%s\">host "
                  "search</a> to get a list of the hosts.") % search_url)

        domains = cls._affected_config_domains()

        del all_sites[site_id]
        cls.save_sites(all_sites)
        cmk.gui.watolib.activate_changes.clear_site_replication_status(site_id)
        cmk.gui.watolib.changes.add_change("edit-sites",
                                           _("Deleted site %s") % site_id,
                                           domains=domains,
                                           sites=[omd_site()])
Exemplo n.º 5
0
    def __init__(self, config):
        super().__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(),
                omd_site(),
            )
        else:
            self._site_url = site_config[1]

        self._errors = []
Exemplo n.º 6
0
 def activate(self, settings: Optional[SerializedSettings] = None) -> ConfigurationWarnings:
     if getattr(config, "mkeventd_enabled", False):
         mkeventd.execute_command("RELOAD", site=omd_site())
         log_audit("mkeventd-activate", _("Activated changes of event console configuration"))
         if hooks.registered("mkeventd-activate-changes"):
             hooks.call("mkeventd-activate-changes")
     return []
Exemplo n.º 7
0
 def execute(self) -> Iterator[ACResult]:
     if self._tmpfs_mounted(omd_site()):
         yield ACResultOK(_("The temporary filesystem is mounted"))
     else:
         yield ACResultWARN(
             _("The temporary filesystem is not mounted. Your installation "
               "may work with degraded performance."))
Exemplo n.º 8
0
def test_openapi_version(wsgi_app, with_automation_user):
    username, secret = with_automation_user
    wsgi_app.set_authorization(("Bearer", username + " " + secret))
    resp = wsgi_app.get("/NO_SITE/check_mk/api/1.0/version",
                        headers={"Accept": "application/json"},
                        status=200)
    assert resp.json["site"] == omd_site()
Exemplo n.º 9
0
    def action(self) -> ActionResult:
        local_site = omd_site()
        renamed_host_site = self._host.site_id()
        if (SiteChanges(SiteChanges.make_path(local_site)).read() or
                SiteChanges(SiteChanges.make_path(renamed_host_site)).read()):
            raise MKUserError(
                "newname",
                _("You cannot rename a host while you have "
                  "pending changes on the central site (%s) or the "
                  "site the host is monitored on (%s).") %
                (local_site, renamed_host_site),
            )

        newname = request.var("newname")
        self._check_new_host_name("newname", newname)
        # Creating pending entry. That makes the site dirty and that will force a sync of
        # the config to that site before the automation is being done.
        host_renaming_job = RenameHostBackgroundJob(
            self._host,
            title=_("Renaming of %s -> %s") % (self._host.name(), newname))
        renamings = [(Folder.current(), self._host.name(), newname)]
        host_renaming_job.set_function(rename_hosts_background_job, renamings)

        try:
            host_renaming_job.start()
        except background_job.BackgroundJobAlreadyRunning as e:
            raise MKGeneralException(
                _("Another host renaming job is already running: %s") % e)

        return redirect(host_renaming_job.detail_url())
Exemplo n.º 10
0
def site_attribute_default_value() -> Optional[SiteId]:
    site_id = omd_site()
    authorized_site_ids = global_user.authorized_sites(
        unfiltered_sites=configured_sites()).keys()
    if site_id in authorized_site_ids:
        return site_id
    return None
Exemplo n.º 11
0
 def load(self) -> Mapping[str, HostLabelValueDict]:
     return {
         "cmk/site": {
             "value": omd_site(),
             "plugin_name": "builtin"
         },
     }
Exemplo n.º 12
0
def default_single_site_configuration() -> SiteConfigurations:
    return {
        omd_site(): {
            "alias": _("Local site %s") % omd_site(),
            "socket": ("local", None),
            "disable_wato": True,
            "disabled": False,
            "insecure": False,
            "url_prefix": url_prefix(),
            "multisiteurl": "",
            "persist": False,
            "replicate_ec": False,
            "replication": None,
            "timeout": 5,
            "user_login": True,
            "proxy": None,
        }
    }
Exemplo n.º 13
0
def default_single_site_configuration() -> SiteConfigurations:
    return {
        omd_site(): {
            'alias': _("Local site %s") % omd_site(),
            'socket': ("local", None),
            'disable_wato': True,
            'disabled': False,
            'insecure': False,
            'url_prefix': url_prefix(),
            'multisiteurl': '',
            'persist': False,
            'replicate_ec': False,
            'replication': None,
            'timeout': 5,
            'user_login': True,
            'proxy': None,
        }
    }
Exemplo n.º 14
0
    def _create_key(self, alias: str, passphrase: str) -> None:
        keys = self.key_store.load()

        new_id = 1
        for key_id in keys:
            new_id = max(new_id, key_id + 1)

        assert user.id is not None
        keys[new_id] = generate_key(alias, passphrase, user.id, omd_site())
        self.key_store.save(keys)
Exemplo n.º 15
0
def create_self_signed_cert(pkey):
    cert = crypto.X509()
    cert.get_subject().O = "Check_MK Site %s" % omd_site()
    cert.get_subject().CN = user.id or "### Check_MK ###"
    cert.set_serial_number(1)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(30 * 365 * 24 * 60 * 60)  # valid for 30 years.
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha1")

    return cert
Exemplo n.º 16
0
    def _collect_infos(self) -> Optional[HostName]:
        query = (
            "GET services\nColumns: host_name\nFilter: service_description ~ OMD %s performance\n"
            % omd_site()
        )
        result = livestatus.LocalConnection().query(query)

        result = livestatus.LocalConnection().query(query)
        try:
            return HostName(result[0][0])
        except IndexError:
            return None
Exemplo n.º 17
0
def code_samples(
    endpoint,
    header_params,
    path_params,
    query_params,
) -> List[CodeSample]:
    """Create a list of rendered code sample Objects

    These are not specified by OpenAPI but are specific to ReDoc.

    Examples:

        >>> class Endpoint:
        ...     path = 'foo'
        ...     method = 'get'
        ...     content_type = 'application/json'
        ...     request_schema = _get_schema('CreateHost')
        ...     does_redirects = False

        >>> _endpoint = Endpoint()
        >>> import os
        >>> from unittest import mock
        >>> with mock.patch.dict(os.environ, {"OMD_SITE": "NO_SITE"}):
        ...     samples = code_samples(_endpoint, [], [], [])

        >>> assert len(samples)

    """
    env = _jinja_environment()

    return [{
        'label':
        example.label,
        'lang':
        example.lang,
        'source':
        env.get_template(example.label).render(
            hostname='localhost',
            site=omd_site(),
            username='******',
            password='******',
            endpoint=endpoint,
            path_params=to_openapi(path_params, 'path'),
            query_params=to_openapi(query_params, 'query'),
            header_params=to_openapi(header_params, 'header'),
            request_endpoint=endpoint.path,
            request_method=endpoint.method,
            request_schema=_get_schema(endpoint.request_schema),
            request_schema_multiple=_schema_is_multiple(
                endpoint.request_schema),
        ).strip(),
    } for example in CODE_EXAMPLES]
Exemplo n.º 18
0
def event_match_site(rule: EventRule, context: EventContext) -> Optional[str]:
    if "match_site" not in rule:
        return None

    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", 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))
    return None
Exemplo n.º 19
0
    def deserialize(cls, serialized: Dict[str,
                                          str]) -> "FetchAgentOutputRequest":
        host_name = serialized["host_name"]
        host = watolib.Host.host(host_name)
        if host is None:
            raise MKGeneralException(
                _("Host %s does not exist on remote site %s. This "
                  "may be caused by a failed configuration synchronization. Have a look at "
                  'the <a href="wato.py?folder=&mode=changelog">activate changes page</a> '
                  "for further information.") % (host_name, omd_site()))
        host.need_permission("read")

        return cls(host, serialized["agent_type"])
Exemplo n.º 20
0
def send_command(
    connection,
    command: LivestatusCommand,
    params: List[Any],
    site_id: Optional[SiteId] = None,
):
    """Send a command to livestatus.

    Args:
        connection:
            A livestatus connection object.

        command:
            The livestatus external command to be sent. For reference on these commands have a look
            at this page: https://docs.checkmk.com/master/en/livestatus_references.html

        params:
            A list of anything.

        site_id:
            The site name

    Examples:

        >>> from cmk.gui.livestatus_utils.testing import simple_expect
        >>> with simple_expect(
        ...         "COMMAND [...] ADD_HOST_COMMENT", match_type="ellipsis") as live:
        ...      send_command(live, "ADD_HOST_COMMENT", [])

        >>> with simple_expect(
        ...          "COMMAND [...] ADD_HOST_COMMENT;1;2;3", match_type="ellipsis") as live:
        ...      send_command(live, "ADD_HOST_COMMENT", [1, 2, 3])

        >>> with simple_expect(
        ...         "COMMAND [...] ADD_HOST_COMMENT;1;2;3", match_type="ellipsis") as live:
        ...      send_command(live, "ADD_HOST_COMMENT", [object()])
        Traceback (most recent call last):
        ...
        ValueError: Unknown type of parameter 0: <class 'object'>

    """
    current_time = int(time.time())
    cmd: str = command
    for pos, param in enumerate(params):
        if not isinstance(param, (int, str)):
            raise ValueError(f"Unknown type of parameter {pos}: {type(param)}")
        cmd += f";{param}"

    if not site_id:
        site_id = omd_site()
    connection.command(f"[{current_time}] {cmd}", sitename=site_id)
Exemplo n.º 21
0
    def _get_default_view_hostnames(self, max_nodes: int) -> Set[HostName]:
        """Returns all hosts without any parents"""
        query = "GET hosts\nColumns: name\nFilter: parents ="
        with sites.prepend_site(), sites.only_sites(request.var("site")):
            hosts = [(x[0], x[1]) for x in sites.live().query(query)]

        # If no explicit site is set and the number of initially displayed hosts
        # exceeds the auto growth range, only the hosts of the master site are shown
        if len(hosts) > max_nodes:
            hostnames = {HostName(x[1]) for x in hosts if x[0] == omd_site()}
        else:
            hostnames = {HostName(x[1]) for x in hosts}

        return hostnames
def pre_activate_changes_cleanup(_unused):
    log = open('%s/tmp/hook.log' % cmk.utils.paths.omd_root, 'w')
    log.write('omd_site: %s, omd_root: %s\n' %
              (omd_site(), cmk.utils.paths.omd_root))
    confd = "%s/etc/check_mk/conf.d/wato/" % cmk.utils.paths.omd_root
    for _dirname, dirnames, _filenames in os.walk(confd):
        for subdirname in dirnames:
            if subdirname == cmk.utils.paths.omd_site:
                log.write("keeping subdir: %s\n" % subdirname)
            else:
                log.write("deletinging subdir: %s\n" % subdirname)
                shutil.rmtree(confd + subdirname)
        break
    log.close()
Exemplo n.º 23
0
def code_samples(
    endpoint,
    header_params,
    path_params,
    query_params,
) -> List[CodeSample]:
    """Create a list of rendered code sample Objects

    These are not specified by OpenAPI but are specific to ReDoc.

    Examples:

        >>> class Endpoint:  # doctest: +SKIP
        ...     path = 'foo'
        ...     method = 'get'
        ...     content_type = 'application/json'
        ...     request_schema = _get_schema('CreateHost')
        ...     does_redirects = False

        >>> endpoint = Endpoint()  # doctest: +SKIP
        >>> samples = code_samples(endpoint, [], [], [])  # doctest: +SKIP


    """
    env = _jinja_environment()

    return [
        {
            "label": example.label,
            "lang": example.lang,
            "source": env.get_template(example.label)
            .render(
                hostname="localhost",
                site=omd_site(),
                username="******",
                password="******",
                endpoint=endpoint,
                path_params=to_openapi(path_params, "path"),
                query_params=to_openapi(query_params, "query"),
                header_params=to_openapi(header_params, "header"),
                request_endpoint=endpoint.path,
                request_method=endpoint.method,
                request_schema=_get_schema(endpoint.request_schema),
                request_schema_multiple=_schema_is_multiple(endpoint.request_schema),
            )
            .strip(),
        }
        for example in CODE_EXAMPLES
    ]
Exemplo n.º 24
0
def _show_crash_dump_message(
    crash: "GUICrashReport", plain_text: bool, fail_silently: bool, show_crash_link: Optional[bool]
) -> None:
    """Create a crash dump from a GUI exception and display a message to the user"""

    if show_crash_link is None:
        show_crash_link = user.may("general.see_crash_reports")

    title = _("Internal error")
    message = "%s: %s<br>\n<br>\n" % (title, crash.crash_info["exc_value"])
    # Do not reveal crash context information to unauthenticated users or not permitted
    # users to prevent disclosure of internal information
    if not show_crash_link:
        message += _(
            "An internal error occurred while processing your request. "
            "You can report this issue to your Checkmk administrator. "
            "Detailed information can be found on the crash report page "
            "or in <tt>var/log/web.log</tt>."
        )
    else:
        crash_url = makeuri(
            request,
            [
                ("site", omd_site()),
                ("crash_id", crash.ident_to_text()),
            ],
            filename="crash.py",
        )
        message += (
            _(
                "An internal error occured while processing your request. "
                "You can report this issue to the Checkmk team to help "
                'fixing this issue. Please open the <a href="%s">crash report page</a> '
                "and use the form for reporting the problem."
            )
            % crash_url
        )

    if plain_text:
        response.set_content_type("text/plain")
        response.set_data("%s\n" % escaping.strip_tags(message))
        return

    if fail_silently:
        return

    html.header(title, Breadcrumb())
    html.show_error(message)
    html.footer()
Exemplo n.º 25
0
    def _get_response(self, checkmk_server_name: str,
                      collectors: Collectors) -> requests.Response:
        automation_secret = self._get_automation_secret()

        omd_config = collectors.get_omd_config()
        url = "http://%s:%s/%s/check_mk/report.py?" % (
            omd_config["CONFIG_APACHE_TCP_ADDR"],
            omd_config["CONFIG_APACHE_TCP_PORT"],
            omd_site(),
        ) + urllib.parse.urlencode([
            ("_username", "automation"),
            ("_secret", automation_secret),
            ("host", checkmk_server_name),
            ("name", "host_performance_graphs"),
        ])

        return requests.post(url, verify=False)  # nosec
Exemplo n.º 26
0
def transform_topology_dashlet(
    dashlet_spec: DashletConfig, filter_group: str = ""
) -> DashletConfig:
    site_id = dashlet_spec["context"].get("site", omd_site())

    dashlet_spec.update(
        {
            "type": "url",
            "title": _("Network topology of site %s") % site_id,
            "url": "../nagvis/frontend/nagvis-js/index.php?mod=Map&header_template="
            "on-demand-filter&header_menu=1&label_show=1&sources=automap&act=view"
            "&backend_id=%s&render_mode=undirected&url_target=main&filter_group=%s"
            % (site_id, filter_group),
            "show_in_iframe": True,
        }
    )

    return dashlet_spec
Exemplo n.º 27
0
    def page(self) -> None:
        assert user.id is not None

        _invalidate_auth_session()

        session_id = _get_session_id_from_cookie(user.id,
                                                 revalidate_cookie=True)
        userdb.on_logout(user.id, session_id)

        if auth_type == "cookie":  # type: ignore[has-type]
            raise HTTPRedirect(url_prefix() + "check_mk/login.py")

        # Implement HTTP logout with cookie hack
        if not request.has_cookie("logout"):
            response.headers["WWW-Authenticate"] = (
                'Basic realm="OMD Monitoring Site %s"' % omd_site())
            response.set_http_cookie("logout", "1", secure=request.is_secure)
            raise FinalizeRequest(http.client.UNAUTHORIZED)

        response.delete_cookie("logout")
        raise HTTPRedirect(url_prefix() + "check_mk/")
Exemplo n.º 28
0
    def __init__(self, config: Mapping[str, Any]) -> None:
        self._config = config

        self._credentials = config["credentials"]
        if self._credentials == "automation":
            self._username = self._credentials
            self._secret = (profile_dir / self._username / "automation.secret").read_text(
                encoding="utf-8"
            )
        else:
            self._username, automation_secret = self._credentials[1]
            self._secret = extract(automation_secret)

        site_config = config["site"]

        if site_config == "local":
            self._site_url = "http://localhost:%d/%s" % (
                cmk.utils.site.get_apache_port(),
                omd_site(),
            )
        else:
            self._site_url = site_config[1]
Exemplo n.º 29
0
def search(param):
    """Display some version information"""
    if request.args.get("fail"):
        raise Exception("This is an intentional failure.")
    return constructors.serve_json({
        "site":
        omd_site(),
        "group":
        request.environ.get("mod_wsgi.application_group", "unknown"),
        "rest_api": {
            "revision": "0",
        },
        "versions": {
            "apache": request.environ.get("apache.version", "unknown"),
            "checkmk": cmk_version.omd_version(),
            "python": sys.version,
            "mod_wsgi": request.environ.get("mod_wsgi.version", "unknown"),
            "wsgi": request.environ["wsgi.version"],
        },
        "edition":
        cmk_version.edition().short,
        "demo":
        cmk_version.is_free_edition(),
    })
Exemplo n.º 30
0
def search(param):
    """Display some version information"""
    if request.args.get('fail'):
        raise Exception("This is an intentional failure.")
    return constructors.serve_json({
        "site":
        omd_site(),
        "group":
        request.environ.get('mod_wsgi.application_group', 'unknown'),
        "rest_api": {
            'revision': '0',
        },
        "versions": {
            "apache": request.environ.get('apache.version', 'unknown'),
            "checkmk": cmk_version.omd_version(),
            "python": sys.version,
            'mod_wsgi': request.environ.get('mod_wsgi.version', 'unknown'),
            'wsgi': request.environ['wsgi.version'],
        },
        "edition":
        cmk_version.edition_short(),
        "demo":
        cmk_version.is_free_edition(),
    })