Esempio n. 1
0
def __live_query_to_choices(
    query_callback: Callable[[MultiSiteConnection],
                             Collection[LivestatusColumn]],
    limit: int,
    value: str,
    params: Dict,
) -> Choices:
    selected_sites = get_only_sites_from_context(params.get("context", {}))
    with sites.only_sites(selected_sites), sites.set_limit(limit):
        query_result = query_callback(sites.live())
        choices = [(h, h)
                   for h in sorted(query_result, key=lambda h: h.lower())]

    if len(choices) > limit:
        choices.insert(
            0, (None, _("(Max suggestions reached, be more specific)")))

    if (value, value) not in choices and params["strict"] is False:
        choices.insert(
            0, (value, value))  # User is allowed to enter anything they want
    return choices
Esempio n. 2
0
def service_table_query(properties, context, column_generator):
    filter_headers, only_sites = visuals.get_filter_headers(
        "services", ["host", "service"], context)
    columns = column_generator(properties, context)

    query = ("GET services\n"
             "Columns: %(cols)s\n"
             "%(filter)s" % {
                 "cols": " ".join(columns),
                 "filter": filter_headers,
             })

    with sites.only_sites(only_sites), sites.prepend_site():
        try:
            rows = sites.live().query(query)
        except MKTimeout:
            raise
        except Exception:
            raise MKGeneralException(_("The query returned no data."))

    return ['site'] + columns, rows
Esempio n. 3
0
def _list_services(param):
    live = sites.live()

    q = Query(param['columns'])

    host_name = param.get('host_name')
    if host_name is not None:
        q = q.filter(Services.host_name == host_name)

    query_expr = param.get('query')
    if query_expr:
        q = q.filter(query_expr)

    result = q.iterate(live)

    return constructors.serve_json(
        constructors.collection_object(
            domain_type='service',
            value=[
                constructors.domain_object(
                    domain_type='service',
                    title=f"{entry['description']} on {entry['host_name']}",
                    identifier=f"{entry['host_name']}:{entry['description']}",
                    editable=False,
                    deletable=False,
                    extensions=entry,
                    self_link=constructors.link_rel(
                        rel='cmk/show',
                        href=constructors.object_action_href(
                            'host',
                            entry['host_name'],
                            'show_service',
                            query_params=[('service_description', entry['description'])],
                        ),
                        method='get',
                        title=f"Show the service {entry['description']}",
                    ),
                ) for entry in result
            ],
        ))
def test_servicegroup_service_downtime_and_hosts(mock_livestatus,
                                                 register_builtin_html, dates):
    start_time, end_time = dates

    with mock_livestatus(expect_status_query=True) as live:
        live.expect_query([
            "GET servicegroups",
            "Columns: members",
            "Filter: name = example",
        ])
        live.expect_query(
            'COMMAND [...] SCHEDULE_SVC_DOWNTIME;example.com;Memory;0;86400;17;0;120;;Boom',
            match_type='ellipsis',
        )
        live.expect_query(
            'COMMAND [...] SCHEDULE_SVC_DOWNTIME;example.com;CPU load;0;86400;17;0;120;;Boom',
            match_type='ellipsis',
        )
        live.expect_query(
            'COMMAND [...] SCHEDULE_SVC_DOWNTIME;heute;CPU load;0;86400;17;0;120;;Boom',
            match_type='ellipsis',
        )
        live.expect_query(
            'COMMAND [...] SCHEDULE_HOST_DOWNTIME;example.com;0;86400;17;0;120;;Boom',
            match_type='ellipsis',
        )
        live.expect_query(
            'COMMAND [...] SCHEDULE_HOST_DOWNTIME;heute;0;86400;17;0;120;;Boom',
            match_type='ellipsis',
        )
        downtimes.schedule_servicegroup_service_downtime(
            sites.live(),
            'example',
            start_time,
            end_time,
            include_hosts=True,
            recur="day_of_month",
            duration=120,
            comment="Boom",
        )
Esempio n. 5
0
    def autocomplete_choices(cls, value: str, params: Dict) -> Choices:
        """Return the matching list of dropdown choices
        Called by the webservice with the current input field value and the
        completions_params to get the list of choices"""
        if not (params.get("host") or params.get("service")):
            choices: Iterable[TupleType[str, str]] = ((
                graph_id,
                graph_details.get(
                    "title",
                    graph_id,
                ),
            ) for graph_id, graph_details in graph_info.items())

        else:
            query = "\n".join([
                "GET services",
                "Columns: perf_data metrics check_command",
            ] + [
                f"Filter: {filter_name} = {livestatus.lqencode(filter_value)}"
                for filter_name, filter_value in (
                    ("host_name", params.get("host")),
                    ("service_description", params.get("service")),
                ) if filter_value
            ])
            with sites.set_limit(None):
                choices = set(
                    chain.from_iterable(
                        cls._graph_choices_from_livestatus_row(
                            perf_data,
                            metrics,
                            check_cmd,
                        ) for perf_data, metrics, check_cmd in
                        sites.live().query(query)))

        val_lower = value.lower()
        return sorted(
            (choice for choice in choices if val_lower in choice[1].lower()),
            key=lambda tuple_id_title: tuple_id_title[1],
        )
def test_host_downtime(mock_livestatus, with_request_context, dates):
    start_time, end_time = dates

    with mock_livestatus(
            expect_status_query=True) as live, application_and_request_context(
            ), SuperUserContext():
        load_config()
        live.expect_query(
            "GET hosts\nColumns: name\nFilter: name = example.com")
        live.expect_query(
            "COMMAND [...] SCHEDULE_HOST_DOWNTIME;example.com;0;86400;12;0;120;;Going down",
            match_type="ellipsis",
        )
        downtimes.schedule_host_downtime(
            sites.live(),
            "example.com",
            start_time,
            end_time,
            recur="weekday_start",
            duration=120,
            comment="Going down",
        )
Esempio n. 7
0
def _table_query(properties, context, column_generator, table: str,
                 infos: List[str]):
    filter_headers, only_sites = visuals.get_filter_headers(
        table, infos, context)
    columns = column_generator(properties, context)

    query = (f"GET {table}\n"
             "Columns: %(cols)s\n"
             "%(filter)s" % {
                 "cols": " ".join(columns),
                 "filter": filter_headers,
             })

    with sites.only_sites(only_sites), sites.prepend_site():
        try:
            rows = sites.live().query(query)
        except MKTimeout:
            raise
        except Exception:
            raise MKGeneralException(_("The query returned no data."))

    return ['site'] + columns, rows
Esempio n. 8
0
    def _query_for_metrics_of_host(self, host_name, site_id):
        if not host_name:
            return {}

        query = (
            "GET services\n"
            "Columns: description check_command metrics\n"
            "Filter: host_name = %s\n" % livestatus.lqencode(host_name)
        )

        response = {}

        with sites.only_sites(site_id):
            rows = sites.live().query(query)

        for service_description, check_command, metrics in rows:
            response[service_description] = {
                "check_command": check_command,
                "metrics": self._get_metric_infos(metrics, check_command),
            }

        return response
Esempio n. 9
0
    def _livestatus_get_labels(
            self, only_sites: List[str]) -> List[Dict[SiteId, _Labels]]:
        """Get labels for all sites that need an update and the user is authorized for"""
        query: str = "GET services\n" "Cache: reload\n" "Columns: host_labels labels\n"  #  #

        with sites.prepend_site(), sites.only_sites(only_sites):
            rows = [(x[0], x[1], x[2]) for x in sites.live(user).query(query)]

        host_labels: Dict[SiteId, _Labels] = {}
        service_labels: Dict[SiteId, _Labels] = {}
        for row in rows:
            site_id = row[0]
            host_label = row[1]
            service_label = row[2]

            for key, value in host_label.items():
                host_labels.setdefault(site_id, {}).update({key: value})

            for key, value in service_label.items():
                service_labels.setdefault(site_id, {}).update({key: value})

        return [host_labels, service_labels]
Esempio n. 10
0
def find_host_services(
    host_name: str,
    service_description: str = ""
) -> Iterator[Tuple[str, str, Tuple[str, ...]]]:
    if not host_name and not service_description:  # optimization: avoid query with empty result
        return
    # TODO: site hint!

    # Also fetch host data with the *same* query. This saves one round trip. And head
    # host has at least one service
    query = (
        "GET services\n"
        "Columns: description check_command perf_data metrics host_check_command host_metrics \n"
    )

    if host_name:
        query += "Filter: host_name = %s\n" % livestatus.lqencode(host_name)

    if service_description:
        query += "Filter: service_description = %s\n" % livestatus.lqencode(
            service_description)

    host_check_command, host_metrics = None, None
    for (
            svc_desc,
            check_command,
            perf_data,
            rrd_metrics,
            host_check_command,
            host_metrics,
    ) in sites.live().query(query):
        parsed_perf_data, check_command = parse_perf_data(
            perf_data, check_command)
        known_metrics = set([perf[0]
                             for perf in parsed_perf_data] + rrd_metrics)
        yield svc_desc, check_command, tuple(known_metrics)

    if host_check_command:
        yield "_HOST_", host_check_command, tuple(host_metrics)
Esempio n. 11
0
    def _fetch_simple_number_data(self, properties, context):
        mode_properties = properties["render_mode"][1]
        time_range = self._int_time_range_from_rangespec(
            mode_properties["time_range"])
        filter_headers, only_sites = get_filter_headers(
            "log", self.filter_infos(), context)
        object_type_filter = self._get_object_type_filter(properties)

        query = ("GET log\n"
                 "Stats: log_type != \n"
                 "Filter: class = %d\n"
                 "Filter: log_time >= %f\n"
                 "Filter: log_time <= %f\n"
                 "%s"
                 "%s" % (self.log_class, time_range[0], time_range[1],
                         object_type_filter, lqencode(filter_headers)))

        with sites.only_sites(only_sites):
            try:
                return sites.live().query_summed_stats(query)
            except livestatus.MKLivestatusNotFoundError:
                raise MKGeneralException(_("The query returned no data."))
Esempio n. 12
0
def set_acknowledgement_for_service(params):
    """Acknowledge for a service globally"""
    service_description = unquote(params['service_description'])
    body = params['body']

    live = sites.live()

    services = Query(
        [Services.host_name, Services.description],
        And(
            Services.description.equals(service_description),
            Or(
                Services.state == 1,
                Services.state == 2,
            ),
        ),
    ).fetch_values(live)

    if not len(services):
        return problem(
            status=400,
            title=f'No services {service_description!r} with problems found.',
            detail='All services are OK.',
        )

    for _host_name, _service_description in services:
        acknowledge_service_problem(
            live,
            _host_name,
            _service_description,
            sticky=body.get('sticky', False),
            notify=body.get('notify', False),
            persistent=body.get('persistent', False),
            user=_user_id(),
            comment=body.get('comment', 'Acknowledged'),
        )

    return http.Response(status=204)
Esempio n. 13
0
    def choices(self) -> Choices:
        self.check_wato_data_update()
        # Note: WATO Folders that the user has not permissions to must not be visible.
        # Permissions in this case means, that the user has view permissions for at
        # least one host in that folder.
        result = sites.live().query(
            "GET hosts\nCache: reload\nColumns: filename\nStats: state >= 0\n")
        allowed_folders = {""}  # The root(Main directory)
        for path, _host_count in result:
            # convert '/wato/server/hosts.mk' to 'server'
            folder = path[6:-9]
            # allow the folder an all of its parents
            parts = folder.split("/")
            subfolder = ""
            for part in parts:
                if subfolder:
                    subfolder += "/"
                subfolder += part
                allowed_folders.add(subfolder)

        return [
            entry for entry in self.selection if entry[0] in allowed_folders
        ]
Esempio n. 14
0
def fetch_rrd_data(
    site: SiteId,
    host_name: HostName,
    service_description: ServiceName,
    metrics: set[MetricProperties],
    graph_recipe: GraphRecipe,
    graph_data_range: GraphDataRange,
) -> list[tuple[MetricProperties, TimeSeriesValues]]:
    start_time, end_time = graph_data_range["time_range"]

    step = graph_data_range["step"]
    # assumes str step is well formatted, colon separated step length & rrd point count
    if not isinstance(step, str):
        step = max(1, step)

    point_range = ":".join(map(str, (start_time, end_time, step)))
    lql_columns = list(
        rrd_columns(metrics, graph_recipe["consolidation_function"],
                    point_range))
    query = livestatus_lql([host_name], lql_columns, service_description)

    with sites.only_sites(site):
        return list(zip(metrics, sites.live().query_row(query)))
Esempio n. 15
0
File: wato.py Progetto: m4c3/checkMK
    def display(self):
        self.check_wato_data_update()
        # Note: WATO Folders that the user has not permissions to must not be visible.
        # Permissions in this case means, that the user has view permissions for at
        # least one host in that folder.
        result = sites.live().query(
            "GET hosts\nCache: reload\nColumns: filename\nStats: state >= 0\n")
        allowed_folders = set([""])
        for path, _host_count in result:
            # convert '/wato/server/hosts.mk' to 'server'
            folder = path[6:-9]
            # allow the folder an all of its parents
            parts = folder.split("/")
            subfolder = ""
            for part in parts:
                if subfolder:
                    subfolder += "/"
                subfolder += part
                allowed_folders.add(subfolder)

        html.dropdown(
            self.ident, [("", "")] +
            [entry for entry in self.selection if entry[0] in allowed_folders])
Esempio n. 16
0
    def _query_for_metrics_of_host(self, site_id, host_name, service_name):
        if not host_name or not service_name:
            return {}

        query = ("GET services\n"
                 "Columns: description check_command service_perf_data host_state service_state\n"
                 "Filter: host_name = %s\n"
                 "Filter: service_description = %s\n" %
                 (livestatus.lqencode(host_name), service_name))
        try:
            rows = sites.live().query(query)
        except Exception:
            raise MKGeneralException(
                _("The query for the given metric, service and host names returned no data."))

        for service_description, check_command, service_perf_data, host_state, svc_state in rows:
            return {
                "service_description": service_description,
                "check_command": check_command,
                "service_perf_data": service_perf_data,
                "host_state": host_state,
                "svc_state": svc_state,
            }
    def _get_data(cls, properties, context, return_column_headers=True):
        time_range = cls.int_time_range_from_rangespec(properties["time_range"])
        c_headers = "ColumnHeaders: on\n" if return_column_headers else ""
        filter_headers, only_sites = get_filter_headers("log", ["host", "service"], context)
        metrics = {
            "CPU load": "load1",
            "CPU utilization": "util",
        }
        service_desc = properties["service"]

        query = (
            "GET services\n"
            "Columns: host_name host_state service_description service_state service_check_command service_metrics service_perf_data rrddata:v1:%(metric)s:%(start)s:%(end)s:%(step)s\n"
            #  rrddata:m1:load1.max:%(start)s:%(end)s:%(step)s rrddata:m5:load5.max:%(start)s:%(end)s:%(step)s rrddata:m15:load15.max:%(start)s:%(end)s:%(step)s
            "%(column)s"
            "Filter: service_description ~~ %(service)s\n"
            "%(filter)s" % {
                "metric": metrics[service_desc],
                "start": time_range[0],
                "end": time_range[1],
                "step": 300,
                "service": service_desc,
                "column": c_headers,
                "filter": filter_headers,
            })

        with sites.only_sites(only_sites), sites.prepend_site():
            try:
                rows = sites.live().query(query)
            except MKTimeout:
                raise
            except Exception:
                raise MKGeneralException(_("The query returned no data."))

        if return_column_headers:
            return rows[0], rows[1:]
        return rows, ""
Esempio n. 18
0
def show_service(params):
    """Show the monitored service of a host"""
    service_description = params["service_description"]
    host_name = params["host_name"]
    live = sites.live()
    q = Query(
        [
            Services.description,
            Services.host_name,
            Services.state_type,
            Services.state,
            Services.last_check,
        ],
        filter_expr=And(
            Services.host_name.op("=", params["host_name"]),
            Services.description.op("=", service_description),
        ),
    )
    try:
        service = q.fetchone(live)
    except ValueError:
        return problem(
            status=404,
            title="The requested service was not found",
            detail=
            f"The service description {service_description} did not match any service",
        )
    return constructors.serve_json(
        constructors.domain_object(
            domain_type="service",
            identifier=f"{host_name}-{service_description}",
            title=f"Service {service_description}",
            extensions=service,
            links=[],
            editable=False,
            deletable=False,
        ))
Esempio n. 19
0
    def _get_data(cls, properties, context):
        time_range = cls._int_time_range_from_rangespec(
            properties["time_range"])
        filter_headers, only_sites = get_filter_headers(
            "log", cls.filter_infos(), context)

        query = (
            "GET log\n"
            "Columns: log_state host_name service_description log_type log_time\n"
            "Filter: class = %d\n"
            "Filter: log_time >= %f\n"
            "Filter: log_time <= %f\n"
            "Filter: log_type ~ %s .*\n"
            "%s" % (cls.log_class(), time_range[0], time_range[1],
                    lqencode(properties["log_target"].upper()),
                    lqencode(filter_headers)))

        with sites.only_sites(only_sites):
            try:
                return sites.live().query(query)
            except MKTimeout:
                raise
            except Exception as _e:
                raise MKGeneralException(_("The query returned no data."))
Esempio n. 20
0
def delete_downtime(params):
    """Delete a scheduled downtime"""
    body = params['body']
    live = sites.live()
    delete_type = body['delete_type']
    if delete_type == "query":
        downtime_commands.delete_downtime_with_query(live, body['query'])
    elif delete_type == "by_id":
        downtime_commands.delete_downtime(live, body['downtime_id'])
    elif delete_type == "params":
        hostname = body['hostname']
        if "services" not in body:
            host_query = {"op": "~", "left": "downtimes.host_name", "right": hostname}
            downtime_commands.delete_downtime_with_query(live, host_query)
        else:
            services_query = {
                "op": "and",
                "expr": [{
                    'op': '=',
                    'left': 'downtimes.host_name',
                    'right': body['hostname']
                }, {
                    'op': 'or',
                    'expr': [{
                        'op': '=',
                        'left': 'downtimes.service_description',
                        'right': service_description
                    } for service_description in body['services']]
                }]
            }
            downtime_commands.delete_downtime_with_query(live, services_query)
    else:
        return problem(status=400,
                       title="Unhandled delete_type.",
                       detail=f"The downtime-type {delete_type!r} is not supported.")
    return Response(status=204)
Esempio n. 21
0
def show_downtimes(param):
    """Show all scheduled downtimes"""
    live = sites.live()
    sites_to_query = param.get('sites')
    if sites_to_query:
        live.only_sites = sites_to_query

    q = Query([
        Downtimes.id,
        Downtimes.host_name,
        Downtimes.service_description,
        Downtimes.is_service,
        Downtimes.author,
        Downtimes.start_time,
        Downtimes.end_time,
        Downtimes.recurring,
        Downtimes.comment,
    ])

    query_expr = param.get('query')
    if query_expr is not None:
        q = q.filter(query_expr)

    host_name = param.get('host_name')
    if host_name is not None:
        q = q.filter(
            And(Downtimes.host_name.op("=", host_name),
                Downtimes.is_service.equals(0)))

    service_description = param.get('service_description')
    if service_description is not None:
        q = q.filter(
            Downtimes.service_description.contains(service_description))

    gen_downtimes = q.iterate(live)
    return _serve_downtimes(gen_downtimes)
Esempio n. 22
0
    def show(self):
        mode = self._host_mode_ident()
        sites.live().set_prepend_site(True)
        query = "GET hosts\nColumns: name state worst_service_state\nLimit: 100\n"
        view = "host"

        if mode == "problems":
            view = "problemsofhost"
            # Exclude hosts and services in downtime
            svc_query = "GET services\nColumns: host_name\n"\
                        "Filter: state > 0\nFilter: scheduled_downtime_depth = 0\n"\
                        "Filter: host_scheduled_downtime_depth = 0\nAnd: 3"
            problem_hosts = {x[1] for x in sites.live().query(svc_query)}

            query += "Filter: state > 0\nFilter: scheduled_downtime_depth = 0\nAnd: 2\n"
            for host in problem_hosts:
                query += "Filter: name = %s\n" % host
            query += "Or: %d\n" % (len(problem_hosts) + 1)

        hosts = sites.live().query(query)
        sites.live().set_prepend_site(False)
        hosts.sort()

        longestname = 0
        for site, host, state, worstsvc in hosts:
            longestname = max(longestname, len(host))
        if longestname > 15:
            num_columns = 1
        else:
            num_columns = 2

        target = views.get_context_link(config.user.id, view)
        html.open_table(class_="allhosts")
        col = 1
        for site, host, state, worstsvc in hosts:
            if col == 1:
                html.open_tr()
            html.open_td()

            if state > 0 or worstsvc == 2:
                statecolor = 2
            elif worstsvc == 1:
                statecolor = 1
            elif worstsvc == 3:
                statecolor = 3
            else:
                statecolor = 0
            html.open_div(class_=["statebullet", "state%d" % statecolor])
            html.nbsp()
            html.close_div()
            link(host, target + "&host=%s&site=%s" % (html.urlencode(host), html.urlencode(site)))
            html.close_td()
            if col == num_columns:
                html.close_tr()
                col = 1
            else:
                col += 1

        if col < num_columns:
            html.close_tr()
        html.close_table()
Esempio n. 23
0
    def show(self):
        items = [
            ("enable_notifications", _("Notifications")),
            ("execute_service_checks", _("Service checks")),
            ("execute_host_checks", _("Host checks")),
            ("enable_flap_detection", _("Flap Detection")),
            ("enable_event_handlers", _("Event handlers")),
            ("process_performance_data", _("Performance data")),
            ("enable_event_handlers", _("Alert handlers")),
        ]

        sites.update_site_states_from_dead_sites()

        site_status_info = {}
        try:
            sites.live().set_prepend_site(True)
            for row in sites.live().query("GET status\nColumns: %s" %
                                          " ".join([i[0] for i in items])):
                site_id, values = row[0], row[1:]
                site_status_info[site_id] = values
        finally:
            sites.live().set_prepend_site(False)

        def _render_master_control_site(site_id):
            site_state = sites.states().get(site_id)
            if site_state["state"] == "dead":
                html.show_error(site_state["exception"])

            elif site_state["state"] == "disabled":
                html.show_message(_("Site is disabled"))

            elif site_state["state"] == "unknown":
                if site_state.get("exception"):
                    html.show_error(site_state["exception"])
                else:
                    html.show_error(_("Site state is unknown"))

            else:
                is_cmc = site_state["program_version"].startswith("Check_MK ")

                try:
                    site_info = site_status_info[site_id]
                except KeyError:
                    site_info = None

                html.open_table(class_="master_control")
                for i, (colname, title) in enumerate(items):
                    # Do not show event handlers on Check_MK Micro Core
                    if is_cmc and title == _("Event handlers"):
                        continue
                    elif not is_cmc and title == _("Alert handlers"):
                        continue

                    colvalue = site_info[i]
                    url = html.makeactionuri_contextless(
                        [
                            ("site", site_id),
                            ("switch", colname),
                            ("state", "%d" % (1 - colvalue)),
                        ],
                        filename="switch_master_state.py")
                    onclick = "cmk.ajax.get_url('%s', cmk.utils.update_contents, 'snapin_master_control')" % url

                    html.open_tr()
                    html.td(title, class_="left")
                    html.open_td()
                    html.toggle_switch(
                        enabled=colvalue,
                        help_txt=_("Switch '%s' to '%s'") %
                        (title, _("off") if colvalue else _("on")),
                        onclick=onclick,
                    )
                    html.close_td()
                    html.close_tr()

                html.close_table()

        for site_id, site_alias in config.sorted_sites():
            if not config.is_single_local_site():
                html.begin_foldable_container("master_control", site_id, True,
                                              site_alias)

            try:
                _render_master_control_site(site_id)
            except Exception as e:
                logger.exception("error rendering master control for site %s",
                                 site_id)
                write_snapin_exception(e)
            finally:
                if not config.is_single_local_site():
                    html.end_foldable_container()
Esempio n. 24
0
def create_downtime(params):
    """Create a scheduled downtime"""
    body = params['body']
    downtime_type: DowntimeType = body['downtime_type']
    if downtime_type == 'host':
        downtime_commands.schedule_host_downtime(
            sites.live(),
            host_name=body['host_name'],
            start_time=body['start_time'],
            end_time=body['end_time'],
            recur=body['recur'],
            duration=body['duration'],
            user_id=config.user.ident,
            comment=body.get('comment',
                             f"Downtime for host {body['host_name']!r}"),
        )
    elif downtime_type == 'hostgroup':
        downtime_commands.schedule_hostgroup_host_downtime(
            sites.live(),
            hostgroup_name=body['hostgroup_name'],
            start_time=body['start_time'],
            end_time=body['end_time'],
            recur=body['recur'],
            duration=body['duration'],
            user_id=config.user.ident,
            comment=body.get(
                'comment',
                f"Downtime for hostgroup {body['hostgroup_name']!r}"),
        )
    elif downtime_type == 'service':
        downtime_commands.schedule_service_downtime(
            sites.live(),
            host_name=body['host_name'],
            service_description=body['service_descriptions'],
            start_time=body['start_time'],
            end_time=body['end_time'],
            recur=body['recur'],
            duration=body['duration'],
            user_id=config.user.ident,
            comment=body.get(
                'comment',
                f"Downtime for services {', '.join(body['service_descriptions'])!r}@{body['host_name']!r}"
            ),
        )
    elif downtime_type == 'servicegroup':
        downtime_commands.schedule_servicegroup_service_downtime(
            sites.live(),
            servicegroup_name=body['servicegroup_name'],
            start_time=body['start_time'],
            end_time=body['end_time'],
            recur=body['recur'],
            duration=body['duration'],
            user_id=config.user.ident,
            comment=body.get(
                'comment',
                f"Downtime for servicegroup {body['servicegroup_name']!r}"),
        )
    else:
        return problem(
            status=400,
            title="Unhandled downtime-type.",
            detail=f"The downtime-type {downtime_type!r} is not supported.")

    return Response(status=204)
Esempio n. 25
0
def set_acknowledgement_on_hosts(params):
    """Set acknowledgement on related hosts"""
    body = params['body']
    live = sites.live()

    sticky = body['sticky']
    notify = body['notify']
    persistent = body['persistent']
    comment = body['comment']

    acknowledge_type = body['acknowledge_type']

    if acknowledge_type == 'host':
        name = body['host_name']
        host_state = Query([Hosts.state], Hosts.name == name).value(live)
        if not host_state:
            raise ProblemException(
                status=422,
                title=f'Host {name!r} has no problem.',
            )
        acknowledge_host_problem(
            live,
            name,
            sticky=sticky,
            notify=notify,
            persistent=persistent,
            user=config.user.ident,
            comment=comment,
        )
    elif acknowledge_type == 'hostgroup':
        host_group = body['hostgroup_name']
        try:
            acknowledge_hostgroup_problem(
                live,
                host_group,
                sticky=sticky,
                notify=notify,
                persistent=persistent,
                user=config.user.ident,
                comment=comment,
            )
        except ValueError:
            raise ProblemException(
                404,
                title="Hostgroup could not be found.",
                detail=f"Unknown hostgroup: {host_group}",
            )
    elif acknowledge_type == 'host_by_query':
        query = body['query']
        hosts = Query([Hosts.name], query).fetchall(live)
        if not hosts:
            raise ProblemException(
                status=422,
                title="The provided query returned no monitored hosts",
            )
        for host in hosts:
            acknowledge_host_problem(
                live,
                host.name,
                sticky=sticky,
                notify=notify,
                persistent=persistent,
                user=config.user.ident,
                comment=comment,
            )
    else:
        raise ProblemException(
            status=400,
            title="Unhandled acknowledge-type.",
            detail=
            f"The acknowledge-type {acknowledge_type!r} is not supported.",
        )

    return http.Response(status=204)
Esempio n. 26
0
def set_acknowledgement_on_services(params):
    """Set acknowledgement on related services"""
    body = params['body']
    live = sites.live()

    sticky = body['sticky']
    notify = body['notify']
    persistent = body['persistent']
    comment = body['comment']
    acknowledge_type = body['acknowledge_type']

    if acknowledge_type == 'service':
        description = unquote(body['service_description'])
        host_name = body['host_name']
        service = Query(
            [Services.host_name, Services.description, Services.state],
            And(Services.host_name == host_name,
                Services.description == description)).first(live)
        if not service:
            raise ProblemException(
                status=404,
                title=
                f'Service {description!r}@{host_name!r} could not be found.',
            )
        if not service.state:
            raise ProblemException(
                status=422,
                title=f'Service {description!r}@{host_name!r} has no problem.',
            )
        acknowledge_service_problem(
            live,
            service.host_name,
            service.description,
            sticky=sticky,
            notify=notify,
            persistent=persistent,
            user=config.user.ident,
            comment=comment,
        )
    elif acknowledge_type == 'servicegroup':
        service_group = body['servicegroup_name']
        try:
            acknowledge_servicegroup_problem(
                live,
                service_group,
                sticky=sticky,
                notify=notify,
                persistent=persistent,
                user=config.user.ident,
                comment=comment,
            )
        except ValueError:
            raise ProblemException(
                status=404,
                title="Servicegroup could not be found.",
                detail=f"Unknown servicegroup: {service_group}",
            )
    elif acknowledge_type == 'service_by_query':
        services = Query(
            [Services.host_name, Services.description, Services.state],
            body['query'],
        ).fetchall(live)
        if not services:
            raise ProblemException(
                status=422,
                title='No services with problems found.',
                detail='All queried services are OK.',
            )

        for service in services:
            if not service.state:
                continue
            acknowledge_service_problem(
                live,
                service.host_name,
                service.description,
                sticky=sticky,
                notify=notify,
                persistent=persistent,
                user=config.user.ident,
                comment=comment,
            )
    else:
        raise ProblemException(
            status=400,
            title="Unhandled acknowledge-type.",
            detail=
            f"The acknowledge-type {acknowledge_type!r} is not supported.",
        )

    return http.Response(status=204)
Esempio n. 27
0
def host_is_monitored(host_name: str) -> bool:
    return bool(
        Query([Hosts.name], Hosts.name == host_name).first_value(sites.live()))
Esempio n. 28
0
 def _query_for_host_names(self, site_id):
     with sites.only_sites(site_id):
         return sites.live().query_column("GET hosts\nColumns: name\n")
Esempio n. 29
0
def all_logs():
    sites.live().set_prepend_site(True)
    rows = sites.live().query("GET hosts\n"
                              "Columns: name mk_logwatch_files\n")
    sites.live().set_prepend_site(False)
    return rows
Esempio n. 30
0
def acknowledge_logfile(site, host_name, int_filename, display_name):
    if not may_see(site, host_name):
        raise MKAuthException(_('Permission denied.'))

    command = "MK_LOGWATCH_ACKNOWLEDGE;%s;%s" % (host_name, int_filename)
    sites.live().command("[%d] %s" % (int(time.time()), command), site)