Пример #1
0
def load_tag_group(ident: str) -> Optional[TagGroup]:
    """Load a tag group

    Args:
        ident:
            identifier of the tag group

    """
    tag_config = load_tag_config()
    tag_config += BuiltinTagConfig()
    return tag_config.get_tag_group(ident)
Пример #2
0
def test_openapi_host_tag_group_get_collection(aut_user_auth_wsgi_app: WebTestAppForCMK):
    base = "/NO_SITE/check_mk/api/1.0"

    builtin_groups_count = len(BuiltinTagConfig().tag_groups)

    col_resp = aut_user_auth_wsgi_app.call_method(
        "get",
        base + "/domain-types/host_tag_group/collections/all",
        headers={"Accept": "application/json"},
        status=200,
    )
    assert len(col_resp.json_body["value"]) == builtin_groups_count
Пример #3
0
def test_openapi_host_tag_group_get_collection(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"

    builtin_groups_count = len(BuiltinTagConfig().tag_groups)

    col_resp = wsgi_app.call_method(
        "get",
        base + "/domain-types/host_tag_group/collections/all",
        status=200,
    )
    assert len(col_resp.json_body["value"]) == builtin_groups_count
Пример #4
0
def test_openapi_host_tag_group_built_in(wsgi_app, with_automation_user, suppress_automation_calls):
    username, secret = with_automation_user
    wsgi_app.set_authorization(("Bearer", username + " " + secret))

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

    resp = wsgi_app.call_method(
        "get",
        base + "/domain-types/host_tag_group/collections/all",
        status=200,
    )
    built_in_tags = [tag_group.title for tag_group in BuiltinTagConfig().tag_groups]
    assert all(
        title in (entry["title"] for entry in resp.json_body["value"]) for title in built_in_tags
    )

    resp = wsgi_app.call_method(
        "get",
        base + "/objects/host_tag_group/agent",
        status=200,
    )

    _resp = wsgi_app.call_method(
        "put",
        base + "/objects/host_tag_group/agent",
        params=json.dumps(
            {
                "tags": [
                    {
                        "ident": "tutu",
                        "title": "something",
                    }
                ]
            }
        ),
        headers={"If-Match": resp.headers["ETag"]},
        status=405,
        content_type="application/json",
    )

    _resp = wsgi_app.call_method(
        "delete",
        base + "/objects/host_tag_group/agent",
        params=json.dumps({}),
        status=405,
        content_type="application/json",
    )
Пример #5
0
def test_openapi_host_tag_group_built_in(aut_user_auth_wsgi_app: WebTestAppForCMK):
    base = "/NO_SITE/check_mk/api/1.0"

    resp = aut_user_auth_wsgi_app.call_method(
        "get",
        base + "/domain-types/host_tag_group/collections/all",
        headers={"Accept": "application/json"},
        status=200,
    )
    built_in_tags = [tag_group.title for tag_group in BuiltinTagConfig().tag_groups]
    assert all(
        title in (entry["title"] for entry in resp.json_body["value"]) for title in built_in_tags
    )

    resp = aut_user_auth_wsgi_app.call_method(
        "get",
        base + "/objects/host_tag_group/agent",
        headers={"Accept": "application/json"},
        status=200,
    )

    _resp = aut_user_auth_wsgi_app.call_method(
        "put",
        base + "/objects/host_tag_group/agent",
        params=json.dumps(
            {
                "tags": [
                    {
                        "ident": "tutu",
                        "title": "something",
                    }
                ]
            }
        ),
        headers={"If-Match": resp.headers["ETag"], "Accept": "application/json"},
        status=405,
        content_type="application/json",
    )

    _resp = aut_user_auth_wsgi_app.call_method(
        "delete",
        base + "/objects/host_tag_group/agent",
        params=json.dumps({}),
        headers={"Accept": "application/json"},
        status=405,
        content_type="application/json",
    )
def test_openapi_host_tag_group_built_in(wsgi_app, with_automation_user,
                                         suppress_automation_calls):
    username, secret = with_automation_user
    wsgi_app.set_authorization(('Bearer', username + " " + secret))

    base = '/NO_SITE/check_mk/api/1.0'

    resp = wsgi_app.call_method(
        'get',
        base + '/domain-types/host_tag_group/collections/all',
        status=200,
    )
    built_in_tags = [
        tag_group.title for tag_group in BuiltinTagConfig().tag_groups
    ]
    assert all([
        title in (entry['title'] for entry in resp.json_body['value'])
        for title in built_in_tags
    ])

    resp = wsgi_app.call_method(
        'get',
        base + "/objects/host_tag_group/agent",
        status=200,
    )

    _resp = wsgi_app.call_method(
        'put',
        base + "/objects/host_tag_group/agent",
        params=json.dumps(
            {"tags": [{
                "ident": "tutu",
                "title": "something",
            }]}),
        headers={'If-Match': resp.headers['ETag']},
        status=405,
        content_type='application/json',
    )

    _resp = wsgi_app.call_method(
        'delete',
        base + "/objects/host_tag_group/agent",
        params=json.dumps({}),
        status=405,
        content_type='application/json',
    )
Пример #7
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)
Пример #8
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)
Пример #9
0
def collect_attributes(
    object_type: ObjectType,
    context: ObjectContext,
) -> List[Attr]:
    """Collect all attributes for a specific use case

    Use cases can be host or folder creation or updating.

    Args:
        object_type:
            Either 'host', 'folder' or 'cluster'

        context:
            Either 'create' or 'update'

    Returns:
        A list of attribute describing named-tuples.

    Examples:

        >>> attrs = collect_attributes('host', 'create')
        >>> assert len(attrs) > 10

        >>> attrs = collect_attributes('host', 'update')
        >>> assert len(attrs) > 10

        >>> attrs = collect_attributes('cluster', 'create')
        >>> assert len(attrs) > 10

        >>> attrs = collect_attributes('cluster', 'update')
        >>> assert len(attrs) > 10

        >>> attrs = collect_attributes('folder', 'create')
        >>> assert len(attrs) > 10

        >>> attrs = collect_attributes('folder', 'update')
        >>> assert len(attrs) > 10

    To check the content of the list, uncomment this one.

        # >>> import pprint
        # >>> pprint.pprint(attrs)

    """
    something = TypeVar("something")

    def _ensure(optional: Optional[something]) -> something:
        if optional is None:
            raise ValueError
        return optional

    T = typing.TypeVar("T")

    def maybe_call(func: Optional[Callable[[], T]]) -> Optional[T]:
        if func is None:
            return None
        return func()

    result = []
    new = context == "create"
    for topic_id, topic_title in watolib.get_sorted_host_attribute_topics(
            object_type, new):
        for attr in watolib.get_sorted_host_attributes_by_topic(topic_id):
            if not attr.is_visible(object_type, new):
                continue
            help_text: str = attr.help() or ""
            # TODO: what to do with attr.depends_on_tags()?
            attr_entry = Attr(
                name=attr.name(),
                description=help_text,
                section=topic_title,
                mandatory=attr.is_mandatory(),
                field=maybe_call(getattr(attr, "openapi_field", None)),
            )
            result.append(attr_entry)

    tag_config = load_tag_config()
    tag_config += BuiltinTagConfig()

    def _format(tag_id: Optional[str]) -> str:
        if tag_id is None:
            return "`null`"
        return f'`"{tag_id}"`'

    tag_group: TagGroup
    for tag_group in tag_config.tag_groups:
        description: List[str] = []
        if tag_group.help:
            description.append(tag_group.help)

        if tag_group.tags:
            description.append("Choices:")
            for tag in tag_group.tags:
                description.append(f" * {_format(tag.id)}: {tag.title}")

        result.append(
            Attr(
                name=_ensure(f"tag_{tag_group.id}"),
                section=tag_group.topic or "No topic",
                mandatory=False,
                description="\n\n".join(description),
                enum=[tag.id for tag in tag_group.tags],
                field=None,
            ))

    return result
Пример #10
0
def tag_group_exists(ident: str, builtin_included=False) -> bool:
    """Verify if a tag group exists"""
    tag_config = load_tag_config()
    if builtin_included:
        tag_config += BuiltinTagConfig()
    return tag_config.tag_group_exists(ident)
Пример #11
0
def is_builtin(ident: str) -> bool:
    """Verify if a tag group is a built-in"""
    tag_config = BuiltinTagConfig()
    return tag_config.tag_group_exists(ident)
Пример #12
0
def is_builtin(ident: str) -> bool:
    """Verify if a tag group is a built-in"""
    if user:
        user.need_permission("wato.hosttags")
    tag_config = BuiltinTagConfig()
    return tag_config.tag_group_exists(ident)