def list_rules(param): """List rules""" all_sets = watolib.AllRulesets() all_sets.load() ruleset_name = param["ruleset_name"] try: ruleset = all_sets.get(ruleset_name.replace("-", ":")) except KeyError: return problem( status=400, title="Unknown ruleset.", detail=f"The ruleset of name {ruleset_name!r} is not known.", ) result = [] for folder, index, rule in ruleset.get_rules(): result.append(_serialize_rule(folder, index, rule)) return serve_json( constructors.collection_object( domain_type="rule", value=result, extensions={ "found_rules": len(result), }, ) )
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 ], ) )
def bulk_update(params): """Bulk update host-groups""" body = params['body'] entries = body['entries'] updated_contact_groups = update_groups("contact", entries) return constructors.serve_json( serialize_group_list('contact_group_config', updated_contact_groups))
def list_folders(params): """Show all folders""" if params["recursive"]: folders = params["parent"].all_folders_recursively() else: folders = params["parent"].subfolders() return constructors.serve_json(_folders_collection(folders, params["show_hosts"]))
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)
def bulk_update(params): """Bulk update service-groups""" body = params['body'] entries = body['entries'] updated_service_groups = update_groups("service", entries) return constructors.serve_json( serialize_group_list('service_group_config', updated_service_groups))
def _update_bi_rule(params, must_exist: bool): user.need_permission("wato.edit") user.need_permission("wato.bi_rules") bi_packs = get_cached_bi_packs() bi_packs.load_config() rule_config = params["body"] try: target_pack = bi_packs.get_pack_mandatory(rule_config["pack_id"]) except KeyError: _bailout_with_message("Unknown bi_pack: %s" % rule_config["pack_id"]) rule_id = params["rule_id"] rule_exists = bool(bi_packs.get_rule(rule_id)) if rule_exists and not must_exist: _bailout_with_message("This rule_id already exists: %s" % rule_id) if not rule_exists and must_exist: _bailout_with_message("This rule_id does not exist: %s" % rule_id) rule_config["id"] = rule_id bi_rule = BIRule(rule_config) target_pack.add_rule(bi_rule) bi_packs.save_config() data = {"pack_id": bi_rule.pack_id} data.update(bi_rule.schema()().dump(bi_rule)) return constructors.serve_json(data)
def _update_bi_pack(params, must_exist: bool): user.need_permission("wato.edit") user.need_permission("wato.bi_rules") user.need_permission("wato.bi_admin") bi_packs = get_cached_bi_packs() bi_packs.load_config() pack_id = params["pack_id"] existing_pack = bi_packs.get_pack(pack_id) if existing_pack and not must_exist: _bailout_with_message("This pack_id already exists: %s" % pack_id) if not existing_pack and must_exist: _bailout_with_message("This pack_id does not exist: %s" % pack_id) pack_config = {} if existing_pack: # Serialize the old pack # Rules and aggregations will be transferred to the new pack pack_config.update(existing_pack.serialize()) pack_config["id"] = pack_id pack_config.update(BIPackEndpointSchema().dump(params["body"])) new_pack = BIAggregationPack(pack_config) bi_packs.add_pack(new_pack) bi_packs.save_config() return constructors.serve_json(BIPackEndpointSchema().dump(new_pack.serialize()))
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)
def show_service(params): """Show the monitored service of a host""" service_description = params["service_description"] host_name = params["host_name"] live = sites.live() q = Query( [ Services.description, Services.host_name, Services.state_type, Services.state, Services.last_check, ], filter_expr=And(Services.host_name.op("=", params["host_name"]), Services.description.op("=", service_description)), ) try: service = q.fetchone(live) except ValueError: return problem( status=404, title="The requested service was not found", detail= f"The service description {service_description} did not match any service", ) return constructors.serve_json( constructors.domain_object( domain_type='service', identifier=f"{host_name}-{service_description}", title=f"Service {service_description}", extensions=service, links=[], editable=False, deletable=False))
def _update_bi_aggregation(params, must_exist: bool): user.need_permission("wato.edit") user.need_permission("wato.bi_rules") bi_packs = get_cached_bi_packs() bi_packs.load_config() aggregation_config = params["body"] try: target_pack = bi_packs.get_pack_mandatory(aggregation_config["pack_id"]) except MKGeneralException: _bailout_with_message("Unknown bi_pack: %s" % aggregation_config["pack_id"]) aggregation_id = params["aggregation_id"] aggregation_exists = bool(bi_packs.get_aggregation(aggregation_id)) if aggregation_exists and not must_exist: _bailout_with_message("This aggregation_id already exists: %s" % aggregation_id) if not aggregation_exists and must_exist: _bailout_with_message("This aggregation_id does not exist: %s" % aggregation_id) aggregation_config["id"] = aggregation_id bi_aggregation = BIAggregation(aggregation_config) target_pack.add_aggregation(bi_aggregation) bi_packs.save_config() data = {"pack_id": bi_aggregation.pack_id} data.update(bi_aggregation.schema()().dump(bi_aggregation)) return constructors.serve_json(data)
def _list_services(param): live = sites.live() columns = verify_columns(Services, param['columns']) q = Query(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=entry['description'], editable=False, deletable=False, extensions=entry, ) for entry in result ], ))
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 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 ], ))
def bulk_update(params): """Bulk update folders""" body = params['body'] entries = body['entries'] folders = [] for update_details in entries: folder = update_details['folder'] title = update_details['title'] replace_attributes = update_details.get('attributes') update_attributes = update_details.get('update_attributes') attributes = folder.attributes().copy() if replace_attributes: attributes = replace_attributes if update_attributes: attributes.update(update_attributes) # FIXME: see above in update # You can't update the attributes without updating the title, so the title is mandatory. # This shouldn't be the case though. folder.edit(title, attributes) folders.append(folder) return constructors.serve_json(_folders_collection(folders))
def bulk_update(params): """Bulk update folders""" body = params['body'] entries = body['entries'] folders = [] for update_details in entries: folder = update_details['folder'] title = update_details['title'] replace_attributes = update_details['attributes'] update_attributes = update_details['update_attributes'] remove_attributes = update_attributes['remove_attributes'] attributes = folder.attributes().copy() if replace_attributes: attributes = replace_attributes if update_attributes: attributes.update(update_attributes) for attribute in remove_attributes: folder.remove_attribute(attribute) folder.edit(title, attributes) folders.append(folder) return constructors.serve_json(_folders_collection(folders))
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)
def show_ruleset(param): """Show a ruleset""" ruleset_name = param["ruleset_name"] collection = watolib.SingleRulesetRecursively(ruleset_name) collection.load() ruleset = collection.get(ruleset_name) return serve_json(_serialize_ruleset(ruleset))
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))
def create_rule(param): """Create rule""" body = param["body"] folder = body["folder"] value = body["value_raw"] rulesets = watolib.FolderRulesets(folder) rulesets.load() try: ruleset = rulesets.get(body["ruleset"]) except KeyError: return problem( status=400, detail=f"Ruleset {body['ruleset']!r} could not be found.", ) try: ruleset.valuespec().validate_value(value, "") except exceptions.MKUserError as exc: if exc.varname is None: title = "A field has a problem" else: field_name = exc.varname.replace("_p_", "") title = f"Problem in (sub-)field {field_name!r}" return problem( status=400, detail=strip_tags(exc.message), title=title, ) rule = watolib.Rule( gen_id(), folder, ruleset, RuleConditions( host_folder=folder, host_tags=body["conditions"].get("host_tag"), host_labels=body["conditions"].get("host_label"), host_name=body["conditions"].get("host_name"), service_description=body["conditions"].get("service_description"), service_labels=body["conditions"].get("service_label"), ), RuleOptions.from_config(body["properties"]), value, ) index = ruleset.append_rule(folder, rule) rulesets.save() # TODO Duplicated code is in pages/rulesets.py:2670- # TODO Move to watolib add_change( "new-rule", _l('Created new rule #%d in ruleset "%s" in folder "%s"') % (index, ruleset.title(), folder.alias_path()), sites=folder.all_site_ids(), diff_text=make_diff_text({}, rule.to_log()), object_ref=rule.object_ref(), ) return serve_json(_serialize_rule(folder, index, rule))
def get_bi_aggregation_state(params): """Get the state of BI aggregations""" user.need_permission("wato.bi_rules") filter_config = params.get("body", {}) filter_names = filter_config.get("filter_names") filter_groups = filter_config.get("filter_groups") return constructors.serve_json( api_get_aggregation_state(filter_names=filter_names, filter_groups=filter_groups) )
def list_group(params): """Show all contact groups""" user.need_permission("wato.users") collection = [{ "id": k, "alias": v["alias"] } for k, v in load_contact_group_information().items()] return constructors.serve_json( serialize_group_list("contact_group_config", collection), )
def show_host(params) -> Response: """Show a host""" host = Host.load_host(params["host_name"]) return constructors.serve_json( { "site": host.site_id(), "is_cluster": host.is_cluster(), } )
def list_folders(_params): return constructors.serve_json({ 'id': 'folders', 'value': [ constructors.collection_object('folders', 'folder', folder) for folder in watolib.Folder.root_folder().subfolders() ], 'links': [constructors.link_rel('self', '/collections/folder')] })
def _serve_folder( folder, profile=None, show_hosts=False, ): folder_json = _serialize_folder(folder, show_hosts) response = constructors.serve_json(folder_json, profile=profile) if not folder.is_root(): response.headers.add("ETag", etag_of_folder(folder).to_header()) return response
def list_folders(params): """Show all folders""" parent: CREFolder = params["parent"] if params["recursive"]: parent.need_recursive_permission("read") folders = parent.all_folders_recursively() else: parent.need_permission("read") folders = parent.subfolders() return constructors.serve_json(_folders_collection(folders, params["show_hosts"]))
def root_cert(param) -> Response: """X.509 PEM-encoded root certificate""" if not _user_is_authorized(): raise ProblemException( status=403, title=_403_STATUS_DESCRIPTION, ) return constructors.serve_json({ "cert": _serialized_root_cert(), })
def list_groups(params): """List service-groups""" return constructors.serve_json({ 'id': 'folders', 'value': [ constructors.collection_object('service_group', 'service_group', group) for group in load_service_group_information().values() ], 'links': [constructors.link_rel('self', '/collections/service_group')] })
def list_users(params): """Show all users""" users = [] for user_id, attrs in userdb.load_users(False).items(): user_attributes = _internal_to_api_format(attrs) users.append( serialize_user(user_id, complement_customer(user_attributes))) return constructors.serve_json( constructors.collection_object(domain_type="user_config", value=users))
def get_bi_rule(params): """Get BI Rule""" bi_packs.load_config() bi_rule = bi_packs.get_rule(params["rule_id"]) if bi_rule is None: _bailout_with_message("Unknown bi_rule: %s" % params["rule_id"]) assert bi_rule is not None data = {"pack_id": bi_rule.pack_id} data.update(BIRuleSchema().dump(bi_rule).data) return constructors.serve_json(data)
def list_group(params): return constructors.serve_json({ 'id': 'folders', 'value': [ constructors.collection_object('contact_group', 'contact_group', group) for group in load_contact_group_information().values() ], 'links': [constructors.link_rel('self', '/collections/contact_group')] })