Ejemplo n.º 1
0
    def _discover_services(self, request):
        mode = request.get("mode", "new")
        hostname = request.get("hostname")

        check_hostname(hostname, should_exist=True)

        host = watolib.Host.host(hostname)

        host_attributes = host.effective_attributes()

        if host.is_cluster():
            # This is currently the only way to get some actual discovery statitics.
            # Start a dry-run -> Get statistics
            # Do an actual discovery on the nodes -> data is written
            try_result = watolib.check_mk_automation(host_attributes.get("site"), "try-inventory",
                                                     ["@scan"] + [hostname])

            new = 0
            old = 0
            for entry in try_result["check_table"]:
                if entry[0] == "new":
                    new += 1
                elif entry[0] == "old":
                    old += 1

            result = DiscoveryResult(self_new=new, self_kept=old, self_total=new + old)
            watolib.check_mk_automation(host_attributes.get("site"), "inventory",
                                        ["@scan", mode] + host.cluster_nodes())
        else:
            response = execute_automation_discovery(site_id=host_attributes.get("site"),
                                                    args=["@scan", mode, hostname])
            result = response.results[hostname]

        if result.error_text:
            if not host.discovery_failed():
                host.set_discovery_failed()
            raise MKUserError(None, _("Failed to discover %s: %s") % (hostname, result.error_text))

        if host.discovery_failed():
            host.clear_discovery_failed()

        if mode == "refresh":
            message = _("Refreshed check configuration of host [%s] with %d services") % (
                hostname, result.self_total)
            watolib.add_service_change(host, "refresh-autochecks", message)
        else:
            message = _("Saved check configuration of host [%s] with %d services") % (
                hostname, result.self_total)
            watolib.add_service_change(host, "set-autochecks", message)

        msg = _("Service discovery successful. Added %d, removed %d, kept %d, total %d services "
                "and %d new, %d total host labels") % (
                    result.self_new,
                    result.self_removed,
                    result.self_kept,
                    result.self_total,
                    result.self_new_host_labels,
                    result.self_total_host_labels,
                )
        return msg
Ejemplo n.º 2
0
    def _discover_services(self, request):
        mode = request.get("mode", "new")
        hostname = request.get("hostname")

        check_hostname(hostname, should_exist=True)

        host = watolib.Host.host(hostname)

        host_attributes = host.effective_attributes()

        if host.is_cluster():
            # This is currently the only way to get some actual discovery statitics.
            # Start a dry-run -> Get statistics
            # Do an actual discovery on the nodes -> data is written
            result = watolib.check_mk_automation(host_attributes.get("site"), "try-inventory",
                                                 ["@scan"] + [hostname])
            counts = {"new": 0, "old": 0}
            for entry in result["check_table"]:
                if entry[0] in counts:
                    counts[entry[0]] += 1

            counts = {
                hostname: (
                    counts["new"],
                    0,  # this info is not available for clusters
                    counts["old"],
                    counts["new"] + counts["old"])
            }

            # A cluster cannot fail, just the nodes. This information is currently discarded
            failed_hosts = None
            watolib.check_mk_automation(host_attributes.get("site"), "inventory",
                                        ["@scan", mode] + host.cluster_nodes())
        else:
            counts, failed_hosts = watolib.check_mk_automation(host_attributes.get("site"),
                                                               "inventory",
                                                               ["@scan", mode] + [hostname])

        if failed_hosts:
            if not host.discovery_failed():
                host.set_discovery_failed()
            raise MKUserError(
                None,
                _("Failed to inventorize %s: %s") % (hostname, failed_hosts[hostname]))

        if host.discovery_failed():
            host.clear_discovery_failed()

        if mode == "refresh":
            message = _("Refreshed check configuration of host [%s] with %d services") % (
                hostname, counts[hostname][3])
            watolib.add_service_change(host, "refresh-autochecks", message)
        else:
            message = _("Saved check configuration of host [%s] with %d services") % (
                hostname, counts[hostname][3])
            watolib.add_service_change(host, "set-autochecks", message)

        msg = _("Service discovery successful. Added %d, removed %d, kept %d, total %d services "
                "and %d new, %d total host labels") % tuple(counts[hostname])
        return msg
Ejemplo n.º 3
0
    def action(self) -> ActionResult:
        folder = watolib.Folder.current()
        if not html.check_transaction():
            return redirect(mode_url("folder", folder=folder.path()))

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

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

        attributes = watolib.collect_attributes("host" if not self._is_cluster() else "cluster",
                                                new=False)
        watolib.Host.host(self._host.name()).edit(attributes, self._get_cluster_nodes())
        self._host = folder.host(self._host.name())

        if html.request.var("services"):
            return redirect(mode_url("inventory", folder=folder.path(), host=self._host.name()))
        if html.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()))
Ejemplo n.º 4
0
    def _fetch_agent_output(self, job_interface):
        job_interface.send_progress_update(
            _("Fetching '%s'...") % self._request.agent_type)

        success, output, agent_data = watolib.check_mk_automation(
            self._request.host.site_id(), "get-agent-output",
            [self._request.host.name(), self._request.agent_type])

        if not success:
            job_interface.send_progress_update(_("Failed: %s") % output)

        preview_filepath = os.path.join(
            job_interface.get_work_dir(),
            AgentOutputPage.file_name(self._request))
        store.save_file(preview_filepath, agent_data)

        download_url = makeuri_contextless(
            request,
            [("host", self._request.host.name()),
             ("type", self._request.agent_type)],
            filename="download_agent_output.py",
        )

        button = html.render_icon_button(download_url, _("Download"),
                                         "agent_output")
        job_interface.send_progress_update(
            _("Finished. Click on the icon to download the data."))
        job_interface.send_result_message(_("%s Finished.") % button)
Ejemplo n.º 5
0
    def action(self):
        if html.request.var("_update_dns_cache"):
            if not html.check_transaction():
                return None
            config.user.need_permission("wato.update_dns_cache")
            num_updated, failed_hosts = watolib.check_mk_automation(
                self._host.site_id(), "update-dns-cache", [])
            infotext = _(
                "Successfully updated IP addresses of %d hosts.") % num_updated
            if failed_hosts:
                infotext += "<br><br><b>Hostnames failed to lookup:</b> " \
                          + ", ".join(["<tt>%s</tt>" % h for h in failed_hosts])
            return None, infotext

        if html.request.var("delete"):  # Delete this host
            if not html.transaction_valid():
                return "folder"
            return delete_host_after_confirm(self._host.name())

        if html.check_transaction():
            attributes = watolib.collect_attributes(
                "host" if not self._is_cluster() else "cluster", new=False)
            watolib.Host.host(self._host.name()).edit(
                attributes, self._get_cluster_nodes())
            self._host = watolib.Folder.current().host(self._host.name())

        if html.request.var("services"):
            return "inventory"
        if html.request.var("diag_host"):
            html.request.set_var("_start_on_load", "1")
            return "diag_host"
        return "folder"
Ejemplo n.º 6
0
 def _execute_parent_scan(self, task, settings):
     params = map(str, [
         settings["timeout"],
         settings["probes"],
         settings["max_ttl"],
         settings["ping_probes"],
     ])
     return watolib.check_mk_automation(task.site_id, "scan-parents", params + [task.host_name])
Ejemplo n.º 7
0
    def _show_host_info(self):
        host_info = watolib.check_mk_automation(self._host.site_id(), "analyse-host",
                                                [self._hostname])
        if not host_info:
            return

        forms.header(_("Host information"), isopen=True, narrow=True, css="rulesettings")
        self._show_labels(host_info["labels"], "host", host_info["label_sources"])
Ejemplo n.º 8
0
 def _execute_parent_scan(self, task: ParentScanTask, settings: ParentScanSettings) -> List:
     params = list(
         map(str, [
             settings.timeout,
             settings.probes,
             settings.max_ttl,
             settings.ping_probes,
         ]))
     return watolib.check_mk_automation(task.site_id, "scan-parents", params + [task.host_name])
Ejemplo n.º 9
0
def rename_hosts_in_check_mk(renamings):
    action_counts = {}
    for site_id, name_pairs in group_renamings_by_site(renamings).items():
        message = _("Renamed host %s") % ", ".join(
            [_("%s into %s") % (oldname, newname) for (oldname, newname) in name_pairs])

        # Restart is done by remote automation (below), so don't do it during rename/sync
        # The sync is automatically done by the remote automation call
        add_change("renamed-hosts", message, sites=[site_id], need_restart=False)

        new_counts = watolib.check_mk_automation(site_id, "rename-hosts", [], name_pairs)

        merge_action_counts(action_counts, new_counts)
    return action_counts
Ejemplo n.º 10
0
    def _show_service_info(self, all_rulesets):
        serviceinfo = watolib.check_mk_automation(
            self._host.site_id(), "analyse-service",
            [self._hostname, self._service])
        if not serviceinfo:
            return

        forms.header(_("Check origin and parameters"),
                     isopen=True,
                     narrow=True,
                     css="rulesettings")
        origin = serviceinfo["origin"]
        origin_txt = {
            "active": _("Active check"),
            "static": _("Manual check"),
            "auto": _("Inventorized check"),
            "classic": _("Classical check"),
        }[origin]
        self._render_rule_reason(_("Type of check"), None, "", "", False,
                                 origin_txt)

        # First case: discovered checks. They come from var/check_mk/autochecks/HOST.
        if origin == "auto":
            checkgroup = serviceinfo["checkgroup"]
            checktype = serviceinfo["checktype"]
            if not checkgroup:
                self._render_rule_reason(
                    _("Parameters"), None, "", "", True,
                    _("This check is not configurable via WATO"))

            # Logwatch needs a special handling, since it is not configured
            # via checkgroup_parameters but via "logwatch_rules" in a special
            # WATO module.
            elif checkgroup == "logwatch":
                rulespec = rulespec_registry["logwatch_rules"]
                self._output_analysed_ruleset(
                    all_rulesets,
                    rulespec,
                    svc_desc_or_item=serviceinfo["item"],
                    svc_desc=self._service,
                    known_settings=serviceinfo["parameters"])

            else:
                # Note: some discovered checks have a check group but
                # *no* ruleset for discovered checks. One example is "ps".
                # That can be configured as a manual check or created by
                # inventory. But in the later case all parameters are set
                # by the inventory. This will be changed in a later version,
                # but we need to address it anyway.
                grouprule = "checkgroup_parameters:" + checkgroup
                if grouprule not in rulespec_registry:
                    try:
                        rulespec = rulespec_registry["static_checks:" +
                                                     checkgroup]
                    except KeyError:
                        rulespec = None

                    if rulespec:
                        url = watolib.folder_preserving_link([
                            ('mode', 'edit_ruleset'),
                            ('varname', "static_checks:" + checkgroup),
                            ('host', self._hostname)
                        ])
                        self._render_rule_reason(
                            _("Parameters"), url, _("Determined by discovery"),
                            None, False,
                            rulespec.valuespec._elements[2].value_to_text(
                                serviceinfo["parameters"]))
                    else:
                        self._render_rule_reason(
                            _("Parameters"), None, "", "", True,
                            _("This check is not configurable via WATO"))

                else:
                    rulespec = rulespec_registry[grouprule]
                    self._output_analysed_ruleset(
                        all_rulesets,
                        rulespec,
                        svc_desc_or_item=serviceinfo["item"],
                        svc_desc=self._service,
                        known_settings=serviceinfo["parameters"])

        elif origin == "static":
            checkgroup = serviceinfo["checkgroup"]
            checktype = serviceinfo["checktype"]
            if not checkgroup:
                html.write_text(_("This check is not configurable via WATO"))
            else:
                rulespec = rulespec_registry["static_checks:" + checkgroup]
                itemspec = rulespec.item_spec
                if itemspec:
                    item_text = itemspec.value_to_text(serviceinfo["item"])
                    title = rulespec.item_spec.title()
                else:
                    item_text = serviceinfo["item"]
                    title = _("Item")
                self._render_rule_reason(title, None, "", "", False, item_text)
                self._output_analysed_ruleset(
                    all_rulesets,
                    rulespec,
                    svc_desc_or_item=serviceinfo["item"],
                    svc_desc=self._service,
                    known_settings=self._PARAMETERS_OMIT)
                html.write(rulespec.valuespec._elements[2].value_to_text(
                    serviceinfo["parameters"]))
                html.close_td()
                html.close_tr()
                html.close_table()

        elif origin == "active":
            checktype = serviceinfo["checktype"]
            rulespec = rulespec_registry["active_checks:" + checktype]
            self._output_analysed_ruleset(
                all_rulesets,
                rulespec,
                svc_desc_or_item=None,
                svc_desc=None,
                known_settings=serviceinfo["parameters"])

        elif origin == "classic":
            ruleset = all_rulesets.get("custom_checks")
            origin_rule_result = self._get_custom_check_origin_rule(
                ruleset, self._hostname, self._service)
            if origin_rule_result is None:
                raise MKUserError(
                    None,
                    _("Failed to determine origin rule of %s / %s") %
                    (self._hostname, self._service))
            rule_folder, rule_index, _rule = origin_rule_result

            url = watolib.folder_preserving_link([('mode', 'edit_ruleset'),
                                                  ('varname', "custom_checks"),
                                                  ('host', self._hostname)])
            forms.section(html.render_a(_("Command Line"), href=url))
            url = watolib.folder_preserving_link([('mode', 'edit_rule'),
                                                  ('varname', "custom_checks"),
                                                  ('rule_folder',
                                                   rule_folder.path()),
                                                  ('rulenr', rule_index),
                                                  ('host', self._hostname)])

            html.open_table(class_="setting")
            html.open_tr()

            html.open_td(class_="reason")
            html.a("%s %d %s %s" %
                   (_("Rule"), rule_index + 1, _("in"), rule_folder.title()),
                   href=url)
            html.close_td()
            html.open_td(class_=["settingvalue", "used"])
            if "command_line" in serviceinfo:
                html.tt(serviceinfo["command_line"])
            else:
                html.write_text(_("(no command line, passive check)"))
            html.close_td()

            html.close_tr()
            html.close_table()

        self._show_labels(serviceinfo.get("labels", {}), "service",
                          serviceinfo.get("label_sources", {}))
Ejemplo n.º 11
0
    def page(self):
        watolib.init_wato_datastructures(with_wato_lock=True)

        if not config.user.may('wato.diag_host'):
            raise MKAuthException(
                _('You are not permitted to perform this action.'))

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

        request = self.webapi_request()

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

        host = watolib.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 = 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()).keys():
            raise MKGeneralException(_('Invalid test.'))

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

        if config.user.may('wato.add_or_modify_executables'):
            args[6] = request.get("datasource_program", "")

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

            args[7] = snmpv3_use
            if snmpv3_use != u"noAuthNoPriv":
                snmpv3_auth_proto = {
                    six.text_type(DropdownChoice.option_id("md5")): u"md5",
                    six.text_type(DropdownChoice.option_id("sha")): u"sha"
                }.get(request.get("snmpv3_auth_proto", u""), u"")

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

                if snmpv3_use == "authPriv":
                    snmpv3_privacy_proto = {
                        six.text_type(DropdownChoice.option_id("DES")): u"DES",
                        six.text_type(DropdownChoice.option_id("AES")): u"AES"
                    }.get(request.get("snmpv3_privacy_proto", u""), u"")

                    args[11] = snmpv3_privacy_proto

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

        result = watolib.check_mk_automation(host.site_id(), "diag-host",
                                             [hostname, _test] + args)
        return {
            "next_transid": html.transaction_manager.fresh_transid(),
            "status_code": result[0],
            "output": six.ensure_text(result[1], errors="replace"),
        }