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

[Ingest Manager] Ingest setup upgrade #78081

Merged
merged 30 commits into from
Sep 28, 2020
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
30 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
11b677d
Merge pull request #7 from jfsiii/ingest-setup-upgrade
jonathan-buttner Sep 28, 2020
4afbb56
Merge branch 'master' of github.com:elastic/kibana into ingest-setup-…
jonathan-buttner Sep 28, 2020
3f8295d
Adding additional test
jonathan-buttner Sep 28, 2020
7f02b5f
Fixing type error
jonathan-buttner Sep 28, 2020
0427b9d
Merge branch 'master' into ingest-setup-upgrade
elasticmachine Sep 28, 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
4 changes: 2 additions & 2 deletions x-pack/plugins/ingest_manager/common/types/rest_spec/epm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export interface InstallPackageResponse {
response: AssetReference[];
}

export interface IBulkInstallPackageError {
export interface IBulkInstallPackageHTTPError {
name: string;
statusCode: number;
error: string | Error;
Expand All @@ -86,7 +86,7 @@ export interface BulkInstallPackageInfo {
}

export interface BulkInstallPackagesResponse {
response: Array<BulkInstallPackageInfo | IBulkInstallPackageError>;
response: Array<BulkInstallPackageInfo | IBulkInstallPackageHTTPError>;
}

export interface BulkInstallPackagesRequest {
Expand Down
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,
IBulkInstallPackageHTTPError,
} 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 | IBulkInstallPackageHTTPError => {
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,144 @@
/*
* 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, SavedObjectsClientContract } from 'src/core/server';

jest.mock('./install');
jest.mock('./bulk_install_packages');
jest.mock('./get');

import { bulkInstallPackages, isBulkInstallError } from './bulk_install_packages';
const { ensureInstalledDefaultPackages } = jest.requireActual('./install');
const { isBulkInstallError: actualIsBulkInstallError } = jest.requireActual(
'./bulk_install_packages'
);
import { getInstallation } from './get';
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 mockedIsBulkInstallError = isBulkInstallError as jest.MockedFunction<
typeof isBulkInstallError
>;
const mockedGetInstallation = getInstallation as jest.MockedFunction<typeof getInstallation>;

// I was unable to get the actual implementation set in the `jest.mock()` call at the top to work
// so this will set the `isBulkInstallError` function back to the actual implementation
mockedIsBulkInstallError.mockImplementation(actualIsBulkInstallError);

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 package',
version: '1.0.0',
install_status: 'installed',
install_version: '1.0.0',
install_started_at: new Date().toISOString(),
},
};

describe('ensureInstalledDefaultPackages', () => {
let soClient: jest.Mocked<SavedObjectsClientContract>;
beforeEach(async () => {
soClient = savedObjectsClientMock.create();
appContextService.start(createAppContextStartContractMock());
});
afterEach(async () => {
appContextService.stop();
});
it('should return an array of Installation objects when successful', async () => {
mockedGetInstallation.mockImplementation(async () => {
return mockInstallation.attributes;
});
mockedBulkInstallPackages.mockImplementationOnce(async function () {
return [
{
name: mockInstallation.attributes.name,
assets: [],
newVersion: '',
oldVersion: '',
statusCode: 200,
},
];
});
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 {}
mockedGetInstallation.mockImplementation(async () => {
return mockInstallation.attributes;
});
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 installPromise = ensureInstalledDefaultPackages(soClient, jest.fn());
expect.assertions(2);
expect(installPromise).rejects.toThrow(SomeCustomError);
expect(installPromise).rejects.toThrow('abc 123');
});
it('should throw an error when get installation returns undefined', async () => {
mockedGetInstallation.mockImplementation(async () => {
return undefined;
});
mockedBulkInstallPackages.mockImplementationOnce(async function () {
return [
{
name: 'undefined package',
assets: [],
newVersion: '',
oldVersion: '',
statusCode: 200,
},
];
});
const installPromise = ensureInstalledDefaultPackages(soClient, jest.fn());
expect.assertions(1);
expect(installPromise).rejects.toThrow();
});
});
Loading