kibana/x-pack/plugins/actions/server/plugin.ts

550 lines
19 KiB
TypeScript
Raw Normal View History

/*
* 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 type { PublicMethodsOf } from '@kbn/utility-types';
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import {
PluginInitializerContext,
Plugin,
CoreSetup,
CoreStart,
KibanaRequest,
Logger,
IContextProvider,
ElasticsearchServiceStart,
SavedObjectsClientContract,
SavedObjectsBulkGetObject,
} from '../../../../src/core/server';
import {
EncryptedSavedObjectsPluginSetup,
EncryptedSavedObjectsPluginStart,
} from '../../encrypted_saved_objects/server';
import { TaskManagerSetupContract, TaskManagerStartContract } from '../../task_manager/server';
import { LicensingPluginSetup, LicensingPluginStart } from '../../licensing/server';
import { SpacesPluginStart, SpacesPluginSetup } from '../../spaces/server';
import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server';
import { SecurityPluginSetup } from '../../security/server';
import {
ensureCleanupFailedExecutionsTaskScheduled,
registerCleanupFailedExecutionsTaskDefinition,
} from './cleanup_failed_executions';
import { ActionsConfig, getValidatedConfig } from './config';
import { resolveCustomHosts } from './lib/custom_host_settings';
import { ActionsClient } from './actions_client';
import { ActionTypeRegistry } from './action_type_registry';
[Alerting] Change execution of alerts from async to sync (#97311) * added ability to run ephemeral tasks * fixed typing * added typing on plugin * WIP * Fix type issues * Hook up the ephemeral task into the task runner for actions * Tasks can now run independently of one another * Use deferred language * Refactor taskParams slightly * Use Promise.all * Remove deferred logic * Add config options to limit the amount of tasks executing at once * Add ephemeral task monitoring * WIP * Add single test so far * Ensure we log after actions have executed * Remove confusing * 1 * Add logic to ensure we fallback to default enqueueing if the total actions is above the config * Add additional test * Fix tests a bit, ensure we log the alerting:actions-execute right away and the tests should listen for alerts:execute * Better tests * If the queue is at capacity, attempt to execute the ephemeral task as a regular action * Ensure we run ephemeral tasks before to avoid them getting stuck in the queue * Do not handle the promise anymore * Remove unnecessary code * Properly handle errors from ephemeral task lifecycle * moved acitons domain out of alerting and into actions plugin * Remove some tests * Fix TS and test issues * Fix type issues * Fix more type issues * Fix more type issues * Fix jest tests * Fix more jest tests * Off by default * Fix jest tests * Update config for this suite too * Start of telemetry code * Fix types and add missing files * Fix telemetry schema * Fix types * Fix more types * moved load event emission to pollingcycle and added health stats on Ephemeral tasks * Add more telemetry data based on new health metrics for the ephemeral queue * Fix tests and types * Add separate request capacity for ephemeral queue * Fix telemetry schema and add tests for usage collection * track polled tasks by persistence and use in capacity estimation instead of executions * fixed typing * Bump default capacity * added delay metric to ephemeral stats * Fix bad merge * Fix tests * Fix tests * Fix types * Skip failing tests * Exclude ephemeral stats from capacity estimation tests * PR feedback * More PR feedback * PR feedback * Fix merge conflict * Try fixing CI * Fix broken lock file from merge * Match master * Add this back * PR feedback * Change to queue and add test * Disable ephemeral queue in tests * Updated desc * Comment out ephemeral-specific tests tha require the entire test suite to support ephemeral tasks * Add clarifying comment Co-authored-by: Gidi Meir Morris <github@gidi.io> Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-07-20 19:24:24 +02:00
import {
createExecutionEnqueuerFunction,
createEphemeralExecutionEnqueuerFunction,
} from './create_execute_function';
import { registerBuiltInActionTypes } from './builtin_action_types';
import { registerActionsUsageCollector } from './usage';
import {
ActionExecutor,
TaskRunnerFactory,
LicenseState,
ILicenseState,
spaceIdToNamespace,
} from './lib';
import {
Services,
ActionType,
PreConfiguredAction,
ActionTypeConfig,
ActionTypeSecrets,
ActionTypeParams,
ActionsRequestHandlerContext,
} from './types';
import { getActionsConfigurationUtilities } from './actions_config';
import { defineRoutes } from './routes';
import { IEventLogger, IEventLogService } from '../../event_log/server';
import { initializeActionsTelemetry, scheduleActionsTelemetry } from './usage/task';
import {
ACTION_SAVED_OBJECT_TYPE,
ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE,
ALERT_SAVED_OBJECT_TYPE,
} from './constants/saved_objects';
import { setupSavedObjects } from './saved_objects';
import { ACTIONS_FEATURE } from './feature';
import { ActionsAuthorization } from './authorization/actions_authorization';
import { ActionsAuthorizationAuditLogger } from './authorization/audit_logger';
import { ActionExecutionSource } from './lib/action_execution_source';
import {
getAuthorizationModeBySource,
AuthorizationMode,
} from './authorization/get_authorization_mode_by_source';
import { ensureSufficientLicense } from './lib/ensure_sufficient_license';
import { renderMustacheObject } from './lib/mustache_renderer';
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
import { getAlertHistoryEsIndex } from './preconfigured_connectors/alert_history_es_index/alert_history_es_index';
import { createAlertHistoryIndexTemplate } from './preconfigured_connectors/alert_history_es_index/create_alert_history_index_template';
import { AlertHistoryEsIndexConnectorId } from '../common';
import { EVENT_LOG_ACTIONS, EVENT_LOG_PROVIDER } from './constants/event_log';
export interface PluginSetupContract {
registerType<
Config extends ActionTypeConfig = ActionTypeConfig,
Secrets extends ActionTypeSecrets = ActionTypeSecrets,
2020-10-30 23:26:12 +01:00
Params extends ActionTypeParams = ActionTypeParams,
ExecutorResultData = void
>(
2020-10-30 23:26:12 +01:00
actionType: ActionType<Config, Secrets, Params, ExecutorResultData>
): void;
}
export interface PluginStartContract {
isActionTypeEnabled(id: string, options?: { notifyUsage: boolean }): boolean;
isActionExecutable(
actionId: string,
actionTypeId: string,
options?: { notifyUsage: boolean }
): boolean;
getActionsClientWithRequest(request: KibanaRequest): Promise<PublicMethodsOf<ActionsClient>>;
getActionsAuthorizationWithRequest(request: KibanaRequest): PublicMethodsOf<ActionsAuthorization>;
preconfiguredActions: PreConfiguredAction[];
renderActionParameterTemplates<Params extends ActionTypeParams = ActionTypeParams>(
actionTypeId: string,
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
actionId: string,
params: Params,
variables: Record<string, unknown>
): Params;
}
export interface ActionsPluginsSetup {
taskManager: TaskManagerSetupContract;
encryptedSavedObjects: EncryptedSavedObjectsPluginSetup;
licensing: LicensingPluginSetup;
eventLog: IEventLogService;
usageCollection?: UsageCollectionSetup;
security?: SecurityPluginSetup;
features: FeaturesPluginSetup;
spaces?: SpacesPluginSetup;
}
export interface ActionsPluginsStart {
encryptedSavedObjects: EncryptedSavedObjectsPluginStart;
taskManager: TaskManagerStartContract;
licensing: LicensingPluginStart;
spaces?: SpacesPluginStart;
}
const includedHiddenTypes = [
ACTION_SAVED_OBJECT_TYPE,
ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE,
ALERT_SAVED_OBJECT_TYPE,
];
export class ActionsPlugin implements Plugin<PluginSetupContract, PluginStartContract> {
private readonly logger: Logger;
private readonly actionsConfig: ActionsConfig;
private taskRunnerFactory?: TaskRunnerFactory;
private actionTypeRegistry?: ActionTypeRegistry;
private actionExecutor?: ActionExecutor;
License checks for actions plugin (#59070) * Define minimum license required for each action type (#58668) * Add minimum required license * Require at least gold license as a minimum license required on third party action types * Use strings for license references * Ensure license type is valid * Fix some tests * Add servicenow to gold * Add tests * Set license requirements on other built in action types * Use jest.Mocked<ActionType> instead * Change servicenow to platinum Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> * Make actions config mock and license state mock use factory pattern and jest mocks (#59370) * Add license checks to action HTTP APIs (#59153) * Initial work * Handle errors in update action API * Add unit tests for APIs * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Add license checks within alerting / actions framework (#59699) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Fix confusing assertion * Add comment explaining double mock * Log warning when alert action isn't scheduled * Disable action types in UI when license doesn't support it (#59819) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Return enabledInConfig and enabledInLicense from actions get types API * Disable cards that have invalid license in create connector flyout * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Disable when creating alert action * Return minimumLicenseRequired in /types API * Disable row in connectors when action type is disabled * Fix failing jest test * Some refactoring * Card in edit alert flyout * Sort action types by name * Add tooltips to create connector action type selector * Add tooltips to alert flyout action type selector * Add get more actions link in alert flyout * Add callout when creating a connector * Typos * remove float right and use flexgroup * replace pixels with eui variables * turn on sass lint for triggers_actions_ui dir * trying to add padding around cards * Add callout in edit alert screen when some actions are disabled * improve card selection for Add Connector flyout * Fix cards for create connector * Add tests * ESLint issue * Cleanup * Cleanup pt2 * Fix type check errors * moving to 3-columns cards for connector selection * Change re-enable to enable terminology * Revert "Change re-enable to enable terminology" This reverts commit b497dfd6b6bc88db862ad97826e8d03b094c8ed0. * Add re-enable comment * Remove unecessary fragment * Add type to actionTypeNodes * Fix EuiLink to not have opacity of 0.7 when not hovered * design cleanup in progress * updating classNames * using EuiIconTip * Remove label on icon tip * Fix failing jest test Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com> * Add index to .index action type test * PR feedback * Add isErrorThatHandlesItsOwnResponse Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com>
2020-03-20 15:49:37 +01:00
private licenseState: ILicenseState | null = null;
private security?: SecurityPluginSetup;
private eventLogService?: IEventLogService;
private eventLogger?: IEventLogger;
private isESOCanEncrypt?: boolean;
private readonly telemetryLogger: Logger;
private readonly preconfiguredActions: PreConfiguredAction[];
private readonly kibanaIndexConfig: { kibana: { index: string } };
constructor(initContext: PluginInitializerContext) {
this.logger = initContext.logger.get();
this.actionsConfig = getValidatedConfig(
this.logger,
resolveCustomHosts(this.logger, initContext.config.get<ActionsConfig>())
);
this.telemetryLogger = initContext.logger.get('usage');
this.preconfiguredActions = [];
this.kibanaIndexConfig = initContext.config.legacy.get();
}
public setup(
core: CoreSetup<ActionsPluginsStart>,
plugins: ActionsPluginsSetup
): PluginSetupContract {
License checks for actions plugin (#59070) * Define minimum license required for each action type (#58668) * Add minimum required license * Require at least gold license as a minimum license required on third party action types * Use strings for license references * Ensure license type is valid * Fix some tests * Add servicenow to gold * Add tests * Set license requirements on other built in action types * Use jest.Mocked<ActionType> instead * Change servicenow to platinum Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> * Make actions config mock and license state mock use factory pattern and jest mocks (#59370) * Add license checks to action HTTP APIs (#59153) * Initial work * Handle errors in update action API * Add unit tests for APIs * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Add license checks within alerting / actions framework (#59699) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Fix confusing assertion * Add comment explaining double mock * Log warning when alert action isn't scheduled * Disable action types in UI when license doesn't support it (#59819) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Return enabledInConfig and enabledInLicense from actions get types API * Disable cards that have invalid license in create connector flyout * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Disable when creating alert action * Return minimumLicenseRequired in /types API * Disable row in connectors when action type is disabled * Fix failing jest test * Some refactoring * Card in edit alert flyout * Sort action types by name * Add tooltips to create connector action type selector * Add tooltips to alert flyout action type selector * Add get more actions link in alert flyout * Add callout when creating a connector * Typos * remove float right and use flexgroup * replace pixels with eui variables * turn on sass lint for triggers_actions_ui dir * trying to add padding around cards * Add callout in edit alert screen when some actions are disabled * improve card selection for Add Connector flyout * Fix cards for create connector * Add tests * ESLint issue * Cleanup * Cleanup pt2 * Fix type check errors * moving to 3-columns cards for connector selection * Change re-enable to enable terminology * Revert "Change re-enable to enable terminology" This reverts commit b497dfd6b6bc88db862ad97826e8d03b094c8ed0. * Add re-enable comment * Remove unecessary fragment * Add type to actionTypeNodes * Fix EuiLink to not have opacity of 0.7 when not hovered * design cleanup in progress * updating classNames * using EuiIconTip * Remove label on icon tip * Fix failing jest test Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com> * Add index to .index action type test * PR feedback * Add isErrorThatHandlesItsOwnResponse Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com>
2020-03-20 15:49:37 +01:00
this.licenseState = new LicenseState(plugins.licensing.license$);
this.isESOCanEncrypt = plugins.encryptedSavedObjects.canEncrypt;
if (!this.isESOCanEncrypt) {
this.logger.warn(
'APIs are disabled because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.'
);
}
plugins.features.registerKibanaFeature(ACTIONS_FEATURE);
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 },
});
const actionExecutor = new ActionExecutor({
isESOCanEncrypt: this.isESOCanEncrypt,
});
// get executions count
const taskRunnerFactory = new TaskRunnerFactory(actionExecutor);
const actionsConfigUtils = getActionsConfigurationUtilities(this.actionsConfig);
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
if (this.actionsConfig.preconfiguredAlertHistoryEsIndex) {
this.preconfiguredActions.push(getAlertHistoryEsIndex());
}
for (const preconfiguredId of Object.keys(this.actionsConfig.preconfigured)) {
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
if (preconfiguredId !== AlertHistoryEsIndexConnectorId) {
this.preconfiguredActions.push({
...this.actionsConfig.preconfigured[preconfiguredId],
id: preconfiguredId,
isPreconfigured: true,
});
} else {
this.logger.warn(
`Preconfigured connectors cannot have the id "${AlertHistoryEsIndexConnectorId}" because this is a reserved id.`
);
}
}
const actionTypeRegistry = new ActionTypeRegistry({
licensing: plugins.licensing,
taskRunnerFactory,
taskManager: plugins.taskManager,
actionsConfigUtils,
License checks for actions plugin (#59070) * Define minimum license required for each action type (#58668) * Add minimum required license * Require at least gold license as a minimum license required on third party action types * Use strings for license references * Ensure license type is valid * Fix some tests * Add servicenow to gold * Add tests * Set license requirements on other built in action types * Use jest.Mocked<ActionType> instead * Change servicenow to platinum Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> * Make actions config mock and license state mock use factory pattern and jest mocks (#59370) * Add license checks to action HTTP APIs (#59153) * Initial work * Handle errors in update action API * Add unit tests for APIs * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Add license checks within alerting / actions framework (#59699) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Fix confusing assertion * Add comment explaining double mock * Log warning when alert action isn't scheduled * Disable action types in UI when license doesn't support it (#59819) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Return enabledInConfig and enabledInLicense from actions get types API * Disable cards that have invalid license in create connector flyout * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Disable when creating alert action * Return minimumLicenseRequired in /types API * Disable row in connectors when action type is disabled * Fix failing jest test * Some refactoring * Card in edit alert flyout * Sort action types by name * Add tooltips to create connector action type selector * Add tooltips to alert flyout action type selector * Add get more actions link in alert flyout * Add callout when creating a connector * Typos * remove float right and use flexgroup * replace pixels with eui variables * turn on sass lint for triggers_actions_ui dir * trying to add padding around cards * Add callout in edit alert screen when some actions are disabled * improve card selection for Add Connector flyout * Fix cards for create connector * Add tests * ESLint issue * Cleanup * Cleanup pt2 * Fix type check errors * moving to 3-columns cards for connector selection * Change re-enable to enable terminology * Revert "Change re-enable to enable terminology" This reverts commit b497dfd6b6bc88db862ad97826e8d03b094c8ed0. * Add re-enable comment * Remove unecessary fragment * Add type to actionTypeNodes * Fix EuiLink to not have opacity of 0.7 when not hovered * design cleanup in progress * updating classNames * using EuiIconTip * Remove label on icon tip * Fix failing jest test Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com> * Add index to .index action type test * PR feedback * Add isErrorThatHandlesItsOwnResponse Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com>
2020-03-20 15:49:37 +01:00
licenseState: this.licenseState,
preconfiguredActions: this.preconfiguredActions,
});
this.taskRunnerFactory = taskRunnerFactory;
this.actionTypeRegistry = actionTypeRegistry;
this.actionExecutor = actionExecutor;
this.security = plugins.security;
setupSavedObjects(
core.savedObjects,
plugins.encryptedSavedObjects,
this.actionTypeRegistry!,
plugins.taskManager.index
);
registerBuiltInActionTypes({
logger: this.logger,
actionTypeRegistry,
actionsConfigUtils,
publicBaseUrl: core.http.basePath.publicBaseUrl,
});
const usageCollection = plugins.usageCollection;
if (usageCollection) {
registerActionsUsageCollector(
usageCollection,
this.actionsConfig,
core.getStartServices().then(([_, { taskManager }]) => taskManager)
);
}
core.http.registerRouteHandlerContext<ActionsRequestHandlerContext, 'actions'>(
'actions',
this.createRouteHandlerContext(core, this.kibanaIndexConfig.kibana.index)
);
if (usageCollection) {
initializeActionsTelemetry(
this.telemetryLogger,
plugins.taskManager,
core,
this.kibanaIndexConfig.kibana.index
);
}
// Routes
defineRoutes(core.http.createRouter<ActionsRequestHandlerContext>(), this.licenseState);
// Cleanup failed execution task definition
if (this.actionsConfig.cleanupFailedExecutionsTask.enabled) {
registerCleanupFailedExecutionsTaskDefinition(plugins.taskManager, {
actionTypeRegistry,
logger: this.logger,
coreStartServices: core.getStartServices(),
config: this.actionsConfig.cleanupFailedExecutionsTask,
kibanaIndex: this.kibanaIndexConfig.kibana.index,
taskManagerIndex: plugins.taskManager.index,
});
}
return {
registerType: <
Config extends ActionTypeConfig = ActionTypeConfig,
Secrets extends ActionTypeSecrets = ActionTypeSecrets,
Params extends ActionTypeParams = ActionTypeParams,
ExecutorResultData = void
>(
actionType: ActionType<Config, Secrets, Params, ExecutorResultData>
) => {
ensureSufficientLicense(actionType);
License checks for actions plugin (#59070) * Define minimum license required for each action type (#58668) * Add minimum required license * Require at least gold license as a minimum license required on third party action types * Use strings for license references * Ensure license type is valid * Fix some tests * Add servicenow to gold * Add tests * Set license requirements on other built in action types * Use jest.Mocked<ActionType> instead * Change servicenow to platinum Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> * Make actions config mock and license state mock use factory pattern and jest mocks (#59370) * Add license checks to action HTTP APIs (#59153) * Initial work * Handle errors in update action API * Add unit tests for APIs * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Add license checks within alerting / actions framework (#59699) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Fix confusing assertion * Add comment explaining double mock * Log warning when alert action isn't scheduled * Disable action types in UI when license doesn't support it (#59819) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Return enabledInConfig and enabledInLicense from actions get types API * Disable cards that have invalid license in create connector flyout * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Disable when creating alert action * Return minimumLicenseRequired in /types API * Disable row in connectors when action type is disabled * Fix failing jest test * Some refactoring * Card in edit alert flyout * Sort action types by name * Add tooltips to create connector action type selector * Add tooltips to alert flyout action type selector * Add get more actions link in alert flyout * Add callout when creating a connector * Typos * remove float right and use flexgroup * replace pixels with eui variables * turn on sass lint for triggers_actions_ui dir * trying to add padding around cards * Add callout in edit alert screen when some actions are disabled * improve card selection for Add Connector flyout * Fix cards for create connector * Add tests * ESLint issue * Cleanup * Cleanup pt2 * Fix type check errors * moving to 3-columns cards for connector selection * Change re-enable to enable terminology * Revert "Change re-enable to enable terminology" This reverts commit b497dfd6b6bc88db862ad97826e8d03b094c8ed0. * Add re-enable comment * Remove unecessary fragment * Add type to actionTypeNodes * Fix EuiLink to not have opacity of 0.7 when not hovered * design cleanup in progress * updating classNames * using EuiIconTip * Remove label on icon tip * Fix failing jest test Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com> * Add index to .index action type test * PR feedback * Add isErrorThatHandlesItsOwnResponse Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com>
2020-03-20 15:49:37 +01:00
actionTypeRegistry.register(actionType);
},
};
}
public start(core: CoreStart, plugins: ActionsPluginsStart): PluginStartContract {
const {
logger,
licenseState,
actionExecutor,
actionTypeRegistry,
taskRunnerFactory,
kibanaIndexConfig,
isESOCanEncrypt,
preconfiguredActions,
instantiateAuthorization,
getUnsecuredSavedObjectsClient,
} = this;
licenseState?.setNotifyUsage(plugins.licensing.featureUsage.notifyUsage);
const encryptedSavedObjectsClient = plugins.encryptedSavedObjects.getClient({
includedHiddenTypes,
});
const getActionsClientWithRequest = async (
request: KibanaRequest,
authorizationContext?: ActionExecutionSource<unknown>
) => {
if (isESOCanEncrypt !== true) {
throw new Error(
`Unable to create actions client because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.`
);
}
const unsecuredSavedObjectsClient = getUnsecuredSavedObjectsClient(
core.savedObjects,
request
);
const kibanaIndex = kibanaIndexConfig.kibana.index;
return new ActionsClient({
unsecuredSavedObjectsClient,
actionTypeRegistry: actionTypeRegistry!,
defaultKibanaIndex: kibanaIndex,
scopedClusterClient: core.elasticsearch.client.asScoped(request),
preconfiguredActions,
request,
authorization: instantiateAuthorization(
request,
await getAuthorizationModeBySource(unsecuredSavedObjectsClient, authorizationContext)
),
actionExecutor: actionExecutor!,
[Alerting] Change execution of alerts from async to sync (#97311) * added ability to run ephemeral tasks * fixed typing * added typing on plugin * WIP * Fix type issues * Hook up the ephemeral task into the task runner for actions * Tasks can now run independently of one another * Use deferred language * Refactor taskParams slightly * Use Promise.all * Remove deferred logic * Add config options to limit the amount of tasks executing at once * Add ephemeral task monitoring * WIP * Add single test so far * Ensure we log after actions have executed * Remove confusing * 1 * Add logic to ensure we fallback to default enqueueing if the total actions is above the config * Add additional test * Fix tests a bit, ensure we log the alerting:actions-execute right away and the tests should listen for alerts:execute * Better tests * If the queue is at capacity, attempt to execute the ephemeral task as a regular action * Ensure we run ephemeral tasks before to avoid them getting stuck in the queue * Do not handle the promise anymore * Remove unnecessary code * Properly handle errors from ephemeral task lifecycle * moved acitons domain out of alerting and into actions plugin * Remove some tests * Fix TS and test issues * Fix type issues * Fix more type issues * Fix more type issues * Fix jest tests * Fix more jest tests * Off by default * Fix jest tests * Update config for this suite too * Start of telemetry code * Fix types and add missing files * Fix telemetry schema * Fix types * Fix more types * moved load event emission to pollingcycle and added health stats on Ephemeral tasks * Add more telemetry data based on new health metrics for the ephemeral queue * Fix tests and types * Add separate request capacity for ephemeral queue * Fix telemetry schema and add tests for usage collection * track polled tasks by persistence and use in capacity estimation instead of executions * fixed typing * Bump default capacity * added delay metric to ephemeral stats * Fix bad merge * Fix tests * Fix tests * Fix types * Skip failing tests * Exclude ephemeral stats from capacity estimation tests * PR feedback * More PR feedback * PR feedback * Fix merge conflict * Try fixing CI * Fix broken lock file from merge * Match master * Add this back * PR feedback * Change to queue and add test * Disable ephemeral queue in tests * Updated desc * Comment out ephemeral-specific tests tha require the entire test suite to support ephemeral tasks * Add clarifying comment Co-authored-by: Gidi Meir Morris <github@gidi.io> Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-07-20 19:24:24 +02:00
ephemeralExecutionEnqueuer: createEphemeralExecutionEnqueuerFunction({
taskManager: plugins.taskManager,
actionTypeRegistry: actionTypeRegistry!,
isESOCanEncrypt: isESOCanEncrypt!,
preconfiguredActions,
}),
executionEnqueuer: createExecutionEnqueuerFunction({
taskManager: plugins.taskManager,
actionTypeRegistry: actionTypeRegistry!,
isESOCanEncrypt: isESOCanEncrypt!,
preconfiguredActions,
}),
auditLogger: this.security?.audit.asScoped(request),
});
};
// Ensure the public API cannot be used to circumvent authorization
// using our legacy exemption mechanism by passing in a legacy SO
// as authorizationContext which would then set a Legacy AuthorizationMode
const secureGetActionsClientWithRequest = (request: KibanaRequest) =>
getActionsClientWithRequest(request);
this.eventLogService!.registerSavedObjectProvider('action', (request) => {
const client = secureGetActionsClientWithRequest(request);
return (objects?: SavedObjectsBulkGetObject[]) =>
objects
? Promise.all(
objects.map(async (objectItem) => await (await client).get({ id: objectItem.id }))
)
: Promise.resolve([]);
});
const getScopedSavedObjectsClientWithoutAccessToActions = (request: KibanaRequest) =>
core.savedObjects.getScopedClient(request);
actionExecutor!.initialize({
logger,
eventLogger: this.eventLogger!,
spaces: plugins.spaces?.spacesService,
getActionsClientWithRequest,
getServices: this.getServicesFactory(
getScopedSavedObjectsClientWithoutAccessToActions,
core.elasticsearch
),
encryptedSavedObjectsClient,
actionTypeRegistry: actionTypeRegistry!,
preconfiguredActions,
});
taskRunnerFactory!.initialize({
logger,
License checks for actions plugin (#59070) * Define minimum license required for each action type (#58668) * Add minimum required license * Require at least gold license as a minimum license required on third party action types * Use strings for license references * Ensure license type is valid * Fix some tests * Add servicenow to gold * Add tests * Set license requirements on other built in action types * Use jest.Mocked<ActionType> instead * Change servicenow to platinum Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> * Make actions config mock and license state mock use factory pattern and jest mocks (#59370) * Add license checks to action HTTP APIs (#59153) * Initial work * Handle errors in update action API * Add unit tests for APIs * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Add license checks within alerting / actions framework (#59699) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Fix confusing assertion * Add comment explaining double mock * Log warning when alert action isn't scheduled * Disable action types in UI when license doesn't support it (#59819) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Return enabledInConfig and enabledInLicense from actions get types API * Disable cards that have invalid license in create connector flyout * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Disable when creating alert action * Return minimumLicenseRequired in /types API * Disable row in connectors when action type is disabled * Fix failing jest test * Some refactoring * Card in edit alert flyout * Sort action types by name * Add tooltips to create connector action type selector * Add tooltips to alert flyout action type selector * Add get more actions link in alert flyout * Add callout when creating a connector * Typos * remove float right and use flexgroup * replace pixels with eui variables * turn on sass lint for triggers_actions_ui dir * trying to add padding around cards * Add callout in edit alert screen when some actions are disabled * improve card selection for Add Connector flyout * Fix cards for create connector * Add tests * ESLint issue * Cleanup * Cleanup pt2 * Fix type check errors * moving to 3-columns cards for connector selection * Change re-enable to enable terminology * Revert "Change re-enable to enable terminology" This reverts commit b497dfd6b6bc88db862ad97826e8d03b094c8ed0. * Add re-enable comment * Remove unecessary fragment * Add type to actionTypeNodes * Fix EuiLink to not have opacity of 0.7 when not hovered * design cleanup in progress * updating classNames * using EuiIconTip * Remove label on icon tip * Fix failing jest test Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com> * Add index to .index action type test * PR feedback * Add isErrorThatHandlesItsOwnResponse Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com>
2020-03-20 15:49:37 +01:00
actionTypeRegistry: actionTypeRegistry!,
encryptedSavedObjectsClient,
basePathService: core.http.basePath,
spaceIdToNamespace: (spaceId?: string) => spaceIdToNamespace(plugins.spaces, spaceId),
getUnsecuredSavedObjectsClient: (request: KibanaRequest) =>
this.getUnsecuredSavedObjectsClient(core.savedObjects, request),
});
scheduleActionsTelemetry(this.telemetryLogger, plugins.taskManager);
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
if (this.actionsConfig.preconfiguredAlertHistoryEsIndex) {
createAlertHistoryIndexTemplate({
client: core.elasticsearch.client.asInternalUser,
logger: this.logger,
});
}
// Cleanup failed execution task
if (this.actionsConfig.cleanupFailedExecutionsTask.enabled) {
ensureCleanupFailedExecutionsTaskScheduled(
plugins.taskManager,
this.logger,
this.actionsConfig.cleanupFailedExecutionsTask
);
}
return {
isActionTypeEnabled: (id, options = { notifyUsage: false }) => {
return this.actionTypeRegistry!.isActionTypeEnabled(id, options);
License checks for actions plugin (#59070) * Define minimum license required for each action type (#58668) * Add minimum required license * Require at least gold license as a minimum license required on third party action types * Use strings for license references * Ensure license type is valid * Fix some tests * Add servicenow to gold * Add tests * Set license requirements on other built in action types * Use jest.Mocked<ActionType> instead * Change servicenow to platinum Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> * Make actions config mock and license state mock use factory pattern and jest mocks (#59370) * Add license checks to action HTTP APIs (#59153) * Initial work * Handle errors in update action API * Add unit tests for APIs * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Add license checks within alerting / actions framework (#59699) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Fix confusing assertion * Add comment explaining double mock * Log warning when alert action isn't scheduled * Disable action types in UI when license doesn't support it (#59819) * Initial work * Handle errors in update action API * Add unit tests for APIs * Verify action type before scheduling action task * Make actions plugin.execute throw error if action type is disabled * Bug fixes * Make action executor throw when action type isn't enabled * Add test suite for basic license * Fix ESLint errors * Stop action task from re-running when license check fails * Fix failing tests * Attempt 1 to fix CI * ESLint fixes * Return enabledInConfig and enabledInLicense from actions get types API * Disable cards that have invalid license in create connector flyout * Create sendResponse function on ActionTypeDisabledError * Make disabled action types by config return 403 * Remove switch case * Fix ESLint * Disable when creating alert action * Return minimumLicenseRequired in /types API * Disable row in connectors when action type is disabled * Fix failing jest test * Some refactoring * Card in edit alert flyout * Sort action types by name * Add tooltips to create connector action type selector * Add tooltips to alert flyout action type selector * Add get more actions link in alert flyout * Add callout when creating a connector * Typos * remove float right and use flexgroup * replace pixels with eui variables * turn on sass lint for triggers_actions_ui dir * trying to add padding around cards * Add callout in edit alert screen when some actions are disabled * improve card selection for Add Connector flyout * Fix cards for create connector * Add tests * ESLint issue * Cleanup * Cleanup pt2 * Fix type check errors * moving to 3-columns cards for connector selection * Change re-enable to enable terminology * Revert "Change re-enable to enable terminology" This reverts commit b497dfd6b6bc88db862ad97826e8d03b094c8ed0. * Add re-enable comment * Remove unecessary fragment * Add type to actionTypeNodes * Fix EuiLink to not have opacity of 0.7 when not hovered * design cleanup in progress * updating classNames * using EuiIconTip * Remove label on icon tip * Fix failing jest test Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com> * Add index to .index action type test * PR feedback * Add isErrorThatHandlesItsOwnResponse Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Andrea Del Rio <delrio.andre@gmail.com>
2020-03-20 15:49:37 +01:00
},
isActionExecutable: (
actionId: string,
actionTypeId: string,
options = { notifyUsage: false }
) => {
return this.actionTypeRegistry!.isActionExecutable(actionId, actionTypeId, options);
},
getActionsAuthorizationWithRequest(request: KibanaRequest) {
return instantiateAuthorization(request);
},
getActionsClientWithRequest: secureGetActionsClientWithRequest,
preconfiguredActions,
renderActionParameterTemplates: (...args) =>
renderActionParameterTemplates(actionTypeRegistry, ...args),
};
}
private getUnsecuredSavedObjectsClient = (
savedObjects: CoreStart['savedObjects'],
request: KibanaRequest
) =>
savedObjects.getScopedClient(request, {
excludedWrappers: ['security'],
includedHiddenTypes,
});
private instantiateAuthorization = (
request: KibanaRequest,
authorizationMode?: AuthorizationMode
) => {
return new ActionsAuthorization({
request,
authorizationMode,
authorization: this.security?.authz,
authentication: this.security?.authc,
auditLogger: new ActionsAuthorizationAuditLogger(
this.security?.audit.getLogger(ACTIONS_FEATURE.id)
),
});
};
private getServicesFactory(
getScopedClient: (request: KibanaRequest) => SavedObjectsClientContract,
elasticsearch: ElasticsearchServiceStart
): (request: KibanaRequest) => Services {
2020-05-22 09:08:58 +02:00
return (request) => ({
savedObjectsClient: getScopedClient(request),
scopedClusterClient: elasticsearch.client.asScoped(request).asCurrentUser,
});
}
private createRouteHandlerContext = (
core: CoreSetup<ActionsPluginsStart>,
defaultKibanaIndex: string
): IContextProvider<ActionsRequestHandlerContext, 'actions'> => {
const {
actionTypeRegistry,
isESOCanEncrypt,
preconfiguredActions,
actionExecutor,
instantiateAuthorization,
security,
} = this;
return async function actionsRouteHandlerContext(context, request) {
const [{ savedObjects }, { taskManager }] = await core.getStartServices();
return {
getActionsClient: () => {
if (isESOCanEncrypt !== true) {
throw new Error(
`Unable to create actions client because the Encrypted Saved Objects plugin is missing encryption key. Please set xpack.encryptedSavedObjects.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.`
);
}
return new ActionsClient({
unsecuredSavedObjectsClient: savedObjects.getScopedClient(request, {
excludedWrappers: ['security'],
includedHiddenTypes,
}),
actionTypeRegistry: actionTypeRegistry!,
defaultKibanaIndex,
scopedClusterClient: context.core.elasticsearch.client,
preconfiguredActions,
request,
authorization: instantiateAuthorization(request),
actionExecutor: actionExecutor!,
[Alerting] Change execution of alerts from async to sync (#97311) * added ability to run ephemeral tasks * fixed typing * added typing on plugin * WIP * Fix type issues * Hook up the ephemeral task into the task runner for actions * Tasks can now run independently of one another * Use deferred language * Refactor taskParams slightly * Use Promise.all * Remove deferred logic * Add config options to limit the amount of tasks executing at once * Add ephemeral task monitoring * WIP * Add single test so far * Ensure we log after actions have executed * Remove confusing * 1 * Add logic to ensure we fallback to default enqueueing if the total actions is above the config * Add additional test * Fix tests a bit, ensure we log the alerting:actions-execute right away and the tests should listen for alerts:execute * Better tests * If the queue is at capacity, attempt to execute the ephemeral task as a regular action * Ensure we run ephemeral tasks before to avoid them getting stuck in the queue * Do not handle the promise anymore * Remove unnecessary code * Properly handle errors from ephemeral task lifecycle * moved acitons domain out of alerting and into actions plugin * Remove some tests * Fix TS and test issues * Fix type issues * Fix more type issues * Fix more type issues * Fix jest tests * Fix more jest tests * Off by default * Fix jest tests * Update config for this suite too * Start of telemetry code * Fix types and add missing files * Fix telemetry schema * Fix types * Fix more types * moved load event emission to pollingcycle and added health stats on Ephemeral tasks * Add more telemetry data based on new health metrics for the ephemeral queue * Fix tests and types * Add separate request capacity for ephemeral queue * Fix telemetry schema and add tests for usage collection * track polled tasks by persistence and use in capacity estimation instead of executions * fixed typing * Bump default capacity * added delay metric to ephemeral stats * Fix bad merge * Fix tests * Fix tests * Fix types * Skip failing tests * Exclude ephemeral stats from capacity estimation tests * PR feedback * More PR feedback * PR feedback * Fix merge conflict * Try fixing CI * Fix broken lock file from merge * Match master * Add this back * PR feedback * Change to queue and add test * Disable ephemeral queue in tests * Updated desc * Comment out ephemeral-specific tests tha require the entire test suite to support ephemeral tasks * Add clarifying comment Co-authored-by: Gidi Meir Morris <github@gidi.io> Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-07-20 19:24:24 +02:00
ephemeralExecutionEnqueuer: createEphemeralExecutionEnqueuerFunction({
taskManager,
actionTypeRegistry: actionTypeRegistry!,
isESOCanEncrypt: isESOCanEncrypt!,
preconfiguredActions,
}),
executionEnqueuer: createExecutionEnqueuerFunction({
taskManager,
actionTypeRegistry: actionTypeRegistry!,
isESOCanEncrypt: isESOCanEncrypt!,
preconfiguredActions,
}),
auditLogger: security?.audit.asScoped(request),
});
},
listTypes: actionTypeRegistry!.list.bind(actionTypeRegistry!),
};
};
};
public stop() {
if (this.licenseState) {
this.licenseState.clean();
}
}
}
export function renderActionParameterTemplates<Params extends ActionTypeParams = ActionTypeParams>(
actionTypeRegistry: ActionTypeRegistry | undefined,
actionTypeId: string,
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
actionId: string,
params: Params,
variables: Record<string, unknown>
): Params {
const actionType = actionTypeRegistry?.get(actionTypeId);
if (actionType?.renderParameterTemplates) {
[Alerting] Preconfigured alert history index connector (#94909) * Adding preconfigured alert history index * Adding functions to build alert history document * Adding functions to build alert history document * Moving index template creation to plugin start * Adding unit tests * Adding unit tests * Adding unit tests * Simplifying * Revert "Merge branch 'master' of https://github.com/elastic/kibana into alerting/default-es-index-schema" This reverts commit 957c333aa474e4a65e47a3119e4d60a7f19215fe, reversing changes made to 4b1b78761ea6d26bede52d0785419cfc0ae3d5a0. * Reverting some changes * Reverting some changes * Adding index override * Updating UI with index override * Only allow indexOverride for preconfigured alert history connector * Handling preconfigured connector id clashes * Cleanup * UI unit tests * Fixing default schema shown in UI * Fixing functional tests * Adding functional test * Fixing functional tests * Adding docs and link to docs * Adding config to docker allowlist * Fixing wrong typescript operator * Changing default for config to false * Cleanup * Adding note about index privileges to docs * Fixing i18n * PR fixes * PR fixes * PR fixes * PR fixes - wording * PR fixes * Fixing unit and functional tests * Fixing types check * ES -> Elasticsearch * Moving files * Adding kibana- to beginning of prefix * Namespacing alert data within schema with kibana * Fix i18n * Updating docs * Fixing unit tests * Fixing doc links * Fixing types check * PR fixes Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-04-09 00:18:44 +02:00
return actionType.renderParameterTemplates(params, variables, actionId) as Params;
} else {
return renderMustacheObject(params, variables);
}
}