Skip to content

Commit

Permalink
Simplifying
Browse files Browse the repository at this point in the history
  • Loading branch information
ymao1 committed Mar 22, 2021
1 parent b9ad6c3 commit 4b1b787
Show file tree
Hide file tree
Showing 21 changed files with 121 additions and 226 deletions.
1 change: 0 additions & 1 deletion x-pack/plugins/actions/server/actions_client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,6 @@ describe('create()', () => {
enabled: true,
enabledActionTypes: ['some-not-ignored-action-type'],
allowedHosts: ['*'],
preconfiguredAlertHistoryEsIndex: true,
preconfigured: {},
proxyRejectUnauthorizedCertificates: true,
rejectUnauthorized: true,
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/actions/server/actions_config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ const defaultActionsConfig: ActionsConfig = {
enabled: false,
allowedHosts: [],
enabledActionTypes: [],
preconfiguredAlertHistoryEsIndex: true,
preconfigured: {},
proxyRejectUnauthorizedCertificates: true,
rejectUnauthorized: true,
Expand Down

This file was deleted.

This file was deleted.

19 changes: 11 additions & 8 deletions x-pack/plugins/actions/server/builtin_action_types/es_index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { schema, TypeOf } from '@kbn/config-schema';
import { Logger } from '../../../../../src/core/server';
import { ActionType, ActionTypeExecutorOptions, ActionTypeExecutorResult } from '../types';
import { renderMustacheObject } from '../lib/mustache_renderer';
import { buildAlertHistoryDocument, AlertHistoryEsIndexConnectorId } from '../../common';
import { buildAlertHistoryDocument } from '../../common';

export type ESIndexActionType = ActionType<ActionTypeConfigType, {}, ActionParamsType, unknown>;
export type ESIndexActionTypeExecutorOptions = ActionTypeExecutorOptions<
Expand Down Expand Up @@ -39,6 +39,7 @@ export type ActionParamsType = TypeOf<typeof ParamsSchema>;
// eventually: https://github.com/elastic/kibana/projects/26#card-24087404
const ParamsSchema = schema.object({
documents: schema.arrayOf(schema.recordOf(schema.string(), schema.any())),
usePreconfiguredSchema: schema.boolean({ defaultValue: false }),
});

export const ActionTypeId = '.index';
Expand Down Expand Up @@ -111,20 +112,22 @@ async function executor(

function renderParameterTemplates(
params: ActionParamsType,
variables: Record<string, unknown>,
actionId: string
variables: Record<string, unknown>
): ActionParamsType {
const { documents } = renderMustacheObject<ActionParamsType>(params, variables);
const { documents, usePreconfiguredSchema } = renderMustacheObject<ActionParamsType>(
params,
variables
);

if (actionId === AlertHistoryEsIndexConnectorId) {
if (usePreconfiguredSchema) {
const alertHistoryDoc = buildAlertHistoryDocument(variables);
if (!alertHistoryDoc) {
throw new Error(`error creating alert history document for ${actionId} connector`);
throw new Error(`error creating alert history document`);
}
return { documents: [alertHistoryDoc] };
return { documents: [alertHistoryDoc], usePreconfiguredSchema };
}

return { documents };
return { documents, usePreconfiguredSchema };
}

function wrapErr(
Expand Down
2 changes: 0 additions & 2 deletions x-pack/plugins/actions/server/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ describe('config validation', () => {
"*",
],
"preconfigured": Object {},
"preconfiguredAlertHistoryEsIndex": true,
"proxyRejectUnauthorizedCertificates": true,
"rejectUnauthorized": true,
}
Expand Down Expand Up @@ -60,7 +59,6 @@ describe('config validation', () => {
"secrets": Object {},
},
},
"preconfiguredAlertHistoryEsIndex": true,
"proxyRejectUnauthorizedCertificates": false,
"rejectUnauthorized": false,
}
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/actions/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export const configSchema = schema.object({
defaultValue: [AllowedHosts.Any],
}
),
preconfiguredAlertHistoryEsIndex: schema.boolean({ defaultValue: true }),
preconfigured: schema.recordOf(schema.string(), preconfiguredActionSchema, {
defaultValue: {},
validate: validatePreconfigured,
Expand Down
3 changes: 1 addition & 2 deletions x-pack/plugins/actions/server/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,10 @@ const createStartMock = () => {
// this is a default renderer that escapes nothing
export function renderActionParameterTemplatesDefault<RecordType>(
actionTypeId: string,
actionId: string,
params: Record<string, unknown>,
variables: Record<string, unknown>
) {
return renderActionParameterTemplates(undefined, actionTypeId, actionId, params, variables);
return renderActionParameterTemplates(undefined, actionTypeId, params, variables);
}

const createServicesMock = () => {
Expand Down
11 changes: 0 additions & 11 deletions x-pack/plugins/actions/server/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ describe('Actions Plugin', () => {
enabled: true,
enabledActionTypes: ['*'],
allowedHosts: ['*'],
preconfiguredAlertHistoryEsIndex: true,
preconfigured: {},
proxyRejectUnauthorizedCertificates: true,
rejectUnauthorized: true,
Expand Down Expand Up @@ -188,7 +187,6 @@ describe('Actions Plugin', () => {
enabled: true,
enabledActionTypes: ['*'],
allowedHosts: ['*'],
preconfiguredAlertHistoryEsIndex: true,
preconfigured: {
preconfiguredServerLog: {
actionTypeId: '.server-log',
Expand Down Expand Up @@ -228,15 +226,6 @@ describe('Actions Plugin', () => {
expect(pluginStart.isActionExecutable('preconfiguredServerLog', '.server-log')).toBe(true);
});

it('should handle preconfiguredAlertHistoryEsIndex = true', async () => {
await plugin.setup(coreSetup, pluginsSetup);
const pluginStart = await plugin.start(coreStart, pluginsStart);

expect(
pluginStart.isActionExecutable('preconfigured-alert-history-es-index', '.index')
).toBe(true);
});

it('should not throw error when ESO plugin has encryption key', async () => {
await plugin.setup(coreSetup, {
...pluginsSetup,
Expand Down
20 changes: 1 addition & 19 deletions x-pack/plugins/actions/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ import {
} from './authorization/get_authorization_mode_by_source';
import { ensureSufficientLicense } from './lib/ensure_sufficient_license';
import { renderMustacheObject } from './lib/mustache_renderer';
import { getAlertHistoryEsIndex } from './builtin_action_types/alert_history_es_index/alert_history_es_index';
import { createAlertHistoryEsIndex } from './builtin_action_types/alert_history_es_index/create_alert_history_es_index';

const EVENT_LOG_PROVIDER = 'actions';
export const EVENT_LOG_ACTIONS = {
Expand Down Expand Up @@ -100,7 +98,6 @@ export interface PluginStartContract {
preconfiguredActions: PreConfiguredAction[];
renderActionParameterTemplates<Params extends ActionTypeParams = ActionTypeParams>(
actionTypeId: string,
actionId: string,
params: Params,
variables: Record<string, unknown>
): Params;
Expand Down Expand Up @@ -142,15 +139,13 @@ export class ActionsPlugin implements Plugin<PluginSetupContract, PluginStartCon
private readonly telemetryLogger: Logger;
private readonly preconfiguredActions: PreConfiguredAction[];
private readonly kibanaIndexConfig: { kibana: { index: string } };
private kibanaVersion: PluginInitializerContext['env']['packageInfo']['version'];

constructor(initContext: PluginInitializerContext) {
this.actionsConfig = initContext.config.get<ActionsConfig>();
this.logger = initContext.logger.get('actions');
this.telemetryLogger = initContext.logger.get('usage');
this.preconfiguredActions = [];
this.kibanaIndexConfig = initContext.config.legacy.get();
this.kibanaVersion = initContext.env.packageInfo.version;
}

public setup(
Expand Down Expand Up @@ -183,10 +178,6 @@ export class ActionsPlugin implements Plugin<PluginSetupContract, PluginStartCon
const taskRunnerFactory = new TaskRunnerFactory(actionExecutor);
const actionsConfigUtils = getActionsConfigurationUtilities(this.actionsConfig);

if (this.actionsConfig.preconfiguredAlertHistoryEsIndex) {
this.preconfiguredActions.push(getAlertHistoryEsIndex(this.kibanaVersion));
}

for (const preconfiguredId of Object.keys(this.actionsConfig.preconfigured)) {
this.preconfiguredActions.push({
...this.actionsConfig.preconfigured[preconfiguredId],
Expand Down Expand Up @@ -364,14 +355,6 @@ export class ActionsPlugin implements Plugin<PluginSetupContract, PluginStartCon

scheduleActionsTelemetry(this.telemetryLogger, plugins.taskManager);

if (this.actionsConfig.preconfiguredAlertHistoryEsIndex) {
createAlertHistoryEsIndex({
client: core.elasticsearch.client.asInternalUser,
kibanaVersion: this.kibanaVersion,
logger: this.logger,
});
}

return {
isActionTypeEnabled: (id, options = { notifyUsage: false }) => {
return this.actionTypeRegistry!.isActionTypeEnabled(id, options);
Expand Down Expand Up @@ -485,13 +468,12 @@ export class ActionsPlugin implements Plugin<PluginSetupContract, PluginStartCon
export function renderActionParameterTemplates<Params extends ActionTypeParams = ActionTypeParams>(
actionTypeRegistry: ActionTypeRegistry | undefined,
actionTypeId: string,
actionId: string,
params: Params,
variables: Record<string, unknown>
): Params {
const actionType = actionTypeRegistry?.get(actionTypeId);
if (actionType?.renderParameterTemplates) {
return actionType.renderParameterTemplates(params, variables, actionId) as Params;
return actionType.renderParameterTemplates(params, variables) as Params;
} else {
return renderMustacheObject(params, variables);
}
Expand Down
6 changes: 1 addition & 5 deletions x-pack/plugins/actions/server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,7 @@ export interface ActionType<
config?: ValidatorType<Config>;
secrets?: ValidatorType<Secrets>;
};
renderParameterTemplates?(
params: Params,
variables: Record<string, unknown>,
actionId?: string
): Params;
renderParameterTemplates?(params: Params, variables: Record<string, unknown>): Params;
executor: ExecutorType<Config, Secrets, Params, ExecutorResultData>;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { contextMock } from './context.mock';
import { initializeEs } from './init';

describe('initializeEs', () => {
let esContext = contextMock.create();

beforeEach(() => {
esContext = contextMock.create();
});

test(`should create ILM policy if it doesn't exist`, async () => {
esContext.esAdapter.doesIlmPolicyExist.mockResolvedValue(false);

await initializeEs(esContext);
expect(esContext.esAdapter.doesIlmPolicyExist).toHaveBeenCalled();
expect(esContext.esAdapter.createIlmPolicy).toHaveBeenCalled();
});

test(`shouldn't create ILM policy if it exists`, async () => {
esContext.esAdapter.doesIlmPolicyExist.mockResolvedValue(true);

await initializeEs(esContext);
expect(esContext.esAdapter.doesIlmPolicyExist).toHaveBeenCalled();
expect(esContext.esAdapter.createIlmPolicy).not.toHaveBeenCalled();
});

test(`should create index template if it doesn't exist`, async () => {
esContext.esAdapter.doesIndexTemplateExist.mockResolvedValue(false);

await initializeEs(esContext);
expect(esContext.esAdapter.doesIndexTemplateExist).toHaveBeenCalled();
expect(esContext.esAdapter.createIndexTemplate).toHaveBeenCalled();
});

test(`shouldn't create index template if it already exists`, async () => {
esContext.esAdapter.doesIndexTemplateExist.mockResolvedValue(true);

await initializeEs(esContext);
expect(esContext.esAdapter.doesIndexTemplateExist).toHaveBeenCalled();
expect(esContext.esAdapter.createIndexTemplate).not.toHaveBeenCalled();
});

test(`should create initial index if it doesn't exist`, async () => {
esContext.esAdapter.doesAliasExist.mockResolvedValue(false);

await initializeEs(esContext);
expect(esContext.esAdapter.doesAliasExist).toHaveBeenCalled();
expect(esContext.esAdapter.createIndex).toHaveBeenCalled();
});

test(`shouldn't create initial index if it already exists`, async () => {
esContext.esAdapter.doesAliasExist.mockResolvedValue(true);

await initializeEs(esContext);
expect(esContext.esAdapter.doesAliasExist).toHaveBeenCalled();
expect(esContext.esAdapter.createIndex).not.toHaveBeenCalled();
});
});
Loading

0 comments on commit 4b1b787

Please sign in to comment.