Exemple #1
0
def list_time_periods(params):
    """Show all time periods"""
    time_periods = []
    for time_period_id, time_period_details in load_timeperiods().items():
        alias = time_period_details["alias"]
        if not isinstance(alias, str):  # check for mypy
            continue
        time_periods.append(
            constructors.collection_item(
                domain_type="time_period",
                title=alias,
                identifier=time_period_id,
            ))
    time_period_collection = {
        "id":
        "timeperiod",
        "domainType":
        "time_period",
        "value":
        time_periods,
        "links": [
            constructors.link_rel("self",
                                  constructors.collection_href("time_period"))
        ],
    }
    return constructors.serve_json(time_period_collection)
Exemple #2
0
def list_time_periods(params):
    """Show all time periods"""
    time_periods = []
    for time_period_id, time_period_details in load_timeperiods().items():
        alias = time_period_details['alias']
        if not isinstance(alias, str):  # check for mypy
            continue
        time_periods.append(
            constructors.collection_item(
                domain_type='time_period',
                obj={
                    'title': alias,
                    'id': time_period_id
                },
            ))
    time_period_collection = {
        'id':
        "timeperiod",
        'domainType':
        'time_period',
        'value':
        time_periods,
        'links': [
            constructors.link_rel('self',
                                  constructors.collection_href('time_period'))
        ],
    }
    return constructors.serve_json(time_period_collection)
Exemple #3
0
def _host_collection(hosts: Iterable[watolib.CREHost]) -> dict[str, Any]:
    return {
        "id": "host",
        "domainType": "host_config",
        "value": [serialize_host(host, effective_attributes=False) for host in hosts],
        "links": [constructors.link_rel("self", constructors.collection_href("host_config"))],
    }
Exemple #4
0
def test_openapi_list_currently_running_activations(aut_user_auth_wsgi_app: WebTestAppForCMK):
    base = "/NO_SITE/check_mk/api/1.0"
    aut_user_auth_wsgi_app.call_method(
        "get",
        base + constructors.collection_href("activation_run", "running"),
        status=200,
        headers={"Accept": "application/json"},
    )
def test_openapi_list_currently_running_activations(
    wsgi_app,
    with_automation_user,
):
    username, secret = with_automation_user
    wsgi_app.set_authorization(('Bearer', username + " " + secret))

    base = "/NO_SITE/check_mk/api/1.0"

    wsgi_app.call_method(
        'get',
        base + constructors.collection_href('activation_run', 'running'),
        status=200,
    )
Exemple #6
0
def _host_collection(hosts):
    return constructors.serve_json({
        'id': 'host',
        'value': [
            constructors.collection_item(
                domain_type='host',
                obj={
                    'title': host.name(),
                    'id': host.id()
                },
            ) for host in hosts
        ],
        'links': [constructors.link_rel('self', constructors.collection_href('host_config'))],
    })
Exemple #7
0
def host_collection(hosts: Iterable[watolib.CREHost]) -> Response:
    _hosts = {
        "id":
        "host",
        "domainType":
        "host_config",
        "value":
        [serialize_host(host, effective_attributes=False) for host in hosts],
        "links": [
            constructors.link_rel("self",
                                  constructors.collection_href("host_config"))
        ],
    }
    return constructors.serve_json(_hosts)
Exemple #8
0
def _folders_collection(folders):
    collection_object = constructors.collection_object(
        domain_type='folder_config',
        value=[
            constructors.collection_item(
                domain_type='folder_config',
                obj={
                    'title': folder.title(),
                    'id': folder.id()
                },
            ) for folder in folders
        ],
        links=[constructors.link_rel('self', constructors.collection_href('folder_config'))],
    )
    return collection_object
Exemple #9
0
def list_passwords(params):
    """Show all passwords"""
    password_collection = {
        'id': 'password',
        'domainType': 'password',
        'value': [
            constructors.collection_item(domain_type='password',
                                         obj={
                                             'title': details['title'],
                                             'id': password_id,
                                         }) for password_id, details in load_passwords().items()
        ],
        'links': [constructors.link_rel('self', constructors.collection_href('password'))],
    }
    return constructors.serve_json(password_collection)
Exemple #10
0
def list_hosts(param):
    """List all hosts"""
    return constructors.serve_json({
        'id': 'host',
        'value': [
            constructors.collection_item(
                domain_type='host',
                obj={
                    'title': host.name(),
                    'id': host.id()
                },
            ) for host in watolib.Folder.root_folder().all_hosts_recursively().values()
        ],
        'links': [constructors.link_rel('self', constructors.collection_href('host_config'))],
    })
Exemple #11
0
def list_passwords(params):
    """Show all passwords"""
    password_collection = {
        "id": "password",
        "domainType": "password",
        "value": [
            constructors.collection_item(
                domain_type="password",
                title=details["title"],
                identifier=password_id,
            )
            for password_id, details in load_passwords().items()
        ],
        "links": [constructors.link_rel("self", constructors.collection_href("password"))],
    }
    return constructors.serve_json(password_collection)
Exemple #12
0
def serialize_group_list(
    domain_type: GroupName,
    collection: Sequence[Dict[str, Any]],
) -> constructors.CollectionObject:
    return constructors.collection_object(
        domain_type=domain_type,
        value=[
            constructors.collection_item(
                domain_type=domain_type,
                title=group["alias"],
                identifier=group["id"],
            )
            for group in collection
        ],
        links=[constructors.link_rel("self", constructors.collection_href(domain_type))],
    )
Exemple #13
0
def list_users(params):
    """Show all users"""
    user_collection = {
        "id": "user",
        "domainType": "user_config",
        "value": [
            constructors.collection_item(
                domain_type="user_config",
                title=attrs["alias"],
                identifier=user_id,
            )
            for user_id, attrs in userdb.load_users(False).items()
        ],
        "links": [constructors.link_rel("self", constructors.collection_href("user_config"))],
    }
    return constructors.serve_json(user_collection)
Exemple #14
0
def serialize_group_list(
    domain_type: GroupName,
    collection: Sequence[Dict[str, Any]],
) -> constructors.CollectionObject:
    return constructors.collection_object(
        domain_type=domain_type,
        value=[
            constructors.collection_item(
                domain_type=domain_type,
                obj={
                    'title': group['alias'],
                    'id': group['id'],
                },
            ) for group in collection
        ],
        links=[constructors.link_rel('self', constructors.collection_href(domain_type))],
    )
Exemple #15
0
def list_host_tag_groups(params):
    """Show all host tag groups"""
    tag_config = load_tag_config()
    tag_config += BuiltinTagConfig()
    tag_groups_collection = {
        'id': 'host_tag',
        'domainType': 'host_tag_group',
        'value': [
            constructors.collection_item(
                domain_type='host_tag_group',
                obj={
                    'title': tag_group_obj.title,
                    'id': tag_group_obj.id
                },
            ) for tag_group_obj in tag_config.get_tag_groups()
        ],
        'links': [constructors.link_rel('self', constructors.collection_href('host_tag_group'))]
    }
    return constructors.serve_json(tag_groups_collection)
Exemple #16
0
def get_bi_packs(params):
    """Show all BI packs"""
    user.need_permission("wato.bi_rules")
    bi_packs = get_cached_bi_packs()
    bi_packs.load_config()
    packs = [
        constructors.collection_item(
            domain_type="bi_pack",
            identifier=pack.id,
            title=pack.title,
        )
        for pack in bi_packs.packs.values()
    ]

    collection_object = constructors.collection_object(
        domain_type="bi_pack",
        value=packs,
        links=[constructors.link_rel("self", constructors.collection_href("bi_pack"))],
    )
    return constructors.serve_json(collection_object)
Exemple #17
0
def host_collection(hosts: Iterable[watolib.CREHost]) -> Response:
    _hosts = {
        'id':
        'host',
        'domainType':
        'host_config',
        'value': [
            constructors.collection_item(
                domain_type='host_config',
                obj={
                    'title': host.name(),
                    'id': host.id()
                },
            ) for host in hosts
        ],
        'links': [
            constructors.link_rel('self',
                                  constructors.collection_href('host_config'))
        ],
    }
    return constructors.serve_json(_hosts)
Exemple #18
0
def get_bi_packs(params):
    """Show all BI Packs"""

    bi_packs = get_cached_bi_packs()
    bi_packs.load_config()
    packs = [
        constructors.collection_item(
            domain_type='bi_pack',
            obj={
                'id': pack.id,
                'title': pack.title,
            },
        ) for pack in bi_packs.packs.values()
    ]

    collection_object = constructors.collection_object(
        domain_type='bi_pack',
        value=packs,
        links=[constructors.link_rel('self', constructors.collection_href('bi_pack'))],
    )
    return constructors.serve_json(collection_object)
Exemple #19
0
def host_collection(hosts: Iterable[watolib.CREHost]) -> Response:
    _hosts = {
        "id":
        "host",
        "domainType":
        "host_config",
        "value": [
            constructors.collection_item(
                domain_type="host_config",
                obj={
                    "title": host.name(),
                    "id": host.id()
                },
            ) for host in hosts
        ],
        "links": [
            constructors.link_rel("self",
                                  constructors.collection_href("host_config"))
        ],
    }
    return constructors.serve_json(_hosts)
Exemple #20
0
def list_folders(_params):
    """List folders"""
    folders = [
        constructors.collection_item(
            domain_type='folder_config',
            obj={
                'title': folder.title(),
                'id': folder.id()
            },
        ) for folder in watolib.Folder.root_folder().subfolders()
    ]

    collection_object = constructors.collection_object(
        domain_type='folder_config',
        value=folders,
        links=[
            constructors.link_rel(
                'self', constructors.collection_href('folder_config'))
        ],
    )

    return constructors.serve_json(collection_object)
Exemple #21
0
def list_host_tag_groups(params):
    """Show all host tag groups"""
    tag_config = load_tag_config()
    tag_config += BuiltinTagConfig()
    tag_groups_collection = {
        "id":
        "host_tag",
        "domainType":
        "host_tag_group",
        "value": [
            constructors.collection_item(
                domain_type="host_tag_group",
                title=tag_group_obj.title,
                identifier=tag_group_obj.id,
            ) for tag_group_obj in tag_config.get_tag_groups()
        ],
        "links": [
            constructors.link_rel(
                "self", constructors.collection_href("host_tag_group"))
        ],
    }
    return constructors.serve_json(tag_groups_collection)
Exemple #22
0
def list_users(params):
    """Show all users"""
    user_collection = {
        'id':
        'user',
        'domainType':
        'user_config',
        'value': [
            constructors.collection_item(
                domain_type='user_config',
                obj={
                    'title': attrs['alias'],
                    'id': user_id
                },
            ) for user_id, attrs in userdb.load_users(False).items()
        ],
        'links': [
            constructors.link_rel('self',
                                  constructors.collection_href('user_config'))
        ],
    }
    return constructors.serve_json(user_collection)
Exemple #23
0
def get_bi_packs(params):
    """Show all BI packs"""

    bi_packs = get_cached_bi_packs()
    bi_packs.load_config()
    packs = [
        constructors.collection_item(
            domain_type="bi_pack",
            obj={
                "id": pack.id,
                "title": pack.title,
            },
        )
        for pack in bi_packs.packs.values()
    ]

    collection_object = constructors.collection_object(
        domain_type="bi_pack",
        value=packs,
        links=[constructors.link_rel("self", constructors.collection_href("bi_pack"))],
    )
    return constructors.serve_json(collection_object)
Exemple #24
0
    constructors,
    Endpoint,
    request_schemas,
)
from cmk.gui.plugins.openapi.utils import problem

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


@Endpoint(constructors.collection_href('acknowledge', 'host'),
          'cmk/create',
          method='post',
          tag_group='Monitoring',
          request_schema=request_schemas.AcknowledgeHostRelatedProblem,
          output_empty=True)
def set_acknowledgement_related_to_host(params):
    """Set acknowledgement on related hosts"""
    body = params['body']
    live = sites.live()

    sticky = body['sticky']
    notify = body['notify']
    persistent = body['persistent']
    comment = body['comment']
Exemple #25
0
    columns = gui_fields.column_field(Hosts, mandatory=[Hosts.name], example=["name"])


PERMISSIONS = permissions.Ignore(
    permissions.AnyPerm(
        [
            permissions.Perm("general.see_all"),
            permissions.Perm("bi.see_all"),
            permissions.Perm("mkeventd.seeall"),
        ]
    )
)


@Endpoint(
    constructors.collection_href("host"),
    ".../collection",
    method="get",
    tag_group="Monitoring",
    blacklist_in=["swagger-ui"],
    query_params=[HostParameters],
    response_schema=response_schemas.DomainObjectCollection,
    permissions_required=PERMISSIONS,
)
def list_hosts(param):
    """Show hosts of specific condition"""
    live = sites.live()
    sites_to_query = param["sites"]
    if sites_to_query:
        live.only_sites = sites_to_query
Exemple #26
0
          '.../collection',
          method='get',
          path_params=[HOST_NAME],
          query_params=PARAMETERS,
          tag_group='Monitoring',
          blacklist_in=['swagger-ui'],
          response_schema=response_schemas.DomainObjectCollection)
def _list_host_services(param):
    """Show the monitored services of a host

    This list is filterable by various parameters."""
    return _list_services(param)


@Endpoint(
    constructors.collection_href('service'),
    '.../collection',
    method='get',
    query_params=[OPTIONAL_HOST_NAME, *PARAMETERS],
    tag_group='Monitoring',
    response_schema=response_schemas.DomainObjectCollection,
)
def _list_all_services(param):
    """Show all monitored services

    This list is filterable by various parameters."""
    return _list_services(param)


def _list_services(param):
    live = sites.live()
Exemple #27
0
from cmk.gui.plugins.openapi.restful_objects import (
    constructors,
    endpoint_schema,
    request_schemas,
    response_schemas,
)
from cmk.gui.plugins.openapi.restful_objects.parameters import IDENT_FIELD
from cmk.gui.plugins.openapi.utils import ProblemException
from cmk.gui.watolib import CREFolder

# TODO: Remove all hard-coded response creation in favour of a generic one
# TODO: Implement formal description (GET endpoint) of move action
# TODO: add redoc.js


@endpoint_schema(constructors.collection_href('folder_config'),
                 'cmk/create',
                 method='post',
                 response_schema=response_schemas.ConcreteFolder,
                 etag='output',
                 request_body_required=True,
                 request_schema=request_schemas.CreateFolder)
def create(params):
    """Create a folder"""
    put_body = params['body']
    name = put_body['name']
    title = put_body['title']
    parent_folder = put_body['parent']
    attributes = put_body.get('attributes', {})

    folder = parent_folder.create_subfolder(name, title, attributes)
Exemple #28
0
PATH_FOLDER_FIELD = {
    "folder":
    fields.FolderField(
        description=
        ("The path of the folder being requested. Please be aware that slashes can't "
         "be used in the URL. Also, escaping the slashes via %2f will not work. Please "
         "replace the path delimiters with the tilde character `~`."),
        example="~my~fine~folder",
        required=True,
    )
}


@Endpoint(
    constructors.collection_href("folder_config"),
    "cmk/create",
    method="post",
    etag="output",
    response_schema=response_schemas.FolderSchema,
    request_schema=request_schemas.CreateFolder,
)
def create(params):
    """Create a folder"""
    put_body = params["body"]
    name = put_body["name"]
    title = put_body["title"]
    parent_folder = put_body["parent"]
    attributes = put_body.get("attributes", {})

    if parent_folder.has_subfolder(name):
Exemple #29
0
    schema_string_pattern='|'.join(sorted(SERVICE_DISCOVERY_STATES.keys())),
    example='monitored',
    required=True)

DISCOVERY_MODE = ParamDict.create(
    'discover_mode',
    'path',
    description=(
        'The mode of the discovery action. May be one of the following: ' +
        ', '.join(sorted(DISCOVERY_ACTION.keys()))),
    schema_string_pattern='|'.join(sorted(DISCOVERY_ACTION.keys())),
    example='tabula-rasa',
    required=True)


@endpoint_schema(collection_href("service", "services"),
                 '.../collection',
                 method='get',
                 response_schema=response_schemas.DomainObject,
                 parameters=[DISCOVERY_HOST, DISCOVERY_SOURCE_STATE])
def show_services(params):
    """Show services of specific state"""
    host = watolib.Host.host(params["host"])
    discovery_request = StartDiscoveryRequest(
        host=host,
        folder=host.folder(),
        options=DiscoveryOptions(action='',
                                 show_checkboxes=False,
                                 show_parameters=False,
                                 show_discovered_labels=False,
                                 show_plugin_names=False,
    update_groups,
    updated_group_details,
)
from cmk.gui.plugins.openapi.restful_objects import (
    constructors,
    Endpoint,
    permissions,
    request_schemas,
    response_schemas,
)
from cmk.gui.plugins.openapi.restful_objects.parameters import NAME_FIELD
from cmk.gui.watolib.groups import add_group, edit_group


@Endpoint(
    constructors.collection_href("host_group_config"),
    "cmk/create",
    method="post",
    etag="output",
    request_schema=request_schemas.InputHostGroup,
    response_schema=response_schemas.HostGroup,
    permissions_required=permissions.Perm("wato.groups"),
)
def create(params):
    """Create a host group"""
    body = params["body"]
    name = body["name"]
    group_details = {"alias": body.get("alias")}
    if version.is_managed_edition():
        group_details = update_customer_info(group_details, body["customer"])
    add_group(name, "host", group_details)