From c7eb007e81df448565e26bd1c730eee6994f3df8 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Mon, 17 Jun 2019 12:56:44 -0400 Subject: [PATCH 01/13] Initial user guides --- x-pack/plugins/actions/README.md | 158 ++++++++++++++++++++++++++++++ x-pack/plugins/alerting/README.md | 143 +++++++++++++++++++++++++++ 2 files changed, 301 insertions(+) create mode 100644 x-pack/plugins/actions/README.md create mode 100644 x-pack/plugins/alerting/README.md diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md new file mode 100644 index 0000000000000..fad8f1cd1e6b0 --- /dev/null +++ b/x-pack/plugins/actions/README.md @@ -0,0 +1,158 @@ +# Kibana actions + +The Kibana actions plugin provides a common place to execute actions. It supports: + +- Registering types of actions +- List the registered types of actions +- Fire actions +- CRUD on actions w/ encrypted configurations + +## Terminology + +Action Type: A programatically defined integration with another service, with an expected set of configuration and parameters. + +Action: A user-defined configuration that satisfies an action type's expected configuration. + +## Usage + +Before using actions, there needs to be an action type that can handle the type of action you're looking for. For example, before being able to send emails, an email action type must be registered. (see Action types -> Example) + +Once the action type exists, an action saved object must be created before firing. The action saved object will contain which action type to use as well as what configuration to pass in at execution time. These actions are created via the RESTful API. (See Actions -> Create action) + +Once the action saved object exists, the it can now be fired as many times as you like. (See Firing actions) + +## Action types + +Defining an action type contains the following attributes: + +- `id` (string): Unique identifyer for the action type. +- `name` (string): A user friendly name for the action type. +- `unencryptedAttributes` (array): A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available. +- `validate` (optional) + - `params`: (optional) Joi object validation + - `actionTypeConfig` (optional) Joi object validation +- `executor` (function): A function to be called for executing an action. + +Action type executors are provided the following: + +- `services`: + - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. + - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently uses the saved objects repository which bypasses security and user authorization. + - `log`: use this to create server logs. +- `actionTypeConfig`: The decrypted configuration given to an action +- `params`: Parameters for the execution + +### Example + +``` +server.plugins.actions.registerType({ + id: 'my-action', + name: 'My action', + unencryptedAttributes: ['unencryptedAttribute'], + validate: { + params: Joi.object() + .keys({ + param1: Joi.string().required(), + param2: Joi.string().default('value'), + }) + .required(), + actionTypeConfig: Joi.object() + .keys({ + param1: Joi.string().required(), + param2: Joi.string().default('value'), + }) + .required(), + }, + async executor({ actionTypeConfig, params, services }) { + // Some execution code here + }, +}); +``` + +## Actions + +Using an action type requires an action to be created which will contain and encrypt configuration for a given action type. + +### API + +#### `POST /api/action`: Create action + +Payload: + +- `attributes` (object) + - `description` (string) + - `actionTypeId` (string) + - `actionTypeConfig` (object) +- `references` (optional) (array) + - `name` (string) + - `type` (string) + - `id` (string) +- `migrationVersion` (optional) (object) + +#### `DELETE /api/action/{id}`: Delete action + +Params: + +- `id` (string) + +#### `GET /api/action/_find`: Find actions + +Params: + +- `per_page` (optional) (number) +- `page` (optional) (number) +- `search` (optional) (string) +- `default_search_operator` (optional) (string) +- `search_fields` (optional) (array) +- `sort_field` (optional) (string) +- `has_reference` (optional) + - `type` (string) + - `id` (string) +- `fields` (optional) (array) + +#### `GET /api/action/{id}`: Get action + +Params: + +- `id` (string) + +#### `GET /api/action/types` List action types + +#### `PUT /api/action/{id}`: Update action + +Params: + +- `id` (string) + +Payload: + +- `attributes` (object) + - `description` (string) + - `actionTypeConfig` (object) +- `version` (string) +- `references` (optional) (array) + - `name` (string) + - `type` (string) + - `id` (string) + +## Firing actions + +The plugin exposes a fire function that can be used to fire actions. + +### Example + +This example makes action `3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5` fire an email. The action plugin will load the saved object and find what action type to call with `params`. + +``` +server.plugins.actions.fire({ + id: '3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5', + params: { + from: 'example@elastic.co', + to: 'destination@elastic.co', + subject: 'My email subject', + body: 'My email body', + }, + namespace: undefined, // The namespace the action exists within + basePath: undefined, // Usually `request.getBasePath();` +}); +``` diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md new file mode 100644 index 0000000000000..ec554c3038de3 --- /dev/null +++ b/x-pack/plugins/alerting/README.md @@ -0,0 +1,143 @@ +# Kibana alerting + +The Kibana alerting plugin provides a common place to setup alerts. It supports: + +- Registering types of alerts +- List the registered types of alerts +- CRUD on alerts + +## Alert types + +Defining an alert type contains the following attributes: + +- `id` (string): Unique identifier for the alert type. +- `name` (string): A user friendly name for the alert type. +- `validate` (optional) + - `params` (optional): Joi object validation +- `execute` (function): A function to be called for executing an alert. + +Alert type executors are provided the following: + +- `services`: + - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. + - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently uses the saved objects repository which bypasses security and user authorization. + - `log`: use this to create server logs. + - `alertInstanceFactory`: Use to create instances of alert and fire them +- `scheduledRunAt`: The date and time the alert type was supposed to be called +- `previousScheduledRunAt`: The previous date and time the alert type was supposed to be called +- `params`: Parameters for the execution +- `state`: State returned from previous execution + +### Example + +``` +server.plugins.alerting.registerType({ + id: 'my-alert-type', + name: 'My alert type', + validate: { + params: Joi.object() + .keys({ + myParam: Joi.string().required(), + }) + .required(), + }, + async execute({ + scheduledRunAt, + previousScheduledRunAt, + services, + params, + state, + }: AlertExecuteOptions) { + // Pass in parameters, also validated + const { + myParam + } = params; + + // Available services + const { + log, + callCluster, + savedObjectsClient, + alertInstanceFactory, + } = services; + + // Firing actions + alertInstanceFactory('server_1') + .replaceState({ + // Alert instance level state, use getState() for + // previous and persisted values + ... + }) + .fire('default', { + server: 'server_1', + }); + + // Returning updated alert type level state + return { + ... + }; + }, +}); +``` + +## Alerts + +Using an alert type requires an alert to be created which will contain parameters and actions for a given alert type. + +The alerting plugin exposes the following APIs: + +#### `POST /api/alert`: Create alert + +Payload: + +- `alertTypeId` (string) +- `interval` (number) +- `alertTypeParams` (object) +- `actions` (array) + - `group` (string) + - `id` (string) + - `params` (object) + +#### `DELETE /api/alert/{id}`: Delete alert + +Params: + +- `id` (string) + +#### `GET /api/alert/_find`: Find alerts + +Params: + +- `per_page` (optional) (number) +- `page` (optional) (number) +- `search` (optional) (string) +- `default_search_operator` (optional) (string) +- `search_fields` (optional) (array) +- `sort_field` (optional) (string) +- `has_reference` (optional) + - `type` (string) + - `id` (string) +- `fields` (optional) (array) + +#### `GET /api/alert/{id}`: Get alert + +Params: + +- `id` (string) + +#### `GET /api/alert/types`: List alert types + +#### `PUT /api/alert/{id}`: Update alert + +Params: + +- `id` (string) + +Payload: + +- `interval` (number) +- `alertTypeParams` (object) +- `actions` (array) + - `group` (string) + - `id` (string) + - `params` (object) From c3830495efe0a8de86618902c74d2a1cf42df04b Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Mon, 17 Jun 2019 13:07:28 -0400 Subject: [PATCH 02/13] Cleanup --- x-pack/plugins/actions/README.md | 8 ++++---- x-pack/plugins/alerting/README.md | 12 ++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index fad8f1cd1e6b0..8943ab72eef19 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -30,7 +30,7 @@ Defining an action type contains the following attributes: - `unencryptedAttributes` (array): A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available. - `validate` (optional) - `params`: (optional) Joi object validation - - `actionTypeConfig` (optional) Joi object validation + - `config` (optional) Joi object validation - `executor` (function): A function to be called for executing an action. Action type executors are provided the following: @@ -39,7 +39,7 @@ Action type executors are provided the following: - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently uses the saved objects repository which bypasses security and user authorization. - `log`: use this to create server logs. -- `actionTypeConfig`: The decrypted configuration given to an action +- `config`: The decrypted configuration given to an action - `params`: Parameters for the execution ### Example @@ -56,14 +56,14 @@ server.plugins.actions.registerType({ param2: Joi.string().default('value'), }) .required(), - actionTypeConfig: Joi.object() + config: Joi.object() .keys({ param1: Joi.string().required(), param2: Joi.string().default('value'), }) .required(), }, - async executor({ actionTypeConfig, params, services }) { + async executor({ config, params, services }) { // Some execution code here }, }); diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index ec554c3038de3..dd6b108377b4a 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -6,6 +6,18 @@ The Kibana alerting plugin provides a common place to setup alerts. It supports: - List the registered types of alerts - CRUD on alerts +## Terminology + +Alert Type: A function that takes parameters and fires actions to alert instances. + +Alert: A configuration that defines a schedule, an alert type w/ parameters, state information and actions. + +## Usage + +Before using alerts, there needs to be an alert type that can execute the alert on an interval basis. For example, beofre being able to check CPU usage, there needs to be a check CPU usage type of alert. (See Alert types -> Example) + +Once the alert type exists, the RESTful API can be used to create alerts. (See Alerts -> Create) + ## Alert types Defining an alert type contains the following attributes: From 02b078a395777a7b92103160b77a4b4595f86602 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Mon, 17 Jun 2019 13:39:53 -0400 Subject: [PATCH 03/13] Typos, example changes --- x-pack/plugins/actions/README.md | 33 ++++++++++++++++++------------- x-pack/plugins/alerting/README.md | 8 +++++--- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 8943ab72eef19..1d16867153836 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -9,9 +9,9 @@ The Kibana actions plugin provides a common place to execute actions. It support ## Terminology -Action Type: A programatically defined integration with another service, with an expected set of configuration and parameters. +**Action Type**: A programatically defined integration with another service, with an expected set of configuration and parameters. -Action: A user-defined configuration that satisfies an action type's expected configuration. +**Action**: A user-defined configuration that satisfies an action type's expected configuration. ## Usage @@ -19,7 +19,7 @@ Before using actions, there needs to be an action type that can handle the type Once the action type exists, an action saved object must be created before firing. The action saved object will contain which action type to use as well as what configuration to pass in at execution time. These actions are created via the RESTful API. (See Actions -> Create action) -Once the action saved object exists, the it can now be fired as many times as you like. (See Firing actions) +Once the action saved object exists, it can now be fired as many times as you like. (See Firing actions) ## Action types @@ -33,12 +33,12 @@ Defining an action type contains the following attributes: - `config` (optional) Joi object validation - `executor` (function): A function to be called for executing an action. -Action type executors are provided the following: +Action type executors are provided the following as the first argument object: - `services`: - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. - - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently uses the saved objects repository which bypasses security and user authorization. - - `log`: use this to create server logs. + - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens. + - `log`: use this to create server logs. (This is the same function as server.log) - `config`: The decrypted configuration given to an action - `params`: Parameters for the execution @@ -46,25 +46,30 @@ Action type executors are provided the following: ``` server.plugins.actions.registerType({ - id: 'my-action', - name: 'My action', - unencryptedAttributes: ['unencryptedAttribute'], + id: 'smtp', + name: 'Email', + unencryptedAttributes: ['host', 'port'], validate: { params: Joi.object() .keys({ - param1: Joi.string().required(), - param2: Joi.string().default('value'), + to: Joi.array().items(Joi.string()).required(), + from: Joi.string().required(), + subject: Joi.string().required(), + body: Joi.string().required(), }) .required(), config: Joi.object() .keys({ - param1: Joi.string().required(), - param2: Joi.string().default('value'), + host: Joi.string().required(), + port: Joi.number().default(465), + username: Joi.string().required(), + password: Joi.string().required(), }) .required(), }, async executor({ config, params, services }) { - // Some execution code here + const transporter = nodemailer. createTransport(config); + await transporter.sendMail(params); }, }); ``` diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index dd6b108377b4a..98369bc26c886 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -8,9 +8,11 @@ The Kibana alerting plugin provides a common place to setup alerts. It supports: ## Terminology -Alert Type: A function that takes parameters and fires actions to alert instances. +**Alert Type**: A function that takes parameters and fires actions to alert instances. -Alert: A configuration that defines a schedule, an alert type w/ parameters, state information and actions. +**Alert**: A configuration that defines a schedule, an alert type w/ parameters, state information and actions. + +**Alert Instance**: The instances created from the an alert type execution. ## Usage @@ -28,7 +30,7 @@ Defining an alert type contains the following attributes: - `params` (optional): Joi object validation - `execute` (function): A function to be called for executing an alert. -Alert type executors are provided the following: +Alert type executors are provided the following as the first argument object: - `services`: - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. From b0dc72325e588c698808b954fa9b249f0b76e281 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Tue, 18 Jun 2019 08:57:28 -0400 Subject: [PATCH 04/13] Switch to tables, use ordered list for usage --- x-pack/plugins/actions/README.md | 112 +++++++++++++++++------------- x-pack/plugins/alerting/README.md | 95 +++++++++++++------------ 2 files changed, 113 insertions(+), 94 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 1d16867153836..e53b9a9f4749a 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -15,32 +15,40 @@ The Kibana actions plugin provides a common place to execute actions. It support ## Usage -Before using actions, there needs to be an action type that can handle the type of action you're looking for. For example, before being able to send emails, an email action type must be registered. (see Action types -> Example) +1. Create an action type (see action types -> example). +2. Create an action by using the RESTful API (see actions -> create action). +3. Use alerts to fire actions or fire manually (see firing actions). -Once the action type exists, an action saved object must be created before firing. The action saved object will contain which action type to use as well as what configuration to pass in at execution time. These actions are created via the RESTful API. (See Actions -> Create action) +## Action types -Once the action saved object exists, it can now be fired as many times as you like. (See Firing actions) +### Methods -## Action types +**server.plugins.actions.registerType(options)** + +The following table describes the properties of the `options` object. + +|Property|Description|Type| +|---|---|---| +|id|Unique identifier for the action type.|string| +|name|A user friendly name for the action type.|string| +|unencryptedAttributes|A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available.|array of strings| +|validate.params|Joi object validation for the parameters the executor receives.|Joi schema| +|validate.config|Joi object validation for the configuration the executor receives.|Joi schema| +|executor|A function to be called for executing an action. See executor below.|Function| -Defining an action type contains the following attributes: +### Executor -- `id` (string): Unique identifyer for the action type. -- `name` (string): A user friendly name for the action type. -- `unencryptedAttributes` (array): A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available. -- `validate` (optional) - - `params`: (optional) Joi object validation - - `config` (optional) Joi object validation -- `executor` (function): A function to be called for executing an action. +This is the primary function for an action type, whenever the action needs to execute, this function will perform the action. It receives a variety of parameters, the following table describes the properties the executor receives. -Action type executors are provided the following as the first argument object: +**executor(options)** -- `services`: - - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. - - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens. - - `log`: use this to create server logs. (This is the same function as server.log) -- `config`: The decrypted configuration given to an action -- `params`: Parameters for the execution +|Property|Description| +|---|---| +|config|The decrypted configuration given to an action.| +|params|Parameters for the execution.| +|services.callCluster|Use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR.| +|services.savedObjectsClient|Use this to manipulate saved objects. NOTE: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| +|services.log|Use this to create server logs. (This is the same function as server.log)| ### Example @@ -84,66 +92,72 @@ Using an action type requires an action to be created which will contain and enc Payload: -- `attributes` (object) - - `description` (string) - - `actionTypeId` (string) - - `actionTypeConfig` (object) -- `references` (optional) (array) - - `name` (string) - - `type` (string) - - `id` (string) -- `migrationVersion` (optional) (object) +|Property|Description|Type| +|---|---|---| +|attributes.description|A description to reference and search in the future.|string| +|attributes.actionTypeId|The id value of the action type you want to call when the action executes.|string| +|attributes.actionTypeConfig|The configuration the action type expects.|object| +|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.|Array| +|migrationVersion|The version of the most recent migrations. This is the same as `migrationVersion` in the saved objects API, see saved objects API documentation.|object| #### `DELETE /api/action/{id}`: Delete action Params: -- `id` (string) +|Property|Description|Type| +|---|---|---| +|id|The id of the action you're trying to delete.|string| #### `GET /api/action/_find`: Find actions Params: -- `per_page` (optional) (number) -- `page` (optional) (number) -- `search` (optional) (string) -- `default_search_operator` (optional) (string) -- `search_fields` (optional) (array) -- `sort_field` (optional) (string) -- `has_reference` (optional) - - `type` (string) - - `id` (string) -- `fields` (optional) (array) +See saved objects API documentation for find, all the properties are the same except you cannot pass in `type`. #### `GET /api/action/{id}`: Get action Params: -- `id` (string) +|Property|Description|Type| +|---|---|---| +|id|The id of the action you're trying to get.|string| #### `GET /api/action/types` List action types +No parameters. + #### `PUT /api/action/{id}`: Update action Params: -- `id` (string) +|Property|Description|Type| +|---|---|---| +|id|The id of the action you're trying to update.|string| Payload: -- `attributes` (object) - - `description` (string) - - `actionTypeConfig` (object) -- `version` (string) -- `references` (optional) (array) - - `name` (string) - - `type` (string) - - `id` (string) +|Property|Description|Type| +|---|---|---| +|attributes.description|The action description to reference and search in the future.|string| +|attributes.actionTypeConfig|The configuration the action type expects.|object| +|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.|Array| +|version|The document version when read|string| ## Firing actions The plugin exposes a fire function that can be used to fire actions. +**server.plugins.actions.fire(options)** + +The following table describes the properties of the `options` object. + +|Property|Description|Type| +|---|---|---| +|id|The id of the action you want to fire.|string| +|params|The `params` value to give the action type executor|object| +|namespace|The namespace the action exists within|string| +|basePath|The request's basePath value, usually `request.getBasePath()`|string| + ### Example This example makes action `3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5` fire an email. The action plugin will load the saved object and find what action type to call with `params`. diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index 98369bc26c886..a4673922bd14d 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -16,31 +16,39 @@ The Kibana alerting plugin provides a common place to setup alerts. It supports: ## Usage -Before using alerts, there needs to be an alert type that can execute the alert on an interval basis. For example, beofre being able to check CPU usage, there needs to be a check CPU usage type of alert. (See Alert types -> Example) - -Once the alert type exists, the RESTful API can be used to create alerts. (See Alerts -> Create) +1. Create an alert type (see alert types -> example). +2. Create an alert using the RESTful API (see alerts -> create). ## Alert types -Defining an alert type contains the following attributes: +### Methods + +**server.plugins.alerting.registerType(options)** + +The following table describes the properties of the `options` object. -- `id` (string): Unique identifier for the alert type. -- `name` (string): A user friendly name for the alert type. -- `validate` (optional) - - `params` (optional): Joi object validation -- `execute` (function): A function to be called for executing an alert. +|Property|Description|Type| +|---|---|---| +|id|Unique identifier for the alert type.|string| +|name|A user friendly name for the alert type.|string| +|validate.params|Joi object validation for the parameters the executor receives.|Joi schema| +|execute|A function to be called when executing an alert. See executor below.|Function| -Alert type executors are provided the following as the first argument object: +### Executor -- `services`: - - `callCluster`: use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR. - - `savedObjectsClient`: use this to manipulate saved objects. NOTE: This currently uses the saved objects repository which bypasses security and user authorization. - - `log`: use this to create server logs. - - `alertInstanceFactory`: Use to create instances of alert and fire them -- `scheduledRunAt`: The date and time the alert type was supposed to be called -- `previousScheduledRunAt`: The previous date and time the alert type was supposed to be called -- `params`: Parameters for the execution -- `state`: State returned from previous execution +This is the primary function for an alert type, whenever the alert needs to execute, this function will perform the execution. It receives a variety of parameters, the following table describes the properties the executor receives. + +**execute(options)** + +|Property|Description| +|---|---| +|services.callCluster|Use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR.| +|services.savedObjectsClient|Use this to manipulate saved objects. NOTE: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| +|services.log|Use this to create server logs. (This is the same function as server.log)| +|scheduledRunAt|The date and time the alert type was supposed to be called.| +|previousScheduledRunAt|The previous date and time the alert type was supposed to be called.| +|params|Parameters for the execution.| +|state|State returned from previous execution.| ### Example @@ -104,54 +112,51 @@ The alerting plugin exposes the following APIs: Payload: -- `alertTypeId` (string) -- `interval` (number) -- `alertTypeParams` (object) -- `actions` (array) - - `group` (string) - - `id` (string) - - `params` (object) +|Property|Description|Type| +|---|---|---| +|alertTypeId|The id value of the alert type you want to call when the alert is scheduled to execute.|string| +|interval|The interval in milliseconds the alert should execute.|number| +|alertTypeParams|The parameters to pass in to the alert type executor `params` value.|object| +|action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings. The templates have access to `context` and `state` objects.|array| #### `DELETE /api/alert/{id}`: Delete alert Params: -- `id` (string) +|Property|Description|Type| +|---|---|---| +|id|The id of the alert you're trying to delete.|string| #### `GET /api/alert/_find`: Find alerts Params: -- `per_page` (optional) (number) -- `page` (optional) (number) -- `search` (optional) (string) -- `default_search_operator` (optional) (string) -- `search_fields` (optional) (array) -- `sort_field` (optional) (string) -- `has_reference` (optional) - - `type` (string) - - `id` (string) -- `fields` (optional) (array) +See saved objects API documentation for find, all the properties are the same except you cannot pass in `type`. #### `GET /api/alert/{id}`: Get alert Params: -- `id` (string) +|Property|Description|Type| +|---|---|---| +|id|The id of the alert you're trying to get.|string| #### `GET /api/alert/types`: List alert types +No parameters. + #### `PUT /api/alert/{id}`: Update alert Params: -- `id` (string) +|Property|Description|Type| +|---|---|---| +|id|The id of the alert you're trying to update.|string| Payload: -- `interval` (number) -- `alertTypeParams` (object) -- `actions` (array) - - `group` (string) - - `id` (string) - - `params` (object) +|Property|Description|Type| +|---|---|---| +|interval|The interval in milliseconds the alert should execute.|number| +|alertTypeParams|The parameters to pass in to the alert type executor `params` value.|object| +|action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings. The templates have access to `context` and `state` objects.|array| From e601a2e16dc9adae8c29123f57097b82b9c3ec96 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Tue, 18 Jun 2019 09:29:39 -0400 Subject: [PATCH 05/13] Start docs around alert instances and templating --- x-pack/plugins/alerting/README.md | 72 ++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index a4673922bd14d..90d2985954dec 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -117,7 +117,7 @@ Payload: |alertTypeId|The id value of the alert type you want to call when the alert is scheduled to execute.|string| |interval|The interval in milliseconds the alert should execute.|number| |alertTypeParams|The parameters to pass in to the alert type executor `params` value.|object| -|action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings. The templates have access to `context` and `state` objects.|array| +|action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings, see templating actions section for more details.|array| #### `DELETE /api/alert/{id}`: Delete alert @@ -160,3 +160,73 @@ Payload: |interval|The interval in milliseconds the alert should execute.|number| |alertTypeParams|The parameters to pass in to the alert type executor `params` value.|object| |action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings. The templates have access to `context` and `state` objects.|array| + +## Alert instance factory + +**alertInstanceFactory(id)** + +One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and lookups of previous instances with the same id to gather previous state. + +This returns an instance of `AlertInstance`. The alert instance class has the following methods, note that most of these are for internal use but they work as they are described: + +|Method|Description| +|---|---| +|shouldFire()|Function returns `true` or `false` whether the alert instance should fire or not. This value turns to true when `.fire(...)` is called.| +|getFireOptions()|Function returns an object of `actionGroup`, `context` and `state` to use for firing the actions.| +|resetFire()|Reverts a `.fire(...)` call and makes the instance no longer fire.| +|getState()|Get the current state of the alert instance.| +|getMeta()|Get the internal set meta attributes for the alert instance.| +|fire(actionGroup, context)|Called to fire actions.| +|replaceState(state)|Used to replace the current state of the alert instance.| +|replaceMeta(meta)|Function to replace internal meta attributes.| + +## Templating actions + +Each action within an alert contains its mapping of parameters to give an action type. To facilitate the mapping and to avoid having to make alert types aware of the actions, we added a templating system to allow converting content and state into parameters for an action type. + +When an alert instance fires, the first argument is the `group` of actions to fire and the second is the context the alert exposes to templates. We iterate through each action attributes recursively and render templates if they are a string. Templates have access to the `context` and the alert instance's `state`. + +### Examples + +The following code would be within an alert type. As you can see `cpuUsage ` will replace the state of the alert instance and `server` is the context for the alert instance to fire. The difference between the two is `cpuUsage ` will be accessible at the next execution. + +``` +alertInstanceFactory('server_1') + .replaceState({ + cpuUsage: 80, + }) + .fire('default', { + server: 'server_1', + }); +``` + +Below is an example of an alert that takes advantage of templating: + +``` +{ + ... + actions: [ + { + "group": "default", + "id": "3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5", + "params": { + "from": "example@elastic.co", + "to": "destination@elastic.co", + "subject": "A notification about {{context.server}}" + "body": "The server {{context.server}} has a CPU usage of {{state.cpuUsage}}%" + } + } + ] +} +``` + +The templating system will take the alert and alert type as described above and convert the action parameters to the following: + +``` +{ + "from": "example@elastic.co", + "to": "destination@elastic.co", + "subject": "A notification about server_1" + "body": "The server server_1 has a CPU usage of 80%" +} +``` From 9572715c275579ab56f1684cd9087ef71e1fe0dd Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Tue, 18 Jun 2019 17:23:11 -0400 Subject: [PATCH 06/13] Documentation changes --- x-pack/plugins/actions/README.md | 46 ++++++++--------- x-pack/plugins/alerting/README.md | 83 +++++++++++++++---------------- 2 files changed, 62 insertions(+), 67 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index e53b9a9f4749a..4bdcb65d9b6da 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -15,7 +15,7 @@ The Kibana actions plugin provides a common place to execute actions. It support ## Usage -1. Create an action type (see action types -> example). +1. Develop and register an action type (see action types -> example). 2. Create an action by using the RESTful API (see actions -> create action). 3. Use alerts to fire actions or fire manually (see firing actions). @@ -29,12 +29,12 @@ The following table describes the properties of the `options` object. |Property|Description|Type| |---|---|---| -|id|Unique identifier for the action type.|string| -|name|A user friendly name for the action type.|string| -|unencryptedAttributes|A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available.|array of strings| -|validate.params|Joi object validation for the parameters the executor receives.|Joi schema| -|validate.config|Joi object validation for the configuration the executor receives.|Joi schema| -|executor|A function to be called for executing an action. See executor below.|Function| +|id|Unique identifier for the action type. For convention, ids starting with `.` are reserved for built in action types. We recommend using a convention like `.mySpecialAction` for your action types.|string| +|name|A user friendly name for the action type. These will be displayed in dropdowns when chosing action types.|string| +|unencryptedAttributes|A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available. These attributes will also be readable / displayed when it comes to a table / edit screen.|array of strings| +|validate.params|When developing an action type, it needs to accept parameters to know what to do with the action. (Example to, from, subject, body of an email). Use joi object validation if you would like `params` to be validated before being passed to the executor.|Joi schema| +|validate.config|Similar to params, a config is required when creating an action. (for example host, port, username, password of an email server). Use the joi object validation if you would like the config to be validated before being passed to the executor.|Joi schema| +|executor|This is where the code of an action type lives. This is a function to be called for executing an action by either alerting or manually by using the exposed function by the plugin (see firing actions). For full details, see executor section below.|Function| ### Executor @@ -44,11 +44,11 @@ This is the primary function for an action type, whenever the action needs to ex |Property|Description| |---|---| -|config|The decrypted configuration given to an action.| -|params|Parameters for the execution.| -|services.callCluster|Use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR.| -|services.savedObjectsClient|Use this to manipulate saved objects. NOTE: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| -|services.log|Use this to create server logs. (This is the same function as server.log)| +|config|The decrypted configuration given to an action. This comes from the action saved object which is partially or fully encrypted within the data store. If you would like to validate the config before being passed to the executor, define `validate.config` within the action type.| +|params|Parameters for the execution. These will be given at fire time by either an alert or manually provided when calling the plugin provided fire function.| +|services.callCluster(path, opts)|Use this to do elasticsearch queries on the cluster Kibana connects to. This function is the same as any other `callCluster` in Kibana.

**NOTE**: This currently authenticates as the Kibana internal user, this will change in a future PR.| +|services.savedObjectsClient|This is an instance of the saved objects client. This provides the ability to do CRUD on any saved objects within the same space the alert lives in.

**NOTE**: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| +|services.log(tags, [data], [timestamp])|Use this to create server logs. (This is the same function as server.log)| ### Example @@ -94,11 +94,11 @@ Payload: |Property|Description|Type| |---|---|---| -|attributes.description|A description to reference and search in the future.|string| +|attributes.description|A description to reference and search in the future. This value will be used to populate dropdowns.|string| |attributes.actionTypeId|The id value of the action type you want to call when the action executes.|string| -|attributes.actionTypeConfig|The configuration the action type expects.|object| -|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.|Array| -|migrationVersion|The version of the most recent migrations. This is the same as `migrationVersion` in the saved objects API, see saved objects API documentation.|object| +|attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate agains the action type if config validation is defined.|object| +|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|Array| +|migrationVersion|The version of the most recent migrations. This is the same as `migrationVersion` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|object| #### `DELETE /api/action/{id}`: Delete action @@ -138,9 +138,9 @@ Payload: |Property|Description|Type| |---|---|---| -|attributes.description|The action description to reference and search in the future.|string| -|attributes.actionTypeConfig|The configuration the action type expects.|object| -|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.|Array| +|attributes.description|A description to reference and search in the future. This value will be used to populate dropdowns.|string| +|attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate agains the action type if config validation is defined.|object| +|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|Array| |version|The document version when read|string| ## Firing actions @@ -154,9 +154,9 @@ The following table describes the properties of the `options` object. |Property|Description|Type| |---|---|---| |id|The id of the action you want to fire.|string| -|params|The `params` value to give the action type executor|object| -|namespace|The namespace the action exists within|string| -|basePath|The request's basePath value, usually `request.getBasePath()`|string| +|params|The `params` value to give the action type executor.|object| +|namespace|The saved object namespace the action exists within.|string| +|basePath|This is a temporary parameter, but we need to capture and track the value of `request.getBasePath()` until future changes are made.

In most cases this can be `undefined` unless you need cross spaces support.|string| ### Example @@ -172,6 +172,6 @@ server.plugins.actions.fire({ body: 'My email body', }, namespace: undefined, // The namespace the action exists within - basePath: undefined, // Usually `request.getBasePath();` + basePath: undefined, // Usually `request.getBasePath();` or `undefined` }); ``` diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index 90d2985954dec..b4e70eec3c0a7 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -12,11 +12,11 @@ The Kibana alerting plugin provides a common place to setup alerts. It supports: **Alert**: A configuration that defines a schedule, an alert type w/ parameters, state information and actions. -**Alert Instance**: The instances created from the an alert type execution. +**Alert Instance**: The instance(s) created from an alert type execution. ## Usage -1. Create an alert type (see alert types -> example). +1. Develop and register an alert type (see alert types -> example). 2. Create an alert using the RESTful API (see alerts -> create). ## Alert types @@ -29,10 +29,10 @@ The following table describes the properties of the `options` object. |Property|Description|Type| |---|---|---| -|id|Unique identifier for the alert type.|string| -|name|A user friendly name for the alert type.|string| -|validate.params|Joi object validation for the parameters the executor receives.|Joi schema| -|execute|A function to be called when executing an alert. See executor below.|Function| +|id|Unique identifier for the alert type. For convention purposes, ids starting with `.` are reserved for built in alert types. We recommend using a convention like `.mySpecialAlert` for your alert types to avoid conflicting with another plugin.|string| +|name|A user friendly name for the alert type. These will be displayed in dropdowns when chosing alert types.|string| +|validate.params|When developing an alert type, you can choose to accept a series of parameters. You may also have the parameters validated before they are passed to the `execute` function or created as an alert saved object. In order to do this, provide a joi schema that we will use to validate the `params` attribute.|Joi schema| +|execute|This is where the code of the alert type lives. This is a function to be called when executing an alert on an interval basis. For full details, see executor section below.|Function| ### Executor @@ -42,13 +42,13 @@ This is the primary function for an alert type, whenever the alert needs to exec |Property|Description| |---|---| -|services.callCluster|Use this to do elasticsearch queries on the cluster Kibana connects to. NOTE: This currently authenticates as the Kibana internal user, this will change in a future PR.| -|services.savedObjectsClient|Use this to manipulate saved objects. NOTE: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| -|services.log|Use this to create server logs. (This is the same function as server.log)| -|scheduledRunAt|The date and time the alert type was supposed to be called.| -|previousScheduledRunAt|The previous date and time the alert type was supposed to be called.| -|params|Parameters for the execution.| -|state|State returned from previous execution.| +|services.callCluster(path, opts)|Use this to do elasticsearch queries on the cluster Kibana connects to. This function is the same as any other `callCluster` in Kibana.

**NOTE**: This currently authenticates as the Kibana internal user, this will change in a future PR.| +|services.savedObjectsClient|This is an instance of the saved objects client. This provides the ability to do CRUD on any saved objects within the same space the alert lives in.

**NOTE**: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| +|services.log(tags, [data], [timestamp])|Use this to create server logs. (This is the same function as server.log)| +|scheduledRunAt|The date and time the alert type execution was scheduled to be called.| +|previousScheduledRunAt|The previous date and time the alert type was scheduled to be called.| +|params|Parameters for the execution. This is where the parameters you require will be passed in. (example threshold). Use alert type validation to ensure values are set before execution.| +|state|State returned from previous execution. This is the alert level state, what is returned by the executor will be serialized and provided here at the next execution.| ### Example @@ -69,21 +69,8 @@ server.plugins.alerting.registerType({ services, params, state, - }: AlertExecuteOptions) { - // Pass in parameters, also validated - const { - myParam - } = params; - - // Available services - const { - log, - callCluster, - savedObjectsClient, - alertInstanceFactory, - } = services; - - // Firing actions + }: AlertExecuteOptions) { + // Use this example to fire a single action alertInstanceFactory('server_1') .replaceState({ // Alert instance level state, use getState() for @@ -94,6 +81,17 @@ server.plugins.alerting.registerType({ server: 'server_1', }); + // Use this example to fire multiple actions + // This scenario allows a single query and "fan-off" zero, one or many alerts based on the results + for (const server of ['server_1', 'server_2', 'server_3']) { + alertInstanceFactory(server) + .replaceState({ + // State specific to "server_x" + ... + }) + .fire('default', { server }); + } + // Returning updated alert type level state return { ... @@ -106,7 +104,7 @@ server.plugins.alerting.registerType({ Using an alert type requires an alert to be created which will contain parameters and actions for a given alert type. -The alerting plugin exposes the following APIs: +### RESTful API #### `POST /api/alert`: Create alert @@ -116,8 +114,8 @@ Payload: |---|---|---| |alertTypeId|The id value of the alert type you want to call when the alert is scheduled to execute.|string| |interval|The interval in milliseconds the alert should execute.|number| -|alertTypeParams|The parameters to pass in to the alert type executor `params` value.|object| -|action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings, see templating actions section for more details.|array| +|alertTypeParams|The parameters to pass in to the alert type executor `params` value. This will also validate against the alert type params validator if defined.|object| +|actions|Array of the following:
- `group` (string): We support grouping actions in the scenario of escalations or different types of alert instances. If you don't need this, feel free to use `default` as a value.
- `id` (string): The id of the action saved object to fire.
- `params` (object): There map to the `params` the action type will receive. In order to help apply context to strings, we handle them as mustache templates and pass in a default set of context. (see templating actions).|array| #### `DELETE /api/alert/{id}`: Delete alert @@ -158,33 +156,28 @@ Payload: |Property|Description|Type| |---|---|---| |interval|The interval in milliseconds the alert should execute.|number| -|alertTypeParams|The parameters to pass in to the alert type executor `params` value.|object| -|action|An array of `group` (string), `id` (string) and params (object) to fire whenever the alert fires. The group allows the alert type fire fire different groups of actions. For example `warning` and `severe`. The id is the id of the action saved object to use. The params are the `params` value the action type expects. This uses mustache templates recursively on strings. The templates have access to `context` and `state` objects.|array| +|alertTypeParams|The parameters to pass in to the alert type executor `params` value. This will also validate against the alert type params validator if defined.|object| +|actions|Array of the following:
- `group` (string): We support grouping actions in the scenario of escalations or different types of alert instances. If you don't need this, feel free to use `default` as a value.
- `id` (string): The id of the action saved object to fire.
- `params` (object): There map to the `params` the action type will receive. In order to help apply context to strings, we handle them as mustache templates and pass in a default set of context. (see templating actions).|array| ## Alert instance factory **alertInstanceFactory(id)** -One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and lookups of previous instances with the same id to gather previous state. +One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to fire actions. These instances support state persisting between alert type execution but will clear out once the alert instance stops firing. -This returns an instance of `AlertInstance`. The alert instance class has the following methods, note that most of these are for internal use but they work as they are described: +This factory returns an instance of `AlertInstance`. The alert instance class has the following methods, note that we have removed the methods that you shouldn't touch. |Method|Description| |---|---| -|shouldFire()|Function returns `true` or `false` whether the alert instance should fire or not. This value turns to true when `.fire(...)` is called.| -|getFireOptions()|Function returns an object of `actionGroup`, `context` and `state` to use for firing the actions.| -|resetFire()|Reverts a `.fire(...)` call and makes the instance no longer fire.| |getState()|Get the current state of the alert instance.| -|getMeta()|Get the internal set meta attributes for the alert instance.| -|fire(actionGroup, context)|Called to fire actions.| -|replaceState(state)|Used to replace the current state of the alert instance.| -|replaceMeta(meta)|Function to replace internal meta attributes.| +|fire(actionGroup, context)|Called to fire actions. The group relates to the group of alert `actions` to fire and the context will be used for templating purposes.| +|replaceState(state)|Used to replace the current state of the alert instance. This doesn't work like react, the entire state must be provided. Use this feature as you see fit. The state that is set will persist between alert type executions whenever you re-create an alert instance with the same id. The instance state will be erased when fire isn't called during an execution.| ## Templating actions -Each action within an alert contains its mapping of parameters to give an action type. To facilitate the mapping and to avoid having to make alert types aware of the actions, we added a templating system to allow converting content and state into parameters for an action type. +There needs to be a way to map alert context into action parameters. For this, we started off by adding template support. Any string within the `params` of an alert saved object's `actions` will be processed as a template and can inject context or state values. -When an alert instance fires, the first argument is the `group` of actions to fire and the second is the context the alert exposes to templates. We iterate through each action attributes recursively and render templates if they are a string. Templates have access to the `context` and the alert instance's `state`. +When an alert instance fires, the first argument is the `group` of actions to fire and the second is the context the alert exposes to templates. We iterate through each action attributes recursively and render templates if they are a string. Templates have access to the `context` (provided by second argument of `.fire(...)` on an alert instance) and the alert instance's `state` (provided by the most recent `replaceState` call on an alert instance). ### Examples @@ -230,3 +223,5 @@ The templating system will take the alert and alert type as described above and "body": "The server server_1 has a CPU usage of 80%" } ``` + +There are limitations that we are aware of using only templates, we are gathering feedback and use cases for these. (for example passing an array of strings to an action). From af7b104980e6a19efcb81cf371a3ac6f29eb9771 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Wed, 19 Jun 2019 07:44:40 -0400 Subject: [PATCH 07/13] Some adjustments --- x-pack/plugins/actions/README.md | 4 ++-- x-pack/plugins/alerting/README.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 4bdcb65d9b6da..9d6eff6f52e78 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -34,7 +34,7 @@ The following table describes the properties of the `options` object. |unencryptedAttributes|A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available. These attributes will also be readable / displayed when it comes to a table / edit screen.|array of strings| |validate.params|When developing an action type, it needs to accept parameters to know what to do with the action. (Example to, from, subject, body of an email). Use joi object validation if you would like `params` to be validated before being passed to the executor.|Joi schema| |validate.config|Similar to params, a config is required when creating an action. (for example host, port, username, password of an email server). Use the joi object validation if you would like the config to be validated before being passed to the executor.|Joi schema| -|executor|This is where the code of an action type lives. This is a function to be called for executing an action by either alerting or manually by using the exposed function by the plugin (see firing actions). For full details, see executor section below.|Function| +|executor|This is where the code of an action type lives. This is a function gets called for executing an action from either alerting or manually by using the exposed function (see firing actions). For full details, see executor section below.|Function| ### Executor @@ -96,7 +96,7 @@ Payload: |---|---|---| |attributes.description|A description to reference and search in the future. This value will be used to populate dropdowns.|string| |attributes.actionTypeId|The id value of the action type you want to call when the action executes.|string| -|attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate agains the action type if config validation is defined.|object| +|attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate against the action type if config validation is defined.|object| |references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|Array| |migrationVersion|The version of the most recent migrations. This is the same as `migrationVersion` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|object| diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index b4e70eec3c0a7..51ad2ccaf2053 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -115,7 +115,7 @@ Payload: |alertTypeId|The id value of the alert type you want to call when the alert is scheduled to execute.|string| |interval|The interval in milliseconds the alert should execute.|number| |alertTypeParams|The parameters to pass in to the alert type executor `params` value. This will also validate against the alert type params validator if defined.|object| -|actions|Array of the following:
- `group` (string): We support grouping actions in the scenario of escalations or different types of alert instances. If you don't need this, feel free to use `default` as a value.
- `id` (string): The id of the action saved object to fire.
- `params` (object): There map to the `params` the action type will receive. In order to help apply context to strings, we handle them as mustache templates and pass in a default set of context. (see templating actions).|array| +|actions|Array of the following:
- `group` (string): We support grouping actions in the scenario of escalations or different types of alert instances. If you don't need this, feel free to use `default` as a value.
- `id` (string): The id of the action saved object to fire.
- `params` (object): The map to the `params` the action type will receive. In order to help apply context to strings, we handle them as mustache templates and pass in a default set of context. (see templating actions).|array| #### `DELETE /api/alert/{id}`: Delete alert @@ -170,14 +170,14 @@ This factory returns an instance of `AlertInstance`. The alert instance class ha |Method|Description| |---|---| |getState()|Get the current state of the alert instance.| -|fire(actionGroup, context)|Called to fire actions. The group relates to the group of alert `actions` to fire and the context will be used for templating purposes.| +|fire(actionGroup, context)|Called to fire actions. The actionGroup relates to the group of alert `actions` to fire and the context will be used for templating purposes. This should only be called once per alert instance.| |replaceState(state)|Used to replace the current state of the alert instance. This doesn't work like react, the entire state must be provided. Use this feature as you see fit. The state that is set will persist between alert type executions whenever you re-create an alert instance with the same id. The instance state will be erased when fire isn't called during an execution.| ## Templating actions There needs to be a way to map alert context into action parameters. For this, we started off by adding template support. Any string within the `params` of an alert saved object's `actions` will be processed as a template and can inject context or state values. -When an alert instance fires, the first argument is the `group` of actions to fire and the second is the context the alert exposes to templates. We iterate through each action attributes recursively and render templates if they are a string. Templates have access to the `context` (provided by second argument of `.fire(...)` on an alert instance) and the alert instance's `state` (provided by the most recent `replaceState` call on an alert instance). +When an alert instance fires, the first argument is the `group` of actions to fire and the second is the context the alert exposes to templates. We iterate through each action params attributes recursively and render templates if they are a string. Templates have access to the `context` (provided by second argument of `.fire(...)` on an alert instance) and the alert instance's `state` (provided by the most recent `replaceState` call on an alert instance). ### Examples From 64b246d614317d8c6dc23666189602a6bc29b65a Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Wed, 19 Jun 2019 14:21:19 -0400 Subject: [PATCH 08/13] Apply PR feedback --- x-pack/plugins/actions/README.md | 2 +- x-pack/plugins/alerting/README.md | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 9d6eff6f52e78..650fb6243a16c 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -167,7 +167,7 @@ server.plugins.actions.fire({ id: '3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5', params: { from: 'example@elastic.co', - to: 'destination@elastic.co', + to: ['destination@elastic.co'], subject: 'My email subject', body: 'My email body', }, diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index 51ad2ccaf2053..07ba556fb1072 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -70,13 +70,15 @@ server.plugins.alerting.registerType({ params, state, }: AlertExecuteOptions) { - // Use this example to fire a single action - alertInstanceFactory('server_1') + // Use this example to fire a single action, server_1 is a unique identifier of the server + // the instance is about. This will be used to make `getState()` return previous state on matching identifiers. + services.alertInstanceFactory('server_1') .replaceState({ // Alert instance level state, use getState() for // previous and persisted values ... }) + // 'default' refers to a group of actions to fire, see 'actions' in create alert section .fire('default', { server: 'server_1', }); @@ -84,7 +86,7 @@ server.plugins.alerting.registerType({ // Use this example to fire multiple actions // This scenario allows a single query and "fan-off" zero, one or many alerts based on the results for (const server of ['server_1', 'server_2', 'server_3']) { - alertInstanceFactory(server) + services.alertInstanceFactory(server) .replaceState({ // State specific to "server_x" ... @@ -163,7 +165,7 @@ Payload: **alertInstanceFactory(id)** -One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to fire actions. These instances support state persisting between alert type execution but will clear out once the alert instance stops firing. +One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to fire actions. The id you give to the alert instance factory is a unique identifyer to the alert instance (ex: server identifier if the instance is about the server). The instance factory will use this identifier to retrieve state of previous instances with the same id. These instances support state persisting between alert type execution but will clear out once the alert instance stops firing. This factory returns an instance of `AlertInstance`. The alert instance class has the following methods, note that we have removed the methods that you shouldn't touch. @@ -204,7 +206,7 @@ Below is an example of an alert that takes advantage of templating: "id": "3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5", "params": { "from": "example@elastic.co", - "to": "destination@elastic.co", + "to": ["destination@elastic.co"], "subject": "A notification about {{context.server}}" "body": "The server {{context.server}} has a CPU usage of {{state.cpuUsage}}%" } @@ -218,7 +220,7 @@ The templating system will take the alert and alert type as described above and ``` { "from": "example@elastic.co", - "to": "destination@elastic.co", + "to": ["destination@elastic.co"], "subject": "A notification about server_1" "body": "The server server_1 has a CPU usage of 80%" } From 5918aa6dbe2434c03680859fe9d2ca8e263ab419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20C=C3=B4t=C3=A9?= Date: Wed, 19 Jun 2019 20:18:05 -0400 Subject: [PATCH 09/13] Apply suggestions from code review Co-Authored-By: gchaps <33642766+gchaps@users.noreply.github.com> --- x-pack/plugins/actions/README.md | 28 ++++++++++++++-------------- x-pack/plugins/alerting/README.md | 24 ++++++++++++------------ 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 650fb6243a16c..1755ca0406714 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -30,24 +30,24 @@ The following table describes the properties of the `options` object. |Property|Description|Type| |---|---|---| |id|Unique identifier for the action type. For convention, ids starting with `.` are reserved for built in action types. We recommend using a convention like `.mySpecialAction` for your action types.|string| -|name|A user friendly name for the action type. These will be displayed in dropdowns when chosing action types.|string| -|unencryptedAttributes|A list of opt-out attributes that don't need to be encrypted, these attributes won't need to be re-entered on import / export when the feature becomes available. These attributes will also be readable / displayed when it comes to a table / edit screen.|array of strings| +|name|A user-friendly name for the action type. These will be displayed in dropdowns when chosing action types.|string| +|unencryptedAttributes|A list of opt-out attributes that don't need to be encrypted. These attributes won't need to be re-entered on import / export when the feature becomes available. These attributes will also be readable / displayed when it comes to a table / edit screen.|array of strings| |validate.params|When developing an action type, it needs to accept parameters to know what to do with the action. (Example to, from, subject, body of an email). Use joi object validation if you would like `params` to be validated before being passed to the executor.|Joi schema| -|validate.config|Similar to params, a config is required when creating an action. (for example host, port, username, password of an email server). Use the joi object validation if you would like the config to be validated before being passed to the executor.|Joi schema| +|validate.config|Similar to params, a config is required when creating an action (for example host, port, username, and password of an email server). Use the joi object validation if you would like the config to be validated before being passed to the executor.|Joi schema| |executor|This is where the code of an action type lives. This is a function gets called for executing an action from either alerting or manually by using the exposed function (see firing actions). For full details, see executor section below.|Function| ### Executor -This is the primary function for an action type, whenever the action needs to execute, this function will perform the action. It receives a variety of parameters, the following table describes the properties the executor receives. +This is the primary function for an action type. Whenever the action needs to execute, this function will perform the action. It receives a variety of parameters. The following table describes the properties that the executor receives. **executor(options)** |Property|Description| |---|---| -|config|The decrypted configuration given to an action. This comes from the action saved object which is partially or fully encrypted within the data store. If you would like to validate the config before being passed to the executor, define `validate.config` within the action type.| +|config|The decrypted configuration given to an action. This comes from the action saved object that is partially or fully encrypted within the data store. If you would like to validate the config before being passed to the executor, define `validate.config` within the action type.| |params|Parameters for the execution. These will be given at fire time by either an alert or manually provided when calling the plugin provided fire function.| -|services.callCluster(path, opts)|Use this to do elasticsearch queries on the cluster Kibana connects to. This function is the same as any other `callCluster` in Kibana.

**NOTE**: This currently authenticates as the Kibana internal user, this will change in a future PR.| -|services.savedObjectsClient|This is an instance of the saved objects client. This provides the ability to do CRUD on any saved objects within the same space the alert lives in.

**NOTE**: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| +|services.callCluster(path, opts)|Use this to do Elasticsearch queries on the cluster Kibana connects to. This function is the same as any other `callCluster` in Kibana.

**NOTE**: This currently authenticates as the Kibana internal user, but will change in a future PR.| +|services.savedObjectsClient|This is an instance of the saved objects client. This provides the ability to do CRUD on any saved objects within the same space the alert lives in.

**NOTE**: This currently only works when security is disabled. A future PR will add support for enabling security using Elasticsearch API tokens.| |services.log(tags, [data], [timestamp])|Use this to create server logs. (This is the same function as server.log)| ### Example @@ -84,7 +84,7 @@ server.plugins.actions.registerType({ ## Actions -Using an action type requires an action to be created which will contain and encrypt configuration for a given action type. +Using an action type requires an action to be created that will contain and encrypt configuration for a given action type. ### API @@ -97,8 +97,8 @@ Payload: |attributes.description|A description to reference and search in the future. This value will be used to populate dropdowns.|string| |attributes.actionTypeId|The id value of the action type you want to call when the action executes.|string| |attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate against the action type if config validation is defined.|object| -|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|Array| -|migrationVersion|The version of the most recent migrations. This is the same as `migrationVersion` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|object| +|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API. See the saved objects API documentation.

In most cases, you can leave this empty.|Array| +|migrationVersion|The version of the most recent migrations. This is the same as `migrationVersion` in the saved objects API. See the saved objects API documentation.

In most cases, you can leave this empty.|object| #### `DELETE /api/action/{id}`: Delete action @@ -112,7 +112,7 @@ Params: Params: -See saved objects API documentation for find, all the properties are the same except you cannot pass in `type`. +See the saved objects API documentation for find. All the properties are the same except that you cannot pass in `type`. #### `GET /api/action/{id}`: Get action @@ -139,13 +139,13 @@ Payload: |Property|Description|Type| |---|---|---| |attributes.description|A description to reference and search in the future. This value will be used to populate dropdowns.|string| -|attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate agains the action type if config validation is defined.|object| -|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API, see saved objects API documentation.

In most cases you can leave this empty.|Array| +|attributes.actionTypeConfig|The configuration the action type expects. See related action type to see what attributes is expected. This will also validate against the action type if config validation is defined.|object| +|references|An array of `name`, `type` and `id`. This is the same as `references` in the saved objects API. See the saved objects API documentation.

In most cases, you can leave this empty.|Array| |version|The document version when read|string| ## Firing actions -The plugin exposes a fire function that can be used to fire actions. +The plugin exposes a fire function that you can use to fire actions. **server.plugins.actions.fire(options)** diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index 07ba556fb1072..ead9626c63d58 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -1,10 +1,10 @@ # Kibana alerting -The Kibana alerting plugin provides a common place to setup alerts. It supports: +The Kibana alerting plugin provides a common place to set up alerts. You can: -- Registering types of alerts -- List the registered types of alerts -- CRUD on alerts +- Register types of alerts +- List the types of registered alerts +- Perform CRUD actions on alerts ## Terminology @@ -30,25 +30,25 @@ The following table describes the properties of the `options` object. |Property|Description|Type| |---|---|---| |id|Unique identifier for the alert type. For convention purposes, ids starting with `.` are reserved for built in alert types. We recommend using a convention like `.mySpecialAlert` for your alert types to avoid conflicting with another plugin.|string| -|name|A user friendly name for the alert type. These will be displayed in dropdowns when chosing alert types.|string| +|name|A user-friendly name for the alert type. These will be displayed in dropdowns when choosing alert types.|string| |validate.params|When developing an alert type, you can choose to accept a series of parameters. You may also have the parameters validated before they are passed to the `execute` function or created as an alert saved object. In order to do this, provide a joi schema that we will use to validate the `params` attribute.|Joi schema| |execute|This is where the code of the alert type lives. This is a function to be called when executing an alert on an interval basis. For full details, see executor section below.|Function| ### Executor -This is the primary function for an alert type, whenever the alert needs to execute, this function will perform the execution. It receives a variety of parameters, the following table describes the properties the executor receives. +This is the primary function for an alert type. Whenever the alert needs to execute, this function will perform the execution. It receives a variety of parameters. The following table describes the properties the executor receives. **execute(options)** |Property|Description| |---|---| -|services.callCluster(path, opts)|Use this to do elasticsearch queries on the cluster Kibana connects to. This function is the same as any other `callCluster` in Kibana.

**NOTE**: This currently authenticates as the Kibana internal user, this will change in a future PR.| +|services.callCluster(path, opts)|Use this to do Elasticsearch queries on the cluster Kibana connects to. This function is the same as any other `callCluster` in Kibana.

**NOTE**: This currently authenticates as the Kibana internal user, but will change in a future PR.| |services.savedObjectsClient|This is an instance of the saved objects client. This provides the ability to do CRUD on any saved objects within the same space the alert lives in.

**NOTE**: This currently only works when security is disabled. A future PR will add support for enabled security using Elasticsearch API tokens.| |services.log(tags, [data], [timestamp])|Use this to create server logs. (This is the same function as server.log)| |scheduledRunAt|The date and time the alert type execution was scheduled to be called.| |previousScheduledRunAt|The previous date and time the alert type was scheduled to be called.| |params|Parameters for the execution. This is where the parameters you require will be passed in. (example threshold). Use alert type validation to ensure values are set before execution.| -|state|State returned from previous execution. This is the alert level state, what is returned by the executor will be serialized and provided here at the next execution.| +|state|State returned from previous execution. This is the alert level state. What the executor returns will be serialized and provided here at the next execution.| ### Example @@ -104,7 +104,7 @@ server.plugins.alerting.registerType({ ## Alerts -Using an alert type requires an alert to be created which will contain parameters and actions for a given alert type. +Using an alert type requires you to create an alert that will contain parameters and actions for a given alert type. ### RESTful API @@ -131,7 +131,7 @@ Params: Params: -See saved objects API documentation for find, all the properties are the same except you cannot pass in `type`. +See the saved objects API documentation for find. All the properties are the same except you cannot pass in `type`. #### `GET /api/alert/{id}`: Get alert @@ -165,7 +165,7 @@ Payload: **alertInstanceFactory(id)** -One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to fire actions. The id you give to the alert instance factory is a unique identifyer to the alert instance (ex: server identifier if the instance is about the server). The instance factory will use this identifier to retrieve state of previous instances with the same id. These instances support state persisting between alert type execution but will clear out once the alert instance stops firing. +One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to fire actions. The id you give to the alert instance factory is a unique identifier to the alert instance (ex: server identifier if the instance is about the server). The instance factory will use this identifier to retrieve the state of previous instances with the same id. These instances support state persisting between alert type execution, but will clear out once the alert instance stops firing. This factory returns an instance of `AlertInstance`. The alert instance class has the following methods, note that we have removed the methods that you shouldn't touch. @@ -226,4 +226,4 @@ The templating system will take the alert and alert type as described above and } ``` -There are limitations that we are aware of using only templates, we are gathering feedback and use cases for these. (for example passing an array of strings to an action). +There are limitations that we are aware of using only templates, and we are gathering feedback and use cases for these. (for example passing an array of strings to an action). From 7c8af16bae946579c7af7c4b5f73915daa01a498 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Wed, 19 Jun 2019 20:27:20 -0400 Subject: [PATCH 10/13] PR feedback pt2 --- x-pack/plugins/actions/README.md | 18 +++++++++--------- x-pack/plugins/alerting/README.md | 6 ++---- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 1755ca0406714..6b5bbe44c0248 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -1,11 +1,11 @@ # Kibana actions -The Kibana actions plugin provides a common place to execute actions. It supports: +The Kibana actions plugin provides a common place to execute actions. You can: -- Registering types of actions -- List the registered types of actions -- Fire actions -- CRUD on actions w/ encrypted configurations +- Register an action type +- View a list of registered types +- Fire an action either manually or by using an alert +- Perform CRUD on actions with encrypted configurations ## Terminology @@ -52,6 +52,8 @@ This is the primary function for an action type. Whenever the action needs to ex ### Example +Below is an example email action type. The attributes `host` and `port` are configured to be unencrypted by using the `unencryptedAttributes` attribute. + ``` server.plugins.actions.registerType({ id: 'smtp', @@ -82,11 +84,9 @@ server.plugins.actions.registerType({ }); ``` -## Actions - -Using an action type requires an action to be created that will contain and encrypt configuration for a given action type. +## RESTful API -### API +Using an action type requires an action to be created that will contain and encrypt configuration for a given action type. See below for CRUD operations using the API. #### `POST /api/action`: Create action diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index ead9626c63d58..f9d5102eb825d 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -102,11 +102,9 @@ server.plugins.alerting.registerType({ }); ``` -## Alerts +## RESTful API -Using an alert type requires you to create an alert that will contain parameters and actions for a given alert type. - -### RESTful API +Using an alert type requires you to create an alert that will contain parameters and actions for a given alert type. See below for CRUD operations using the API. #### `POST /api/alert`: Create alert From 349010c76a0144979a15b49d7695f854076908ec Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Thu, 20 Jun 2019 09:59:02 -0400 Subject: [PATCH 11/13] Provide better examples for alert types --- x-pack/plugins/alerting/README.md | 160 +++++++++++++++++++++--------- 1 file changed, 115 insertions(+), 45 deletions(-) diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index f9d5102eb825d..0eb2360baa5ec 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -52,53 +52,123 @@ This is the primary function for an alert type. Whenever the alert needs to exec ### Example +This example receives server and threshold as parameters. It will read the CPU usage of the server and fire actions if the reading is greater than the threshold. + ``` server.plugins.alerting.registerType({ - id: 'my-alert-type', - name: 'My alert type', - validate: { - params: Joi.object() - .keys({ - myParam: Joi.string().required(), - }) - .required(), - }, - async execute({ - scheduledRunAt, - previousScheduledRunAt, - services, - params, - state, - }: AlertExecuteOptions) { - // Use this example to fire a single action, server_1 is a unique identifier of the server - // the instance is about. This will be used to make `getState()` return previous state on matching identifiers. - services.alertInstanceFactory('server_1') - .replaceState({ - // Alert instance level state, use getState() for - // previous and persisted values - ... - }) - // 'default' refers to a group of actions to fire, see 'actions' in create alert section - .fire('default', { - server: 'server_1', - }); - - // Use this example to fire multiple actions - // This scenario allows a single query and "fan-off" zero, one or many alerts based on the results - for (const server of ['server_1', 'server_2', 'server_3']) { - services.alertInstanceFactory(server) - .replaceState({ - // State specific to "server_x" - ... - }) - .fire('default', { server }); - } - - // Returning updated alert type level state - return { - ... - }; - }, + id: 'my-alert-type', + name: 'My alert type', + validate: { + params: Joi.object() + .keys({ + server: Joi.string().required(), + threshold: Joi.number().min(0).max(1).required(), + }) + .required(), + }, + async execute({ + scheduledRunAt, + previousScheduledRunAt, + services, + params, + state, + }: AlertExecuteOptions) { + const { server, threshold } = params; // Let's assume params is { server: 'server_1', threshold: 0.8 } + + // Call a function to get the server's current CPU usage + const currentCpuUsage = await getCpuUsage(server); + + // Only fire if CPU usage is greater than threshold + if (currentCpuUsage > threshold) { + // The first argument is a unique identifier the alert instance is about. In this scenario + // the provided server will be used. Also, this id will be used to make `getState()` return + // previous state, if any, on matching identifiers. + const alertInstance = services.alertInstanceFactory(server); + + // State from last execution. This will exist if an alert instance was created and fired + // in the previous execution + const { cpuUsage: previousCpuUsage } = alertInstance.getState(); + + // Replace state entirely with new values + alertInstance.replaceState({ + cpuUsage: currentCpuUsage, + }); + + // 'default' refers to a group of actions to fire, see 'actions' in create alert section + alertInstance.fire('default', { + server, + hasCpuUsageIncreased: currentCpuUsage > previousCpuUsage, + }); + } + + // Returning updated alert type level state, this will become available + // within the `state` function parameter at the next execution + return { + // This is an example attribute you could set, it makes more sense to use this state when + // the alert type fires multiple instances but wants a single place to track certain values. + lastChecked: new Date(), + }; + }, +}); +``` + +This example only receives threshold as a parameter. It will read the CPU usage of all the servers and fire individual actions if the reading for a server is greater than the threshold. This is a better implementation than above as only one query is performed for all the servers instead of one query per server. + +``` +server.plugins.alerting.registerType({ + id: 'my-alert-type', + name: 'My alert type', + validate: { + params: Joi.object() + .keys({ + threshold: Joi.number().min(0).max(1).required(), + }) + .required(), + }, + async execute({ + scheduledRunAt, + previousScheduledRunAt, + services, + params, + state, + }: AlertExecuteOptions) { + const { threshold } = params; // Let's assume params is { threshold: 0.8 } + + // Call a function to get the CPU readings on all the servers. The result will be + // an array of { server, cpuUsage }. + const cpuUsageByServer = await getCpuUsageByServer(); + + for (const { server, cpuUsage: currentCpuUsage } of cpuUsageByServer) { + // Only fire if CPU usage is greater than threshold + if (currentCpuUsage > threshold) { + // The first argument is a unique identifier the alert instance is about. In this scenario + // the provided server will be used. Also, this id will be used to make `getState()` return + // previous state, if any, on matching identifiers. + const alertInstance = services.alertInstanceFactory(server); + + // State from last execution. This will exist if an alert instance was created and fired + // in the previous execution + const { cpuUsage: previousCpuUsage } = alertInstance.getState(); + + // Replace state entirely with new values + alertInstance.replaceState({ + cpuUsage: currentCpuUsage, + }); + + // 'default' refers to a group of actions to fire, see 'actions' in create alert section + alertInstance.fire('default', { + server, + hasCpuUsageIncreased: currentCpuUsage > previousCpuUsage, + }); + } + } + + // Single object containing state that isn't specific to a server, this will become available + // within the `state` function parameter at the next execution + return { + lastChecked: new Date(), + }; + }, }); ``` From 2f4ae508f334be8871c7feb219fae2ab492d7912 Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Thu, 20 Jun 2019 15:07:03 -0400 Subject: [PATCH 12/13] Apply PR feedback --- x-pack/plugins/alerting/README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/x-pack/plugins/alerting/README.md b/x-pack/plugins/alerting/README.md index 0eb2360baa5ec..27bf614da7044 100644 --- a/x-pack/plugins/alerting/README.md +++ b/x-pack/plugins/alerting/README.md @@ -14,6 +14,13 @@ The Kibana alerting plugin provides a common place to set up alerts. You can: **Alert Instance**: The instance(s) created from an alert type execution. +A Kibana alert detects a condition and fires one or more actions when that condition occurs. Alerts work by going through the followings steps: + +1. Run a periodic check to detect a condition (the check is provided by an Alert Type) +2. Convert that condition into one or more stateful Alert Instances +3. Map Alert Instances to pre-defined Actions, using templating +4. Execute the Actions + ## Usage 1. Develop and register an alert type (see alert types -> example). From a1ce2a2e90ed88ef0ef5c3f800f47bfe2106ef6b Mon Sep 17 00:00:00 2001 From: Mike Cote Date: Thu, 20 Jun 2019 16:10:02 -0400 Subject: [PATCH 13/13] Update README locations --- x-pack/{ => legacy}/plugins/actions/README.md | 0 x-pack/{ => legacy}/plugins/alerting/README.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename x-pack/{ => legacy}/plugins/actions/README.md (100%) rename x-pack/{ => legacy}/plugins/alerting/README.md (100%) diff --git a/x-pack/plugins/actions/README.md b/x-pack/legacy/plugins/actions/README.md similarity index 100% rename from x-pack/plugins/actions/README.md rename to x-pack/legacy/plugins/actions/README.md diff --git a/x-pack/plugins/alerting/README.md b/x-pack/legacy/plugins/alerting/README.md similarity index 100% rename from x-pack/plugins/alerting/README.md rename to x-pack/legacy/plugins/alerting/README.md