Exemple #1
0
def _serve_host(host, effective_attributes=False):
    response = Response()
    response.set_data(json.dumps(serialize_host(host, effective_attributes)))
    response.set_content_type('application/json')
    etag = etag_of_host(host)
    response.headers.add('ETag', etag.to_header())
    return response
Exemple #2
0
def _serve_host_tag_group(tag_details: Dict[str, Any]) -> Response:
    response = Response()
    response.set_data(json.dumps(serialize_host_tag_group(tag_details)))
    response.set_content_type('application/json')
    response.headers.add('ETag',
                         constructors.etag_of_dict(tag_details).to_header())
    return response
Exemple #3
0
def serve_group(group, serializer):
    response = Response()
    response.set_data(json.dumps(serializer(group)))
    if response.status_code != 204:
        response.set_content_type('application/json')
    response.headers.add('ETag', constructors.etag_of_dict(group).to_header())
    return response
Exemple #4
0
def _serve_time_period(time_period):
    response = Response()
    response.set_data(json.dumps(time_period))
    response.set_content_type("application/json")
    response.headers.add("ETag",
                         constructors.etag_of_dict(time_period).to_header())
    return response
Exemple #5
0
def serve_user(user_id):
    response = Response()
    user_attributes = user_config_attributes(user_id)
    response.set_data(json.dumps(serialize_user(user_id, user_attributes)))
    response.set_content_type('application/json')
    response.headers.add('ETag', constructors.etag_of_dict(user_attributes).to_header())
    return response
Exemple #6
0
def _serve_host(host, effective_attributes=False):
    response = Response()
    response.set_data(json.dumps(serialize_host(host, effective_attributes)))
    response.set_content_type("application/json")
    etag = constructors.etag_of_dict(_host_etag_values(host))
    response.headers.add("ETag", etag.to_header())
    return response
Exemple #7
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)
def bulk_delete(params):
    """Bulk delete service groups"""
    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:
        watolib.delete_group(group_name, group_type="service")
    return Response(status=204)
Exemple #9
0
def serve_json(data: Serializable,
               profile: Optional[Dict[str, str]] = None) -> Response:
    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
Exemple #10
0
    def run(self):
        self._logger.log(VERBOSE, "Initializing application...")
        environ = dict(create_environ(), REQUEST_URI='')
        with AppContext(DummyApplication(environ, None)), \
             RequestContext(htmllib.html(Request(environ), Response(is_secure=False))):
            self._initialize_gui_environment()

            self._logger.log(VERBOSE, "Updating Checkmk configuration...")
            for step_func, title in self._steps():
                self._logger.log(VERBOSE, " + %s..." % title)
                step_func()

        self._logger.log(VERBOSE, "Done")
Exemple #11
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)
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)
Exemple #13
0
    def run(self):
        self._logger.info(
            "Updating Checkmk configuration with \"cmk-update-config -v\"")
        self._initialize_gui_environment()

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

        self._logger.info("Done")
Exemple #14
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':
        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', ''),
        )
    else:
        return problem(
            status=400,
            title="Unhandled downtime-type.",
            detail=f"The downtime-type {downtime_type!r} is not supported.")

    return Response(status=204)
Exemple #15
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
Exemple #16
0
def _serve_password(ident, password_details):
    response = Response()
    response.set_data(json.dumps(serialize_password(ident, password_details)))
    response.set_content_type('application/json')
    response.headers.add(
        'ETag',
        constructors.etag_of_dict(password_details).to_header())
    return response
Exemple #17
0
def _serve_host_tag_group(tag_details: TaggroupSpec) -> Response:
    response = Response()
    response.set_data(json.dumps(serialize_host_tag_group(dict(tag_details))))
    response.set_content_type("application/json")
    response.headers.add(
        "ETag",
        constructors.etag_of_dict(dict(tag_details)).to_header())
    return response
Exemple #18
0
def _serve_services(host, discovered_services, discovery_state):
    response = Response()
    response.set_data(
        json.dumps(
            serialize_service_discovery(host, discovered_services,
                                        discovery_state)))
    response.set_content_type('application/json')
    return response
Exemple #19
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)
Exemple #20
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)
Exemple #21
0
def request_context(environ: Mapping[str, Any]) -> Iterator[None]:
    req = Request(environ)
    resp = Response(mimetype="text/html")
    funnel = OutputFunnel(resp)
    with RequestContext(
            req=req,
            resp=resp,
            funnel=funnel,
            html_obj=html(req, resp, funnel, output_format="html"),
            display_options=DisplayOptions(),
            theme=Theme(),
            prefix_logs_with_url=False,
    ):
        yield
Exemple #22
0
def delete_password(params):
    """Delete a password"""
    user.need_permission("wato.edit")
    user.need_permission("wato.passwords")
    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)
Exemple #23
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)
Exemple #24
0
def execute(params):
    """Execute a service discovery on a host"""
    host = watolib.Host.host(params["host_name"])
    discovery_request = StartDiscoveryRequest(host=host,
                                              folder=host.folder(),
                                              options=DiscoveryOptions(
                                                  action=DISCOVERY_ACTION[params["discover_mode"]],
                                                  show_checkboxes=False,
                                                  show_parameters=False,
                                                  show_discovered_labels=False,
                                                  show_plugin_names=False,
                                                  ignore_errors=True))
    _discovery_result = get_check_table(discovery_request)
    return Response(status=204)
Exemple #25
0
def with_request_context():
    environ = create_environ()
    resp = Response()
    with AppContext(session_wsgi_app(debug=False), stack=app_stack()), RequestContext(
        req=Request(environ),
        resp=resp,
        funnel=OutputFunnel(resp),
        config_obj=make_config_object(get_default_config()),
        user=LoggedInNobody(),
        display_options=DisplayOptions(),
        stack=request_stack(),
        url_filter=PrependURLFilter(),
    ):
        yield
Exemple #26
0
def serve_json(data: Serializable,
               profile: Optional[Dict[str, str]] = None) -> Response:
    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))
    return response
Exemple #27
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 == "params":
        downtime_commands.delete_downtime(live, body['downtime_id'])
    else:
        return problem(
            status=400,
            title="Unhandled delete_type.",
            detail=f"The downtime-type {delete_type!r} is not supported.")
    return Response(status=204)
Exemple #28
0
def serve_file(
    file_name: str,
    content: bytes,
    default_content_type="text/plain; charset=utf-8",
) -> Response:
    """Construct and cache a Response from a static file."""
    content_type, _ = mimetypes.guess_type(file_name)

    resp = Response()
    resp.direct_passthrough = True
    resp.data = content
    if content_type is not None:
        resp.headers["Content-Type"] = content_type
    else:
        resp.headers["Content-Type"] = default_content_type
    resp.freeze()
    return resp
Exemple #29
0
def bulk_delete(params):
    """Bulk delete folders based upon folder id"""
    # TODO: etag implementation
    entries = params['entries']
    folders = []
    for folder_ident in entries:
        folders.append(
            load_folder(
                folder_ident,
                status=400,
                message="folder config %s was not found" % folder_ident,
            ))
    for folder in folders:
        _delete_specific(folder)
    return Response(status=204)
Exemple #30
0
def _render_exception(e: Exception, title: str) -> Response:
    if plain_error():
        return Response(
            response=[
                "%s%s\n" % (("%s: " % title) if title else "", e),
            ],
            mimetype="text/plain",
        )

    if not fail_silently():
        html.header(title, Breadcrumb())
        html.show_error(str(e))
        html.footer()

    return response