Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce basic alerting and actions plugin #37042

Merged
merged 21 commits into from
Jun 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
0241553
Create actions plugin (#35679)
mikecote May 23, 2019
1671d5d
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote May 28, 2019
ac7b3e2
Pass services to action executors (#37194)
mikecote May 28, 2019
9ea8594
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote May 30, 2019
ee0917e
Cleanup actions plugin (#37250)
mikecote May 30, 2019
4be76d3
add server log action for alerting (#37530)
pmuellr May 31, 2019
3c46d13
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote Jun 4, 2019
1c501dd
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote Jun 6, 2019
b1a6583
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote Jun 10, 2019
8a09767
Create alerting plugin (#37043)
mikecote Jun 18, 2019
3074ef2
Merge with master
mikecote Jun 18, 2019
91a4219
Fix failing jest tests
mikecote Jun 18, 2019
f8b39a5
Accept core api changes
mikecote Jun 18, 2019
5839a9d
Fix saved objects client mock
mikecote Jun 18, 2019
a762bff
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote Jun 18, 2019
76ec667
Merge branch 'master' of github.com:elastic/kibana into feature/alerting
mikecote Jun 19, 2019
68445b1
PR feedback pt1
mikecote Jun 19, 2019
49ac129
Fix eslint issues
mikecote Jun 19, 2019
8478d21
Throw error when alert instance already fired (#39251)
mikecote Jun 20, 2019
d771163
Merge with master
mikecote Jun 20, 2019
c3ceb4d
Actions & alerting getting started user guides (#39093)
mikecote Jun 20, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .i18nrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"tagCloud": "src/legacy/core_plugins/tagcloud",
"tsvb": "src/legacy/core_plugins/metrics",
"kbnESQuery": "packages/kbn-es-query",
"xpack.actions": "x-pack/legacy/plugins/actions",
"xpack.alerting": "x-pack/legacy/plugins/alerting",
"xpack.apm": "x-pack/legacy/plugins/apm",
"xpack.beatsManagement": "x-pack/legacy/plugins/beats_management",
"xpack.canvas": "x-pack/legacy/plugins/canvas",
Expand Down
1 change: 1 addition & 0 deletions src/core/server/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ export { configServiceMock } from './config/config_service.mock';
export { elasticsearchServiceMock } from './elasticsearch/elasticsearch_service.mock';
export { httpServiceMock } from './http/http_service.mock';
export { loggingServiceMock } from './logging/logging_service.mock';
export { SavedObjectsClientMock } from './saved_objects/service/saved_objects_client.mock';
15 changes: 14 additions & 1 deletion src/core/server/saved_objects/service/saved_objects_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,25 @@ export interface SavedObjectsMigrationVersion {
[pluginName: string]: string;
}

/**
*
* @public
*/
export type SavedObjectAttribute =
| string
| number
| boolean
| null
| undefined
| SavedObjectAttributes
| SavedObjectAttributes[];

/**
*
* @public
*/
export interface SavedObjectAttributes {
[key: string]: SavedObjectAttributes | string | number | boolean | null;
[key: string]: SavedObjectAttribute | SavedObjectAttribute[];
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/core/server/server.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -421,8 +421,10 @@ export interface SavedObject<T extends SavedObjectAttributes = any> {

// @public (undocumented)
export interface SavedObjectAttributes {
// Warning: (ae-forgotten-export) The symbol "SavedObjectAttribute" needs to be exported by the entry point index.d.ts
//
// (undocumented)
[key: string]: SavedObjectAttributes | string | number | boolean | null;
[key: string]: SavedObjectAttribute | SavedObjectAttribute[];
}

// @public
Expand Down
4 changes: 4 additions & 0 deletions x-pack/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import { fileUpload } from './legacy/plugins/file_upload';
import { telemetry } from './legacy/plugins/telemetry';
import { encryptedSavedObjects } from './legacy/plugins/encrypted_saved_objects';
import { snapshotRestore } from './legacy/plugins/snapshot_restore';
import { actions } from './legacy/plugins/actions';
import { alerting } from './legacy/plugins/alerting';

module.exports = function (kibana) {
return [
Expand Down Expand Up @@ -85,5 +87,7 @@ module.exports = function (kibana) {
fileUpload(kibana),
encryptedSavedObjects(kibana),
snapshotRestore(kibana),
actions(kibana),
alerting(kibana),
];
};
177 changes: 177 additions & 0 deletions x-pack/legacy/plugins/actions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Kibana actions

The Kibana actions plugin provides a common place to execute actions. You can:

- 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

**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

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).

## Action types

### Methods

**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. For convention, ids starting with `.` are reserved for built in action types. We recommend using a convention like `<plugin_id>.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, 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 that the executor receives.

**executor(options)**

|Property|Description|
|---|---|
|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.<br><br>**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.<br><br>**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

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',
name: 'Email',
unencryptedAttributes: ['host', 'port'],
validate: {
params: Joi.object()
.keys({
to: Joi.array().items(Joi.string()).required(),
from: Joi.string().required(),
subject: Joi.string().required(),
body: Joi.string().required(),
})
.required(),
config: Joi.object()
.keys({
host: Joi.string().required(),
port: Joi.number().default(465),
username: Joi.string().required(),
password: Joi.string().required(),
})
.required(),
},
async executor({ config, params, services }) {
const transporter = nodemailer. createTransport(config);
await transporter.sendMail(params);
},
});
```

## RESTful 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

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.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 the saved objects API documentation.<br><br>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.<br><br>In most cases, you can leave this empty.|object|

#### `DELETE /api/action/{id}`: Delete action

Params:

|Property|Description|Type|
|---|---|---|
|id|The id of the action you're trying to delete.|string|

#### `GET /api/action/_find`: Find actions

Params:

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

Params:

|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:

|Property|Description|Type|
|---|---|---|
|id|The id of the action you're trying to update.|string|

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 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.<br><br>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 you can use 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 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.<br><br>In most cases this can be `undefined` unless you need cross spaces support.|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`.

```
server.plugins.actions.fire({
id: '3c5b2bd4-5424-4e4b-8cf5-c0a58c762cc5',
params: {
from: '[email protected]',
to: ['[email protected]'],
subject: 'My email subject',
body: 'My email body',
},
namespace: undefined, // The namespace the action exists within
basePath: undefined, // Usually `request.getBasePath();` or `undefined`
});
```
38 changes: 38 additions & 0 deletions x-pack/legacy/plugins/actions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { Legacy } from 'kibana';
import { Root } from 'joi';
import mappings from './mappings.json';
import { init } from './server';

export { ActionsPlugin, ActionsClient, ActionType, ActionTypeExecutorOptions } from './server';

export function actions(kibana: any) {
return new kibana.Plugin({
id: 'actions',
configPrefix: 'xpack.actions',
require: ['kibana', 'elasticsearch', 'task_manager', 'encrypted_saved_objects'],
isEnabled(config: Legacy.KibanaConfig) {
return (
config.get('xpack.encrypted_saved_objects.enabled') === true &&
config.get('xpack.actions.enabled') === true &&
config.get('xpack.task_manager.enabled') === true
);
},
config(Joi: Root) {
return Joi.object()
.keys({
enabled: Joi.boolean().default(true),
})
.default();
},
init,
uiExports: {
mappings,
},
});
}
19 changes: 19 additions & 0 deletions x-pack/legacy/plugins/actions/mappings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"action": {
"properties": {
"description": {
"type": "text"
},
"actionTypeId": {
"type": "keyword"
},
"actionTypeConfig": {
"enabled": false,
"type": "object"
},
"actionTypeConfigSecrets": {
"type": "binary"
}
}
}
}
23 changes: 23 additions & 0 deletions x-pack/legacy/plugins/actions/server/action_type_registry.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { ActionTypeRegistry } from './action_type_registry';

type ActionTypeRegistryContract = PublicMethodsOf<ActionTypeRegistry>;

const createActionTypeRegistryMock = () => {
const mocked: jest.Mocked<ActionTypeRegistryContract> = {
has: jest.fn(),
register: jest.fn(),
get: jest.fn(),
list: jest.fn(),
};
return mocked;
};

export const actionTypeRegistryMock = {
create: createActionTypeRegistryMock,
};
Loading