Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
76df74d
Adding bulk upgrade api
jonathan-buttner Sep 17, 2020
6dea606
Addressing comments
jonathan-buttner Sep 18, 2020
268c526
Removing todo
jonathan-buttner Sep 18, 2020
04a39bd
Resolving conflicts
jonathan-buttner Sep 18, 2020
f111406
Changing body field
jonathan-buttner Sep 18, 2020
2846b76
Adding helper for getting the bulk install route
jonathan-buttner Sep 18, 2020
20357fd
Adding request spec
jonathan-buttner Sep 18, 2020
9b29802
Pulling in Johns changes
jonathan-buttner Sep 21, 2020
3d2a686
Merge branch 'master' of github.com:elastic/kibana into ingest-bulk-u…
jonathan-buttner Sep 21, 2020
7cb80e9
Removing test for same package upgraded multiple times
jonathan-buttner Sep 21, 2020
6e333ab
Adding upgrade to setup route
jonathan-buttner Sep 21, 2020
99f6aee
Fixing merge conflicts
jonathan-buttner Sep 22, 2020
8a41396
Adding setup integration test
jonathan-buttner Sep 22, 2020
219cfa9
Clean up error handling
jonathan-buttner Sep 24, 2020
ba00737
Beginning to add tests
jonathan-buttner Sep 24, 2020
267931b
Merge branch 'master' of github.com:elastic/kibana into ingest-setup-…
jonathan-buttner Sep 24, 2020
037ba98
Failing jest mock tests
jonathan-buttner Sep 24, 2020
a76006f
Break up tests & modules for easier testing.
Sep 25, 2020
5c259d1
Add test confirming update error result will throw
Sep 25, 2020
06cfadc
Keep orig error. Add status code in http handler
Sep 26, 2020
a3c77ce
Leave error as-is
Sep 27, 2020
25c3cd0
Removing accidental code changes. File rename.
Sep 27, 2020
202b7a2
Missed a function when moving to a new file
Sep 27, 2020
ee4c774
Add missing type imports
Sep 27, 2020
c906aea
Lift .map lambda into named outer function
Sep 27, 2020
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
32 changes: 25 additions & 7 deletions x-pack/plugins/ingest_manager/server/routes/epm/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import {
GetCategoriesResponse,
GetPackagesResponse,
GetLimitedPackagesResponse,
BulkInstallPackageInfo,
BulkInstallPackagesResponse,
IBulkInstallPackageError,
} from '../../../common';
import {
GetCategoriesRequestSchema,
Expand All @@ -26,21 +28,21 @@ import {
BulkUpgradePackagesFromRegistryRequestSchema,
} from '../../types';
import {
BulkInstallResponse,
bulkInstallPackages,
getCategories,
getPackages,
getFile,
getPackageInfo,
handleInstallPackageFailure,
installPackage,
isBulkInstallError,
removeInstallation,
getLimitedPackages,
getInstallationObject,
} from '../../services/epm/packages';
import { defaultIngestErrorHandler } from '../../errors';
import { defaultIngestErrorHandler, ingestErrorToResponseOptions } from '../../errors';
import { splitPkgKey } from '../../services/epm/registry';
import {
handleInstallPackageFailure,
bulkInstallPackages,
} from '../../services/epm/packages/install';

export const getCategoriesHandler: RequestHandler<
undefined,
Expand Down Expand Up @@ -171,20 +173,36 @@ export const installPackageFromRegistryHandler: RequestHandler<
}
};

const bulkInstallServiceResponseToHttpEntry = (
result: BulkInstallResponse
): BulkInstallPackageInfo | IBulkInstallPackageError => {
if (isBulkInstallError(result)) {
const { statusCode, body } = ingestErrorToResponseOptions(result.error);
return {
name: result.name,
statusCode,
error: body.message,
};
} else {
return result;
}
};

export const bulkInstallPackagesFromRegistryHandler: RequestHandler<
undefined,
undefined,
TypeOf<typeof BulkUpgradePackagesFromRegistryRequestSchema.body>
> = async (context, request, response) => {
const savedObjectsClient = context.core.savedObjects.client;
const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser;
const res = await bulkInstallPackages({
const bulkInstalledResponses = await bulkInstallPackages({
savedObjectsClient,
callCluster,
packagesToUpgrade: request.body.packages,
});
const payload = bulkInstalledResponses.map(bulkInstallServiceResponseToHttpEntry);
const body: BulkInstallPackagesResponse = {
response: res,
response: payload,
};
return response.ok({ body });
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { SavedObjectsClientContract } from 'src/core/server';
import { CallESAsCurrentUser } from '../../../types';
import * as Registry from '../registry';
import { getInstallationObject } from './index';
import { BulkInstallResponse, IBulkInstallPackageError, upgradePackage } from './install';

interface BulkInstallPackagesParams {
savedObjectsClient: SavedObjectsClientContract;
packagesToUpgrade: string[];
callCluster: CallESAsCurrentUser;
}

export async function bulkInstallPackages({
savedObjectsClient,
packagesToUpgrade,
callCluster,
}: BulkInstallPackagesParams): Promise<BulkInstallResponse[]> {
const installedAndLatestPromises = packagesToUpgrade.map((pkgToUpgrade) =>
Promise.all([
getInstallationObject({ savedObjectsClient, pkgName: pkgToUpgrade }),
Registry.fetchFindLatestPackage(pkgToUpgrade),
])
);
const installedAndLatestResults = await Promise.allSettled(installedAndLatestPromises);
const installResponsePromises = installedAndLatestResults.map(async (result, index) => {
const pkgToUpgrade = packagesToUpgrade[index];
if (result.status === 'fulfilled') {
const [installedPkg, latestPkg] = result.value;
return upgradePackage({
savedObjectsClient,
callCluster,
installedPkg,
latestPkg,
pkgToUpgrade,
});
} else {
return { name: pkgToUpgrade, error: result.reason };
}
});
const installResults = await Promise.allSettled(installResponsePromises);
const installResponses = installResults.map((result, index) => {
const pkgToUpgrade = packagesToUpgrade[index];
if (result.status === 'fulfilled') {
return result.value;
} else {
return { name: pkgToUpgrade, error: result.reason };
}
});

return installResponses;
}

export function isBulkInstallError(test: any): test is IBulkInstallPackageError {
return 'error' in test && test.error instanceof Error;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { ElasticsearchAssetType, Installation, KibanaAssetType } from '../../../types';
import { SavedObject } from 'src/core/server';

jest.mock('./install');
jest.mock('./bulk_install_packages');
jest.mock('./get', () => ({
...(jest.requireActual('./get') as {}),
getInstallation: jest.fn(async () => {
return mockInstallation.attributes;
}),
}));
import { bulkInstallPackages } from './bulk_install_packages';
const { ensureInstalledDefaultPackages } = jest.requireActual('./install');
import { savedObjectsClientMock } from 'src/core/server/mocks';
import { appContextService } from '../../app_context';
import { createAppContextStartContractMock } from '../../../mocks';

// if we add this assertion, TS will type check the return value
// and the editor will also know about .mockImplementation, .mock.calls, etc
const mockedBulkInstallPackages = bulkInstallPackages as jest.MockedFunction<
typeof bulkInstallPackages
>;

const mockInstallation: SavedObject<Installation> = {
id: 'test-pkg',
references: [],
type: 'epm-packages',
attributes: {
id: 'test-pkg',
installed_kibana: [{ type: KibanaAssetType.dashboard, id: 'dashboard-1' }],
installed_es: [{ type: ElasticsearchAssetType.ingestPipeline, id: 'pipeline' }],
es_index_patterns: { pattern: 'pattern-name' },
name: 'test packagek',
version: '1.0.0',
install_status: 'installed',
install_version: '1.0.0',
install_started_at: new Date().toISOString(),
},
};

describe('ensureInstalledDefaultPackages', () => {
beforeEach(async () => {
appContextService.start(createAppContextStartContractMock());
});
afterEach(async () => {
appContextService.stop();
});
it('should return an array of Installation objects when successful', async () => {
mockedBulkInstallPackages.mockImplementationOnce(async function () {
return [
{
name: 'blah',
assets: [],
newVersion: '',
oldVersion: '',
statusCode: 200,
},
];
});
const soClient = savedObjectsClientMock.create();
const resp = await ensureInstalledDefaultPackages(soClient, jest.fn());
expect(resp).toEqual([mockInstallation.attributes]);
});
it('should throw the first Error it finds', async () => {
class SomeCustomError extends Error {}
mockedBulkInstallPackages.mockImplementationOnce(async function () {
return [
{
name: 'success one',
assets: [],
newVersion: '',
oldVersion: '',
statusCode: 200,
},
{
name: 'success two',
assets: [],
newVersion: '',
oldVersion: '',
statusCode: 200,
},
{
name: 'failure one',
error: new SomeCustomError('abc 123'),
},
{
name: 'success three',
assets: [],
newVersion: '',
oldVersion: '',
statusCode: 200,
},
{
name: 'failure two',
error: new Error('zzz'),
},
];
});
const soClient = savedObjectsClientMock.create();
const installPromise = ensureInstalledDefaultPackages(soClient, jest.fn());
expect(installPromise).rejects.toThrow(SomeCustomError);
expect(installPromise).rejects.toThrow('abc 123');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { SavedObject } from 'src/core/server';
import { ElasticsearchAssetType, Installation, KibanaAssetType } from '../../../types';
import { getInstallType } from './install';

const mockInstallation: SavedObject<Installation> = {
id: 'test-pkg',
references: [],
type: 'epm-packages',
attributes: {
id: 'test-pkg',
installed_kibana: [{ type: KibanaAssetType.dashboard, id: 'dashboard-1' }],
installed_es: [{ type: ElasticsearchAssetType.ingestPipeline, id: 'pipeline' }],
es_index_patterns: { pattern: 'pattern-name' },
name: 'test packagek',
version: '1.0.0',
install_status: 'installed',
install_version: '1.0.0',
install_started_at: new Date().toISOString(),
},
};
const mockInstallationUpdateFail: SavedObject<Installation> = {
id: 'test-pkg',
references: [],
type: 'epm-packages',
attributes: {
id: 'test-pkg',
installed_kibana: [{ type: KibanaAssetType.dashboard, id: 'dashboard-1' }],
installed_es: [{ type: ElasticsearchAssetType.ingestPipeline, id: 'pipeline' }],
es_index_patterns: { pattern: 'pattern-name' },
name: 'test packagek',
version: '1.0.0',
install_status: 'installing',
install_version: '1.0.1',
install_started_at: new Date().toISOString(),
},
};

describe('getInstallType', () => {
it('should return correct type when installing and no other version is currently installed', () => {
const installTypeInstall = getInstallType({ pkgVersion: '1.0.0', installedPkg: undefined });
expect(installTypeInstall).toBe('install');

// @ts-expect-error can only be 'install' if no installedPkg given
expect(installTypeInstall === 'update').toBe(false);
// @ts-expect-error can only be 'install' if no installedPkg given
expect(installTypeInstall === 'reinstall').toBe(false);
// @ts-expect-error can only be 'install' if no installedPkg given
expect(installTypeInstall === 'reupdate').toBe(false);
// @ts-expect-error can only be 'install' if no installedPkg given
expect(installTypeInstall === 'rollback').toBe(false);
});

it('should return correct type when installing the same version', () => {
const installTypeReinstall = getInstallType({
pkgVersion: '1.0.0',
installedPkg: mockInstallation,
});
expect(installTypeReinstall).toBe('reinstall');

// @ts-expect-error cannot be 'install' if given installedPkg
expect(installTypeReinstall === 'install').toBe(false);
});

it('should return correct type when moving from one version to another', () => {
const installTypeUpdate = getInstallType({
pkgVersion: '1.0.1',
installedPkg: mockInstallation,
});
expect(installTypeUpdate).toBe('update');

// @ts-expect-error cannot be 'install' if given installedPkg
expect(installTypeUpdate === 'install').toBe(false);
});

it('should return correct type when update fails and trys again', () => {
const installTypeReupdate = getInstallType({
pkgVersion: '1.0.1',
installedPkg: mockInstallationUpdateFail,
});
expect(installTypeReupdate).toBe('reupdate');

// @ts-expect-error cannot be 'install' if given installedPkg
expect(installTypeReupdate === 'install').toBe(false);
});

it('should return correct type when attempting to rollback from a failed update', () => {
const installTypeRollback = getInstallType({
pkgVersion: '1.0.0',
installedPkg: mockInstallationUpdateFail,
});
expect(installTypeRollback).toBe('rollback');

// @ts-expect-error cannot be 'install' if given installedPkg
expect(installTypeRollback === 'install').toBe(false);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
InstallationStatus,
KibanaAssetType,
} from '../../../types';

export { bulkInstallPackages, isBulkInstallError } from './bulk_install_packages';
export {
getCategories,
getFile,
Expand All @@ -23,7 +25,13 @@ export {
SearchParams,
} from './get';

export { installPackage, ensureInstalledPackage } from './install';
export {
BulkInstallResponse,
handleInstallPackageFailure,
installPackage,
IBulkInstallPackageError,
ensureInstalledPackage,
} from './install';
export { removeInstallation } from './remove';

type RequiredPackage = 'system' | 'endpoint';
Expand Down
Loading