Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fleet] Optimize package installation performance, phase 1 #130906

Merged
merged 7 commits into from
May 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export async function saveArchiveEntries(opts: {
})
);

const results = await savedObjectsClient.bulkCreate<PackageAsset>(bulkBody);
const results = await savedObjectsClient.bulkCreate<PackageAsset>(bulkBody, { refresh: false });
return results;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ import type {
InstallablePackage,
RegistryDataStream,
} from '../../../../../common/types/models';
import { getInstallation } from '../../packages';
import { saveInstalledEsRefs } from '../../packages/install';
import { updateEsAssetReferences } from '../../packages/install';
import { getAsset } from '../transform/common';

import { getESAssetMetadata } from '../meta';
import { retryTransientEsErrors } from '../retry';

import { deleteIlmRefs, deleteIlms } from './remove';
import { deleteIlms } from './remove';

interface IlmInstallation {
installationName: string;
Expand All @@ -37,24 +36,39 @@ export const installIlmForDataStream = async (
paths: string[],
esClient: ElasticsearchClient,
savedObjectsClient: SavedObjectsClientContract,
logger: Logger
logger: Logger,
esReferences: EsAssetReference[]
) => {
const installation = await getInstallation({ savedObjectsClient, pkgName: registryPackage.name });
let previousInstalledIlmEsAssets: EsAssetReference[] = [];
if (installation) {
previousInstalledIlmEsAssets = installation.installed_es.filter(
({ type, id }) => type === ElasticsearchAssetType.dataStreamIlmPolicy
);
}
const previousInstalledIlmEsAssets = esReferences.filter(
({ type }) => type === ElasticsearchAssetType.dataStreamIlmPolicy
);

// delete all previous ilm
await deleteIlms(
esClient,
previousInstalledIlmEsAssets.map((asset) => asset.id)
);

if (previousInstalledIlmEsAssets.length > 0) {
// remove the saved object reference
esReferences = await updateEsAssetReferences(
savedObjectsClient,
registryPackage.name,
esReferences,
{
assetsToRemove: previousInstalledIlmEsAssets,
}
);
}

// install the latest dataset
const dataStreams = registryPackage.data_streams;
if (!dataStreams?.length) return [];
if (!dataStreams?.length)
return {
installedIlms: [],
esReferences,
};

const dataStreamIlmPaths = paths.filter((path) => isDataStreamIlm(path));
let installedIlms: EsAssetReference[] = [];
if (dataStreamIlmPaths.length > 0) {
Expand All @@ -77,12 +91,17 @@ export const installIlmForDataStream = async (
return acc;
}, []);

await saveInstalledEsRefs(savedObjectsClient, registryPackage.name, ilmRefs);
esReferences = await updateEsAssetReferences(
savedObjectsClient,
registryPackage.name,
esReferences,
{ assetsToAdd: ilmRefs }
);

const ilmInstallations: IlmInstallation[] = ilmPathDatasets.map(
(ilmPathDataset: IlmPathDataset) => {
const content = JSON.parse(getAsset(ilmPathDataset.path).toString('utf-8'));
content.policy._meta = getESAssetMetadata({ packageName: installation?.name });
content.policy._meta = getESAssetMetadata({ packageName: registryPackage.name });

return {
installationName: getIlmNameForInstallation(ilmPathDataset),
Expand All @@ -98,22 +117,7 @@ export const installIlmForDataStream = async (
installedIlms = await Promise.all(installationPromises).then((results) => results.flat());
}

if (previousInstalledIlmEsAssets.length > 0) {
const currentInstallation = await getInstallation({
savedObjectsClient,
pkgName: registryPackage.name,
});

// remove the saved object reference
await deleteIlmRefs(
savedObjectsClient,
currentInstallation?.installed_es || [],
registryPackage.name,
previousInstalledIlmEsAssets.map((asset) => asset.id),
installedIlms.map((installed) => installed.id)
);
}
return installedIlms;
return { installedIlms, esReferences };
};

async function handleIlmInstall({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
* 2.0.
*/

import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server';

import { ElasticsearchAssetType } from '../../../../types';
import type { EsAssetReference } from '../../../../types';
import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../../../common/constants';
import type { ElasticsearchClient } from '@kbn/core/server';

export const deleteIlms = async (esClient: ElasticsearchClient, ilmPolicyIds: string[]) => {
await Promise.all(
Expand All @@ -26,24 +22,3 @@ export const deleteIlms = async (esClient: ElasticsearchClient, ilmPolicyIds: st
})
);
};

export const deleteIlmRefs = async (
savedObjectsClient: SavedObjectsClientContract,
installedEsAssets: EsAssetReference[],
pkgName: string,
installedEsIdToRemove: string[],
currentInstalledEsIlmIds: string[]
) => {
const seen = new Set<string>();
const filteredAssets = installedEsAssets.filter(({ type, id }) => {
if (type !== ElasticsearchAssetType.dataStreamIlmPolicy) return true;
const add =
(currentInstalledEsIlmIds.includes(id) || !installedEsIdToRemove.includes(id)) &&
!seen.has(id);
seen.add(id);
return add;
});
return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, {
installed_es: filteredAssets,
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,54 @@
* 2.0.
*/

import type { ElasticsearchClient, Logger } from '@kbn/core/server';
import type { ElasticsearchClient, Logger, SavedObjectsClientContract } from '@kbn/core/server';

import type { InstallablePackage } from '../../../../types';
import type { EsAssetReference, InstallablePackage } from '../../../../types';

import { ElasticsearchAssetType } from '../../../../types';
import { getAsset, getPathParts } from '../../archive';
import { updateEsAssetReferences } from '../../packages/install';
import { getESAssetMetadata } from '../meta';
import { retryTransientEsErrors } from '../retry';

export async function installILMPolicy(
packageInfo: InstallablePackage,
paths: string[],
esClient: ElasticsearchClient,
logger: Logger
) {
savedObjectsClient: SavedObjectsClientContract,
logger: Logger,
esReferences: EsAssetReference[]
): Promise<EsAssetReference[]> {
const ilmPaths = paths.filter((path) => isILMPolicy(path));
if (!ilmPaths.length) return;
await Promise.all(
ilmPaths.map(async (path) => {
const body = JSON.parse(getAsset(path).toString('utf-8'));
if (!ilmPaths.length) return esReferences;

const ilmPolicies = ilmPaths.map((path) => {
const body = JSON.parse(getAsset(path).toString('utf-8'));

body.policy._meta = getESAssetMetadata({ packageName: packageInfo.name });

const { file } = getPathParts(path);
const name = file.substr(0, file.lastIndexOf('.'));

body.policy._meta = getESAssetMetadata({ packageName: packageInfo.name });
return { name, body };
});

const { file } = getPathParts(path);
const name = file.substr(0, file.lastIndexOf('.'));
esReferences = await updateEsAssetReferences(savedObjectsClient, packageInfo.name, esReferences, {
assetsToAdd: ilmPolicies.map((policy) => ({
type: ElasticsearchAssetType.ilmPolicy,
id: policy.name,
})),
});
Comment on lines +40 to +45
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We weren't previously keeping track of these references so these weren't getting deleted on uninstall. Fixed in this PR.


await Promise.all(
ilmPolicies.map(async (policy) => {
try {
await retryTransientEsErrors(
() =>
esClient.transport.request({
method: 'PUT',
path: '/_ilm/policy/' + name,
body,
path: '/_ilm/policy/' + policy.name,
body: policy.body,
}),
{ logger }
);
Expand All @@ -45,6 +61,8 @@ export async function installILMPolicy(
}
})
);

return esReferences;
}

const isILMPolicy = (path: string) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import { ElasticsearchAssetType } from '../../../../types';
import type { EsAssetReference, RegistryDataStream, InstallablePackage } from '../../../../types';
import { getAsset, getPathParts } from '../../archive';
import type { ArchiveEntry } from '../../archive';
import { saveInstalledEsRefs } from '../../packages/install';
import { getInstallationObject } from '../../packages';
import { updateEsAssetReferences } from '../../packages/install';
import {
FLEET_FINAL_PIPELINE_CONTENT,
FLEET_FINAL_PIPELINE_ID,
Expand All @@ -24,8 +23,6 @@ import { appendMetadataToIngestPipeline } from '../meta';

import { retryTransientEsErrors } from '../retry';

import { deletePipelineRefs } from './remove';

interface RewriteSubstitution {
source: string;
target: string;
Expand All @@ -44,7 +41,8 @@ export const installPipelines = async (
paths: string[],
esClient: ElasticsearchClient,
savedObjectsClient: SavedObjectsClientContract,
logger: Logger
logger: Logger,
esReferences: EsAssetReference[]
) => {
// unlike other ES assets, pipeline names are versioned so after a template is updated
// it can be created pointing to the new template, without removing the old one and effecting data
Expand All @@ -67,7 +65,7 @@ export const installPipelines = async (
const nameForInstallation = getPipelineNameForInstallation({
pipelineName: name,
dataStream,
packageVersion: installablePackage.version,
packageVersion: pkgVersion,
});
return { id: nameForInstallation, type: ElasticsearchAssetType.ingestPipeline };
});
Expand All @@ -80,27 +78,17 @@ export const installPipelines = async (
const { name } = getNameAndExtension(path);
const nameForInstallation = getPipelineNameForInstallation({
pipelineName: name,
packageVersion: installablePackage.version,
packageVersion: pkgVersion,
});
return { id: nameForInstallation, type: ElasticsearchAssetType.ingestPipeline };
});

pipelineRefs = [...pipelineRefs, ...topLevelPipelineRefs];

// check that we don't duplicate the pipeline refs if the user is reinstalling
const installedPkg = await getInstallationObject({
savedObjectsClient,
pkgName,
esReferences = await updateEsAssetReferences(savedObjectsClient, pkgName, esReferences, {
assetsToAdd: pipelineRefs,
});
if (!installedPkg) throw new Error("integration wasn't found while installing pipelines");
// remove the current pipeline refs, if any exist, associated with this version before saving new ones so no duplicates occur
await deletePipelineRefs(
savedObjectsClient,
installedPkg.attributes.installed_es,
pkgName,
pkgVersion
);
await saveInstalledEsRefs(savedObjectsClient, installablePackage.name, pipelineRefs);

const pipelines = dataStreams
? dataStreams.reduce<Array<Promise<EsAssetReference[]>>>((acc, dataStream) => {
if (dataStream.ingest_pipeline) {
Expand Down Expand Up @@ -130,7 +118,8 @@ export const installPipelines = async (
);
}

return await Promise.all(pipelines).then((results) => results.flat());
await Promise.all(pipelines);
return esReferences;
};

export function rewriteIngestPipeline(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,54 +10,38 @@ import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/
import { appContextService } from '../../..';
import { ElasticsearchAssetType } from '../../../../types';
import { IngestManagerError } from '../../../../errors';
import { getInstallation } from '../../packages/get';
import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../../../common';
import type { EsAssetReference } from '../../../../../common';
import { updateEsAssetReferences } from '../../packages/install';

export const deletePreviousPipelines = async (
esClient: ElasticsearchClient,
savedObjectsClient: SavedObjectsClientContract,
pkgName: string,
previousPkgVersion: string
previousPkgVersion: string,
esReferences: EsAssetReference[]
) => {
const logger = appContextService.getLogger();
const installation = await getInstallation({ savedObjectsClient, pkgName });
if (!installation) return;
const installedEsAssets = installation.installed_es;
const installedPipelines = installedEsAssets.filter(
const installedPipelines = esReferences.filter(
({ type, id }) =>
type === ElasticsearchAssetType.ingestPipeline && id.includes(previousPkgVersion)
);
const deletePipelinePromises = installedPipelines.map(({ type, id }) => {
return deletePipeline(esClient, id);
});
try {
await Promise.all(deletePipelinePromises);
} catch (e) {
logger.error(e);
}
try {
await deletePipelineRefs(savedObjectsClient, installedEsAssets, pkgName, previousPkgVersion);
await Promise.all(
installedPipelines.map(({ type, id }) => {
return deletePipeline(esClient, id);
})
);
} catch (e) {
logger.error(e);
}
};

export const deletePipelineRefs = async (
savedObjectsClient: SavedObjectsClientContract,
installedEsAssets: EsAssetReference[],
pkgName: string,
pkgVersion: string
) => {
const filteredAssets = installedEsAssets.filter(({ type, id }) => {
if (type !== ElasticsearchAssetType.ingestPipeline) return true;
if (!id.includes(pkgVersion)) return true;
return false;
});
return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, {
installed_es: filteredAssets,
return await updateEsAssetReferences(savedObjectsClient, pkgName, esReferences, {
assetsToRemove: esReferences.filter(({ type, id }) => {
return type === ElasticsearchAssetType.ingestPipeline && id.includes(previousPkgVersion);
}),
});
};

export async function deletePipeline(esClient: ElasticsearchClient, id: string): Promise<void> {
// '*' shouldn't ever appear here, but it still would delete all ingest pipelines
if (id && id !== '*') {
Expand Down
Loading