Example #1
0
def serialize_host(host):
    base = constructors.object_href('host_config', host.ident())
    members = constructors.DomainObjectMembers(base)
    members.object_property(
        name='folder_config',
        value=constructors.object_href('folder_config',
                                       host.folder().id()),
        prop_format='string',
    )

    attributes = host.attributes().copy()
    del attributes['meta_data']

    return constructors.domain_object(
        domain_type='host_config',
        identifier=host.id(),
        title=host.alias(),
        members=members.to_dict(),
        extensions={
            'attributes': attributes,
            'is_cluster': host.is_cluster(),
            'is_offline': host.is_offline(),
            'cluster_nodes': host.cluster_nodes(),
        },
    )
Example #2
0
def serialize_host(host, attributes):
    # TODO: readd link mechanism once object ref between endpoints is in place
    base = constructors.object_href('host_config', host.ident())
    members = constructors.DomainObjectMembers(base)
    members.object_property(
        name='folder_config',
        value=constructors.object_href('folder_config',
                                       host.folder().id()),
        prop_format='string',
        linkable=False,
    )

    if 'meta_data' in attributes:
        attributes = attributes.copy()
        del attributes['meta_data']

    return constructors.domain_object(
        domain_type='host_config',
        identifier=host.id(),
        title=host.alias(),
        members=members.to_dict(),
        extensions={
            'attributes': attributes,
            'is_cluster': host.is_cluster(),
            'is_offline': host.is_offline(),
            'cluster_nodes': host.cluster_nodes(),
        },
    )
Example #3
0
def get_bi_pack(params):
    """Get BI Pack"""
    bi_packs.load_config()
    bi_pack = bi_packs.get_pack(params["pack_id"])
    if bi_pack is None:
        _bailout_with_message("Unknown bi_pack: %s" % params["pack_id"])
    assert bi_pack is not None

    uri = constructors.object_href('bi_pack', bi_pack.id)
    domain_members = {}
    for (name, entities) in [("aggregation", bi_pack.get_aggregations()),
                             ("rule", bi_pack.get_rules())]:
        elements = entities.values()  # type: ignore[attr-defined]
        domain_members["%ss" % name] = constructors.object_collection(
            name=name,
            domain_type="bi_" + name,  # type: ignore[arg-type]
            entries=[
                constructors.link_rel(
                    rel='.../value',
                    parameters={'collection': "items"},
                    href=constructors.object_href(
                        "bi_" + name  # type: ignore[arg-type]
                        ,
                        element.id),
                ) for element in elements
            ],
            base=uri,
        )

    domain_object = constructors.domain_object(domain_type='bi_pack',
                                               identifier=bi_pack.id,
                                               title=bi_pack.title,
                                               members=domain_members)

    return constructors.serve_json(domain_object)
Example #4
0
def _serialize_folder(folder: CREFolder):
    uri = constructors.object_href('folder_config', folder.id())
    return constructors.domain_object(
        domain_type='folder_config',
        identifier=folder.id(),
        title=folder.title(),
        members={
            'move': constructors.object_action(
                name='move',
                base=uri,
                parameters=dict([
                    constructors.action_parameter(
                        action='move',
                        parameter='destination',
                        friendly_name='The destination folder of this move action',
                        optional=False,
                        pattern="[0-9a-fA-F]{32}|root",
                    ),
                ]),
            ),
        },
        extensions={
            'attributes': folder.attributes().copy(),
        },
    )
Example #5
0
def serialize_password(details):
    return constructors.domain_object(domain_type="password",
                                      identifier=details["ident"],
                                      title=details["title"],
                                      members={
                                          "title":
                                          constructors.object_property(
                                              name='title',
                                              value=details["title"],
                                              prop_format='string',
                                              base=constructors.object_href(
                                                  'password',
                                                  details["ident"]),
                                          )
                                      },
                                      extensions={
                                          key: details[key]
                                          for key in details if key in (
                                              "comment",
                                              "docu_url",
                                              "password",
                                              "owned_by",
                                              "shared_with",
                                          )
                                      })
Example #6
0
def serialize_password(ident, details):
    return constructors.domain_object(
        domain_type="password",
        identifier=ident,
        title=details["title"],
        members={
            "title":
            constructors.object_property(
                name="title",
                value=details["title"],
                prop_format="string",
                base=constructors.object_href("password", ident),
            )
        },
        extensions={
            k: v
            for k, v in complement_customer(details).items() if k in (
                "comment",
                "docu_url",
                "password",
                "owned_by",
                "shared_with",
                "customer",
            )
        },
    )
Example #7
0
def serialize_host(host: watolib.CREHost, effective_attributes: bool):
    if effective_attributes:
        attributes = host.effective_attributes()
    else:
        attributes = host.attributes()

    if 'meta_data' in attributes:
        attributes = attributes.copy()
        del attributes['meta_data']

    return constructors.domain_object(
        domain_type='host_config',
        identifier=host.id(),
        title=host.alias(),
        links=[
            constructors.link_rel(
                rel='cmk/folder_config',
                href=constructors.object_href('folder_config',
                                              folder_slug(host.folder())),
                method='get',
                title='The folder config of the host.',
            ),
        ],
        extensions={
            'attributes': attributes,
            'is_cluster': host.is_cluster(),
            'is_offline': host.is_offline(),
            'cluster_nodes': host.cluster_nodes(),
        },
    )
Example #8
0
def serialize_host(host: watolib.CREHost, effective_attributes: bool):
    extensions = {
        "folder":
        host.folder().path(),
        "attributes":
        host.attributes(),
        "effective_attributes":
        host.effective_attributes() if effective_attributes else None,
        "is_cluster":
        host.is_cluster(),
        "is_offline":
        host.is_offline(),
        "cluster_nodes":
        host.cluster_nodes(),
    }
    return constructors.domain_object(
        domain_type="host_config",
        identifier=host.id(),
        title=host.alias() or host.name(),
        links=[
            constructors.link_rel(
                rel="cmk/folder_config",
                href=constructors.object_href("folder_config",
                                              folder_slug(host.folder())),
                method="get",
                title="The folder config of the host.",
            ),
        ],
        extensions=extensions,
    )
Example #9
0
    def _serializer(group):
        # type: (Dict[str, str]) -> Any
        ident = group['id']
        extensions = {}
        if "customer" in group:
            customer_id = group["customer"]
            extensions[
                "customer"] = "global" if customer_id is None else customer_id
        elif is_managed_edition():
            extensions["customer"] = managed.default_customer_id()

        return constructors.domain_object(
            domain_type=name,
            identifier=ident,
            title=group['alias'],
            members={
                'title':
                constructors.object_property(
                    name='title',
                    value=group['alias'],
                    prop_format='string',
                    base=constructors.object_href(name, ident),
                ),
            },
            extensions=extensions,
        )
Example #10
0
def serialize_host(host: watolib.CREHost, effective_attributes: bool):
    extensions = {
        'folder':
        host.folder().path(),
        'attributes':
        host.attributes(),
        'effective_attributes':
        host.effective_attributes() if effective_attributes else None,
        'is_cluster':
        host.is_cluster(),
        'is_offline':
        host.is_offline(),
        'cluster_nodes':
        host.cluster_nodes(),
    }
    return constructors.domain_object(
        domain_type='host_config',
        identifier=host.id(),
        title=host.alias() or host.name(),
        links=[
            constructors.link_rel(
                rel='cmk/folder_config',
                href=constructors.object_href('folder_config',
                                              folder_slug(host.folder())),
                method='get',
                title='The folder config of the host.',
            ),
        ],
        extensions=extensions,
    )
Example #11
0
def _serialize_single_downtime(downtime):
    links = []
    if downtime["is_service"]:
        downtime_detail = f"service: {downtime['service_description']}"
    else:
        host_name = downtime["host_name"]
        downtime_detail = f"host: {host_name}"
        links.append(
            constructors.link_rel(
                rel="cmk/host_config",
                href=constructors.object_href("host_config", host_name),
                title="This host of this downtime.",
                method="get",
            )
        )

    downtime_id = downtime["id"]
    return constructors.domain_object(
        domain_type="downtime",
        identifier=str(downtime_id),
        title="Downtime for %s" % downtime_detail,
        extensions=_downtime_properties(downtime),
        links=[
            constructors.link_rel(
                rel=".../delete",
                href=constructors.domain_type_action_href("downtime", "delete"),
                method="post",
                title="Delete the downtime",
                body_params={"delete_type": "by_id", "downtime_id": downtime_id},
            ),
        ],
        editable=False,
        deletable=False,
    )
Example #12
0
def get_bi_pack(params):
    """Get a BI pack and its rules and aggregations"""
    user.need_permission("wato.bi_rules")
    bi_packs = get_cached_bi_packs()
    bi_packs.load_config()
    bi_pack = bi_packs.get_pack(params["pack_id"])
    if bi_pack is None:
        _bailout_with_message("This pack_id does not exist: %s" % params["pack_id"])
    assert bi_pack is not None

    uri = constructors.object_href("bi_pack", bi_pack.id)
    domain_members = {}
    for (name, entities) in [
        ("aggregation", bi_pack.get_aggregations()),
        ("rule", bi_pack.get_rules()),
    ]:
        elements = entities.values()
        domain_members["%ss" % name] = constructors.object_collection(
            name=name,
            domain_type="bi_" + name,  # type: ignore[arg-type]
            entries=[
                constructors.link_rel(
                    rel=".../value",
                    parameters={"collection": "items"},
                    href=constructors.object_href(
                        "bi_" + name, element.id  # type: ignore[arg-type]
                    ),
                )
                for element in elements
            ],
            base=uri,
        )

    extensions = {
        "title": bi_pack.title,
        "contact_groups": bi_pack.contact_groups,
        "public": bi_pack.public,
    }
    domain_object = constructors.domain_object(
        domain_type="bi_pack",
        identifier=bi_pack.id,
        title=bi_pack.title,
        extensions=extensions,
        members=domain_members,
    )

    return constructors.serve_json(domain_object)
Example #13
0
def serialize_host(host):
    base = constructors.object_href('host_config', host.ident())
    members = constructors.DomainObjectMembers(base)
    members.object_property(
        name='folder_config',
        value=constructors.object_href('folder_config',
                                       host.folder().id()),
        prop_format='string',
    )

    return constructors.domain_object(
        domain_type='host_config',
        identifier=host.id(),
        title=host.alias(),
        members=members.to_dict(),
        extensions={},
    )
Example #14
0
def test_openapi_show_single_activation(
        aut_user_auth_wsgi_app: WebTestAppForCMK):
    base = "/NO_SITE/check_mk/api/1.0"
    aut_user_auth_wsgi_app.call_method(
        "get",
        base + constructors.object_href("activation_run", "asdf"),
        status=404,
        headers={"Accept": "application/json"},
    )
Example #15
0
def _serialize_folder(folder: CREFolder) -> DomainObject:
    uri = constructors.object_href('folder_config', folder.id())
    return constructors.domain_object(
        domain_type='folder_config',
        identifier=folder.id(),
        title=folder.title(),
        members={
            'hosts':
            constructors.object_collection(
                name='hosts',
                domain_type='host_config',
                entries=[
                    constructors.link_rel(
                        rel='.../value',
                        parameters={'collection': "items"},
                        href=constructors.object_href('host_config', host),
                    ) for host in folder.hosts().values()
                ],
                base=uri,
            ),
            'move':
            constructors.object_action(
                name='move',
                base=uri,
                parameters=dict([
                    constructors.action_parameter(
                        action='move',
                        parameter='destination',
                        friendly_name=
                        'The destination folder of this move action',
                        optional=False,
                        pattern="[0-9a-fA-F]{32}|root",
                    ),
                ]),
            ),
        },
        extensions={
            'attributes': folder.attributes(),
        },
    )
Example #16
0
def serialize_host(host: watolib.CREHost, effective_attributes: bool):
    extensions = {
        "folder":
        host.folder().path(),
        "attributes":
        host.attributes(),
        "effective_attributes":
        host.effective_attributes() if effective_attributes else None,
        "is_cluster":
        host.is_cluster(),
        "is_offline":
        host.is_offline(),
        "cluster_nodes":
        host.cluster_nodes(),
    }

    agent_links = []
    if not cmk_version.is_raw_edition():
        import cmk.gui.cee.agent_bakery as agent_bakery  # pylint: disable=no-name-in-module

        for agent_type in sorted(agent_bakery.agent_package_types().keys()):
            agent_links.append(
                constructors.link_rel(
                    rel="cmk/download",
                    href="{}?{}".format(
                        constructors.domain_type_action_href(
                            "agent", "download"),
                        urlencode({
                            "os_type": agent_type,
                            "host_name": host.id()
                        }),
                    ),
                    method="get",
                    title=f"Download the {agent_type} agent of the host.",
                ))

    return constructors.domain_object(
        domain_type="host_config",
        identifier=host.id(),
        title=host.alias() or host.name(),
        links=[
            constructors.link_rel(
                rel="cmk/folder_config",
                href=constructors.object_href("folder_config",
                                              folder_slug(host.folder())),
                method="get",
                title="The folder config of the host.",
            ),
        ] + agent_links,
        extensions=extensions,
    )
Example #17
0
def serialize_host_tag_group(details: Dict[str, Any]):
    return constructors.domain_object(
        domain_type='host_tag_group',
        identifier=details['id'],
        title=details['title'],
        members={
            "title": constructors.object_property(
                name='title',
                value=details['title'],
                prop_format='string',
                base=constructors.object_href('host_tag_group', details['id']),
            )
        },
        extensions={key: details[key] for key in details if key in ('topic', 'tags')})
Example #18
0
def serialize_host(host):
    base = '/objects/host/%s' % (host.ident(), )
    return constructors.domain_object(
        domain_type='host',
        identifier=host.id(),
        title=host.alias(),
        members=dict([
            constructors.object_property_member(
                'folder',
                constructors.object_href('folder', host.folder()),
                base,
            ),
        ]),
        extensions={},
    )
Example #19
0
def serialize_host(host):
    base = '/objects/host/%s' % (host.ident(),)
    return constructors.domain_object(
        domain_type='host',
        identifier=host.id(),
        title=host.alias(),
        members={
            'folder': constructors.object_property(
                name='folder',
                value=constructors.object_href('folder', host.folder()),
                prop_format='string',
                base=base,
            ),
        },
        extensions={},
    )
Example #20
0
 def _serializer(group):
     # type: (Dict[str, str]) -> Any
     ident = group['id']
     return constructors.domain_object(
         domain_type=name,
         identifier=ident,
         title=group['alias'],
         members={
             'title': constructors.object_property(
                 name='title',
                 value=group['alias'],
                 prop_format='string',
                 base=constructors.object_href(name, ident),
             ),
         },
         extensions={},
     )
Example #21
0
def _serialize_folder(folder):
    # type: (CREFolder) -> DomainObject
    uri = '/objects/folder/%s' % (folder.id(), )
    return constructors.domain_object(
        domain_type='folder',
        identifier=folder.id(),
        title=folder.title(),
        members={
            'hosts':
            constructors.object_collection(
                name='hosts',
                entries=[
                    constructors.link_rel(
                        rel='.../value;collection="items"',
                        href=constructors.object_href('host', host),
                    ) for host in folder.hosts().values()
                ],
                base=uri,
            ),
            'move':
            constructors.object_action(
                name='move',
                base=uri,
                parameters=dict([
                    constructors.action_parameter(
                        action='move',
                        parameter='destination',
                        friendly_name=
                        'The destination folder of this move action',
                        optional=False,
                        pattern="[0-9a-fA-F]{32}|root",
                    ),
                ]),
            ),
            'title':
            constructors.object_property(
                name='title',
                value=folder.title(),
                prop_format='string',
                base=uri,
            ),
        },
        extensions={
            'attributes': folder.attributes(),
        },
    )
Example #22
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
Example #23
0
def serialize_host_tag_group(details: Dict[str, Any]):
    return constructors.domain_object(
        domain_type="host_tag_group",
        identifier=details["id"],
        title=details["title"],
        members={
            "title":
            constructors.object_property(
                name="title",
                value=details["title"],
                prop_format="string",
                base=constructors.object_href("host_tag_group", details["id"]),
            )
        },
        extensions={
            key: details[key]
            for key in details if key in ("topic", "tags")
        },
    )
Example #24
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
Example #25
0
def _serialize_single_downtime(downtime):
    links = []
    if downtime["is_service"]:
        downtime_detail = f"service: {downtime['service_description']}"
    else:
        host_name = downtime['host_name']
        downtime_detail = f"host: {host_name}"
        links.append(
            constructors.link_rel(
                rel='cmk/host_config',
                href=constructors.object_href('host_config', host_name),
                title='This host of this downtime.',
                method='get',
            ))

    downtime_id = downtime['id']
    return constructors.domain_object(
        domain_type='downtime',
        identifier=downtime_id,
        title='Downtime for %s' % downtime_detail,
        extensions=_downtime_properties(downtime),
        links=[
            constructors.link_rel(
                rel='.../delete',
                href=constructors.domain_type_action_href(
                    'downtime', 'delete'),
                method='post',
                title='Delete the downtime',
                body_params={
                    'delete_type': 'by_id',
                    'downtime_id': downtime_id
                },
            ),
        ],
        editable=False,
        deletable=False,
    )
Example #26
0
                 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)

    return _serve_folder(folder)


@endpoint_schema(constructors.object_href('folder_config', '{ident}'),
                 '.../persist',
                 method='put',
                 path_params=[IDENT_FIELD],
                 response_schema=response_schemas.ConcreteFolder,
                 etag='both',
                 request_body_required=True,
                 request_schema=request_schemas.UpdateFolder)
def update(params):
    """Update a folder

    Title and attributes can be updated, but there is no checking of the attributes done"""
    ident = params['ident']
    folder = load_folder(ident, status=404)
    constructors.require_etag(constructors.etag_of_obj(folder))
Example #27
0
@Endpoint(
    constructors.domain_object_collection_href("folder_config", "{folder}",
                                               "hosts"),
    ".../collection",
    method="get",
    path_params=[PATH_FOLDER_FIELD],
    response_schema=response_schemas.HostConfigCollection,
)
def hosts_of_folder(params):
    """Show all hosts in a folder"""
    folder: watolib.CREFolder = params["folder"]
    return host_collection(folder.hosts().values())


@Endpoint(
    constructors.object_href("folder_config", "{folder}"),
    ".../persist",
    method="put",
    path_params=[PATH_FOLDER_FIELD],
    etag="both",
    response_schema=response_schemas.FolderSchema,
    request_schema=request_schemas.UpdateFolder,
)
def update(params):
    """Update a folder"""
    folder = params["folder"]
    constructors.require_etag(etag_of_folder(folder))

    post_body = params["body"]
    if "title" in post_body:
        title = post_body["title"]
Example #28
0
    ".../collection",
    method="get",
    response_schema=response_schemas.DomainObjectCollection,
)
def list_groups(params):
    """Show all host groups"""
    collection = [{
        "id": k,
        "alias": v["alias"]
    } for k, v in load_host_group_information().items()]
    return constructors.serve_json(
        serialize_group_list("host_group_config", collection))


@Endpoint(
    constructors.object_href("host_group_config", "{name}"),
    ".../delete",
    method="delete",
    path_params=[NAME_FIELD],
    output_empty=True,
    permissions_required=permissions.Perm("wato.groups"),
)
def delete(params):
    """Delete a host group"""
    name = params["name"]
    watolib.delete_group(name, "host")
    return Response(status=204)


@Endpoint(
    constructors.domain_type_action_href("host_group_config", "bulk-delete"),
Example #29
0
        all_sets = SearchedRulesets(all_sets, search_options)

    ruleset_collection: List[DomainObject] = []
    for ruleset in all_sets.get_rulesets().values():
        ruleset_collection.append(_serialize_ruleset(ruleset))

    # We don't do grouping like in the GUI. This would not add any value here.
    return serve_json(
        constructors.collection_object(
            domain_type="ruleset",
            value=ruleset_collection,
        ))


@Endpoint(
    constructors.object_href(domain_type="ruleset", obj_id="{ruleset_name}"),
    "cmk/show",
    method="get",
    etag="output",
    path_params=[RULESET_NAME],
    response_schema=RulesetObject,
    permissions_required=PERMISSIONS,
)
def show_ruleset(param):
    """Show a ruleset"""
    ruleset_name = param["ruleset_name"]
    user.need_permission("wato.rulesets")
    collection = SingleRulesetRecursively(ruleset_name)

    try:
        collection.load()
Example #30
0
                "owned_by",
                "customer",
            )
        },
    )
    if version.is_managed_edition():
        password_details = update_customer_info(password_details,
                                                body["customer"])
    password_details[
        "owned_by"] = None if body["owned_by"] == "admin" else body["owned_by"]
    save_password(ident, password_details, new_password=True)
    return _serve_password(ident, load_password(ident))


@Endpoint(
    constructors.object_href("password", "{name}"),
    ".../update",
    method="put",
    path_params=[NAME_FIELD],
    request_schema=request_schemas.UpdatePassword,
    etag="both",
    response_schema=response_schemas.DomainObject,
)
def update_password(params):
    """Update a password"""
    body = params["body"]
    ident = params["name"]
    try:
        password_details = load_password_to_modify(ident)
    except KeyError:
        return problem(