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

Revert back ESO migration for alerting, added try/catch logic to avoid failing Kibana on start #76220

Merged
merged 9 commits into from
Sep 4, 2020
10 changes: 6 additions & 4 deletions x-pack/plugins/alerts/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,16 @@ export class AlertingPlugin {
);
}

setupSavedObjects(core.savedObjects, plugins.encryptedSavedObjects);

this.eventLogService = plugins.eventLog;
plugins.eventLog.registerProviderActions(EVENT_LOG_PROVIDER, Object.values(EVENT_LOG_ACTIONS));
this.eventLogger = plugins.eventLog.getLogger({
event: { provider: EVENT_LOG_PROVIDER },
});

setupSavedObjects(core.savedObjects, plugins.encryptedSavedObjects, this.logger);

this.eventLogService = plugins.eventLog;
plugins.eventLog.registerProviderActions(EVENT_LOG_PROVIDER, Object.values(EVENT_LOG_ACTIONS));


const alertTypeRegistry = new AlertTypeRegistry({
taskManager: plugins.taskManager,
taskRunnerFactory: this.taskRunnerFactory,
Expand Down
8 changes: 7 additions & 1 deletion x-pack/plugins/alerts/server/saved_objects/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,22 @@

import { SavedObjectsServiceSetup } from 'kibana/server';
import mappings from './mappings.json';
import { getMigrations } from './migrations';
import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server';
import {
Logger
} from '../../../../../src/core/server';

export function setupSavedObjects(
savedObjects: SavedObjectsServiceSetup,
encryptedSavedObjects: EncryptedSavedObjectsPluginSetup
encryptedSavedObjects: EncryptedSavedObjectsPluginSetup,
logger: Logger
) {
savedObjects.registerType({
name: 'alert',
hidden: true,
namespaceType: 'single',
migrations: getMigrations(encryptedSavedObjects, logger),
mappings: mappings.alert,
});

Expand Down
121 changes: 121 additions & 0 deletions x-pack/plugins/alerts/server/saved_objects/migrations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* 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 uuid from 'uuid';
import { getMigrations } from './migrations';
import { RawAlert } from '../types';
import { SavedObjectUnsanitizedDoc } from 'kibana/server';
import { encryptedSavedObjectsMock } from '../../../encrypted_saved_objects/server/mocks';
import { migrationMocks } from 'src/core/server/mocks';

const { log } = migrationMocks.createContext();
const encryptedSavedObjectsSetup = encryptedSavedObjectsMock.createSetup();

describe('7.9.0', () => {
beforeEach(() => {
jest.resetAllMocks();
encryptedSavedObjectsSetup.createMigration.mockImplementation(
(shouldMigrateWhenPredicate, migration) => migration
);
});

test('changes nothing on alerts by other plugins', () => {
const migration790 = getMigrations(encryptedSavedObjectsSetup)['7.9.0'];
const alert = getMockData({});
expect(migration790(alert, { log })).toMatchObject(alert);

expect(encryptedSavedObjectsSetup.createMigration).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function)
);
});

test('migrates the consumer for alerting', () => {
const migration790 = getMigrations(encryptedSavedObjectsSetup)['7.9.0'];
const alert = getMockData({
consumer: 'alerting',
});
expect(migration790(alert, { log })).toMatchObject({
...alert,
attributes: {
...alert.attributes,
consumer: 'alerts',
},
});
});
});

describe('7.10.0', () => {
beforeEach(() => {
jest.resetAllMocks();
encryptedSavedObjectsSetup.createMigration.mockImplementation(
(shouldMigrateWhenPredicate, migration) => migration
);
});

test('changes nothing on alerts by other plugins', () => {
const migration710 = getMigrations(encryptedSavedObjectsSetup)['7.10.0'];
const alert = getMockData({});
expect(migration710(alert, { log })).toMatchObject(alert);

expect(encryptedSavedObjectsSetup.createMigration).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function)
);
});

test('migrates the consumer for metrics', () => {
const migration710 = getMigrations(encryptedSavedObjectsSetup)['7.10.0'];
const alert = getMockData({
consumer: 'metrics',
});
expect(migration710(alert, { log })).toMatchObject({
...alert,
attributes: {
...alert.attributes,
consumer: 'infrastructure',
},
});
});
});

function getMockData(
overwrites: Record<string, unknown> = {}
): SavedObjectUnsanitizedDoc<RawAlert> {
return {
attributes: {
enabled: true,
name: 'abc',
tags: ['foo'],
alertTypeId: '123',
consumer: 'bar',
apiKey: '',
apiKeyOwner: '',
schedule: { interval: '10s' },
throttle: null,
params: {
bar: true,
},
muteAll: false,
mutedInstanceIds: [],
createdBy: new Date().toISOString(),
updatedBy: new Date().toISOString(),
createdAt: new Date().toISOString(),
actions: [
{
group: 'default',
actionRef: '1',
actionTypeId: '1',
params: {
foo: true,
},
},
],
...overwrites,
},
id: uuid.v4(),
type: 'alert',
};
}
60 changes: 60 additions & 0 deletions x-pack/plugins/alerts/server/saved_objects/migrations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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 {
SavedObjectMigrationMap,
SavedObjectUnsanitizedDoc,
SavedObjectMigrationFn,
Logger
} from '../../../../../src/core/server';
import { RawAlert } from '../types';
import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server';

export function getMigrations(
encryptedSavedObjects: EncryptedSavedObjectsPluginSetup,
eventLogger: Logger
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
): SavedObjectMigrationMap {
const migrations: SavedObjectMigrationMap = {};

const alertsMigration = changeAlertingConsumer(encryptedSavedObjects, 'alerting', 'alerts', eventLogger);
if (alertsMigration) {
migrations['7.9.0'] = alertsMigration;
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
}

const infrastructureMigration = changeAlertingConsumer(encryptedSavedObjects, 'metrics', 'infrastructure', eventLogger);
if (infrastructureMigration) {
migrations['7.10.0'] = infrastructureMigration;
}
YulNaumenko marked this conversation as resolved.
Show resolved Hide resolved
return migrations;
}

function changeAlertingConsumer(
encryptedSavedObjects: EncryptedSavedObjectsPluginSetup,
from: string,
to: string,
eventLogger: Logger
): SavedObjectMigrationFn<RawAlert, RawAlert> | undefined {
try {
return encryptedSavedObjects.createMigration<RawAlert, RawAlert>(
function shouldBeMigrated(doc): doc is SavedObjectUnsanitizedDoc<RawAlert> {
return doc.attributes.consumer === from;
},
(doc: SavedObjectUnsanitizedDoc<RawAlert>): SavedObjectUnsanitizedDoc<RawAlert> => {
const {
attributes: { consumer },
} = doc;
return {
...doc,
attributes: {
...doc.attributes,
consumer: consumer === from ? to : consumer,
},
};
}
);
} catch (ex) {
eventLogger.error(`encryptedSavedObject migration from ${from} to ${to} failed with error: ${ex.message}`)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,8 @@ export default function alertingTests({ loadTestFile }: FtrProviderContext) {
loadTestFile(require.resolve('./alerts_space1'));
loadTestFile(require.resolve('./alerts_default_space'));
loadTestFile(require.resolve('./builtin_alert_types'));

// note that this test will destroy existing spaces
loadTestFile(require.resolve('./migrations'));
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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 expect from '@kbn/expect';
import { getUrlPrefix } from '../../../common/lib';
import { FtrProviderContext } from '../../../common/ftr_provider_context';

// eslint-disable-next-line import/no-default-export
export default function createGetTests({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
const esArchiver = getService('esArchiver');

describe('migrations', () => {
before(async () => {
await esArchiver.load('alerts');
});

after(async () => {
await esArchiver.unload('alerts');
});

it('7.9.0 migrates the `alerting` consumer to be the `alerts`', async () => {
const response = await supertest.get(
`${getUrlPrefix(``)}/api/alerts/alert/74f3e6d7-b7bb-477d-ac28-92ee22728e6e`
);

expect(response.status).to.eql(200);
expect(response.body.consumer).to.equal('alerts');
});

it('7.10.0 migrates the `metrics` consumer to be the `infrastructure`', async () => {
const response = await supertest.get(
`${getUrlPrefix(``)}/api/alerts/alert/74f3e6d7-b7bb-477d-ac28-fdf248d5f2a4`
);

expect(response.status).to.eql(200);
expect(response.body.consumer).to.equal('infrastructure');
});
});
}