Ejemplo n.º 1
0
def serve_json(data, profile=None):
    content_type = 'application/json'
    if profile is not None:
        content_type += ';profile="%s"' % (profile, )
    response = Response()
    response.set_content_type(content_type)
    response.set_data(json.dumps(data))
    # HACK: See wrap_with_validation.
    response.original_data = data  # type: ignore[attr-defined]
    return response
Ejemplo n.º 2
0
def delete_downtime(params):
    """Delete downtime"""
    is_service = Query(
        [Downtimes.is_service],
        Downtimes.id.contains(params['downtime_id']),
    ).value(sites.live())
    downtime_type = "SVC" if is_service else "HOST"
    command_delete = remove_downtime_command(downtime_type, params['downtime_id'])
    execute_livestatus_command(command_delete, params['host_name'])
    return Response(status=204)
Ejemplo n.º 3
0
def delete_password(params):
    """Delete a password"""
    ident = params['name']
    if ident not in load_passwords():
        return problem(
            404, f'Password "{ident}" is not known.',
            'The password you asked for is not known. Please check for eventual misspellings.'
        )
    remove_password(ident)
    return Response(status=204)
Ejemplo n.º 4
0
def link_with_uuid(params) -> Response:
    """Link a host to a UUID"""
    with may_fail(MKAuthException):
        host = _check_host_editing_permissions(host_name := params["host_name"])
    _link_with_uuid(
        host_name,
        host,
        params["body"]["uuid"],
    )
    return Response(status=204)
Ejemplo n.º 5
0
def delete_password(params):
    """Delete a password"""
    ident = params['name']
    entries = load_passwords_to_modify()
    if ident not in entries:
        return problem(
            404, f'Password "{ident}" is not known.',
            'The password you asked for is not known. Please check for eventual misspellings.')
    _ = entries.pop(ident)
    return Response(status=204)
Ejemplo n.º 6
0
def delete(params):
    """Delete a time period"""
    name = params['name']
    time_periods = load_timeperiods()
    if name not in time_periods:
        raise ProblemException(404, http.client.responses[404],
                               f"Time period {name} not found")
    del time_periods[name]
    save_timeperiods(time_periods)
    return Response(status=204)
Ejemplo n.º 7
0
def delete_user(params):
    """Delete a user"""
    username = params['username']
    try:
        delete_users([username])
    except MKUserError:
        return problem(
            404, f'User "{username}" is not known.',
            'The user to delete does not exist. Please check for eventual misspellings.')
    return Response(status=204)
Ejemplo n.º 8
0
def _serve_password(ident, password_details):
    response = Response()
    response.set_data(
        json.dumps(
            serialize_password(ident, complement_customer(password_details))))
    response.set_content_type("application/json")
    response.headers.add(
        "ETag",
        constructors.etag_of_dict(password_details).to_header())
    return response
Ejemplo n.º 9
0
def delete_password(params):
    """Delete a password"""
    ident = params["name"]
    if ident not in load_passwords():
        return problem(
            status=404,
            title='Password "{ident}" is not known.',
            detail="The password you asked for is not known. Please check for eventual misspellings.",
        )
    remove_password(ident)
    return Response(status=204)
Ejemplo n.º 10
0
def create_timeperiod(params):
    """Create a time period"""
    body = params['body']
    exceptions = _format_exceptions(body.get("exceptions", []))
    periods = _daily_time_ranges(body["active_time_ranges"])
    time_period = _time_period(alias=body['alias'],
                               periods=periods,
                               exceptions=exceptions,
                               exclude=body.get("exclude", []))
    save_timeperiod(body['name'], time_period)
    return Response(status=204)
Ejemplo n.º 11
0
def _serve_services(
    host: watolib.CREHost,
    discovered_services: CheckTable,
    discovery_phases: List[str],
):
    response = Response()
    response.set_data(
        json.dumps(serialize_service_discovery(host, discovered_services, discovery_phases)))

    response.set_content_type('application/json')
    return response
Ejemplo n.º 12
0
def create_host_related_downtime(params):
    """Create a host related scheduled downtime"""
    body = params['body']
    live = sites.live()

    downtime_type: DowntimeType = body['downtime_type']

    if downtime_type == 'host':
        downtime_commands.schedule_host_downtime(
            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(
            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 == 'host_by_query':
        try:
            downtime_commands.schedule_hosts_downtimes_with_query(
                live,
                body['query'],
                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', ''),
            )
        except QueryException:
            return problem(
                status=422,
                title="Query did not match any host",
                detail="The provided query returned an empty list so no downtime was set",
            )
    else:
        return problem(status=400,
                       title="Unhandled downtime-type.",
                       detail=f"The downtime-type {downtime_type!r} is not supported.")

    return Response(status=204)
Ejemplo n.º 13
0
def activate_changes_wait_for_completion(params):
    """Wait for activation completion

    This endpoint will periodically redirect on itself to prevent timeouts.
    """
    activation_id = params['activation_id']
    manager = watolib.ActivateChangesManager()
    manager.load()
    try:
        manager.load_activation(activation_id)
    except MKUserError:
        raise ProblemException(
            status=404, title=f"Activation {activation_id!r} not found.")
    done = manager.wait_for_completion(timeout=request.request_timeout - 10)
    if not done:
        response = Response(status=302)
        response.location = request.url
        return response

    return Response(status=204)
Ejemplo n.º 14
0
def with_request_context():
    environ = create_environ()
    resp = Response()
    with AppContext(session_wsgi_app(debug=False)), RequestContext(
            req=Request(environ),
            resp=resp,
            funnel=OutputFunnel(resp),
            config_obj=make_config_object(get_default_config()),
            display_options=DisplayOptions(),
    ):
        yield
Ejemplo n.º 15
0
    def run(self):
        self._logger.log(VERBOSE, "Updating Checkmk configuration...")

        environ = dict(create_environ(), REQUEST_URI='')
        with AppContext(DummyApplication(environ, None)), \
             RequestContext(htmllib.html(Request(environ), Response(is_secure=False))):
            self._initialize_gui_environment()
            for step_func, title in self._steps():
                self._logger.log(VERBOSE, " + %s..." % title)
                step_func()

        self._logger.log(VERBOSE, "Done")
Ejemplo n.º 16
0
def delete(params):
    """Delete a time period"""
    user.need_permission("wato.edit")
    user.need_permission("wato.timeperiods")
    name = params["name"]
    time_periods = load_timeperiods()
    if name not in time_periods:
        raise ProblemException(404, http.client.responses[404],
                               f"Time period {name} not found")
    del time_periods[name]
    save_timeperiods(time_periods)
    return Response(status=204)
Ejemplo n.º 17
0
def serve_user(user_id):
    response = Response()
    user_attributes_internal = _load_user(user_id)
    user_attributes = _internal_to_api_format(user_attributes_internal)
    response.set_data(
        json.dumps(
            serialize_user(user_id, complement_customer(user_attributes))))
    response.set_content_type("application/json")
    response.headers.add(
        "ETag",
        constructors.etag_of_dict(user_attributes).to_header())
    return response
Ejemplo n.º 18
0
def bulk_delete(params):
    """Bulk delete service groups"""
    entries = params['entries']
    for group_name in entries:
        _group = fetch_group(group_name,
                             "service",
                             status=400,
                             message="service group %s was not found" %
                             group_name)
    for group_name in entries:
        watolib.delete_group(group_name, group_type='service')
    return Response(status=204)
Ejemplo n.º 19
0
def create_password(params):
    """Create a password"""
    body = params['body']
    ident = body['ident']
    password_details = {
        k: v
        for k, v in body.items() if k not in ("ident", "owned_by")
    }
    password_details[
        "owned_by"] = None if body['owned_by'] == "admin" else body['owned_by']
    save_password(ident, password_details)
    return Response(status=204)
Ejemplo n.º 20
0
def delete_bi_rule(params):
    """Delete BI rule"""
    bi_packs = get_cached_bi_packs()
    bi_packs.load_config()
    try:
        bi_rule = bi_packs.get_rule_mandatory(params["rule_id"])
    except KeyError:
        _bailout_with_message("Unknown bi_rule: %s" % params["rule_id"])

    bi_packs.delete_rule(bi_rule.id)
    bi_packs.save_config()
    return Response(status=204)
Ejemplo n.º 21
0
def delete_bi_aggregation(params):
    """Delete a BI aggregation"""
    bi_packs = get_cached_bi_packs()
    bi_packs.load_config()
    try:
        bi_aggregation = bi_packs.get_aggregation_mandatory(params["aggregation_id"])
    except KeyError:
        _bailout_with_message("Unknown bi_aggregation: %s" % params["aggregation_id"])

    bi_packs.delete_aggregation(bi_aggregation.id)
    bi_packs.save_config()
    return Response(status=204)
Ejemplo n.º 22
0
def create_service_related_downtime(params):
    """Create a service related scheduled downtime"""
    body = params['body']
    live = sites.live()

    downtime_type: DowntimeType = body['downtime_type']

    if downtime_type == 'service':
        downtime_commands.schedule_service_downtime(
            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(
            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}"),
        )
    elif downtime_type == 'service_by_query':
        downtime_commands.schedule_services_downtimes_with_query(
            live,
            query=body['query'],
            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', ''),
        )
    else:
        return problem(
            status=400,
            title="Unhandled downtime-type.",
            detail=f"The downtime-type {downtime_type!r} is not supported.")

    return Response(status=204)
Ejemplo n.º 23
0
def activate_changes(params):
    """Activate pending changes"""
    body = params['body']
    sites = body['sites']
    with may_fail(MKUserError, status=400):
        activation_id = watolib.activate_changes_start(sites)
    if body['redirect']:
        wait_for = _completion_link(activation_id)
        response = Response(status=301)
        response.location = wait_for['href']
        return response

    return _serve_activation_run(activation_id, is_running=True)
Ejemplo n.º 24
0
def _serve_services(
    host: CREHost,
    discovered_services: Sequence[CheckPreviewEntry],
    discovery_phases: List[str],
) -> Response:
    response = Response()
    response.set_data(
        json.dumps(
            serialize_service_discovery(host, discovered_services,
                                        discovery_phases)))

    response.set_content_type("application/json")
    return response
Ejemplo n.º 25
0
def bulk_delete(params):
    """Bulk delete contact groups"""
    entries = params['entries']
    for group_name in entries:
        _group = fetch_group(
            group_name,
            "contact",
            status=400,
            message=f"contact group {group_name} was not found",
        )
    for group_name in entries:
        watolib.delete_group(group_name, 'contact')
    return Response(status=204)
Ejemplo n.º 26
0
def delete_user(params):
    """Delete a user"""
    username = params["username"]
    try:
        delete_users([username])
    except MKUserError:
        return problem(
            status=404,
            title=f'User "{username}" is not known.',
            detail=
            "The user to delete does not exist. Please check for eventual misspellings.",
        )
    return Response(status=204)
Ejemplo n.º 27
0
def delete_downtime(params):
    live = sites.live()

    q = Query([Downtimes.id, Downtimes.is_service])

    q = q.filter(Downtimes.id.contains(params['downtime_id']))
    gen_downtime = q.iterate(live)
    downtime_info = next(gen_downtime)
    downtime_type = "SVC" if downtime_info['is_service'] else "HOST"
    command_delete = remove_downtime_command(downtime_type,
                                             params['downtime_id'])
    execute_livestatus_command(command_delete, params['host_name'])
    return Response(status=204)
Ejemplo n.º 28
0
def update_service_phase(params):
    """Update the phase of a service"""
    body = params['body']
    host = watolib.Host.host(params["host_name"])
    target_phase = body["target_phase"]
    check_type = body['check_type']
    service_item = body['service_item']
    _update_single_service_phase(
        target_phase,
        host,
        check_type,
        service_item,
    )
    return Response(status=204)
Ejemplo n.º 29
0
def update_service_phase(params) -> Response:
    """Update the phase of a service"""
    body = params["body"]
    host = Host.load_host(params["host_name"])
    target_phase = body["target_phase"]
    check_type = body["check_type"]
    service_item = body["service_item"]
    _update_single_service_phase(
        SERVICE_DISCOVERY_PHASES[target_phase],
        host,
        check_type,
        service_item,
    )
    return Response(status=204)
Ejemplo n.º 30
0
def bulk_delete(params):
    """Bulk delete service groups"""
    user.need_permission("wato.edit")
    body = params["body"]
    entries = body["entries"]
    for group_name in entries:
        _group = fetch_group(group_name,
                             "service",
                             status=400,
                             message="service group %s was not found" %
                             group_name)
    for group_name in entries:
        groups.delete_group(group_name, group_type="service")
    return Response(status=204)