Esempio n. 1
0
def bulk_set_acknowledgement_on_host_service(params):
    """Bulk Acknowledge specific services on specific host"""
    live = sites.live()
    body = params['body']
    host_name = body['host_name']
    entries = body.get('entries', [])

    query = Query([Services.description, Services.state],
                  And(
                      Services.host_name.equals(host_name),
                      Or(*[
                          Services.description.equals(service_description)
                          for service_description in entries
                      ])))

    services = query.to_dict(live)

    not_found = []
    for service_description in entries:
        if service_description not in services:
            not_found.append(service_description)

    if not_found:
        return problem(
            status=400,
            title=
            f"Services {', '.join(not_found)} not found on host {host_name}",
            detail='Currently not monitored')

    up_services = []
    for service_description in entries:
        if services[service_description] == 0:
            up_services.append(service_description)

    if up_services:
        return problem(
            status=400,
            title=f"Services {', '.join(up_services)} do not have a problem",
            detail="The states of these services are OK")

    for service_description in entries:
        acknowledge_service_problem(
            sites.live(),
            host_name,
            service_description,
            sticky=body.get('sticky', False),
            notify=body.get('notify', False),
            persistent=body.get('persistent', False),
            user=str(config.user.id),
            comment=body.get('comment', 'Acknowledged'),
        )
    return http.Response(status=204)
Esempio n. 2
0
def set_acknowledgement_on_hostgroup(params):
    """Acknowledge for hosts of a host group"""
    body = params['body']
    acknowledge_hostgroup_problem(
        sites.live(),
        params['hostgroup_name'],
        sticky=body['sticky'],
        notify=body['notify'],
        persistent=body['persistent'],
        user=config.user.ident,
        comment=body['comment'],
    )
    return http.Response(status=204)
Esempio n. 3
0
def set_acknowledgement_on_service_related(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':
        return _set_acknowledgement_for_service(
            live,
            unquote(body['service_description']),
            sticky,
            notify,
            persistent,
            comment,
        )

    if acknowledge_type == 'servicegroup':
        acknowledge_servicegroup_problem(
            live,
            body['servicegroup_name'],
            sticky=sticky,
            notify=notify,
            persistent=persistent,
            user=_user_id(),
            comment=comment,
        )
        return http.Response(status=204)

    if acknowledge_type == 'service_by_query':
        q = Query([Services.host_name, Services.description,
                   Services.state]).filter(tree_to_expr(body['query']))
        return _set_acknowledgement_on_queried_services(
            live,
            [(row['host_name'], row['description'])
             for row in q.iterate(live) if row['state'] > 0],
            sticky=sticky,
            notify=notify,
            persistent=persistent,
            comment=comment,
        )

    return problem(
        status=400,
        title="Unhandled acknowledge-type.",
        detail=f"The acknowledge-type {acknowledge_type!r} is not supported.")
Esempio n. 4
0
def mock_livestatus(
    with_context: bool = False,
    with_html: bool = False
) -> Generator[MockLiveStatusConnection, None, None]:
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)
    resp = http.Response()

    app_context: ContextManager
    req_context: ContextManager
    if with_html:
        html_obj = None
    else:
        html_obj = html(
            request=req,
            response=resp,
            output_funnel=OutputFunnel(resp),
            output_format="html",
        )
    if with_context:
        app_context = AppContext(None)
        req_context = RequestContext(
            html_obj=html_obj,
            req=req,
            resp=resp,
            funnel=OutputFunnel(resp),
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, \
         mock.patch("cmk.gui.sites._get_enabled_and_disabled_sites",
                    new=live.enabled_and_disabled_sites), \
         mock.patch("livestatus.MultiSiteConnection.set_prepend_site",
                    new=live.set_prepend_site), \
         mock.patch("livestatus.MultiSiteConnection.expect_query",
                    new=live.expect_query, create=True), \
         mock.patch("livestatus.SingleSiteConnection._create_socket", new=live.create_socket), \
         mock.patch.dict(os.environ, {'OMD_ROOT': '/', 'OMD_SITE': 'NO_SITE'}):

        # We don't want to be polluted by other tests.
        version.omd_site.cache_clear()
        yield live
        # We don't want to pollute other tests.
        version.omd_site.cache_clear()
Esempio n. 5
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     resp = http.Response()
     with AppContext(app), RequestContext(
             req=req,
             resp=resp,
             funnel=OutputFunnel(resp),
             config_obj=config.make_config_object(
                 config.get_default_config()),
             user=LoggedInNobody(),
             display_options=DisplayOptions(),
     ), cmk.utils.store.cleanup_locks(), sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
Esempio n. 6
0
def bulk_set_acknowledgement_on_hosts(params):
    """Bulk acknowledge for hosts"""
    live = sites.live()
    entries = params['entries']

    hosts: Dict[str, int] = {
        host_name: host_state
        for host_name, host_state in Query(  # pylint: disable=unnecessary-comprehension
            [Hosts.name, Hosts.state],
            And(*[Hosts.name.equals(host_name) for host_name in entries]),
        ).fetch_values(live)
    }

    not_found = []
    for host_name in entries:
        if host_name not in hosts:
            not_found.append(host_name)

    if not_found:
        return problem(status=400,
                       title=f"Hosts {', '.join(not_found)} not found",
                       detail='Current not monitored')

    up_hosts = []
    for host_name in entries:
        if hosts[host_name] == 0:
            up_hosts.append(host_name)

    if up_hosts:
        return problem(
            status=400,
            title=f"Hosts {', '.join(up_hosts)} do not have a problem",
            detail="The states of these hosts are UP")

    for host_name in entries:
        acknowledge_host_problem(
            sites.live(),
            host_name,
            sticky=params.get('sticky'),
            notify=params.get('notify'),
            persistent=params.get('persistent'),
            user=_user_id(),
            comment=params.get('comment', 'Acknowledged'),
        )
    return http.Response(status=204)
Esempio n. 7
0
def _set_acknowledgement_on_hostgroup(
    connection,
    hostgroup_name: str,
    sticky: bool,
    notify: bool,
    persistent: bool,
    comment: str,
):
    """Acknowledge for hosts of a host group"""
    acknowledge_hostgroup_problem(
        connection,
        hostgroup_name,
        sticky=sticky,
        notify=notify,
        persistent=persistent,
        user=_user_id(),
        comment=comment,
    )
    return http.Response(status=204)
Esempio n. 8
0
def delete_rule(param):
    """Delete a rule"""
    rule_id = param["rule_id"]
    rule: watolib.Rule
    all_sets = watolib.AllRulesets()
    all_sets.load()

    found = False
    for ruleset in all_sets.get_rulesets().values():
        for _folder, _index, rule in ruleset.get_rules():
            if rule.id == rule_id:
                ruleset.delete_rule(rule)
                all_sets.save()
                found = True
    if found:
        return http.Response(status=204)

    return problem(
        status=404,
        title="Rule not found.",
        detail=f"The rule with ID {rule_id!r} could not be found.",
    )
Esempio n. 9
0
def _set_acknowledgement_for_service(
    connection,
    service_description: str,
    sticky: bool,
    notify: bool,
    persistent: bool,
    comment: str,
):
    q = Query([Services.host_name, Services.description,
               Services.state]).filter(
                   tree_to_expr({
                       'op': '=',
                       'left': 'services.description',
                       'right': service_description
                   }))
    services = list(q.iterate(connection))

    if not len(services):
        return problem(
            status=404,
            title=f'No services with {service_description!r} were found.',
        )

    for service in services:
        if service.state == 0:
            continue
        acknowledge_service_problem(
            connection,
            service.host_name,
            service.description,
            sticky=sticky,
            notify=notify,
            persistent=persistent,
            user=_user_id(),
            comment=comment,
        )

    return http.Response(status=204)
Esempio n. 10
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. 11
0
def set_acknowledgement_on_host_service(params):
    """Acknowledge for services on a host"""
    host_name = params['host_name']
    service_description = unquote(params['service_description'])
    body = params['body']

    service = Query([Services.description, Services.state],
                    And(Services.description.equals(service_description),
                        Services.host_name.equals(host_name))).first(
                            sites.live())

    if service is None:
        return problem(
            status=404,
            title=
            f'Service {service_description!r} on host {host_name!r} does not exist.',
            detail='It is not currently monitored.',
        )

    if service.state == 0:
        return problem(
            status=400,
            title=f"Service {service_description!r} does not have a problem.",
            detail="The state is OK.")

    acknowledge_service_problem(
        sites.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. 12
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. 13
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. 14
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=400,
                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=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=user.ident,
                comment=comment,
            )
        except ValueError:
            raise ProblemException(
                status=400,
                title="Service group could not be found.",
                detail=f"Unknown service group: {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=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. 15
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     resp = http.Response(is_secure=req.is_secure)
     with AppContext(app), RequestContext(req=req, resp=resp):
         return app(environ, start_response)