Skip to content

Commit

Permalink
Simplify logic
Browse files Browse the repository at this point in the history
  • Loading branch information
criamico committed Oct 19, 2021
1 parent 07768cf commit 8eab9fc
Showing 1 changed file with 5 additions and 29 deletions.
34 changes: 5 additions & 29 deletions x-pack/plugins/fleet/server/services/package_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -95,37 +95,13 @@ class PackagePolicyService {
skipEnsureInstalled?: boolean;
}
): Promise<PackagePolicy> {
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'];
Expand Down

0 comments on commit 8eab9fc

Please sign in to comment.