Exemplo n.º 1
0
def _serialize_rule(rule_entry: RuleEntry) -> DomainObject:
    rule = rule_entry.rule
    return constructors.domain_object(
        domain_type="rule",
        editable=False,
        identifier=rule.id,
        title=rule.description(),
        extensions={
            "ruleset":
            rule.ruleset.name,
            "folder":
            "/" + rule_entry.folder.path(),
            "folder_index":
            rule_entry.index_nr,
            "properties":
            rule.rule_options.to_config(),
            "value_raw":
            rule.value,
            "conditions":
            denilled({
                "host_name": rule.conditions.host_name,
                "host_tags": rule.conditions.host_tags,
                "host_labels": rule.conditions.host_labels,
                "service_description": rule.conditions.service_description,
                "service_labels": rule.conditions.service_labels,
            }),
        },
    )
Exemplo n.º 2
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,
    )
Exemplo n.º 3
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(),
        },
    )
Exemplo n.º 4
0
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

    q = Query(param["columns"])

    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="host",
            value=[
                constructors.domain_object(
                    domain_type="host",
                    title=f"{entry['name']}",
                    identifier=entry["name"],
                    editable=False,
                    deletable=False,
                    extensions=entry,
                ) for entry in result
            ],
        ))
Exemplo n.º 5
0
def _serialize_downtimes(downtimes):
    entries = []
    for downtime_info in downtimes:
        service_description = downtime_info.get("service_description")
        if service_description:
            downtime_detail = "service: %s" % service_description
        else:
            downtime_detail = "host: %s" % downtime_info["host_name"]

        downtime_id = downtime_info['id']
        entries.append(
            constructors.domain_object(
                domain_type='downtime',
                identifier=downtime_id,
                title='Downtime for %s' % downtime_detail,
                extensions=_downtime_properties(downtime_info),
                links=[
                    constructors.link_rel(rel='.../delete',
                                          href='/objects/host/%s/objects/downtime/%s' %
                                          (downtime_info['host_name'], downtime_id),
                                          method='delete',
                                          title='Delete the downtime'),
                ]))

    return constructors.object_collection(
        name='all',
        domain_type='downtime',
        entries=entries,
        base='',
    )
Exemplo n.º 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",
            )
        },
    )
Exemplo n.º 7
0
def _folders_collection(
    folders: List[CREFolder],
    show_hosts: bool,
):
    folders_ = []
    for folder in folders:
        members = {}
        if show_hosts:
            members["hosts"] = constructors.object_collection(
                name="hosts",
                domain_type="folder_config",
                entries=[
                    constructors.collection_item("host_config", {
                        "title": host,
                        "id": host
                    }) for host in folder.hosts()
                ],
                base="",
            )
        folders_.append(
            constructors.domain_object(
                domain_type="folder_config",
                identifier=folder_slug(folder),
                title=folder.title(),
                extensions={
                    "path": "/" + folder.path(),
                    "attributes": folder.attributes().copy(),
                },
                members=members,
            ))
    return constructors.collection_object(
        domain_type="folder_config",
        value=folders_,
    )
Exemplo n.º 8
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",
                                          )
                                      })
Exemplo n.º 9
0
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

    columns = verify_columns(Hosts, param['columns'])
    q = Query(columns)

    # TODO: add sites parameter
    filter_tree = param.get('query')
    if filter_tree:
        expr = tree_to_expr(filter_tree)
        q = q.filter(expr)

    result = q.iterate(live)

    return constructors.serve_json(
        constructors.collection_object(
            domain_type='host',
            value=[
                constructors.domain_object(
                    domain_type='host',
                    title=f"{entry['name']}",
                    identifier=entry['name'],
                    editable=False,
                    deletable=False,
                    extensions=entry,
                ) for entry in result
            ],
        ))
Exemplo n.º 10
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(),
        },
    )
Exemplo n.º 11
0
def serialize_user(user_id, attributes):
    return constructors.domain_object(
        domain_type="user_config",
        identifier=user_id,
        title=attributes["fullname"],
        extensions=_filter_keys(
            attributes, response_schemas.UserAttributes._declared_fields),
    )
Exemplo n.º 12
0
def serialize_user(user_id, attributes):
    return constructors.domain_object(
        domain_type="user_config",
        identifier=user_id,
        title=attributes["fullname"],
        extensions={
            "attributes": attributes,
        },
    )
Exemplo n.º 13
0
def serialize_user(user_id, attributes):
    return constructors.domain_object(
        domain_type='user_config',
        identifier=user_id,
        title=attributes["alias"],
        extensions={
            'attributes': attributes,
        },
    )
Exemplo n.º 14
0
def _list_services(param):
    live = sites.live()

    default_columns = [
        'host_name',
        'description',
        'last_check',
        'state',
        'state_type',
        'acknowledged',
    ]
    column_names = add_if_missing(param.get('columns', default_columns),
                                  ['host_name', 'description'])
    columns = verify_columns(Services, column_names)
    q = Query(columns)

    host_name = param.get('host_name')
    if host_name is not None:
        q = q.filter(Services.host_name.contains(host_name))

    alias = param.get('host_alias')
    if alias is not None:
        q = q.filter(Services.host_alias.contains(alias))

    in_downtime = param.get('in_downtime')
    if in_downtime is not None:
        q = q.filter(Services.scheduled_downtime_depth == int(in_downtime))

    acknowledged = param.get('acknowledged')
    if acknowledged is not None:
        q = q.filter(Services.acknowledged.equals(acknowledged))

    status = param.get('status')
    if status is not None:
        q = q.filter(Services.state.equals(status))

    result = q.iterate(live)

    return constructors.object_collection(
        name='all',
        domain_type='service',
        entries=[
            constructors.domain_object(
                domain_type='service',
                title=f"{entry['description']} on {entry['host_name']}",
                identifier=entry['description'],
                editable=False,
                deletable=False,
                extensions=entry,
            ) for entry in result
        ],
        base='',
    )
Exemplo n.º 15
0
def list_hosts(param):
    """List currently monitored hosts."""
    live = sites.live()

    default_columns = [
        'name',
        'address',
        'alias',
        'downtimes_with_info',
        'scheduled_downtime_depth',
    ]
    column_names = add_if_missing(param.get('columns', default_columns),
                                  ['name', 'address'])
    columns = verify_columns(Hosts, column_names)
    q = Query(columns)

    host_name = param.get('host_name')
    if host_name is not None:
        q = q.filter(Hosts.name.contains(host_name))

    host_alias = param.get('host_alias')
    if host_alias is not None:
        q = q.filter(Hosts.alias.contains(host_alias))

    in_downtime = param.get('in_downtime')
    if in_downtime is not None:
        q = q.filter(Hosts.scheduled_downtime_depth == int(in_downtime))

    acknowledged = param.get('acknowledged')
    if acknowledged is not None:
        q = q.filter(Hosts.acknowledged.equals(acknowledged))

    status = param.get('status')
    if status is not None:
        q = q.filter(Hosts.state.equals(status))

    result = q.iterate(live)

    return constructors.object_collection(
        name='all',
        domain_type='host',
        entries=[
            constructors.domain_object(
                domain_type='host',
                title=f"{entry['name']} ({entry['address']})",
                identifier=entry['name'],
                editable=False,
                deletable=False,
                extensions=entry,
            ) for entry in result
        ],
        base='',
    )
Exemplo n.º 16
0
def serialize_service_discovery(host, discovered_services, discovery_state):
    members = {}
    for (table_source, check_type, _checkgroup, item, _discovered_params,
         _check_params, descr, _service_state, _output, _perfdata,
         _service_labels) in discovered_services:

        if table_source == SERVICE_DISCOVERY_STATES[discovery_state]:
            service_hash = checkbox_id(check_type, item)
            members[service_hash] = {
                "service_name":
                descr,
                "check_plugin_name":
                check_type,
                "state":
                object_property(
                    name=descr,
                    title="The service is currently %s" % discovery_state,
                    value=table_source,
                    prop_format='string',
                    base='',
                    links=[
                        link_rel(
                            rel="cmk/service.move-monitored",
                            href=
                            "/objects/host/%s/service/%s/action/move/monitored"
                            % (host.ident(), service_hash),
                            method='put',
                            title='Move the service to monitored'),
                        link_rel(
                            rel="cmk/service.move-undecided",
                            href=
                            "/objects/host/%s/service/%s/action/move/undecided"
                            % (host.ident(), service_hash),
                            method='put',
                            title='Move the service to undecided'),
                        link_rel(
                            rel="cmk/service.move-ignored",
                            href=
                            "/objects/host/%s/service/%s/action/move/ignored" %
                            (host.ident(), service_hash),
                            method='put',
                            title='Move the service to ignored'),
                    ]),
            }

    return domain_object(
        domain_type='service_discovery',
        identifier='%s-services-%s' % (host.ident(), "wato"),
        title='Services discovery',
        members=members,
        extensions={},
    )
Exemplo n.º 17
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,
    )
Exemplo n.º 18
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')})
Exemplo n.º 19
0
def _list_services(param):
    live = sites.live()

    q = Query([
        Services.host_name,
        Services.description,
        Services.last_check,
        Services.state,
        Services.state_type,
        Services.acknowledged,
    ])

    host_name = param.get('host_name')
    if host_name is not None:
        q = q.filter(Services.host_name.contains(host_name))

    alias = param.get('host_alias')
    if alias is not None:
        q = q.filter(Services.host_alias.contains(alias))

    in_downtime = param.get('in_downtime')
    if in_downtime is not None:
        q = q.filter(Services.scheduled_downtime_depth == int(in_downtime))

    acknowledged = param.get('acknowledged')
    if acknowledged is not None:
        q = q.filter(Services.acknowledged.equals(acknowledged))

    status = param.get('status')
    if status is not None:
        q = q.filter(Services.state.equals(status))

    result = q.iterate(live)

    return constructors.object_collection(
        name='all',
        domain_type='service',
        entries=[
            constructors.domain_object(
                domain_type='service',
                title=f"{entry['description']} on {entry['host_name']}",
                identifier=entry['description'],
                editable=False,
                deletable=False,
                extensions=dict(entry),
            ) for entry in result
        ],
        base='',
    )
Exemplo n.º 20
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={},
    )
Exemplo n.º 21
0
def _serve_activation_run(activation_id, is_running=False):
    """Serialize the activation response"""
    links = []
    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,
        ))
Exemplo n.º 22
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={},
    )
Exemplo n.º 23
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)
Exemplo n.º 24
0
def list_hosts(param):
    live = sites.live()

    q = Query([
        Hosts.name,
        Hosts.address,
        Hosts.alias,
        Hosts.downtimes_with_info,
        Hosts.scheduled_downtime_depth,
    ])

    hostname = param.get('host_name')
    if hostname is not None:
        q = q.filter(Hosts.name.contains(hostname))

    alias = param.get('host_alias')
    if alias is not None:
        q = q.filter(Hosts.alias.contains(alias))

    in_downtime = param.get('in_downtime')
    if in_downtime is not None:
        q = q.filter(Hosts.scheduled_downtime_depth == int(in_downtime))

    acknowledged = param.get('acknowledged')
    if acknowledged is not None:
        q = q.filter(Hosts.acknowledged.equals(acknowledged))

    status = param.get('status')
    if status is not None:
        q = q.filter(Hosts.state.equals(status))

    result = q.iterate(live)

    return constructors.object_collection(
        name='all',
        domain_type='host',
        entries=[
            constructors.domain_object(
                domain_type='host',
                title=f"{entry['name']} ({entry['address']})",
                identifier=entry['name'],
                editable=False,
                deletable=False,
            ) for entry in result
        ],
        base='',
    )
Exemplo n.º 25
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(),
        },
    )
Exemplo n.º 26
0
def _serve_background_job(job: BulkDiscoveryBackgroundJob) -> Response:
    job_id = job.get_job_id()
    status_details = bulk_discovery_job_status(job)
    return constructors.serve_json(
        constructors.domain_object(
            domain_type="discovery_run",
            identifier=job_id,
            title=
            f"Background job {job_id} {'is active' if status_details['is_active'] else 'is finished'}",
            extensions={
                "active": status_details["is_active"],
                "state": status_details["job_state"],
                "logs": status_details["logs"],
            },
            deletable=False,
            editable=False,
        ))
Exemplo n.º 27
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={},
     )
Exemplo n.º 28
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()

        extensions["alias"] = group["alias"]
        return constructors.domain_object(
            domain_type=name,
            identifier=ident,
            title=group["alias"] or ident,
            extensions=extensions,
        )
Exemplo n.º 29
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={},
    )
Exemplo n.º 30
0
def _serve_activation_run(activation_id, is_running=False):
    """Serialize the activation response."""
    links = []
    if is_running:
        links.append(
            constructors.link_endpoint(
                'cmk.gui.plugins.openapi.endpoints.activate_changes',
                'cmk/wait-for-completion',
                parameters={'activation_id': activation_id}))
    return constructors.domain_object(
        domain_type='activation_run',
        identifier=activation_id,
        title='Activation %s was started.' % (activation_id, ),
        deletable=False,
        editable=False,
        links=links,
    )