コード例 #1
0
def _serialize_folder(folder: CREFolder, show_hosts):
    links = []

    if not folder.is_root():
        links.append(
            constructors.link_rel(
                rel="cmk/move",
                href=constructors.object_action_href(
                    "folder_config",
                    folder_slug(folder),
                    action_name="move",
                ),
                method="post",
                title="Move the folder",
            )
        )

    rv = constructors.domain_object(
        domain_type="folder_config",
        identifier=folder_slug(folder),
        title=folder.title(),
        extensions={
            "path": "/" + folder.path(),
            "attributes": folder.attributes().copy(),
        },
        links=links,
    )
    if show_hosts:
        rv["members"]["hosts"] = constructors.collection_property(
            name="hosts",
            base=constructors.object_href("folder_config", folder_slug(folder)),
            value=[
                constructors.collection_item(
                    domain_type="host_config",
                    obj={
                        "id": host.id(),
                        "title": host.name(),
                    },
                )
                for host in folder.hosts().values()
            ],
        )
    return rv
コード例 #2
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
            ],
        )
    )
コード例 #3
0
ファイル: folder_config.py プロジェクト: petrows/checkmk
def _serialize_folder(folder: CREFolder, show_hosts):
    links = []

    if not folder.is_root():
        links.append(
            constructors.link_rel(
                rel='cmk/move',
                href=constructors.object_action_href(
                    "folder_config",
                    folder_slug(folder),
                    action_name='move',
                ),
                method='post',
                title='Move the folder',
            ))

    rv = constructors.domain_object(
        domain_type='folder_config',
        identifier=folder_slug(folder),
        title=folder.title(),
        extensions={
            'path': '/' + folder.path(),
            'attributes': folder.attributes().copy(),
        },
        links=links,
    )
    if show_hosts:
        rv['members']['hosts'] = constructors.collection_property(
            name='hosts',
            base=constructors.object_href('folder_config',
                                          folder_slug(folder)),
            value=[
                constructors.collection_item(
                    domain_type='host_config',
                    obj={
                        'id': host.id(),
                        'title': host.name(),
                    },
                ) for host in folder.hosts().values()
            ],
        )
    return rv
コード例 #4
0
ファイル: service.py プロジェクト: petrows/checkmk
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
            ],
        ))
コード例 #5
0
@Endpoint(constructors.object_href('folder_config', '{folder}'),
          '.../delete',
          method='delete',
          path_params=[FOLDER_FIELD],
          output_empty=True,
          etag='input')
def delete(params):
    """Delete a folder"""
    folder = params['folder']
    parent = folder.parent()
    parent.delete_subfolder(folder.name())
    return Response(status=204)


@Endpoint(constructors.object_action_href('folder_config', '{folder}', action_name='move'),
          'cmk/move',
          method='post',
          path_params=[FOLDER_FIELD],
          response_schema=response_schemas.ConcreteFolder,
          request_schema=request_schemas.MoveFolder,
          etag='both')
def move(params):
    """Move a folder"""
    folder: watolib.CREFolder = params['folder']
    folder_id = folder.id()

    constructors.require_etag(constructors.etag_of_obj(folder))

    dest_folder: watolib.CREFolder = params['body']['destination']
コード例 #6
0
ファイル: host_config.py プロジェクト: Bastian-Kuhn/checkmk
        hosts.append(host)

    if faulty_hosts:
        return problem(
            status=400,
            title="Some attributes could not be removed",
            detail=
            f"The attributes of the following hosts could not be removed: {', '.join(faulty_hosts)}",
        )

    return host_collection(hosts)


@Endpoint(
    constructors.object_action_href("host_config",
                                    "{host_name}",
                                    action_name="rename"),
    "cmk/rename",
    method="put",
    path_params=[HOST_NAME],
    etag="both",
    additional_status_codes=[409, 422],
    status_descriptions={
        409: "There are pending changes not yet activated.",
        422: "The host could not be renamed.",
    },
    request_schema=request_schemas.RenameHost,
    response_schema=response_schemas.HostConfigSchema,
    permissions_required=permissions.AllPerm([
        *PERMISSIONS.perms,
        permissions.Perm("wato.edit_hosts"),
コード例 #7
0
ファイル: service_discovery.py プロジェクト: petrows/checkmk
    service_item = fields.String(
        description=
        'The value uniquely identifying the service on a given host.',
        example='/home',
        required=True,
    )
    target_phase = fields.String(
        description='The target phase of the service.',
        enum=sorted(SERVICE_DISCOVERY_PHASES.keys()),
        example='monitored',
        required=True,
    )


@Endpoint(
    constructors.object_action_href('host', '{host_name}',
                                    'update_discovery_phase'),
    '.../modify',
    method='put',
    output_empty=True,
    tag_group='Setup',
    path_params=[{
        'host_name':
        fields.HostField(
            description='The host of the service which shall be updated.',
            example='example.com',
        ),
    }],
    status_descriptions={
        404: 'Host could not be found',
    },
    request_schema=UpdateDiscoveryPhase)
コード例 #8
0
    endpoint_schema,
    request_schemas,
)
from cmk.gui.plugins.openapi.restful_objects.parameters import HOST_NAME
from cmk.gui.plugins.openapi.utils import problem

SERVICE_DESCRIPTION = {
    'service_description':
    fields.String(
        description="The service description.",
        example="Memory",
    )
}


@endpoint_schema(constructors.object_action_href('host', '{host_name}',
                                                 'acknowledge'),
                 'cmk/create',
                 method='post',
                 tag_group='Monitoring',
                 path_params=[HOST_NAME],
                 request_schema=request_schemas.AcknowledgeHostProblem,
                 output_empty=True)
def set_acknowledgement_on_host(params):
    """Acknowledge for a specific host"""
    host_name = params['host_name']

    host = Query([Hosts.name, Hosts.state],
                 Hosts.name.equals(host_name)).first(sites.live())
    if host is None:
        return problem(
            status=404,
コード例 #9
0
    action = "has completed"
    if is_running:
        action = "was started"
        links.append(_completion_link(activation_id))
    return constructors.serve_json(
        constructors.domain_object(
            domain_type='activation_run',
            identifier=activation_id,
            title=f'Activation {activation_id} {action}.',
            deletable=False,
            editable=False,
            links=links,
        ))


@Endpoint(constructors.object_action_href('activation_run', '{activation_id}',
                                          'wait-for-completion'),
          'cmk/wait-for-completion',
          method='get',
          status_descriptions={
              204:
              "The activation has been completed.",
              302: ("The activation is still running. Redirecting to the "
                    "'Wait for completion' endpoint."),
              404:
              "There is no running activation with this activation_id.",
          },
          path_params=[ACTIVATION_ID],
          additional_status_codes=[302],
          output_empty=True)
def activate_changes_wait_for_completion(params):
    """Wait for activation completion
コード例 #10
0
        hosts.append(host)

    if faulty_hosts:
        return problem(
            status=400,
            title="Some attributes could not be removed",
            detail=
            f"The attributes of the following hosts could not be removed: {', '.join(faulty_hosts)}",
        )

    return host_collection(hosts)


@Endpoint(constructors.object_action_href('host_config',
                                          '{host_name}',
                                          action_name='rename'),
          'cmk/rename',
          method='put',
          path_params=[HOST_NAME],
          etag='both',
          additional_status_codes=[409, 422],
          status_descriptions={
              409: 'There are pending changes not yet activated.',
              422: 'The host could not be renamed.',
          },
          request_schema=request_schemas.RenameHost,
          response_schema=response_schemas.DomainObject)
def rename_host(params):
    """Rename a host"""
    if activate_changes.get_pending_changes_info():
コード例 #11
0
ファイル: activate_changes.py プロジェクト: tribe29/checkmk
    if is_running:
        action = "was started"
        links.append(_completion_link(activation_id))
    return constructors.serve_json(
        constructors.domain_object(
            domain_type="activation_run",
            identifier=activation_id,
            title=f"Activation {activation_id} {action}.",
            deletable=False,
            editable=False,
            links=links,
        ))


@Endpoint(
    constructors.object_action_href("activation_run", "{activation_id}",
                                    "wait-for-completion"),
    "cmk/wait-for-completion",
    method="get",
    status_descriptions={
        204:
        "The activation has been completed.",
        302: ("The activation is still running. Redirecting to the "
              "'Wait for completion' endpoint."),
        404:
        "There is no running activation with this activation_id.",
    },
    path_params=[ACTIVATION_ID],
    additional_status_codes=[302],
    output_empty=True,
)
def activate_changes_wait_for_completion(params):
コード例 #12
0
ファイル: service.py プロジェクト: petrows/checkmk
        Services,
        required=False,
        example='{"op": "=", "left": "host_name", "right": "example.com"}',
    ),
    'columns':
    fields.column_field(
        Services,
        mandatory=[
            Services.host_name,
            Services.description,
        ],
    )
}]


@Endpoint(object_action_href('host', '{host_name}', 'show_service'),
          'cmk/show',
          method='get',
          path_params=[HOST_NAME],
          query_params=[{
              "service_description":
              fields.String(
                  description="The service description of the selected host",
                  example="Filesystem %boot",
              ),
          }],
          tag_group='Monitoring',
          response_schema=response_schemas.DomainObject)
def show_service(params):
    """Show the monitored service of a host"""
    service_description = params["service_description"]
コード例 #13
0
        description=
        "The value uniquely identifying the service on a given host.",
        example="/home",
        required=True,
        allow_none=True,
    )
    target_phase = fields.String(
        description="The target phase of the service.",
        enum=sorted(SERVICE_DISCOVERY_PHASES.keys()),
        example="monitored",
        required=True,
    )


@Endpoint(
    constructors.object_action_href("host", "{host_name}",
                                    "update_discovery_phase"),
    ".../modify",
    method="put",
    output_empty=True,
    tag_group="Setup",
    path_params=[{
        "host_name":
        gui_fields.HostField(
            description="The host of the service which shall be updated.",
            example="example.com",
        ),
    }],
    status_descriptions={
        404: "Host could not be found",
    },
    request_schema=UpdateDiscoveryPhase,
コード例 #14
0
    host: CREHost,
    uuid: UUID,
) -> None:
    uuid_link_manager = get_uuid_link_manager()
    uuid_link_manager.create_link(
        host_name,
        uuid,
        create_target_dir=host.effective_attributes().get(
            "cmk_agent_connection") == "push-agent",
    )


@Endpoint(
    constructors.object_action_href(
        "host_config",
        "{host_name}",
        action_name="link_uuid",
    ),
    "cmk/link_uuid",
    method="put",
    tag_group="Checkmk Internal",
    additional_status_codes=[401],
    status_descriptions={
        401: "You do not have the permissions to edit this host.",
    },
    path_params=[HOST_NAME],
    request_schema=request_schemas.LinkHostUUID,
    output_empty=True,
)
def link_with_uuid(params) -> Response:
    """Link a host to a UUID"""
コード例 #15
0
ファイル: folder_config.py プロジェクト: troelsarvin/checkmk
    ".../delete",
    method="delete",
    path_params=[PATH_FOLDER_FIELD],
    output_empty=True,
)
def delete(params):
    """Delete a folder"""
    folder = params["folder"]
    parent = folder.parent()
    parent.delete_subfolder(folder.name())
    return Response(status=204)


@Endpoint(
    constructors.object_action_href("folder_config",
                                    "{folder}",
                                    action_name="move"),
    "cmk/move",
    method="post",
    path_params=[PATH_FOLDER_FIELD],
    response_schema=response_schemas.FolderSchema,
    request_schema=request_schemas.MoveFolder,
    etag="both",
)
def move(params):
    """Move a folder"""
    folder: watolib.CREFolder = params["folder"]
    folder_id = folder.id()

    constructors.require_etag(etag_of_folder(folder))
コード例 #16
0
ファイル: service.py プロジェクト: LinuxHaus/checkmk
        example='{"op": "=", "left": "host_name", "right": "example.com"}',
    ),
    "columns":
    gui_fields.column_field(
        Services,
        mandatory=[
            Services.host_name,
            Services.description,
        ],
        example=["host_name", "description"],
    ),
}]


@Endpoint(
    object_action_href("host", "{host_name}", "show_service"),
    "cmk/show",
    method="get",
    path_params=[HOST_NAME],
    query_params=[{
        "service_description":
        fields.String(
            description="The service description of the selected host",
            example="Filesystem %boot",
        ),
    }],
    tag_group="Monitoring",
    response_schema=response_schemas.DomainObject,
    permissions_required=PERMISSIONS,
)
def show_service(params):
コード例 #17
0
                 output_empty=True,
                 etag='input')
def delete(params):
    """Delete a folder"""
    ident = params['ident']
    folder = load_folder(ident, status=404)
    _delete_specific(folder)
    return Response(status=204)


def _delete_specific(folder):
    parent = folder.parent()
    parent.delete_subfolder(folder.name())


@endpoint_schema(constructors.object_action_href('folder_config', '{ident}', action_name='move'),
                 'cmk/move',
                 method='post',
                 path_params=[
                     IDENT_FIELD,
                 ],
                 response_schema=response_schemas.ConcreteFolder,
                 etag='both')
def move(params):
    """Move a folder"""
    ident = params['ident']
    folder = load_folder(ident, status=404)

    constructors.require_etag(constructors.etag_of_obj(folder))

    dest = params['body']['destination']
コード例 #18
0
ファイル: __init__.py プロジェクト: LinuxHaus/checkmk
])


# NOTE: This is a dataclass and no namedtuple because it needs to be mutable. See `move_rule_to`
@dataclasses.dataclass
class RuleEntry:
    rule: Rule
    ruleset: Ruleset
    all_rulesets: AllRulesets
    # NOTE: Can't be called "index", because mypy doesn't like that. Duh.
    index_nr: int
    folder: CREFolder


@Endpoint(
    constructors.object_action_href("rule", "{rule_id}", "move"),
    "cmk/move",
    method="post",
    etag="input",
    path_params=[RULE_ID],
    request_schema=MoveRuleTo,
    response_schema=RuleObject,
    permissions_required=RW_PERMISSIONS,
)
def move_rule_to(param: typing.Mapping[str, typing.Any]) -> http.Response:
    """Move a rule to a specific location"""
    user.need_permission("wato.edit")
    user.need_permission("wato.rulesets")
    rule_id = param["rule_id"]

    body = param["body"]