Exemplo n.º 1
0
def check_hostname(hostname: HostName, should_exist=True) -> None:
    # Validate hostname with valuespec
    Hostname().validate_value(hostname, "hostname")

    if should_exist:
        host = Host.host(hostname)
        if not host:
            raise MKUserError(None, _("No such host"))
    else:
        if (host := Host.host(hostname)) is not None:
            raise MKUserError(
                None,
                _("Host %s already exists in the folder %s") %
                (hostname, host.folder().path()),
            )
Exemplo n.º 2
0
    def _validate(self, value):
        super()._validate(value)

        # Regex gets checked through the `pattern` of the String instance

        if self._should_exist is not None:
            host = Host.host(value)
            if self._should_exist and not host:
                raise self.make_error("should_exist", host_name=value)

            if not self._should_exist and host:
                raise self.make_error("should_not_exist", host_name=value)

        if self._should_be_cluster is not None and (
                host := Host.host(value)) is not None:
            if self._should_be_cluster and not host.is_cluster():
                raise self.make_error("should_be_cluster", host_name=value)

            if not self._should_be_cluster and host.is_cluster():
                raise self.make_error("should_not_be_cluster", host_name=value)
Exemplo n.º 3
0
    def _get_hosts_from_request(self, request: Dict) -> List[DiscoveryHost]:
        if not request["hostnames"]:
            raise MKUserError(None, _("You have to specify some hosts"))

        hosts_to_discover = []
        for host_name in request["hostnames"]:
            host = Host.host(host_name)
            if host is None:
                raise MKUserError(None, _("The host '%s' does not exist") % host_name)
            host.need_permission("write")
            hosts_to_discover.append(DiscoveryHost(host.site_id(), host.folder().path(), host_name))
        return hosts_to_discover
Exemplo n.º 4
0
def _get_object_reference(
        object_ref: Optional[ObjectRef]
) -> Tuple[Optional[str], Optional[str]]:
    if object_ref is None:
        return None, None

    if object_ref.object_type is ObjectRefType.Host:
        host = Host.host(object_ref.ident)
        if host:
            return host.edit_url(), host.name()
        return None, object_ref.ident

    if object_ref.object_type is ObjectRefType.Folder:
        if Folder.folder_exists(object_ref.ident):
            folder = Folder.folder(object_ref.ident)
            return folder.url(), folder.title()
        return None, object_ref.ident

    if object_ref.object_type is ObjectRefType.User:
        url = makeuri_contextless(
            request,
            [
                ("mode", "edit_user"),
                ("edit", object_ref.ident),
            ],
            filename="wato.py",
        )
        return url, object_ref.ident

    if object_ref.object_type is ObjectRefType.Rule:
        url = makeuri_contextless(
            request,
            [
                ("mode", "edit_rule"),
                ("varname", object_ref.labels["ruleset"]),
                ("rule_id", object_ref.ident),
            ],
            filename="wato.py",
        )
        return url, object_ref.ident

    if object_ref.object_type is ObjectRefType.Ruleset:
        url = makeuri_contextless(
            request,
            [
                ("mode", "edit_ruleset"),
                ("varname", object_ref.ident),
            ],
            filename="wato.py",
        )
        return url, object_ref.ident

    return None, object_ref.ident
Exemplo n.º 5
0
def prepare_hosts_for_discovery(
        hostnames: Sequence[str]) -> List[DiscoveryHost]:
    hosts_to_discover = []
    for host_name in hostnames:
        host = Host.host(host_name)
        if host is None:
            raise MKUserError(None,
                              _("The host '%s' does not exist") % host_name)
        host.need_permission("write")
        hosts_to_discover.append(
            DiscoveryHost(host.site_id(),
                          host.folder().path(), host_name))
    return hosts_to_discover
Exemplo n.º 6
0
    def action(self) -> ActionResult:
        folder = Folder.current()
        if not transactions.check_transaction():
            return redirect(mode_url("folder", folder=folder.path()))

        if request.var("_update_dns_cache") and self._should_use_dns_cache():
            user.need_permission("wato.update_dns_cache")
            update_dns_cache_result = update_dns_cache(self._host.site_id())
            infotext = (_("Successfully updated IP addresses of %d hosts.") %
                        update_dns_cache_result.n_updated)
            if update_dns_cache_result.failed_hosts:
                infotext += "<br><br><b>Hostnames failed to lookup:</b> " + ", ".join(
                    [
                        "<tt>%s</tt>" % h
                        for h in update_dns_cache_result.failed_hosts
                    ])
            flash(infotext)
            return None

        if request.var("delete"):  # Delete this host
            folder.delete_hosts([self._host.name()], automation=delete_hosts)
            return redirect(mode_url("folder", folder=folder.path()))

        if request.var("_remove_tls_registration"):
            remove_tls_registration(
                {self._host.site_id(): [self._host.name()]})
            return None

        attributes = collect_attributes(
            "host" if not self._is_cluster() else "cluster", new=False)
        host = Host.host(self._host.name())
        if host is None:
            flash(f"Host {self._host.name()} could not be found.")
            return None

        host.edit(attributes, self._get_cluster_nodes())
        self._host = folder.load_host(self._host.name())

        if request.var("_save"):
            return redirect(
                mode_url("inventory",
                         folder=folder.path(),
                         host=self._host.name()))
        if request.var("diag_host"):
            return redirect(
                mode_url("diag_host",
                         folder=folder.path(),
                         host=self._host.name(),
                         _start_on_load="1"))
        return redirect(mode_url("folder", folder=folder.path()))
Exemplo n.º 7
0
    def deserialize(cls, serialized: Dict[str, Any]) -> 'SiteRequest':
        enforce_host = EnforcedHostRequest(
            **serialized["enforce_host"]) if serialized["enforce_host"] else None

        if enforce_host:
            host = Host.host(enforce_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.") % (enforce_host.host_name, enforce_host.site_id))
            host.need_permission("read")

        newest_host_labels = serialized["newest_host_labels"]
        assert isinstance(newest_host_labels, float)
        return cls(newest_host_labels, enforce_host)
Exemplo n.º 8
0
def validate_host_parents(host):
    for parent_name in host.parents():
        if parent_name == host.name():
            raise MKUserError(
                None,
                _("You configured the host to be it's own parent, which is not allowed."
                  ))

        parent = Host.host(parent_name)
        if not parent:
            raise MKUserError(
                None,
                _("You defined the non-existing host '%s' as a parent.") %
                parent_name)

        if host.site_id() != parent.site_id():
            raise MKUserError(
                None,
                _("The parent '%s' is monitored on site '%s' while the host itself "
                  "is monitored on site '%s'. Both must be monitored on the same site. Remember: The parent/child "
                  "relation is used to describe the reachability of hosts by one monitoring daemon."
                  ) % (parent_name, parent.site_id(), host.site_id()),
            )
Exemplo n.º 9
0
    def page(self):
        check_csrf_token()
        if not user.may("wato.diag_host"):
            raise MKAuthException(_("You are not permitted to perform this action."))

        if not transactions.check_transaction():
            raise MKAuthException(_("Invalid transaction"))

        api_request = self.webapi_request()

        hostname = api_request.get("host")
        if not hostname:
            raise MKGeneralException(_("The hostname is missing."))

        host = Host.host(hostname)

        if not host:
            raise MKGeneralException(_("The given host does not exist."))
        if host.is_cluster():
            raise MKGeneralException(_("This view does not support cluster hosts."))

        host.need_permission("read")

        _test = api_request.get("_test")
        if not _test:
            raise MKGeneralException(_("The test is missing."))

        # Execute a specific test
        if _test not in dict(ModeDiagHost.diag_host_tests()):
            raise MKGeneralException(_("Invalid test."))

        # TODO: Use ModeDiagHost._vs_rules() for processing/validation?
        args: List[str] = [""] * 13
        for idx, what in enumerate(
            [
                "ipaddress",
                "snmp_community",
                "agent_port",
                "snmp_timeout",
                "snmp_retries",
                "tcp_connect_timeout",
            ]
        ):
            args[idx] = api_request.get(what, "")

        if api_request.get("snmpv3_use"):
            snmpv3_use = {
                "0": "noAuthNoPriv",
                "1": "authNoPriv",
                "2": "authPriv",
            }.get(api_request.get("snmpv3_use", ""), "")

            args[7] = snmpv3_use
            if snmpv3_use != "noAuthNoPriv":
                snmpv3_auth_proto = {
                    str(DropdownChoice.option_id("md5")): "md5",
                    str(DropdownChoice.option_id("sha")): "sha",
                }.get(api_request.get("snmpv3_auth_proto", ""), "")

                args[8] = snmpv3_auth_proto
                args[9] = api_request.get("snmpv3_security_name", "")
                args[10] = api_request.get("snmpv3_security_password", "")

                if snmpv3_use == "authPriv":
                    snmpv3_privacy_proto = {
                        str(DropdownChoice.option_id("DES")): "DES",
                        str(DropdownChoice.option_id("AES")): "AES",
                    }.get(api_request.get("snmpv3_privacy_proto", ""), "")

                    args[11] = snmpv3_privacy_proto

                    args[12] = api_request.get("snmpv3_privacy_password", "")
            else:
                args[9] = api_request.get("snmpv3_security_name", "")

        result = diag_host(
            host.site_id(),
            hostname,
            _test,
            *args,
        )
        return {
            "next_transid": transactions.fresh_transid(),
            "status_code": result.return_code,
            "output": result.response,
        }