def _add_host(host): """ Add or update a host Required parameters: - at least one of the canonical facts fields is required - account number """ validated_input_host_dict = HostSchema(strict=True).load(host) input_host = Host.from_json(validated_input_host_dict.data) if not current_identity.is_trusted_system and current_identity.account_number != input_host.account: raise InventoryException( title="Invalid request", detail= "The account number associated with the user does not match the account number associated with the " "host", ) existing_host = find_existing_host(input_host.account, input_host.canonical_facts) if existing_host: return update_existing_host(existing_host, input_host) else: return create_new_host(input_host)
def add_host(host): """ Add or update a host Required parameters: - at least one of the canonical facts fields is required - account number """ logger.debug("add_host(%s)" % host) account_number = host.get("account", None) if current_identity.account_number != account_number: raise InventoryException( title="Invalid request", detail="The account number associated with the user does not " "match the account number associated with the host") input_host = Host.from_json(host) canonical_facts = input_host.canonical_facts if not canonical_facts: raise InventoryException(title="Invalid request", detail="At least one of the canonical fact " "fields must be present.") existing_host = find_existing_host(account_number, canonical_facts) if existing_host: return update_existing_host(existing_host, input_host) else: return create_new_host(input_host)
def addHost(host): print("addHost()") print("host:", host) # Required inputs: # account # canonical_facts canonical_facts = host.get("canonical_facts") found_host = Host.query.filter( Host.canonical_facts.comparator.contains(canonical_facts) | Host.canonical_facts.comparator.contained_by(canonical_facts)).first( ) if not found_host: print("Creating a new host") host = Host.from_json(host) host.save() return host.to_json(), 201 else: print("Updating host...") found_host.update(host) print("*** Updated host:", found_host) return found_host.to_json(), 200
def test_create_host_with_canonical_facts_as_None(flask_app_fixture): # Test to make sure canonical facts that are None or '' do # not get inserted into the db invalid_canonical_facts = {"fqdn": None, "insights_id": ""} valid_canonical_facts = {"bios_uuid": "1234"} host_dict = {**invalid_canonical_facts, **valid_canonical_facts} host = Host.from_json(host_dict) assert valid_canonical_facts == host.canonical_facts
def addHost(host): """ Add or update a host Required parameters: - at least one of the canonical facts fields is required - account number """ current_app.logger.debug("addHost(%s)" % host) account_number = host.get("account", None) if current_identity.account_number != account_number: return ( "The account number associated with the user does not match " "the account number associated with the host", 400, ) input_host = Host.from_json(host) canonical_facts = input_host.canonical_facts if not canonical_facts: return ( "Invalid request: At least one of the canonical fact fields " "must be present.", 400, ) found_host = Host.query.filter( (Host.account == account_number) & (Host.canonical_facts.comparator.contains(canonical_facts) | Host.canonical_facts.comparator.contained_by(canonical_facts)) ).first() if not found_host: current_app.logger.debug("Creating a new host") db.session.add(input_host) db.session.commit() metrics.create_host_count.inc() current_app.logger.debug("Created host:%s" % input_host) return input_host.to_json(), 201 else: current_app.logger.debug("Updating an existing host") found_host.update(input_host) db.session.commit() metrics.update_host_count.inc() current_app.logger.debug("Updated host:%s" % found_host) return found_host.to_json(), 200
def put_file_import(): resp = ResponseFormater() hosts_to_add = [] groups_to_add = [] keep_existing_nodes = str( request.args.get("keep") or next(iter(request.form.getlist('keep')), None)).lower() in [ "on", "true", "1", "yes" ] for file in request.files.values(): fileextention = file.filename.split(".")[-1] to_add = None if fileextention.lower() in ("yaml", "yml"): try: to_add = yaml.load(file, Loader=yaml.FullLoader) resp.add_message("Successfully loaded %s" % (file.filename)) except yaml.YAMLError as _: return resp.failed( msg="failed to read yaml file: %s" % (file.filename), changed=False, status=HTTPStatus.BAD_REQUEST).get_response() elif fileextention.lower() == "json": try: to_add = json.load(file) resp.add_message("Successfully loaded %s" % (file.filename)) except json.JSONDecodeError as _: return resp.failed( msg="failed to read json file: %s" % (file.filename), changed=False, status=HTTPStatus.BAD_REQUEST).get_response() elif fileextention.lower() == "ini": try: data = file.read().decode('utf-8') to_add = _convert_ini(data) except Exception: return resp.failed( msg="failed to read ini file: %s" % (file.filename), changed=False, status=HTTPStatus.BAD_REQUEST).get_response() else: return resp.failed("unsupported extention", changed=False, status=HTTPStatus.BAD_REQUEST).get_response() if "hosts" in to_add and isinstance(to_add["hosts"], list): hosts_to_add.extend(to_add["hosts"]) if "groups" in to_add and isinstance(to_add["groups"], list): groups_to_add.extend(to_add["groups"]) for node in to_add.get("nodes", []): if node.get("type", "").lower() == "host": hosts_to_add.append(node) elif node.get("type", "").lower() == "group": groups_to_add.append(node) if len(hosts_to_add) > 0 or len(groups_to_add) > 0: if not keep_existing_nodes: o_nodes_to_delete = Node.objects() if o_nodes_to_delete.count() > 0: o_nodes_to_delete.delete() resp.add_message("Remove old hosts and groups") logging.info("Remove all existing nodes during import") resp.changed() else: logging.info("Keep existing nodes during import") # first make sure all nodes exist for host in hosts_to_add: if host.get("name") and not Host.objects(name=host.get("name")): Host(name=host.get("name")).save() for group in groups_to_add: if group.get("name") and not Group.objects(name=group.get("name")): Group(name=group.get("name")).save() for host in hosts_to_add: try: o_host = Host.from_json(host, append=True) o_host.save() resp.add_result(o_host) resp.changed() except Exception as _: resp.add_message("Failed to import host %s" % (host.get("name", "unknown"))) for group in groups_to_add: try: o_group = Group.from_json(group, append=True) o_group.save() resp.add_result(o_group) resp.changed() except Exception as _: resp.add_message("Failed to import group %s" % (group.get("name", "unknown"))) else: resp.failed(msg="No valid hosts or groups in import") resp.add_message("Import completed") return resp.get_response()