From f8a261c8023e2d92f7a892033379044fbb6651d8 Mon Sep 17 00:00:00 2001 From: John Schulz Date: Wed, 14 Oct 2020 10:11:38 -0400 Subject: [PATCH] [Ingest Manager] Don't error if updating an agent policy (#80403) (#80502) ## Summary fixes #80136 Haven't added/updated tests yet but tested the various combinations in the UI and all worked as expected.
Screenshots

Policy listing

Screen Shot 2020-10-14 at 7 05 19 AM

Update existing policy succeeds

Screen Shot 2020-10-14 at 7 05 49 AM

Creating new policy w/existing name fails

Screen Shot 2020-10-14 at 7 06 06 AM

Updating policy to existing name fails

Screen Shot 2020-10-14 at 7 08 05 AM
### Checklist - [ ] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios --- .../server/services/agent_policy.ts | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/x-pack/plugins/ingest_manager/server/services/agent_policy.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy.ts index 3a282866171114..44ddb6add8476f 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_policy.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy.ts @@ -128,25 +128,26 @@ class AgentPolicyService { public async requireUniqueName( soClient: SavedObjectsClientContract, - { name, namespace }: Pick + givenPolicy: { id?: string; name: string; namespace: string } ) { const results = await soClient.find({ type: SAVED_OBJECT_TYPE, searchFields: ['namespace', 'name'], - search: `${namespace} + ${escapeSearchQueryPhrase(name)}`, + search: `${givenPolicy.namespace} + ${escapeSearchQueryPhrase(givenPolicy.name)}`, }); - - if (results.total) { - const policies = results.saved_objects; - const isSinglePolicy = policies.length === 1; - const policyList = isSinglePolicy ? policies[0].id : policies.map(({ id }) => id).join(','); - const existClause = isSinglePolicy - ? `Agent Policy '${policyList}' already exists` - : `Agent Policies '${policyList}' already exist`; - - throw new AgentPolicyNameExistsError( - `${existClause} in '${namespace}' namespace with name '${name}'` - ); + const idsWithName = results.total && results.saved_objects.map(({ id }) => id); + if (Array.isArray(idsWithName)) { + const isEditingSelf = givenPolicy.id && idsWithName.includes(givenPolicy.id); + if (!givenPolicy.id || !isEditingSelf) { + const isSinglePolicy = idsWithName.length === 1; + const existClause = isSinglePolicy + ? `Agent Policy '${idsWithName[0]}' already exists` + : `Agent Policies '${idsWithName.join(',')}' already exist`; + + throw new AgentPolicyNameExistsError( + `${existClause} in '${givenPolicy.namespace}' namespace with name '${givenPolicy.name}'` + ); + } } } @@ -237,6 +238,7 @@ class AgentPolicyService { ): Promise { if (agentPolicy.name && agentPolicy.namespace) { await this.requireUniqueName(soClient, { + id, name: agentPolicy.name, namespace: agentPolicy.namespace, });