From 8eab9fceface3948be34dd2839537eeb5ff1b1f1 Mon Sep 17 00:00:00 2001 From: criamico Date: Tue, 19 Oct 2021 15:51:32 +0200 Subject: [PATCH] Simplify logic --- .../fleet/server/services/package_policy.ts | 34 +++---------------- 1 file changed, 5 insertions(+), 29 deletions(-) diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index e01a4d2a5c851d0..db86f073dc0e388 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -40,7 +40,7 @@ import type { UpgradePackagePolicyDryRunResponseItem, RegistryDataStream, } from '../../common'; -import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../constants'; +import { PACKAGE_POLICY_SAVED_OBJECT_TYPE, AGENT_POLICY_SAVED_OBJECT_TYPE } from '../constants'; import { HostedAgentPolicyRestrictionRelatedError, IngestManagerError, @@ -95,37 +95,13 @@ class PackagePolicyService { skipEnsureInstalled?: boolean; } ): Promise { - const packagePolicyNameExists = (agentPoliciesItems: AgentPolicy[], packageName: string) => { - const filteredPolicies = agentPoliciesItems.filter((agentPolicy) => { - const nameIndex = (agentPolicy.package_policies as NewPackagePolicy[]).findIndex( - ({ name }) => name === packageName - ); - return nameIndex !== -1; - }); - return filteredPolicies.length > 0; - }; - - const findParentAgentPolicy = (agentPoliciesItems: AgentPolicy[], policyId: string) => { - return agentPoliciesItems.find((policy) => policy.id === policyId); - }; - - // Get the list of all agent policies - const agentPolicies = await agentPolicyService.list(soClient, { - perPage: 1000, // avoiding pagination - withPackagePolicies: true, + const existingPoliciesWithName = await this.list(soClient, { + perPage: 1, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: "${packagePolicy.name}"`, }); - const parentAgentPolicy = findParentAgentPolicy(agentPolicies.items, packagePolicy.policy_id); - if (!parentAgentPolicy) { - throw new Error('Agent policy not found'); - } - if (parentAgentPolicy.is_managed && !options?.force) { - throw new HostedAgentPolicyRestrictionRelatedError( - `Cannot add integrations to hosted agent policy ${parentAgentPolicy.id}` - ); - } // Check that the name does not exist already across all the agent policies - if (packagePolicyNameExists(agentPolicies.items, packagePolicy.name)) { + if (existingPoliciesWithName.items.length > 0) { throw new IngestManagerError('There is already a package with the same name'); } let elasticsearch: PackagePolicy['elasticsearch'];