diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.ispartial.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.ispartial.md new file mode 100644 index 0000000000000..00a56c6fe9c31 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.ispartial.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IEsSearchResponse](./kibana-plugin-plugins-data-public.iessearchresponse.md) > [isPartial](./kibana-plugin-plugins-data-public.iessearchresponse.ispartial.md) + +## IEsSearchResponse.isPartial property + +Indicates whether the results returned are complete or partial + +Signature: + +```typescript +isPartial?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.isrunning.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.isrunning.md new file mode 100644 index 0000000000000..56fb1a7519811 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.isrunning.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IEsSearchResponse](./kibana-plugin-plugins-data-public.iessearchresponse.md) > [isRunning](./kibana-plugin-plugins-data-public.iessearchresponse.isrunning.md) + +## IEsSearchResponse.isRunning property + +Indicates whether async search is still in flight + +Signature: + +```typescript +isRunning?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.md index ea7e2aef00d6e..041d79de3282e 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iessearchresponse.md @@ -14,5 +14,7 @@ export interface IEsSearchResponse extends IKibanaSearchResponse | Property | Type | Description | | --- | --- | --- | +| [isPartial](./kibana-plugin-plugins-data-public.iessearchresponse.ispartial.md) | boolean | Indicates whether the results returned are complete or partial | +| [isRunning](./kibana-plugin-plugins-data-public.iessearchresponse.isrunning.md) | boolean | Indicates whether async search is still in flight | | [rawResponse](./kibana-plugin-plugins-data-public.iessearchresponse.rawresponse.md) | SearchResponse<any> | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchgeneric.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchgeneric.md index cdf19cd15a298..3bd6a398c8df5 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchgeneric.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchgeneric.md @@ -7,5 +7,5 @@ Signature: ```typescript -export declare type ISearchGeneric = (request: IEsSearchRequest, options?: IStrategyOptions) => Observable; +export declare type ISearchGeneric = (request: IEsSearchRequest, options?: ISearchOptions) => Observable; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.md index 05b7252606289..3eb38dc7d52e0 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.md @@ -15,4 +15,5 @@ export interface ISearchOptions | Property | Type | Description | | --- | --- | --- | | [signal](./kibana-plugin-plugins-data-public.isearchoptions.signal.md) | AbortSignal | | +| [strategy](./kibana-plugin-plugins-data-public.isearchoptions.strategy.md) | string | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.strategy.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.strategy.md new file mode 100644 index 0000000000000..df7e050691a8f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchoptions.strategy.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchOptions](./kibana-plugin-plugins-data-public.isearchoptions.md) > [strategy](./kibana-plugin-plugins-data-public.isearchoptions.strategy.md) + +## ISearchOptions.strategy property + +Signature: + +```typescript +strategy?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md index 30e980b5ffc54..b3b7da05326d0 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md @@ -35,7 +35,7 @@ export declare class SearchInterceptor | Method | Modifiers | Description | | --- | --- | --- | -| [runSearch(request, signal)](./kibana-plugin-plugins-data-public.searchinterceptor.runsearch.md) | | | +| [runSearch(request, signal, strategy)](./kibana-plugin-plugins-data-public.searchinterceptor.runsearch.md) | | | | [search(request, options)](./kibana-plugin-plugins-data-public.searchinterceptor.search.md) | | Searches using the given search method. Overrides the AbortSignal with one that will abort either when cancelPending is called, when the request times out, or when the original AbortSignal is aborted. Updates the pendingCount when the request is started/finalized. | | [setupTimers(options)](./kibana-plugin-plugins-data-public.searchinterceptor.setuptimers.md) | | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.runsearch.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.runsearch.md index 3601a00c48cf3..ad1d1dcb59d7b 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.runsearch.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.runsearch.md @@ -7,7 +7,7 @@ Signature: ```typescript -protected runSearch(request: IEsSearchRequest, signal: AbortSignal): Observable; +protected runSearch(request: IEsSearchRequest, signal: AbortSignal, strategy?: string): Observable; ``` ## Parameters @@ -16,6 +16,7 @@ protected runSearch(request: IEsSearchRequest, signal: AbortSignal): Observable< | --- | --- | --- | | request | IEsSearchRequest | | | signal | AbortSignal | | +| strategy | string | | Returns: diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.indextype.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.indextype.md new file mode 100644 index 0000000000000..aaf4e55ee007b --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.indextype.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchRequest](./kibana-plugin-plugins-data-server.iessearchrequest.md) > [indexType](./kibana-plugin-plugins-data-server.iessearchrequest.indextype.md) + +## IEsSearchRequest.indexType property + +Signature: + +```typescript +indexType?: string; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.md new file mode 100644 index 0000000000000..0dfa23eb64c1b --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.md @@ -0,0 +1,19 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchRequest](./kibana-plugin-plugins-data-server.iessearchrequest.md) + +## IEsSearchRequest interface + +Signature: + +```typescript +export interface IEsSearchRequest extends IKibanaSearchRequest +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [indexType](./kibana-plugin-plugins-data-server.iessearchrequest.indextype.md) | string | | +| [params](./kibana-plugin-plugins-data-server.iessearchrequest.params.md) | ISearchRequestParams | | + diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.params.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.params.md new file mode 100644 index 0000000000000..d65281973c951 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchrequest.params.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchRequest](./kibana-plugin-plugins-data-server.iessearchrequest.md) > [params](./kibana-plugin-plugins-data-server.iessearchrequest.params.md) + +## IEsSearchRequest.params property + +Signature: + +```typescript +params?: ISearchRequestParams; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.ispartial.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.ispartial.md new file mode 100644 index 0000000000000..fbddfc1cd9fc4 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.ispartial.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchResponse](./kibana-plugin-plugins-data-server.iessearchresponse.md) > [isPartial](./kibana-plugin-plugins-data-server.iessearchresponse.ispartial.md) + +## IEsSearchResponse.isPartial property + +Indicates whether the results returned are complete or partial + +Signature: + +```typescript +isPartial?: boolean; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.isrunning.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.isrunning.md new file mode 100644 index 0000000000000..01f3982957d5c --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.isrunning.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchResponse](./kibana-plugin-plugins-data-server.iessearchresponse.md) > [isRunning](./kibana-plugin-plugins-data-server.iessearchresponse.isrunning.md) + +## IEsSearchResponse.isRunning property + +Indicates whether async search is still in flight + +Signature: + +```typescript +isRunning?: boolean; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.md new file mode 100644 index 0000000000000..0407dce5fe418 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchResponse](./kibana-plugin-plugins-data-server.iessearchresponse.md) + +## IEsSearchResponse interface + +Signature: + +```typescript +export interface IEsSearchResponse extends IKibanaSearchResponse +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [isPartial](./kibana-plugin-plugins-data-server.iessearchresponse.ispartial.md) | boolean | Indicates whether the results returned are complete or partial | +| [isRunning](./kibana-plugin-plugins-data-server.iessearchresponse.isrunning.md) | boolean | Indicates whether async search is still in flight | +| [rawResponse](./kibana-plugin-plugins-data-server.iessearchresponse.rawresponse.md) | SearchResponse<any> | | + diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.rawresponse.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.rawresponse.md new file mode 100644 index 0000000000000..0ee1691d0f697 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.iessearchresponse.rawresponse.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IEsSearchResponse](./kibana-plugin-plugins-data-server.iessearchresponse.md) > [rawResponse](./kibana-plugin-plugins-data-server.iessearchresponse.rawresponse.md) + +## IEsSearchResponse.rawResponse property + +Signature: + +```typescript +rawResponse: SearchResponse; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md index 1bcd575803f88..f472064c87755 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md @@ -36,6 +36,8 @@ | [EsQueryConfig](./kibana-plugin-plugins-data-server.esqueryconfig.md) | | | [FieldFormatConfig](./kibana-plugin-plugins-data-server.fieldformatconfig.md) | | | [Filter](./kibana-plugin-plugins-data-server.filter.md) | | +| [IEsSearchRequest](./kibana-plugin-plugins-data-server.iessearchrequest.md) | | +| [IEsSearchResponse](./kibana-plugin-plugins-data-server.iessearchresponse.md) | | | [IFieldSubType](./kibana-plugin-plugins-data-server.ifieldsubtype.md) | | | [IFieldType](./kibana-plugin-plugins-data-server.ifieldtype.md) | | | [IIndexPattern](./kibana-plugin-plugins-data-server.iindexpattern.md) | | diff --git a/docs/user/visualize.asciidoc b/docs/user/visualize.asciidoc index 6919b5a8772ef..dc116962f9e96 100644 --- a/docs/user/visualize.asciidoc +++ b/docs/user/visualize.asciidoc @@ -132,6 +132,7 @@ include::{kib-repo-dir}/visualize/lens.asciidoc[] include::{kib-repo-dir}/visualize/most-frequent.asciidoc[] include::{kib-repo-dir}/visualize/tsvb.asciidoc[] + include::{kib-repo-dir}/visualize/timelion.asciidoc[] include::{kib-repo-dir}/visualize/tilemap.asciidoc[] diff --git a/docs/visualize/images/timelion-add-to-dashboard.png b/docs/visualize/images/timelion-add-to-dashboard.png new file mode 100644 index 0000000000000..a0ccc0af735a8 Binary files /dev/null and b/docs/visualize/images/timelion-add-to-dashboard.png differ diff --git a/docs/visualize/images/timelion-app.png b/docs/visualize/images/timelion-app.png new file mode 100644 index 0000000000000..236f9f2d41808 Binary files /dev/null and b/docs/visualize/images/timelion-app.png differ diff --git a/docs/visualize/images/timelion-copy-expression.png b/docs/visualize/images/timelion-copy-expression.png new file mode 100644 index 0000000000000..376bf7919166e Binary files /dev/null and b/docs/visualize/images/timelion-copy-expression.png differ diff --git a/docs/visualize/images/timelion-create-new-dashboard.png b/docs/visualize/images/timelion-create-new-dashboard.png new file mode 100644 index 0000000000000..4049b6d77cca6 Binary files /dev/null and b/docs/visualize/images/timelion-create-new-dashboard.png differ diff --git a/docs/visualize/images/timelion-dashboard.png b/docs/visualize/images/timelion-dashboard.png new file mode 100644 index 0000000000000..e217dca98d079 Binary files /dev/null and b/docs/visualize/images/timelion-dashboard.png differ diff --git a/docs/visualize/images/timelion-vis-paste-expression.png b/docs/visualize/images/timelion-vis-paste-expression.png new file mode 100644 index 0000000000000..86e175e40815b Binary files /dev/null and b/docs/visualize/images/timelion-vis-paste-expression.png differ diff --git a/docs/visualize/timelion.asciidoc b/docs/visualize/timelion.asciidoc index 9e41cce561454..4869664fab0a4 100644 --- a/docs/visualize/timelion.asciidoc +++ b/docs/visualize/timelion.asciidoc @@ -504,3 +504,44 @@ image::images/timelion-conditional04.png[] {nbsp} For additional information on Timelion conditional capabilities, go to https://www.elastic.co/blog/timeseries-if-then-else-with-timelion[I have but one .condition()]. + +[float] +[[timelion-deprecation]] +=== Timelion App deprecation + +Deprecated since 7.0, the Timelion app will be removed in 8.0. If you have any Timelion worksheets, you must migrate them to a dashboard. + +NOTE: Only the Timelion app is deprecated. {kib} continues to support Timelion visualizations on dashboards, in Visualize, and in Canvas. + +[float] +[[timelion-app-to-vis]] +==== Create a dashboard from a Timelion worksheet + +To replace a Timelion worksheet with a dashboard, follow the same process for adding a visualization. +In addition, you must migrate the Timelion graphs to Visualize. + +. Open the menu, click **Dashboard**, then click **Create dashboard**. + +. On the dashboard, click **Create New**, then select the Timelion visualization. ++ +[role="screenshot"] +image::images/timelion-create-new-dashboard.png[] ++ +The only thing you need is the Timelion expression for each graph. + +. Open the Timelion app on a new tab, select the chart you want to copy, and copy its expression. ++ +[role="screenshot"] +image::images/timelion-copy-expression.png[] + +. Return to the other tab and paste the copied expression to the *Timelion Expression* field and click **Update**. ++ +[role="screenshot"] +image::images/timelion-vis-paste-expression.png[] + +. Save the new visualization, give it a name, and click **Save and Return**. ++ +Your Timelion visualization will appear on the dashboard. Repeat this for all your charts on each worksheet. ++ +[role="screenshot"] +image::images/timelion-dashboard.png[] diff --git a/examples/search_examples/README.md b/examples/search_examples/README.md new file mode 100644 index 0000000000000..bcc17bf7f3333 --- /dev/null +++ b/examples/search_examples/README.md @@ -0,0 +1,9 @@ +# search_examples + +> An awesome Kibana plugin + +--- + +## Development + +See the [kibana contributing guide](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md) for instructions setting up your development environment. diff --git a/examples/search_examples/common/index.ts b/examples/search_examples/common/index.ts new file mode 100644 index 0000000000000..e1e7f6389ae83 --- /dev/null +++ b/examples/search_examples/common/index.ts @@ -0,0 +1,32 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { IEsSearchResponse, IEsSearchRequest } from '../../../src/plugins/data/common'; + +export const PLUGIN_ID = 'searchExamples'; +export const PLUGIN_NAME = 'Search Examples'; + +export interface IMyStrategyRequest extends IEsSearchRequest { + get_cool: boolean; +} +export interface IMyStrategyResponse extends IEsSearchResponse { + cool: string; +} + +export const SERVER_SEARCH_ROUTE_PATH = '/api/examples/search'; diff --git a/examples/search_examples/kibana.json b/examples/search_examples/kibana.json new file mode 100644 index 0000000000000..7e392b8417360 --- /dev/null +++ b/examples/search_examples/kibana.json @@ -0,0 +1,9 @@ +{ + "id": "searchExamples", + "version": "8.0.0", + "server": true, + "ui": true, + "requiredPlugins": ["navigation", "data", "developerExamples"], + "optionalPlugins": [], + "requiredBundles": [] +} diff --git a/examples/search_examples/public/application.tsx b/examples/search_examples/public/application.tsx new file mode 100644 index 0000000000000..81e4ee8514c11 --- /dev/null +++ b/examples/search_examples/public/application.tsx @@ -0,0 +1,44 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React from 'react'; +import ReactDOM from 'react-dom'; +import { AppMountParameters, CoreStart } from '../../../src/core/public'; +import { AppPluginStartDependencies } from './types'; +import { SearchExamplesApp } from './components/app'; + +export const renderApp = ( + { notifications, savedObjects, http }: CoreStart, + { navigation, data }: AppPluginStartDependencies, + { appBasePath, element }: AppMountParameters +) => { + ReactDOM.render( + , + element + ); + + return () => ReactDOM.unmountComponentAtNode(element); +}; diff --git a/examples/search_examples/public/components/app.tsx b/examples/search_examples/public/components/app.tsx new file mode 100644 index 0000000000000..31cc5e420da11 --- /dev/null +++ b/examples/search_examples/public/components/app.tsx @@ -0,0 +1,341 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React, { useState, useEffect } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage, I18nProvider } from '@kbn/i18n/react'; +import { BrowserRouter as Router } from 'react-router-dom'; + +import { + EuiButton, + EuiPage, + EuiPageBody, + EuiPageContent, + EuiPageContentBody, + EuiPageHeader, + EuiTitle, + EuiText, + EuiFlexGrid, + EuiFlexItem, + EuiCheckbox, + EuiSpacer, + EuiCode, + EuiComboBox, + EuiFormLabel, +} from '@elastic/eui'; + +import { CoreStart } from '../../../../src/core/public'; +import { mountReactNode } from '../../../../src/core/public/utils'; +import { NavigationPublicPluginStart } from '../../../../src/plugins/navigation/public'; + +import { + PLUGIN_ID, + PLUGIN_NAME, + IMyStrategyRequest, + IMyStrategyResponse, + SERVER_SEARCH_ROUTE_PATH, +} from '../../common'; + +import { + DataPublicPluginStart, + IndexPatternSelect, + IndexPattern, + IndexPatternField, +} from '../../../../src/plugins/data/public'; + +interface SearchExamplesAppDeps { + basename: string; + notifications: CoreStart['notifications']; + http: CoreStart['http']; + savedObjectsClient: CoreStart['savedObjects']['client']; + navigation: NavigationPublicPluginStart; + data: DataPublicPluginStart; +} + +function formatFieldToComboBox(field?: IndexPatternField | null) { + if (!field) return []; + return formatFieldsToComboBox([field]); +} + +function formatFieldsToComboBox(fields?: IndexPatternField[]) { + if (!fields) return []; + + return fields?.map((field) => { + return { + label: field.displayName || field.name, + }; + }); +} + +export const SearchExamplesApp = ({ + http, + basename, + notifications, + savedObjectsClient, + navigation, + data, +}: SearchExamplesAppDeps) => { + const [getCool, setGetCool] = useState(false); + const [timeTook, setTimeTook] = useState(); + const [indexPattern, setIndexPattern] = useState(); + const [numericFields, setNumericFields] = useState(); + const [selectedField, setSelectedField] = useState(); + + // Fetch the default index pattern using the `data.indexPatterns` service, as the component is mounted. + useEffect(() => { + const setDefaultIndexPattern = async () => { + const defaultIndexPattern = await data.indexPatterns.getDefault(); + setIndexPattern(defaultIndexPattern); + }; + + setDefaultIndexPattern(); + }, [data]); + + // Update the fields list every time the index pattern is modified. + useEffect(() => { + const fields = indexPattern?.fields.filter( + (field) => field.type === 'number' && field.aggregatable + ); + setNumericFields(fields); + setSelectedField(fields?.length ? fields[0] : null); + }, [indexPattern]); + + const doAsyncSearch = async (strategy?: string) => { + if (!indexPattern || !selectedField) return; + + // Constuct the query portion of the search request + const query = data.query.getEsQuery(indexPattern); + + // Constuct the aggregations portion of the search request by using the `data.search.aggs` service. + const aggs = [{ type: 'avg', params: { field: selectedField.name } }]; + const aggsDsl = data.search.aggs.createAggConfigs(indexPattern, aggs).toDsl(); + + const request = { + params: { + index: indexPattern.title, + body: { + aggs: aggsDsl, + query, + }, + }, + }; + + if (strategy) { + // Add a custom request parameter to be consumed by `MyStrategy`. + (request as IMyStrategyRequest).get_cool = getCool; + } + + // Submit the search request using the `data.search` service. + const searchSubscription$ = data.search + .search(request, { + strategy, + }) + .subscribe({ + next: (response) => { + if (!response.isPartial && !response.isRunning) { + setTimeTook(response.rawResponse.took); + const avgResult: number | undefined = response.rawResponse.aggregations + ? response.rawResponse.aggregations[1].value + : undefined; + const message = ( + + Searched {response.rawResponse.hits.total} documents.
+ The average of {selectedField.name} is {avgResult ? Math.floor(avgResult) : 0}. +
+ Is it Cool? {String((response as IMyStrategyResponse).cool)} +
+ ); + notifications.toasts.addSuccess({ + title: 'Query result', + text: mountReactNode(message), + }); + searchSubscription$.unsubscribe(); + } else if (response.isPartial && !response.isRunning) { + // TODO: Make response error status clearer + notifications.toasts.addWarning('An error has occurred'); + searchSubscription$.unsubscribe(); + } + }, + error: () => { + notifications.toasts.addDanger('Failed to run search'); + }, + }); + }; + + const onClickHandler = () => { + doAsyncSearch(); + }; + + const onMyStrategyClickHandler = () => { + doAsyncSearch('myStrategy'); + }; + + const onServerClickHandler = async () => { + if (!indexPattern || !selectedField) return; + try { + const response = await http.get(SERVER_SEARCH_ROUTE_PATH, { + query: { + index: indexPattern.title, + field: selectedField.name, + }, + }); + + notifications.toasts.addSuccess(`Server returned ${JSON.stringify(response)}`); + } catch (e) { + notifications.toasts.addDanger('Failed to run search'); + } + }; + + if (!indexPattern) return null; + + return ( + + + <> + + + + + +

+ +

+
+
+ + + + + + Index Pattern + { + const newIndexPattern = await data.indexPatterns.get(newIndexPatternId); + setIndexPattern(newIndexPattern); + }} + isClearable={false} + /> + + + Numeric Fields + { + const field = indexPattern.getFieldByName(option[0].label); + setSelectedField(field || null); + }} + sortMatchesBy="startsWith" + /> + + + + + + + + +

+ Searching Elasticsearch using data.search +

+
+ + If you want to fetch data from Elasticsearch, you can use the different services + provided by the data plugin. These help you get the index + pattern and search bar configuration, format them into a DSL query and send it + to Elasticsearch. + + + + + + + +

Writing a custom search strategy

+
+ + If you want to do some pre or post processing on the server, you might want to + create a custom search strategy. This example uses such a strategy, passing in + custom input and receiving custom output back. + + + } + checked={getCool} + onChange={(event) => setGetCool(event.target.checked)} + /> + + + + + + +

Using search on the server

+
+ + You can also run your search request from the server, without registering a + search strategy. This request does not take the configuration of{' '} + TopNavMenu into account, but you could pass those down to the + server as well. + + + + +
+
+
+
+ +
+
+ ); +}; diff --git a/examples/search_examples/public/index.scss b/examples/search_examples/public/index.scss new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/search_examples/public/index.ts b/examples/search_examples/public/index.ts new file mode 100644 index 0000000000000..cd3208aa0c088 --- /dev/null +++ b/examples/search_examples/public/index.ts @@ -0,0 +1,29 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import './index.scss'; + +import { SearchExamplesPlugin } from './plugin'; + +// This exports static code and TypeScript types, +// as well as, Kibana Platform `plugin()` initializer. +export function plugin() { + return new SearchExamplesPlugin(); +} +export { SearchExamplesPluginSetup, SearchExamplesPluginStart } from './types'; diff --git a/examples/search_examples/public/plugin.ts b/examples/search_examples/public/plugin.ts new file mode 100644 index 0000000000000..436304e9d5ff6 --- /dev/null +++ b/examples/search_examples/public/plugin.ts @@ -0,0 +1,76 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + AppMountParameters, + CoreSetup, + CoreStart, + Plugin, + AppNavLinkStatus, +} from '../../../src/core/public'; +import { + SearchExamplesPluginSetup, + SearchExamplesPluginStart, + AppPluginSetupDependencies, + AppPluginStartDependencies, +} from './types'; +import { PLUGIN_NAME } from '../common'; + +export class SearchExamplesPlugin + implements + Plugin< + SearchExamplesPluginSetup, + SearchExamplesPluginStart, + AppPluginSetupDependencies, + AppPluginStartDependencies + > { + public setup( + core: CoreSetup, + { developerExamples }: AppPluginSetupDependencies + ): SearchExamplesPluginSetup { + // Register an application into the side navigation menu + core.application.register({ + id: 'searchExamples', + title: PLUGIN_NAME, + navLinkStatus: AppNavLinkStatus.hidden, + async mount(params: AppMountParameters) { + // Load application bundle + const { renderApp } = await import('./application'); + // Get start services as specified in kibana.json + const [coreStart, depsStart] = await core.getStartServices(); + // Render the application + return renderApp(coreStart, depsStart, params); + }, + }); + + developerExamples.register({ + appId: 'searchExamples', + title: 'Search Examples', + description: `Search Examples`, + }); + + return {}; + } + + public start(core: CoreStart): SearchExamplesPluginStart { + return {}; + } + + public stop() {} +} diff --git a/examples/search_examples/public/types.ts b/examples/search_examples/public/types.ts new file mode 100644 index 0000000000000..0670cc5907449 --- /dev/null +++ b/examples/search_examples/public/types.ts @@ -0,0 +1,36 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { NavigationPublicPluginStart } from '../../../src/plugins/navigation/public'; +import { DataPublicPluginStart } from '../../../src/plugins/data/public'; +import { DeveloperExamplesSetup } from '../../developer_examples/public'; + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SearchExamplesPluginSetup {} +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SearchExamplesPluginStart {} + +export interface AppPluginSetupDependencies { + developerExamples: DeveloperExamplesSetup; +} + +export interface AppPluginStartDependencies { + navigation: NavigationPublicPluginStart; + data: DataPublicPluginStart; +} diff --git a/examples/search_examples/server/index.ts b/examples/search_examples/server/index.ts new file mode 100644 index 0000000000000..06d41490af57a --- /dev/null +++ b/examples/search_examples/server/index.ts @@ -0,0 +1,27 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { PluginInitializerContext } from '../../../src/core/server'; +import { SearchExamplesPlugin } from './plugin'; + +export function plugin(initializerContext: PluginInitializerContext) { + return new SearchExamplesPlugin(initializerContext); +} + +export { SearchExamplesPluginSetup, SearchExamplesPluginStart } from './types'; diff --git a/examples/search_examples/server/my_strategy.ts b/examples/search_examples/server/my_strategy.ts new file mode 100644 index 0000000000000..a1116ddbd759b --- /dev/null +++ b/examples/search_examples/server/my_strategy.ts @@ -0,0 +1,40 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ISearchStrategy, PluginStart } from '../../../src/plugins/data/server'; +import { IMyStrategyResponse, IMyStrategyRequest } from '../common'; + +export const mySearchStrategyProvider = (data: PluginStart): ISearchStrategy => { + const es = data.search.getSearchStrategy('es'); + return { + search: async (context, request, options): Promise => { + request.debug = true; + const esSearchRes = await es.search(context, request, options); + return { + ...esSearchRes, + cool: (request as IMyStrategyRequest).get_cool ? 'YES' : 'NOPE', + }; + }, + cancel: async (context, id) => { + if (es.cancel) { + es.cancel(context, id); + } + }, + }; +}; diff --git a/examples/search_examples/server/plugin.ts b/examples/search_examples/server/plugin.ts new file mode 100644 index 0000000000000..deef5a53b2b73 --- /dev/null +++ b/examples/search_examples/server/plugin.ts @@ -0,0 +1,73 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + PluginInitializerContext, + CoreSetup, + CoreStart, + Plugin, + Logger, +} from '../../../src/core/server'; + +import { + SearchExamplesPluginSetup, + SearchExamplesPluginStart, + SearchExamplesPluginSetupDeps, + SearchExamplesPluginStartDeps, +} from './types'; +import { mySearchStrategyProvider } from './my_strategy'; +import { registerRoutes } from './routes'; + +export class SearchExamplesPlugin + implements + Plugin< + SearchExamplesPluginSetup, + SearchExamplesPluginStart, + SearchExamplesPluginSetupDeps, + SearchExamplesPluginStartDeps + > { + private readonly logger: Logger; + + constructor(initializerContext: PluginInitializerContext) { + this.logger = initializerContext.logger.get(); + } + + public setup( + core: CoreSetup, + deps: SearchExamplesPluginSetupDeps + ) { + this.logger.debug('search_examples: Setup'); + const router = core.http.createRouter(); + + core.getStartServices().then(([_, depsStart]) => { + const myStrategy = mySearchStrategyProvider(depsStart.data); + deps.data.search.registerSearchStrategy('myStrategy', myStrategy); + registerRoutes(router, depsStart.data); + }); + + return {}; + } + + public start(core: CoreStart) { + this.logger.debug('search_examples: Started'); + return {}; + } + + public stop() {} +} diff --git a/examples/search_examples/server/routes/index.ts b/examples/search_examples/server/routes/index.ts new file mode 100644 index 0000000000000..ea575cf371bb7 --- /dev/null +++ b/examples/search_examples/server/routes/index.ts @@ -0,0 +1,19 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +export { registerRoutes } from './register_routes'; diff --git a/examples/search_examples/server/routes/register_routes.ts b/examples/search_examples/server/routes/register_routes.ts new file mode 100644 index 0000000000000..ac3ea28d89d26 --- /dev/null +++ b/examples/search_examples/server/routes/register_routes.ts @@ -0,0 +1,26 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { IRouter } from 'kibana/server'; +import { PluginStart as DataPluginStart } from 'src/plugins/data/server'; +import { registerServerSearchRoute } from './server_search_route'; + +export function registerRoutes(router: IRouter, data: DataPluginStart) { + registerServerSearchRoute(router, data); +} diff --git a/examples/search_examples/server/routes/server_search_route.ts b/examples/search_examples/server/routes/server_search_route.ts new file mode 100644 index 0000000000000..6eb21cf34b4a3 --- /dev/null +++ b/examples/search_examples/server/routes/server_search_route.ts @@ -0,0 +1,70 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { PluginStart as DataPluginStart, IEsSearchRequest } from 'src/plugins/data/server'; +import { schema } from '@kbn/config-schema'; +import { IEsSearchResponse } from 'src/plugins/data/common'; +import { IRouter } from '../../../../src/core/server'; +import { SERVER_SEARCH_ROUTE_PATH } from '../../common'; + +export function registerServerSearchRoute(router: IRouter, data: DataPluginStart) { + router.get( + { + path: SERVER_SEARCH_ROUTE_PATH, + validate: { + query: schema.object({ + index: schema.maybe(schema.string()), + field: schema.maybe(schema.string()), + }), + }, + }, + async (context, request, response) => { + const { index, field } = request.query; + // Run a synchronous search server side, by enforcing a high keepalive and waiting for completion. + // If you wish to run the search with polling (in basic+), you'd have to poll on the search API. + // Please reach out to the @app-arch-team if you need this to be implemented. + const res = await data.search.search( + context, + { + params: { + index, + body: { + aggs: { + '1': { + avg: { + field, + }, + }, + }, + }, + waitForCompletionTimeout: '5m', + keepAlive: '5m', + }, + } as IEsSearchRequest, + {} + ); + + return response.ok({ + body: { + aggs: (res as IEsSearchResponse).rawResponse.aggregations, + }, + }); + } + ); +} diff --git a/examples/search_examples/server/types.ts b/examples/search_examples/server/types.ts new file mode 100644 index 0000000000000..da0f24a3012bb --- /dev/null +++ b/examples/search_examples/server/types.ts @@ -0,0 +1,34 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// Rename PluginStart to something better +import { PluginSetup, PluginStart } from '../../../src/plugins/data/server'; + +export interface SearchExamplesPluginSetupDeps { + data: PluginSetup; +} + +export interface SearchExamplesPluginStartDeps { + data: PluginStart; +} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SearchExamplesPluginSetup {} +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SearchExamplesPluginStart {} diff --git a/examples/search_examples/tsconfig.json b/examples/search_examples/tsconfig.json new file mode 100644 index 0000000000000..8a3ced743d0fa --- /dev/null +++ b/examples/search_examples/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./target", + "skipLibCheck": true + }, + "include": [ + "index.ts", + "common/**/*.ts", + "public/**/*.ts", + "public/**/*.tsx", + "server/**/*.ts", + "../../typings/**/*", + ], + "exclude": [] +} diff --git a/src/plugins/data/common/search/es_search/types.ts b/src/plugins/data/common/search/es_search/types.ts index db2e31706e95c..6fc0923768703 100644 --- a/src/plugins/data/common/search/es_search/types.ts +++ b/src/plugins/data/common/search/es_search/types.ts @@ -31,5 +31,13 @@ export interface IEsSearchRequest extends IKibanaSearchRequest { } export interface IEsSearchResponse extends IKibanaSearchResponse { + /** + * Indicates whether async search is still in flight + */ + isRunning?: boolean; + /** + * Indicates whether the results returned are complete or partial + */ + isPartial?: boolean; rawResponse: SearchResponse; } diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 216ed018957e0..6225d74fb1b31 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -770,6 +770,8 @@ export interface IEsSearchRequest extends IKibanaSearchRequest { // // @public (undocumented) export interface IEsSearchResponse extends IKibanaSearchResponse { + isPartial?: boolean; + isRunning?: boolean; // (undocumented) rawResponse: SearchResponse_2; } @@ -1213,11 +1215,10 @@ export type InputTimeRange = TimeRange | { // @public (undocumented) export type ISearch = (request: IKibanaSearchRequest, options?: ISearchOptions) => Observable; -// Warning: (ae-forgotten-export) The symbol "IStrategyOptions" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "ISearchGeneric" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export type ISearchGeneric = (request: IEsSearchRequest, options?: IStrategyOptions) => Observable; +export type ISearchGeneric = (request: IEsSearchRequest, options?: ISearchOptions) => Observable; // Warning: (ae-missing-release-tag) "ISearchOptions" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -1225,6 +1226,8 @@ export type ISearchGeneric = (request: IEsSearchRequest, options?: IStrategyOpti export interface ISearchOptions { // (undocumented) signal?: AbortSignal; + // (undocumented) + strategy?: string; } // Warning: (ae-forgotten-export) The symbol "SearchSource" needs to be exported by the entry point index.d.ts @@ -1723,7 +1726,7 @@ export class SearchInterceptor { // (undocumented) protected readonly requestTimeout?: number | undefined; // (undocumented) - protected runSearch(request: IEsSearchRequest, signal: AbortSignal): Observable; + protected runSearch(request: IEsSearchRequest, signal: AbortSignal, strategy?: string): Observable; search(request: IEsSearchRequest, options?: ISearchOptions): Observable; // (undocumented) protected setupTimers(options?: ISearchOptions): { diff --git a/src/plugins/data/public/query/mocks.ts b/src/plugins/data/public/query/mocks.ts index 8c15d9d6d0152..53c177de0fa39 100644 --- a/src/plugins/data/public/query/mocks.ts +++ b/src/plugins/data/public/query/mocks.ts @@ -44,6 +44,7 @@ const createStartContractMock = () => { savedQueries: jest.fn() as any, state$: new Observable(), timefilter: timefilterServiceMock.createStartContract(), + getEsQuery: jest.fn(), }; return startContract; diff --git a/src/plugins/data/public/query/query_service.ts b/src/plugins/data/public/query/query_service.ts index da514c0e24ea4..fe7fdcbb1d113 100644 --- a/src/plugins/data/public/query/query_service.ts +++ b/src/plugins/data/public/query/query_service.ts @@ -26,6 +26,9 @@ import { TimefilterService, TimefilterSetup } from './timefilter'; import { createSavedQueryService } from './saved_query/saved_query_service'; import { createQueryStateObservable } from './state_sync/create_global_query_observable'; import { QueryStringManager, QueryStringContract } from './query_string'; +import { buildEsQuery, getEsQueryConfig } from '../../common'; +import { getUiSettings } from '../services'; +import { IndexPattern } from '..'; /** * Query Service @@ -86,6 +89,16 @@ export class QueryService { savedQueries: createSavedQueryService(savedObjectsClient), state$: this.state$, timefilter: this.timefilter, + getEsQuery: (indexPattern: IndexPattern) => { + const timeFilter = this.timefilter.timefilter.createFilter(indexPattern); + + return buildEsQuery( + indexPattern, + this.queryStringManager.getQuery(), + [...this.filterManager.getFilters(), ...(timeFilter ? [timeFilter] : [])], + getEsQueryConfig(getUiSettings()) + ); + }, }; } diff --git a/src/plugins/data/public/search/search_interceptor.ts b/src/plugins/data/public/search/search_interceptor.ts index 677ad0ccea677..d6fcde8e986f3 100644 --- a/src/plugins/data/public/search/search_interceptor.ts +++ b/src/plugins/data/public/search/search_interceptor.ts @@ -17,11 +17,12 @@ * under the License. */ +import { trimEnd } from 'lodash'; import { BehaviorSubject, throwError, timer, Subscription, defer, from, Observable } from 'rxjs'; import { finalize, filter } from 'rxjs/operators'; import { ApplicationStart, Toast, ToastsStart, CoreStart } from 'kibana/public'; import { getCombinedSignal, AbortError } from '../../common/utils'; -import { IEsSearchRequest, IEsSearchResponse } from '../../common/search'; +import { IEsSearchRequest, IEsSearchResponse, ES_SEARCH_STRATEGY } from '../../common/search'; import { ISearchOptions } from './types'; import { getLongQueryNotification } from './long_query_notification'; import { SearchUsageCollector } from './collectors'; @@ -92,14 +93,20 @@ export class SearchInterceptor { protected runSearch( request: IEsSearchRequest, - signal: AbortSignal + signal: AbortSignal, + strategy?: string ): Observable { const { id, ...searchRequest } = request; - const path = id != null ? `/internal/search/es/${id}` : '/internal/search/es'; - const method = 'POST'; + const path = trimEnd(`/internal/search/${strategy || ES_SEARCH_STRATEGY}/${id || ''}`, '/'); const body = JSON.stringify(id != null ? {} : searchRequest); - const response = this.deps.http.fetch({ path, method, body, signal }); - return from(response); + return from( + this.deps.http.fetch({ + method: 'POST', + path, + body, + signal, + }) + ); } /** @@ -120,7 +127,7 @@ export class SearchInterceptor { const { combinedSignal, cleanup } = this.setupTimers(options); this.pendingCount$.next(++this.pendingCount); - return this.runSearch(request, combinedSignal).pipe( + return this.runSearch(request, combinedSignal, options?.strategy).pipe( finalize(() => { this.pendingCount$.next(--this.pendingCount); cleanup(); diff --git a/src/plugins/data/public/search/types.ts b/src/plugins/data/public/search/types.ts index ec74275f35c04..f80a13d048a68 100644 --- a/src/plugins/data/public/search/types.ts +++ b/src/plugins/data/public/search/types.ts @@ -37,6 +37,7 @@ import { GetInternalStartServicesFn } from '../types'; export interface ISearchOptions { signal?: AbortSignal; + strategy?: string; } export type ISearch = ( @@ -44,14 +45,9 @@ export type ISearch = ( options?: ISearchOptions ) => Observable; -// Service API types -export interface IStrategyOptions extends ISearchOptions { - strategy?: string; -} - export type ISearchGeneric = ( request: IEsSearchRequest, - options?: IStrategyOptions + options?: ISearchOptions ) => Observable; export interface ISearchStartLegacy { diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 1f3d7fbcb9f0f..73ed88850d787 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -161,7 +161,12 @@ import { toAbsoluteDates, } from '../common'; -export { EsaggsExpressionFunctionDefinition, ParsedInterval } from '../common'; +export { + EsaggsExpressionFunctionDefinition, + ParsedInterval, + IEsSearchRequest, + IEsSearchResponse, +} from '../common'; export { ISearchStrategy, diff --git a/src/plugins/data/server/search/es_search/es_search_strategy.test.ts b/src/plugins/data/server/search/es_search/es_search_strategy.test.ts index bc59bdee6a40a..2888f9d9d20b5 100644 --- a/src/plugins/data/server/search/es_search/es_search_strategy.test.ts +++ b/src/plugins/data/server/search/es_search/es_search_strategy.test.ts @@ -78,7 +78,7 @@ describe('ES search strategy', () => { }); }); - it('returns total, loaded, and raw response', async () => { + it('has all response parameters', async () => { const params = { index: 'logstash-*' }; const esSearch = await esSearchStrategyProvider(mockConfig$, mockLogger); @@ -86,7 +86,8 @@ describe('ES search strategy', () => { params, }); - expect(response).toHaveProperty('total'); + expect(response.isRunning).toBe(false); + expect(response.isPartial).toBe(false); expect(response).toHaveProperty('loaded'); expect(response).toHaveProperty('rawResponse'); }); diff --git a/src/plugins/data/server/search/es_search/es_search_strategy.ts b/src/plugins/data/server/search/es_search/es_search_strategy.ts index 78ead6df1a44e..234c30376d6db 100644 --- a/src/plugins/data/server/search/es_search/es_search_strategy.ts +++ b/src/plugins/data/server/search/es_search/es_search_strategy.ts @@ -30,7 +30,7 @@ export const esSearchStrategyProvider = ( ): ISearchStrategy => { return { search: async (context, request, options) => { - logger.info(`search ${JSON.stringify(request.params)}`); + logger.info(`search ${request.params?.index}`); const config = await config$.pipe(first()).toPromise(); const defaultParams = getDefaultSearchParams(config); @@ -56,7 +56,12 @@ export const esSearchStrategyProvider = ( // The above query will either complete or timeout and throw an error. // There is no progress indication on this api. - return { rawResponse, ...getTotalLoaded(rawResponse._shards) }; + return { + isPartial: false, + isRunning: false, + rawResponse, + ...getTotalLoaded(rawResponse._shards), + }; } catch (e) { if (usage) usage.trackError(); throw e; diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 013034c79d3f3..37d569a4bf9fe 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -369,6 +369,30 @@ export function getTotalLoaded({ total, failed, successful }: ShardsResponse): { loaded: number; }; +// Warning: (ae-forgotten-export) The symbol "IKibanaSearchRequest" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "IEsSearchRequest" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface IEsSearchRequest extends IKibanaSearchRequest { + // (undocumented) + indexType?: string; + // Warning: (ae-forgotten-export) The symbol "ISearchRequestParams" needs to be exported by the entry point index.d.ts + // + // (undocumented) + params?: ISearchRequestParams; +} + +// Warning: (ae-forgotten-export) The symbol "IKibanaSearchResponse" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "IEsSearchResponse" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface IEsSearchResponse extends IKibanaSearchResponse { + isPartial?: boolean; + isRunning?: boolean; + // (undocumented) + rawResponse: SearchResponse; +} + // Warning: (ae-missing-release-tag) "IFieldFormatsRegistry" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -547,8 +571,6 @@ export interface ISearchSetup { export interface ISearchStart { getSearchStrategy: (name: string) => ISearchStrategy; // Warning: (ae-forgotten-export) The symbol "RequestHandlerContext" needs to be exported by the entry point index.d.ts - // Warning: (ae-forgotten-export) The symbol "IKibanaSearchRequest" needs to be exported by the entry point index.d.ts - // Warning: (ae-forgotten-export) The symbol "IKibanaSearchResponse" needs to be exported by the entry point index.d.ts // // (undocumented) search: (context: RequestHandlerContext, request: IKibanaSearchRequest, options: ISearchOptions) => Promise; @@ -560,9 +582,6 @@ export interface ISearchStart { export interface ISearchStrategy { // (undocumented) cancel?: (context: RequestHandlerContext, id: string) => Promise; - // Warning: (ae-forgotten-export) The symbol "IEsSearchRequest" needs to be exported by the entry point index.d.ts - // Warning: (ae-forgotten-export) The symbol "IEsSearchResponse" needs to be exported by the entry point index.d.ts - // // (undocumented) search: (context: RequestHandlerContext, request: IEsSearchRequest, options?: ISearchOptions) => Promise; } @@ -817,13 +836,13 @@ export function usageProvider(core: CoreSetup_2): SearchUsage; // src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:127:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:127:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:180:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:181:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:182:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:183:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:184:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:185:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:188:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:185:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:186:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:187:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:188:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:189:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:190:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:193:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) diff --git a/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx b/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx index f10954df432c2..33fa1ceefd3d5 100644 --- a/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx +++ b/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx @@ -70,7 +70,7 @@ function VegaActionsMenu({ formatHJson, formatJson }: VegaActionsMenuProps) { return ( ({ vegaLite: jest.requireActual('vega-lite'), })); +describe(`VegaParser.parseAsync`, () => { + test(`should throw an error in case of $spec is not defined`, async () => { + const vp = new VegaParser('{}'); + + await vp.parseAsync(); + + expect( + vp.error.startsWith('Your specification requires a "$schema" field with a valid URL') + ).toBeTruthy(); + }); +}); + describe(`VegaParser._setDefaultValue`, () => { function check(spec, expected, ...params) { return () => { @@ -149,23 +161,14 @@ describe('VegaParser._resolveEsQueries', () => { ); }); -describe('VegaParser._parseSchema', () => { - function check(schema, isVegaLite, warningCount) { +describe('VegaParser.parseSchema', () => { + function check(schema, isVegaLite) { return () => { const vp = new VegaParser({ $schema: schema }); - expect(vp._parseSchema()).toBe(isVegaLite); - expect(vp.spec).toEqual({ $schema: schema }); - expect(vp.warnings).toHaveLength(warningCount); + expect(vp.parseSchema(vp.spec).isVegaLite).toBe(isVegaLite); }; } - test('should warn on no vega version specified', () => { - const vp = new VegaParser({}); - expect(vp._parseSchema()).toBe(false); - expect(vp.spec).toEqual({ $schema: 'https://vega.github.io/schema/vega/v5.json' }); - expect(vp.warnings).toHaveLength(1); - }); - test( 'should not warn on current vega version', check('https://vega.github.io/schema/vega/v5.json', false, 0) diff --git a/src/plugins/vis_type_vega/public/data_model/vega_parser.ts b/src/plugins/vis_type_vega/public/data_model/vega_parser.ts index 94d79071b8ef2..aceeefd953655 100644 --- a/src/plugins/vis_type_vega/public/data_model/vega_parser.ts +++ b/src/plugins/vis_type_vega/public/data_model/vega_parser.ts @@ -55,7 +55,6 @@ const locToDirMap: Record = { top: 'column-reverse', bottom: 'column', }; -const DEFAULT_SCHEMA: string = 'https://vega.github.io/schema/vega/v5.json'; // If there is no "%type%" parameter, use this parser const DEFAULT_PARSER: string = 'elasticsearch'; @@ -117,8 +116,27 @@ export class VegaParser { if (this.isVegaLite !== undefined) throw new Error(); if (typeof this.spec === 'string') { - this.spec = hjson.parse(this.spec, { legacyRoot: false }); + const spec = hjson.parse(this.spec, { legacyRoot: false }); + + if (!spec.$schema) { + throw new Error( + i18n.translate('visTypeVega.vegaParser.inputSpecDoesNotSpecifySchemaErrorMessage', { + defaultMessage: `Your specification requires a {schemaParam} field with a valid URL for +Vega (see {vegaSchemaUrl}) or +Vega-Lite (see {vegaLiteSchemaUrl}). +The URL is an identifier only. Kibana and your browser will never access this URL.`, + values: { + schemaParam: '"$schema"', + vegaLiteSchemaUrl: 'https://vega.github.io/vega-lite/docs/spec.html#top-level', + vegaSchemaUrl: + 'https://vega.github.io/vega/docs/specification/#top-level-specification-properties', + }, + }) + ); + } + this.spec = spec; } + if (!_.isPlainObject(this.spec)) { throw new Error( i18n.translate('visTypeVega.vegaParser.invalidVegaSpecErrorMessage', { @@ -126,7 +144,7 @@ export class VegaParser { }) ); } - this.isVegaLite = this._parseSchema(); + this.isVegaLite = this.parseSchema(this.spec).isVegaLite; this.useHover = !this.isVegaLite; this._config = this._parseConfig(); @@ -497,23 +515,11 @@ export class VegaParser { /** * Parse Vega schema element - * @returns {boolean} is this a VegaLite schema? + * @returns {object} isVegaLite, libVersion * @private */ - _parseSchema() { - if (!this.spec) return false; - if (!this.spec.$schema) { - this._onWarning( - i18n.translate('visTypeVega.vegaParser.inputSpecDoesNotSpecifySchemaWarningMessage', { - defaultMessage: - 'The input spec does not specify a {schemaParam}, defaulting to {defaultSchema}', - values: { defaultSchema: `"${DEFAULT_SCHEMA}"`, schemaParam: '"$schema"' }, - }) - ); - this.spec.$schema = DEFAULT_SCHEMA; - } - - const schema = schemaParser(this.spec.$schema); + private parseSchema(spec: VegaSpec) { + const schema = schemaParser(spec.$schema); const isVegaLite = schema.library === 'vega-lite'; const libVersion = isVegaLite ? vegaLite.version : vega.version; @@ -531,7 +537,7 @@ export class VegaParser { ); } - return isVegaLite; + return { isVegaLite, libVersion }; } /** diff --git a/src/plugins/vis_type_vega/public/vega_inspector/components/spec_viewer.tsx b/src/plugins/vis_type_vega/public/vega_inspector/components/spec_viewer.tsx index 54f7974960aa2..1c3f178eeab74 100644 --- a/src/plugins/vis_type_vega/public/vega_inspector/components/spec_viewer.tsx +++ b/src/plugins/vis_type_vega/public/vega_inspector/components/spec_viewer.tsx @@ -66,7 +66,13 @@ export const SpecViewer = ({ vegaAdapter, ...rest }: SpecViewerProps) => {
{(copy) => ( - + {copyToClipboardLabel} )} diff --git a/src/plugins/vis_type_vega/public/vega_inspector/vega_data_inspector.tsx b/src/plugins/vis_type_vega/public/vega_inspector/vega_data_inspector.tsx index 3b9427c96e62a..6dfa7a23c4fe8 100644 --- a/src/plugins/vis_type_vega/public/vega_inspector/vega_data_inspector.tsx +++ b/src/plugins/vis_type_vega/public/vega_inspector/vega_data_inspector.tsx @@ -47,11 +47,13 @@ export const VegaDataInspector = ({ adapters }: VegaDataInspectorProps) => { id: 'data-viewer--id', name: dataSetsLabel, content: , + 'data-test-subj': 'vegaDataInspectorDataViewerButton', }, { id: 'signal-viewer--id', name: signalValuesLabel, content: , + 'data-test-subj': 'vegaDataInspectorSignalViewerButton', }, { id: 'spec-viewer--id', @@ -59,6 +61,7 @@ export const VegaDataInspector = ({ adapters }: VegaDataInspectorProps) => { content: ( ), + 'data-test-subj': 'vegaDataInspectorSpecViewerButton', }, ]; diff --git a/test/functional/apps/visualize/_vega_chart.ts b/test/functional/apps/visualize/_vega_chart.ts index a1ed8460f1b22..b59d9590bb62a 100644 --- a/test/functional/apps/visualize/_vega_chart.ts +++ b/test/functional/apps/visualize/_vega_chart.ts @@ -16,10 +16,25 @@ * specific language governing permissions and limitations * under the License. */ - +import { unzip } from 'lodash'; import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; +const getTestSpec = (expression: string) => ` +{ +config: { "kibana": {"renderer": "svg"} } +$schema: https://vega.github.io/schema/vega/v5.json +marks: [{ + type: text + encode: { update: { text: { value: "Test" } } } +}] +signals: [ { + on: [{ + events: click + update: ${expression} + }] +}]}`; + export default function ({ getPageObjects, getService }: FtrProviderContext) { const PageObjects = getPageObjects([ 'timePicker', @@ -29,7 +44,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { 'vegaChart', ]); const filterBar = getService('filterBar'); + const inspector = getService('inspector'); + const vegaDebugInspectorView = getService('vegaDebugInspector'); const log = getService('log'); + const retry = getService('retry'); + const browser = getService('browser'); describe('vega chart in visualize app', () => { before(async () => { @@ -88,5 +107,177 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); }); }); + + describe('Inspector Panel', () => { + it('should have inspector enabled', async () => { + await inspector.expectIsEnabled(); + }); + + describe('Request Tab', () => { + beforeEach(async () => { + await inspector.open(); + }); + + afterEach(async () => { + await inspector.close(); + }); + + it('should contain "Statistics", "Request", "Response" tabs', async () => { + await inspector.openInspectorRequestsView(); + + for (const getFn of [ + inspector.getOpenRequestDetailRequestButton, + inspector.getOpenRequestDetailResponseButton, + inspector.getOpenRequestStatisticButton, + ]) { + await retry.try(async () => { + const requestStatisticTab = await getFn(); + + expect(await requestStatisticTab.isEnabled()).to.be(true); + }); + } + }); + + it('should set the default query name if not given in the schema', async () => { + const requests = await inspector.getRequestNames(); + + expect(requests).to.be('Unnamed request #0'); + }); + + it('should log the request statistic', async () => { + await inspector.openInspectorRequestsView(); + const rawTableData = await inspector.getTableData(); + + expect(unzip(rawTableData)[0].join(', ')).to.be( + 'Hits, Hits (total), Query time, Request timestamp' + ); + }); + }); + + describe('Debug Tab', () => { + beforeEach(async () => { + await inspector.open(); + }); + + afterEach(async () => { + await inspector.close(); + }); + + it('should contain "Data Sets", "Signal Values", "Spec" tabs', async () => { + await vegaDebugInspectorView.openVegaDebugInspectorView(); + + for (const getFn of [ + vegaDebugInspectorView.getOpenDataViewerButton, + vegaDebugInspectorView.getOpenSignalViewerButton, + vegaDebugInspectorView.getOpenSpecViewerButton, + ]) { + await retry.try(async () => { + const requestStatisticTab = await getFn(); + + expect(await requestStatisticTab.isEnabled()).to.be(true); + }); + } + }); + + it('should contain data on "Signal Values" tab', async () => { + await vegaDebugInspectorView.openVegaDebugInspectorView(); + await vegaDebugInspectorView.navigateToSignalViewerTab(); + + const { rows, columns } = await vegaDebugInspectorView.getGridTableData(); + + expect(columns.join(', ')).to.be('Signal, Value'); + expect(rows.length).to.be.greaterThan(0); + expect(rows[0].length).to.be(2); + }); + + it('should contain data on "Signal Values" tab', async () => { + await vegaDebugInspectorView.openVegaDebugInspectorView(); + await vegaDebugInspectorView.navigateToDataViewerTab(); + + const { rows, columns } = await vegaDebugInspectorView.getGridTableData(); + + expect(columns.length).to.be.greaterThan(0); + expect(rows.length).to.be.greaterThan(0); + }); + + it('should be able to copy vega spec to clipboard', async () => { + await vegaDebugInspectorView.openVegaDebugInspectorView(); + await vegaDebugInspectorView.navigateToSpecViewerTab(); + + const copyCopyToClipboardButton = await vegaDebugInspectorView.getCopyClipboardButton(); + + expect(await copyCopyToClipboardButton.isEnabled()).to.be(true); + + // The "clipboard-read" permission of the Permissions API must be granted + if (!(await browser.checkBrowserPermission('clipboard-read'))) { + return; + } + + await copyCopyToClipboardButton.click(); + + expect( + (await browser.getClipboardValue()).includes( + '"$schema": "https://vega.github.io/schema/vega-lite/' + ) + ).to.be(true); + }); + }); + }); + + describe('Vega extension functions', () => { + beforeEach(async () => { + await filterBar.removeAllFilters(); + }); + + const fillSpecAndGo = async (newSpec: string) => { + await PageObjects.vegaChart.fillSpec(newSpec); + await PageObjects.visEditor.clickGo(); + + const viewContainer = await PageObjects.vegaChart.getViewContainer(); + const textElement = await viewContainer.findByTagName('text'); + + await textElement.click(); + }; + + it('should update global time range by calling "kibanaSetTimeFilter" expression', async () => { + await fillSpecAndGo(getTestSpec('kibanaSetTimeFilter("2019", "2020")')); + + const currentTimeRange = await PageObjects.timePicker.getTimeConfig(); + + expect(currentTimeRange.start).to.be('Jan 1, 2019 @ 00:00:00.000'); + expect(currentTimeRange.end).to.be('Jan 1, 2020 @ 00:00:00.000'); + }); + + it('should set filter by calling "kibanaAddFilter" expression', async () => { + await fillSpecAndGo( + getTestSpec('kibanaAddFilter({ query_string: { query: "response:200" }})') + ); + + expect(await filterBar.getFilterCount()).to.be(1); + }); + + it('should remove filter by calling "kibanaRemoveFilter" expression', async () => { + await filterBar.addFilter('response', 'is', '200'); + + expect(await filterBar.getFilterCount()).to.be(1); + + await fillSpecAndGo( + getTestSpec('kibanaRemoveFilter({ match_phrase: { response: "200" }})') + ); + + expect(await filterBar.getFilterCount()).to.be(0); + }); + + it('should remove all filters by calling "kibanaRemoveAllFilters" expression', async () => { + await filterBar.addFilter('response', 'is', '200'); + await filterBar.addFilter('response', 'is', '500'); + + expect(await filterBar.getFilterCount()).to.be(2); + + await fillSpecAndGo(getTestSpec('kibanaRemoveAllFilters()')); + + expect(await filterBar.getFilterCount()).to.be(0); + }); + }); }); } diff --git a/test/functional/page_objects/vega_chart_page.ts b/test/functional/page_objects/vega_chart_page.ts index b9906911b00f1..1173c35af3384 100644 --- a/test/functional/page_objects/vega_chart_page.ts +++ b/test/functional/page_objects/vega_chart_page.ts @@ -18,8 +18,14 @@ */ import { Key } from 'selenium-webdriver'; +import expect from '@kbn/expect'; import { FtrProviderContext } from '../ftr_provider_context'; +const compareSpecs = (first: string, second: string) => { + const normalizeSpec = (spec: string) => spec.replace(/[\n ]/g, ''); + return normalizeSpec(first) === normalizeSpec(second); +}; + export function VegaChartPageProvider({ getService, getPageObjects, @@ -28,24 +34,57 @@ export function VegaChartPageProvider({ const testSubjects = getService('testSubjects'); const browser = getService('browser'); const { common } = getPageObjects(['common']); + const retry = getService('retry'); class VegaChartPage { - public async getSpec() { + public getEditor() { + return testSubjects.find('vega-editor'); + } + + public getViewContainer() { + return find.byCssSelector('div.vgaVis__view'); + } + + public getControlContainer() { + return find.byCssSelector('div.vgaVis__controls'); + } + + public async getRawSpec() { // Adapted from console_page.js:getVisibleTextFromAceEditor(). Is there a common utilities file? - const editor = await testSubjects.find('vega-editor'); + const editor = await this.getEditor(); const lines = await editor.findAllByClassName('ace_line_group'); - const linesText = await Promise.all( + + return await Promise.all( lines.map(async (line) => { return await line.getVisibleText(); }) ); - return linesText.join('\n'); } - public async typeInSpec(text: string) { - const editor = await testSubjects.find('vega-editor'); + public async getSpec() { + return (await this.getRawSpec()).join('\n'); + } + + public async focusEditor() { + const editor = await this.getEditor(); const textarea = await editor.findByClassName('ace_content'); + await textarea.click(); + } + + public async fillSpec(newSpec: string) { + await retry.try(async () => { + await this.cleanSpec(); + await this.focusEditor(); + await browser.pressKeys(newSpec); + + expect(compareSpecs(await this.getSpec(), newSpec)).to.be(true); + }); + } + + public async typeInSpec(text: string) { + await this.focusEditor(); + let repeats = 20; while (--repeats > 0) { await browser.pressKeys(Key.ARROW_UP); @@ -55,12 +94,16 @@ export function VegaChartPageProvider({ await browser.pressKeys(text); } - public async getViewContainer() { - return await find.byCssSelector('div.vgaVis__view'); - } + public async cleanSpec() { + const editor = await this.getEditor(); + const aceGutter = await editor.findByClassName('ace_gutter'); + + await retry.try(async () => { + await aceGutter.doubleClick(); + await browser.pressKeys(Key.BACK_SPACE); - public async getControlContainer() { - return await find.byCssSelector('div.vgaVis__controls'); + expect(await this.getSpec()).to.be(''); + }); } public async getYAxisLabels() { diff --git a/test/functional/services/common/browser.ts b/test/functional/services/common/browser.ts index b0eec5e24f635..e81845023a8fa 100644 --- a/test/functional/services/common/browser.ts +++ b/test/functional/services/common/browser.ts @@ -489,5 +489,17 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { const _id = idOrElement instanceof WebElementWrapper ? idOrElement._webElement : idOrElement; await driver.switchTo().frame(_id); } + + public async checkBrowserPermission(permission: string): Promise { + const result: any = await driver.executeAsyncScript( + `navigator.permissions.query({name:'${permission}'}).then(arguments[0])` + ); + + return Boolean(result?.state === 'granted'); + } + + public getClipboardValue(): Promise { + return driver.executeAsyncScript('navigator.clipboard.readText().then(arguments[0])'); + } })(); } diff --git a/test/functional/services/data_grid.ts b/test/functional/services/data_grid.ts new file mode 100644 index 0000000000000..40157caab5756 --- /dev/null +++ b/test/functional/services/data_grid.ts @@ -0,0 +1,55 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { FtrProviderContext } from '../ftr_provider_context'; + +interface TabbedGridData { + columns: string[]; + rows: string[][]; +} + +export function DataGridProvider({ getService }: FtrProviderContext) { + const find = getService('find'); + + class DataGrid { + async getDataGridTableData(): Promise { + const table = await find.byCssSelector('.euiDataGrid'); + const $ = await table.parseDomContent(); + + const columns = $('.euiDataGridHeaderCell__content') + .toArray() + .map((cell) => $(cell).text()); + const rows = $.findTestSubjects('dataGridRow') + .toArray() + .map((row) => + $(row) + .find('.euiDataGridRowCell__truncate') + .toArray() + .map((cell) => $(cell).text()) + ); + + return { + columns, + rows, + }; + } + } + + return new DataGrid(); +} diff --git a/test/functional/services/index.ts b/test/functional/services/index.ts index 7891a6b00f729..4c97d672bae2e 100644 --- a/test/functional/services/index.ts +++ b/test/functional/services/index.ts @@ -47,7 +47,12 @@ import { RemoteProvider } from './remote'; import { RenderableProvider } from './renderable'; import { TableProvider } from './table'; import { ToastsProvider } from './toasts'; -import { PieChartProvider, ElasticChartProvider } from './visualizations'; +import { DataGridProvider } from './data_grid'; +import { + PieChartProvider, + ElasticChartProvider, + VegaDebugInspectorViewProvider, +} from './visualizations'; import { ListingTableProvider } from './listing_table'; import { SavedQueryManagementComponentProvider } from './saved_query_management_component'; import { KibanaSupertestProvider } from './supertest'; @@ -72,12 +77,14 @@ export const services = { dashboardPanelActions: DashboardPanelActionsProvider, flyout: FlyoutProvider, comboBox: ComboBoxProvider, + dataGrid: DataGridProvider, embedding: EmbeddingProvider, renderable: RenderableProvider, table: TableProvider, browser: BrowserProvider, pieChart: PieChartProvider, inspector: InspectorProvider, + vegaDebugInspector: VegaDebugInspectorViewProvider, appsMenu: AppsMenuProvider, globalNav: GlobalNavProvider, toasts: ToastsProvider, diff --git a/test/functional/services/inspector.ts b/test/functional/services/inspector.ts index d8ac224ddd9bc..1c0bf7ad46df1 100644 --- a/test/functional/services/inspector.ts +++ b/test/functional/services/inspector.ts @@ -233,6 +233,18 @@ export function InspectorProvider({ getService }: FtrProviderContext) { const singleRequest = await testSubjects.find('inspectorRequestName'); return await singleRequest.getVisibleText(); } + + public getOpenRequestStatisticButton() { + return testSubjects.find('inspectorRequestDetailStatistics'); + } + + public getOpenRequestDetailRequestButton() { + return testSubjects.find('inspectorRequestDetailRequest'); + } + + public getOpenRequestDetailResponseButton() { + return testSubjects.find('inspectorRequestDetailResponse'); + } } return new Inspector(); diff --git a/test/functional/services/remote/webdriver.ts b/test/functional/services/remote/webdriver.ts index 09fede7fe2546..d51b32f3cc497 100644 --- a/test/functional/services/remote/webdriver.ts +++ b/test/functional/services/remote/webdriver.ts @@ -53,9 +53,15 @@ const SECOND = 1000; const MINUTE = 60 * SECOND; const NO_QUEUE_COMMANDS = ['getLog', 'getStatus', 'newSession', 'quit']; const downloadDir = resolve(REPO_ROOT, 'target/functional-tests/downloads'); -const chromiumDownloadPrefs = { +const chromiumUserPrefs = { 'download.default_directory': downloadDir, 'download.prompt_for_download': false, + 'profile.content_settings.exceptions.clipboard': { + '[*.],*': { + last_modified: Date.now(), + setting: 1, + }, + }, }; /** @@ -135,7 +141,7 @@ async function attemptToCreateCommand( const prefs = new logging.Preferences(); prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); - chromeOptions.setUserPreferences(chromiumDownloadPrefs); + chromeOptions.setUserPreferences(chromiumUserPrefs); chromeOptions.setLoggingPrefs(prefs); chromeOptions.set('unexpectedAlertBehaviour', 'accept'); chromeOptions.setAcceptInsecureCerts(config.acceptInsecureCerts); @@ -185,7 +191,7 @@ async function attemptToCreateCommand( edgeOptions.setBinaryPath(edgePaths.browserPath); const options = edgeOptions.get('ms:edgeOptions'); // overriding options to include preferences - Object.assign(options, { prefs: chromiumDownloadPrefs }); + Object.assign(options, { prefs: chromiumUserPrefs }); edgeOptions.set('ms:edgeOptions', options); const session = await new Builder() .forBrowser('MicrosoftEdge') diff --git a/test/functional/services/visualizations/index.ts b/test/functional/services/visualizations/index.ts index 1da1691b07c2a..10019e63d684e 100644 --- a/test/functional/services/visualizations/index.ts +++ b/test/functional/services/visualizations/index.ts @@ -19,3 +19,4 @@ export { PieChartProvider } from './pie_chart'; export { ElasticChartProvider } from './elastic_chart'; +export { VegaDebugInspectorViewProvider } from './vega_debug_inspector'; diff --git a/test/functional/services/visualizations/vega_debug_inspector.ts b/test/functional/services/visualizations/vega_debug_inspector.ts new file mode 100644 index 0000000000000..3847ebbbf1279 --- /dev/null +++ b/test/functional/services/visualizations/vega_debug_inspector.ts @@ -0,0 +1,68 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import { FtrProviderContext } from '../../ftr_provider_context'; + +export function VegaDebugInspectorViewProvider({ getService }: FtrProviderContext) { + const testSubjects = getService('testSubjects'); + const inspector = getService('inspector'); + const dataGrid = getService('dataGrid'); + + class VegaDebugInspectorView { + async openVegaDebugInspectorView() { + await inspector.openInspectorView('inspectorViewChooserVega debug'); + } + + public getOpenDataViewerButton() { + return testSubjects.find('vegaDataInspectorDataViewerButton'); + } + + public getOpenSignalViewerButton() { + return testSubjects.find('vegaDataInspectorSignalViewerButton'); + } + + public getOpenSpecViewerButton() { + return testSubjects.find('vegaDataInspectorSpecViewerButton'); + } + + public getCopyClipboardButton() { + return testSubjects.find('vegaDataInspectorCopyClipboardButton'); + } + + public getGridTableData() { + return dataGrid.getDataGridTableData(); + } + + public async navigateToDataViewerTab() { + const dataViewerButton = await this.getOpenDataViewerButton(); + await dataViewerButton.click(); + } + + public async navigateToSignalViewerTab() { + const signalViewerButton = await this.getOpenSignalViewerButton(); + await signalViewerButton.click(); + } + + public async navigateToSpecViewerTab() { + const specViewerButton = await this.getOpenSpecViewerButton(); + await specViewerButton.click(); + } + } + + return new VegaDebugInspectorView(); +} diff --git a/x-pack/package.json b/x-pack/package.json index 962233a3a3973..b426e790c2d47 100644 --- a/x-pack/package.json +++ b/x-pack/package.json @@ -217,7 +217,7 @@ "@kbn/interpreter": "1.0.0", "@kbn/ui-framework": "1.0.0", "@mapbox/geojson-rewind": "^0.4.1", - "@mapbox/mapbox-gl-draw": "^1.1.2", + "@mapbox/mapbox-gl-draw": "^1.2.0", "@mapbox/mapbox-gl-rtl-text": "^0.2.3", "@scant/router": "^0.1.0", "@slack/webhook": "^5.0.0", @@ -397,4 +397,4 @@ "cypress-multi-reporters" ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/data_enhanced/common/index.ts b/x-pack/plugins/data_enhanced/common/index.ts index 4d38e5486907c..1f1cd938c97d1 100644 --- a/x-pack/plugins/data_enhanced/common/index.ts +++ b/x-pack/plugins/data_enhanced/common/index.ts @@ -4,9 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { - EnhancedSearchParams, - IEnhancedEsSearchRequest, - IAsyncSearchRequest, - IAsyncSearchResponse, -} from './search'; +export { EnhancedSearchParams, IEnhancedEsSearchRequest, IAsyncSearchRequest } from './search'; diff --git a/x-pack/plugins/data_enhanced/common/search/index.ts b/x-pack/plugins/data_enhanced/common/search/index.ts index 9137e551adeb2..129e412a47ccf 100644 --- a/x-pack/plugins/data_enhanced/common/search/index.ts +++ b/x-pack/plugins/data_enhanced/common/search/index.ts @@ -4,9 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { - EnhancedSearchParams, - IEnhancedEsSearchRequest, - IAsyncSearchRequest, - IAsyncSearchResponse, -} from './types'; +export { EnhancedSearchParams, IEnhancedEsSearchRequest, IAsyncSearchRequest } from './types'; diff --git a/x-pack/plugins/data_enhanced/common/search/types.ts b/x-pack/plugins/data_enhanced/common/search/types.ts index c29deee5e4cb3..a5d7d326cecd5 100644 --- a/x-pack/plugins/data_enhanced/common/search/types.ts +++ b/x-pack/plugins/data_enhanced/common/search/types.ts @@ -4,11 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - IEsSearchRequest, - IEsSearchResponse, - ISearchRequestParams, -} from '../../../../../src/plugins/data/common'; +import { IEsSearchRequest, ISearchRequestParams } from '../../../../../src/plugins/data/common'; export interface EnhancedSearchParams extends ISearchRequestParams { ignoreThrottled: boolean; @@ -23,17 +19,6 @@ export interface IAsyncSearchRequest extends IEsSearchRequest { params?: EnhancedSearchParams; } -export interface IAsyncSearchResponse extends IEsSearchResponse { - /** - * Indicates whether async search is still in flight - */ - is_running?: boolean; - /** - * Indicates whether the results returned are complete or partial - */ - is_partial?: boolean; -} - export interface IEnhancedEsSearchRequest extends IEsSearchRequest { /** * Used to determine whether to use the _rollups_search or a regular search endpoint. diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts index 639f56d0cafca..d004511fa4674 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts @@ -72,8 +72,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, rawResponse: { took: 1, @@ -99,8 +99,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: false, - is_running: true, + isPartial: false, + isRunning: true, id: 1, rawResponse: { took: 1, @@ -110,8 +110,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 20, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, rawResponse: { took: 1, @@ -144,8 +144,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: true, - is_running: false, + isPartial: true, + isRunning: false, id: 1, }, }, @@ -168,8 +168,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 500, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, }, @@ -194,16 +194,16 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: false, - is_running: true, + isPartial: false, + isRunning: true, id: 1, }, }, { time: 300, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, }, @@ -238,8 +238,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 2000, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, }, @@ -262,16 +262,16 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: false, - is_running: true, + isPartial: false, + isRunning: true, id: 1, }, }, { time: 2000, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, }, @@ -302,8 +302,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: false, - is_running: true, + isPartial: false, + isRunning: true, id: 1, }, }, @@ -311,8 +311,8 @@ describe('EnhancedSearchInterceptor', () => { time: 10, value: { error: 'oh no', - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, isError: true, @@ -346,16 +346,16 @@ describe('EnhancedSearchInterceptor', () => { { time: 10, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, }, { time: 20, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, }, }, @@ -380,8 +380,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 250, value: { - is_partial: true, - is_running: true, + isPartial: true, + isRunning: true, id: 1, rawResponse: { took: 1, @@ -391,8 +391,8 @@ describe('EnhancedSearchInterceptor', () => { { time: 2000, value: { - is_partial: false, - is_running: false, + isPartial: false, + isRunning: false, id: 1, rawResponse: { took: 1, diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts index 9662b9e17248b..bff9e2cb9048c 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Observable, throwError, EMPTY, timer, from } from 'rxjs'; +import { throwError, EMPTY, timer, from } from 'rxjs'; import { mergeMap, expand, takeUntil, finalize, tap } from 'rxjs/operators'; import { getLongQueryNotification } from './long_query_notification'; import { @@ -14,7 +14,7 @@ import { } from '../../../../../src/plugins/data/public'; import { AbortError, toPromise } from '../../../../../src/plugins/data/common'; import { IAsyncSearchOptions } from '.'; -import { IAsyncSearchRequest, IAsyncSearchResponse } from '../../common'; +import { IAsyncSearchRequest } from '../../common'; export class EnhancedSearchInterceptor extends SearchInterceptor { /** @@ -67,7 +67,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { public search( request: IAsyncSearchRequest, { pollInterval = 1000, ...options }: IAsyncSearchOptions = {} - ): Observable { + ) { let { id } = request; request.params = { @@ -80,15 +80,15 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { this.pendingCount$.next(++this.pendingCount); - return (this.runSearch(request, combinedSignal) as Observable).pipe( - expand((response: IAsyncSearchResponse) => { + return this.runSearch(request, combinedSignal, options?.strategy).pipe( + expand((response) => { // If the response indicates of an error, stop polling and complete the observable - if (!response || (!response.is_running && response.is_partial)) { + if (!response || (!response.isRunning && response.isPartial)) { return throwError(new AbortError()); } // If the response indicates it is complete, stop polling and complete the observable - if (!response.is_running) { + if (!response.isRunning) { return EMPTY; } @@ -97,7 +97,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { return timer(pollInterval).pipe( // Send future requests using just the ID from the response mergeMap(() => { - return this.runSearch({ id }, combinedSignal) as Observable; + return this.runSearch({ id }, combinedSignal, options?.strategy); }) ); }), diff --git a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts index 0ed5485cfb6c9..95f1285363f49 100644 --- a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts +++ b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts @@ -128,8 +128,8 @@ async function asyncSearch( return { id, - is_partial, - is_running, + isPartial: is_partial, + isRunning: is_running, rawResponse: shimHitsTotal(response), ...getTotalLoaded(response._shards), }; diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js b/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js index ac28a2d5d5a6d..2daa4b2c900f5 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js @@ -18,9 +18,12 @@ import { } from '../../../../elasticsearch_geo_utils'; import { DrawTooltip } from './draw_tooltip'; +const DRAW_RECTANGLE = 'draw_rectangle'; +const DRAW_CIRCLE = 'draw_circle'; + const mbDrawModes = MapboxDraw.modes; -mbDrawModes.draw_rectangle = DrawRectangle; -mbDrawModes.draw_circle = DrawCircle; +mbDrawModes[DRAW_RECTANGLE] = DrawRectangle; +mbDrawModes[DRAW_CIRCLE] = DrawCircle; export class DrawControl extends React.Component { constructor() { @@ -45,8 +48,10 @@ export class DrawControl extends React.Component { this._removeDrawControl(); } + // debounce with zero timeout needed to allow mapbox-draw finish logic to complete + // before _removeDrawControl is called _syncDrawControl = _.debounce(() => { - if (!this.props.mbMap) { + if (!this._isMounted) { return; } @@ -55,7 +60,7 @@ export class DrawControl extends React.Component { } else { this._removeDrawControl(); } - }, 256); + }, 0); _onDraw = (e) => { if (!e.features.length) { @@ -118,7 +123,7 @@ export class DrawControl extends React.Component { }; _removeDrawControl() { - if (!this._mbDrawControlAdded) { + if (!this.props.mbMap || !this._mbDrawControlAdded) { return; } @@ -129,6 +134,10 @@ export class DrawControl extends React.Component { } _updateDrawControl() { + if (!this.props.mbMap) { + return; + } + if (!this._mbDrawControlAdded) { this.props.mbMap.addControl(this._mbDrawControl); this._mbDrawControlAdded = true; @@ -136,11 +145,15 @@ export class DrawControl extends React.Component { this.props.mbMap.on('draw.create', this._onDraw); } - if (this.props.drawState.drawType === DRAW_TYPE.BOUNDS) { - this._mbDrawControl.changeMode('draw_rectangle'); - } else if (this.props.drawState.drawType === DRAW_TYPE.DISTANCE) { - this._mbDrawControl.changeMode('draw_circle'); - } else if (this.props.drawState.drawType === DRAW_TYPE.POLYGON) { + const drawMode = this._mbDrawControl.getMode(); + if (drawMode !== DRAW_RECTANGLE && this.props.drawState.drawType === DRAW_TYPE.BOUNDS) { + this._mbDrawControl.changeMode(DRAW_RECTANGLE); + } else if (drawMode !== DRAW_CIRCLE && this.props.drawState.drawType === DRAW_TYPE.DISTANCE) { + this._mbDrawControl.changeMode(DRAW_CIRCLE); + } else if ( + drawMode !== this._mbDrawControl.modes.DRAW_POLYGON && + this.props.drawState.drawType === DRAW_TYPE.POLYGON + ) { this._mbDrawControl.changeMode(this._mbDrawControl.modes.DRAW_POLYGON); } } diff --git a/x-pack/plugins/maps/public/routing/routes/maps_app/index.js b/x-pack/plugins/maps/public/routing/routes/maps_app/index.js index c5f959c54fb66..a2a4ab87affcd 100644 --- a/x-pack/plugins/maps/public/routing/routes/maps_app/index.js +++ b/x-pack/plugins/maps/public/routing/routes/maps_app/index.js @@ -14,7 +14,7 @@ import { getRefreshConfig, getTimeFilters, hasDirtyState, - hasUnsavedChanges, + getLayerListConfigOnly, } from '../../../selectors/map_selectors'; import { replaceLayerList, @@ -45,9 +45,7 @@ function mapStateToProps(state = {}) { flyoutDisplay: getFlyoutDisplay(state), refreshConfig: getRefreshConfig(state), filters: getFilters(state), - hasUnsavedChanges: (savedMap, initialLayerListConfig) => { - return hasUnsavedChanges(state, savedMap, initialLayerListConfig); - }, + layerListConfigOnly: getLayerListConfigOnly(state), query: getQuery(state), timeFilters: getTimeFilters(state), }; diff --git a/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js b/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js index 97a08f11a6757..91d00990772f4 100644 --- a/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js +++ b/x-pack/plugins/maps/public/routing/routes/maps_app/maps_app_view.js @@ -103,7 +103,15 @@ export class MapsAppView extends React.Component { } _hasUnsavedChanges() { - return this.props.hasUnsavedChanges(this.props.savedMap, this.state.initialLayerListConfig); + const savedLayerList = this.props.savedMap.getLayerList(); + return !savedLayerList + ? !_.isEqual(this.props.layerListConfigOnly, this.state.initialLayerListConfig) + : // savedMap stores layerList as a JSON string using JSON.stringify. + // JSON.stringify removes undefined properties from objects. + // savedMap.getLayerList converts the JSON string back into Javascript array of objects. + // Need to perform the same process for layerListConfigOnly to compare apples to apples + // and avoid undefined properties in layerListConfigOnly triggering unsaved changes. + !_.isEqual(JSON.parse(JSON.stringify(this.props.layerListConfigOnly)), savedLayerList); } _setBreadcrumbs = () => { @@ -356,22 +364,20 @@ export class MapsAppView extends React.Component { ); } - render() { - const { filters, isFullScreen } = this.props; + _addFilter = (newFilters) => { + newFilters.forEach((filter) => { + filter.$state = { store: esFilters.FilterStateStore.APP_STATE }; + }); + this._onFiltersChange([...this.props.filters, ...newFilters]); + }; + render() { return this.state.initialized ? ( -
+
{this._renderTopNav()}

{`screenTitle placeholder`}

- { - newFilters.forEach((filter) => { - filter.$state = { store: esFilters.FilterStateStore.APP_STATE }; - }); - this._onFiltersChange([...filters, ...newFilters]); - }} - /> +
) : null; diff --git a/x-pack/plugins/maps/public/selectors/map_selectors.ts b/x-pack/plugins/maps/public/selectors/map_selectors.ts index e082398a02a9e..40ffda3f31c26 100644 --- a/x-pack/plugins/maps/public/selectors/map_selectors.ts +++ b/x-pack/plugins/maps/public/selectors/map_selectors.ts @@ -52,7 +52,6 @@ import { ISource } from '../classes/sources/source'; import { ITMSSource } from '../classes/sources/tms_source'; import { IVectorSource } from '../classes/sources/vector_source'; import { ILayer } from '../classes/layers/layer'; -import { ISavedGisMap } from '../routing/bootstrap/services/saved_gis_map'; function createLayerInstance( layerDescriptor: LayerDescriptor, @@ -298,6 +297,10 @@ export const getLayerList = createSelector( } ); +export const getLayerListConfigOnly = createSelector(getLayerListRaw, (layerDescriptorList) => { + return copyPersistentState(layerDescriptorList); +}); + export function getLayerById(layerId: string | null, state: MapStoreState): ILayer | undefined { return getLayerList(state).find((layer) => { return layerId === layer.getId(); @@ -417,22 +420,3 @@ export const areLayersLoaded = createSelector( return true; } ); - -export function hasUnsavedChanges( - state: MapStoreState, - savedMap: ISavedGisMap, - initialLayerListConfig: LayerDescriptor[] -) { - const layerListConfigOnly = copyPersistentState(getLayerListRaw(state)); - - const savedLayerList = savedMap.getLayerList(); - - return !savedLayerList - ? !_.isEqual(layerListConfigOnly, initialLayerListConfig) - : // savedMap stores layerList as a JSON string using JSON.stringify. - // JSON.stringify removes undefined properties from objects. - // savedMap.getLayerList converts the JSON string back into Javascript array of objects. - // Need to perform the same process for layerListConfigOnly to compare apples to apples - // and avoid undefined properties in layerListConfigOnly triggering unsaved changes. - !_.isEqual(JSON.parse(JSON.stringify(layerListConfigOnly)), savedLayerList); -} diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index bb0e351ebfec8..8e6933ed5924f 100644 --- a/x-pack/plugins/ml/common/util/job_utils.ts +++ b/x-pack/plugins/ml/common/util/job_utils.ts @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import isEmpty from 'lodash/isEmpty'; +import isEqual from 'lodash/isEqual'; +import each from 'lodash/each'; +import pick from 'lodash/pick'; + import semver from 'semver'; import moment, { Duration } from 'moment'; // @ts-ignore @@ -307,7 +311,7 @@ export function getSafeAggregationName(fieldName: string, index: number): string export function uniqWithIsEqual(arr: T): T { return arr.reduce((dedupedArray, value) => { - if (dedupedArray.filter((compareValue: any) => _.isEqual(compareValue, value)).length === 0) { + if (dedupedArray.filter((compareValue: any) => isEqual(compareValue, value)).length === 0) { dedupedArray.push(value); } return dedupedArray; @@ -328,7 +332,7 @@ export function basicJobValidation( if (job) { // Job details - if (_.isEmpty(job.job_id)) { + if (isEmpty(job.job_id)) { messages.push({ id: 'job_id_empty' }); valid = false; } else if (isJobIdValid(job.job_id) === false) { @@ -350,7 +354,7 @@ export function basicJobValidation( // Analysis Configuration if (job.analysis_config.categorization_filters) { let v = true; - _.each(job.analysis_config.categorization_filters, (d) => { + each(job.analysis_config.categorization_filters, (d) => { try { new RegExp(d); } catch (e) { @@ -382,8 +386,8 @@ export function basicJobValidation( valid = false; } else { let v = true; - _.each(job.analysis_config.detectors, (d) => { - if (_.isEmpty(d.function)) { + each(job.analysis_config.detectors, (d) => { + if (isEmpty(d.function)) { v = false; } }); @@ -400,7 +404,7 @@ export function basicJobValidation( // create an array of objects with a subset of the attributes // where we want to make sure they are not be the same across detectors const compareSubSet = job.analysis_config.detectors.map((d) => - _.pick(d, [ + pick(d, [ 'function', 'field_name', 'by_field_name', diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js index 69f7635a66032..c6ca4fb821984 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js +++ b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js @@ -9,7 +9,9 @@ * This version supports both fetching the annotations by itself (used in the jobs list) and * getting the annotations via props (used in Anomaly Explorer and Single Series Viewer). */ -import _ from 'lodash'; + +import uniq from 'lodash/uniq'; + import PropTypes from 'prop-types'; import rison from 'rison-node'; import React, { Component, Fragment } from 'react'; @@ -255,18 +257,18 @@ export class AnnotationsTable extends Component { // if the annotation is at the series level // then pass the partitioning field(s) and detector index to the Single Metric Viewer - if (_.has(annotation, 'detector_index')) { + if (annotation.detector_index !== undefined) { mlTimeSeriesExplorer.detectorIndex = annotation.detector_index; } - if (_.has(annotation, 'partition_field_value')) { + if (annotation.partition_field_value !== undefined) { entityCondition[annotation.partition_field_name] = annotation.partition_field_value; } - if (_.has(annotation, 'over_field_value')) { + if (annotation.over_field_value !== undefined) { entityCondition[annotation.over_field_name] = annotation.over_field_value; } - if (_.has(annotation, 'by_field_value')) { + if (annotation.by_field_value !== undefined) { // Note that analyses with by and over fields, will have a top-level by_field_name, // but the by_field_value(s) will be in the nested causes array. entityCondition[annotation.by_field_name] = annotation.by_field_value; @@ -421,7 +423,7 @@ export class AnnotationsTable extends Component { }, ]; - const jobIds = _.uniq(annotations.map((a) => a.job_id)); + const jobIds = uniq(annotations.map((a) => a.job_id)); if (jobIds.length > 1) { columns.unshift({ field: 'job_id', diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js index 2a890f75fecd8..378ee82805173 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js @@ -9,7 +9,7 @@ */ import PropTypes from 'prop-types'; -import _ from 'lodash'; +import get from 'lodash/get'; import React, { Component } from 'react'; @@ -70,7 +70,7 @@ class AnomaliesTable extends Component { } else { const examples = item.entityName === 'mlcategory' - ? _.get(this.props.tableData, ['examplesByJobId', item.jobId, item.entityValue]) + ? get(this.props.tableData, ['examplesByJobId', item.jobId, item.entityValue]) : undefined; let definition = undefined; diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js index af7c6c8e289f3..57f3a08713ffe 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js @@ -7,7 +7,7 @@ import { EuiButtonIcon, EuiLink, EuiScreenReaderOnly } from '@elastic/eui'; import React from 'react'; -import _ from 'lodash'; +import get from 'lodash/get'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -251,7 +251,7 @@ export function getColumns( sortable: false, truncateText: true, render: (item) => { - const examples = _.get(examplesByJobId, [item.jobId, item.entityValue], []); + const examples = get(examplesByJobId, [item.jobId, item.entityValue], []); return ( { - const simplified = _.pick(cause, 'typical', 'actual', 'probability'); + const simplified = pick(cause, 'typical', 'actual', 'probability'); // Get the 'entity field name/value' to display in the cause - // For by and over, use by_field_name/value (over_field_name/value are in the top level fields) // For just an 'over' field - the over_field_name/value appear in both top level and cause. - simplified.entityName = _.has(cause, 'by_field_name') - ? cause.by_field_name - : cause.over_field_name; - simplified.entityValue = _.has(cause, 'by_field_value') - ? cause.by_field_value - : cause.over_field_value; + simplified.entityName = cause.by_field_name ? cause.by_field_name : cause.over_field_name; + simplified.entityValue = cause.by_field_value ? cause.by_field_value : cause.over_field_value; return simplified; }); } @@ -471,7 +468,7 @@ export class AnomalyDetails extends Component { renderDetails() { const detailItems = getDetailsItems(this.props.anomaly, this.props.examples, this.props.filter); - const isInterimResult = _.get(this.props.anomaly, 'source.is_interim', false); + const isInterimResult = get(this.props.anomaly, 'source.is_interim', false); return ( diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js b/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js index 2e42606c048d7..abdb0961351ab 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import each from 'lodash/each'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; @@ -148,7 +148,7 @@ export class InfluencersCell extends Component { const influencers = []; recordInfluencers.forEach((influencer) => { - _.each(influencer, (influencerFieldValue, influencerFieldName) => { + each(influencer, (influencerFieldValue, influencerFieldName) => { influencers.push({ influencerFieldName, influencerFieldValue, diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js index f603264896cd3..0e4d736a01e47 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import cloneDeep from 'lodash/cloneDeep'; import moment from 'moment'; import rison from 'rison-node'; import PropTypes from 'prop-types'; @@ -58,7 +58,7 @@ class LinksMenuUI extends Component { // If url_value contains $earliest$ and $latest$ tokens, add in times to the source record. // Create a copy of the record as we are adding properties into it. - const record = _.cloneDeep(anomaly.source); + const record = cloneDeep(anomaly.source); const timestamp = record.timestamp; const configuredUrlValue = customUrl.url_value; const timeRangeInterval = parseInterval(customUrl.time_range); @@ -99,7 +99,7 @@ class LinksMenuUI extends Component { if ( (configuredUrlValue.includes('$mlcategoryterms$') || configuredUrlValue.includes('$mlcategoryregex$')) && - _.has(record, 'mlcategory') + record.mlcategory !== undefined ) { const jobId = record.job_id; @@ -156,15 +156,15 @@ class LinksMenuUI extends Component { // Extract the by, over and partition fields for the record. const entityCondition = {}; - if (_.has(record, 'partition_field_value')) { + if (record.partition_field_value !== undefined) { entityCondition[record.partition_field_name] = record.partition_field_value; } - if (_.has(record, 'over_field_value')) { + if (record.over_field_value !== undefined) { entityCondition[record.over_field_name] = record.over_field_value; } - if (_.has(record, 'by_field_value')) { + if (record.by_field_value !== undefined) { // Note that analyses with by and over fields, will have a top-level by_field_name, // but the by_field_value(s) will be in the nested causes array. // TODO - drilldown from cause in expanded row only? diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js index b5e9daad7d1c1..b75784c95c520 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js @@ -9,8 +9,6 @@ * the raw data in the Explorer dashboard. */ -import _ from 'lodash'; - import { parseInterval } from '../../../../common/util/parse_interval'; import { getEntityFieldList } from '../../../../common/util/anomaly_utils'; import { buildConfigFromDetector } from '../../util/chart_config_builder'; @@ -30,7 +28,7 @@ export function buildConfig(record) { config.detectorLabel = record.function; if ( - _.has(mlJobService.detectorsByJob, record.job_id) && + mlJobService.detectorsByJob[record.job_id] !== undefined && detectorIndex < mlJobService.detectorsByJob[record.job_id].length ) { config.detectorLabel = diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js index 7a18914957ba9..00aca5d43be85 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js @@ -11,8 +11,8 @@ import PropTypes from 'prop-types'; import React from 'react'; +import { i18n } from '@kbn/i18n'; -import _ from 'lodash'; import d3 from 'd3'; import $ from 'jquery'; import moment from 'moment'; @@ -33,8 +33,6 @@ import { mlFieldFormatService } from '../../services/field_format_service'; import { CHART_TYPE } from '../explorer_constants'; -import { i18n } from '@kbn/i18n'; - const CONTENT_WRAPPER_HEIGHT = 215; // If a rare/event-distribution chart has a cardinality of 10 or less, @@ -403,7 +401,7 @@ export class ExplorerChartDistribution extends React.Component { .attr('cy', (d) => lineChartYScale(d[CHART_Y_ATTRIBUTE])) .attr('class', (d) => { let markerClass = 'metric-value'; - if (_.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity) { + if (d.anomalyScore !== undefined && Number(d.anomalyScore) >= severity) { markerClass += ' anomaly-marker '; markerClass += getSeverityWithLow(d.anomalyScore).id; } @@ -444,7 +442,7 @@ export class ExplorerChartDistribution extends React.Component { const tooltipData = [{ label: formattedDate }]; const seriesKey = config.detectorLabel; - if (_.has(marker, 'entity')) { + if (marker.entity !== undefined) { tooltipData.push({ label: i18n.translate('xpack.ml.explorer.distributionChart.entityLabel', { defaultMessage: 'entity', @@ -457,7 +455,7 @@ export class ExplorerChartDistribution extends React.Component { }); } - if (_.has(marker, 'anomalyScore')) { + if (marker.anomalyScore !== undefined) { const score = parseInt(marker.anomalyScore); const displayScore = score > 0 ? score : '< 1'; tooltipData.push({ @@ -494,7 +492,7 @@ export class ExplorerChartDistribution extends React.Component { valueAccessor: 'typical', }); } - if (typeof marker.byFieldName !== 'undefined' && _.has(marker, 'numberOfCauses')) { + if (typeof marker.byFieldName !== 'undefined' && marker.numberOfCauses !== undefined) { tooltipData.push({ label: i18n.translate( 'xpack.ml.explorer.distributionChart.unusualByFieldValuesLabel', @@ -532,7 +530,7 @@ export class ExplorerChartDistribution extends React.Component { }); } - if (_.has(marker, 'scheduledEvents')) { + if (marker.scheduledEvents !== undefined) { marker.scheduledEvents.forEach((scheduledEvent, i) => { tooltipData.push({ label: i18n.translate( diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js index 63775c5ca312e..4d53e747d4855 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js @@ -12,10 +12,10 @@ import PropTypes from 'prop-types'; import React from 'react'; -import _ from 'lodash'; import d3 from 'd3'; import $ from 'jquery'; import moment from 'moment'; +import { i18n } from '@kbn/i18n'; import { formatHumanReadableDateTime } from '../../util/date_utils'; import { formatValue } from '../../formatters/format_value'; @@ -40,8 +40,6 @@ import { getTimeBucketsFromCache } from '../../util/time_buckets'; import { mlEscape } from '../../util/string_utils'; import { mlFieldFormatService } from '../../services/field_format_service'; -import { i18n } from '@kbn/i18n'; - const CONTENT_WRAPPER_HEIGHT = 215; const CONTENT_WRAPPER_CLASS = 'ml-explorer-chart-content-wrapper'; @@ -307,7 +305,7 @@ export class ExplorerChartSingleMetric extends React.Component { .on('mouseout', () => tooltipService.hide()); const isAnomalyVisible = (d) => - _.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity; + d.anomalyScore !== undefined && Number(d.anomalyScore) >= severity; // Update all dots to new positions. dots @@ -380,7 +378,7 @@ export class ExplorerChartSingleMetric extends React.Component { const tooltipData = [{ label: formattedDate }]; const seriesKey = config.detectorLabel; - if (_.has(marker, 'anomalyScore')) { + if (marker.anomalyScore !== undefined) { const score = parseInt(marker.anomalyScore); const displayScore = score > 0 ? score : '< 1'; tooltipData.push({ @@ -411,7 +409,7 @@ export class ExplorerChartSingleMetric extends React.Component { // Show actual/typical when available except for rare detectors. // Rare detectors always have 1 as actual and the probability as typical. // Exposing those values in the tooltip with actual/typical labels might irritate users. - if (_.has(marker, 'actual') && config.functionDescription !== 'rare') { + if (marker.actual !== undefined && config.functionDescription !== 'rare') { // Display the record actual in preference to the chart value, which may be // different depending on the aggregation interval of the chart. tooltipData.push({ @@ -445,7 +443,7 @@ export class ExplorerChartSingleMetric extends React.Component { }, valueAccessor: 'value', }); - if (_.has(marker, 'byFieldName') && _.has(marker, 'numberOfCauses')) { + if (marker.byFieldName !== undefined && marker.numberOfCauses !== undefined) { tooltipData.push({ label: i18n.translate( 'xpack.ml.explorer.distributionChart.unusualByFieldValuesLabel', @@ -483,7 +481,7 @@ export class ExplorerChartSingleMetric extends React.Component { }); } - if (_.has(marker, 'scheduledEvents')) { + if (marker.scheduledEvents !== undefined) { tooltipData.push({ label: i18n.translate('xpack.ml.explorer.singleMetricChart.scheduledEventsLabel', { defaultMessage: 'Scheduled events', diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.js index 1b83a4ed30560..712b64af2db80 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.js @@ -11,7 +11,12 @@ * and manages the layout of the charts in the containing div. */ -import _ from 'lodash'; +import get from 'lodash/get'; +import each from 'lodash/each'; +import find from 'lodash/find'; +import sortBy from 'lodash/sortBy'; +import map from 'lodash/map'; +import reduce from 'lodash/reduce'; import { buildConfig } from './explorer_chart_config_builder'; import { chartLimits, getChartType } from '../../util/chart_utils'; @@ -113,7 +118,7 @@ export const anomalyDataChange = function ( // If source data can be plotted, use that, otherwise model plot will be available. const useSourceData = isSourceDataChartableForDetector(job, detectorIndex); if (useSourceData === true) { - const datafeedQuery = _.get(config, 'datafeedConfig.query', null); + const datafeedQuery = get(config, 'datafeedConfig.query', null); return mlResultsService .getMetricData( config.datafeedConfig.indices, @@ -131,8 +136,8 @@ export const anomalyDataChange = function ( // Extract the partition, by, over fields on which to filter. const criteriaFields = []; const detector = job.analysis_config.detectors[detectorIndex]; - if (_.has(detector, 'partition_field_name')) { - const partitionEntity = _.find(entityFields, { + if (detector.partition_field_name !== undefined) { + const partitionEntity = find(entityFields, { fieldName: detector.partition_field_name, }); if (partitionEntity !== undefined) { @@ -143,8 +148,8 @@ export const anomalyDataChange = function ( } } - if (_.has(detector, 'over_field_name')) { - const overEntity = _.find(entityFields, { fieldName: detector.over_field_name }); + if (detector.over_field_name !== undefined) { + const overEntity = find(entityFields, { fieldName: detector.over_field_name }); if (overEntity !== undefined) { criteriaFields.push( { fieldName: 'over_field_name', fieldValue: overEntity.fieldName }, @@ -153,8 +158,8 @@ export const anomalyDataChange = function ( } } - if (_.has(detector, 'by_field_name')) { - const byEntity = _.find(entityFields, { fieldName: detector.by_field_name }); + if (detector.by_field_name !== undefined) { + const byEntity = find(entityFields, { fieldName: detector.by_field_name }); if (byEntity !== undefined) { criteriaFields.push( { fieldName: 'by_field_name', fieldValue: byEntity.fieldName }, @@ -236,7 +241,7 @@ export const anomalyDataChange = function ( filterField = config.entityFields.find((f) => f.fieldType === 'partition'); } - const datafeedQuery = _.get(config, 'datafeedConfig.query', null); + const datafeedQuery = get(config, 'datafeedConfig.query', null); return mlResultsService.getEventDistributionData( config.datafeedConfig.indices, splitField, @@ -285,7 +290,7 @@ export const anomalyDataChange = function ( if (eventDistribution.length > 0 && records.length > 0) { const filterField = records[0].by_field_value || records[0].over_field_value; chartData = eventDistribution.filter((d) => d.entity !== filterField); - _.map(metricData, (value, time) => { + map(metricData, (value, time) => { // The filtering for rare/event_distribution charts needs to be handled // differently because of how the source data is structured. // For rare chart values we are only interested wether a value is either `0` or not, @@ -304,7 +309,7 @@ export const anomalyDataChange = function ( } }); } else { - chartData = _.map(metricData, (value, time) => ({ + chartData = map(metricData, (value, time) => ({ date: +time, value: value, })); @@ -314,7 +319,7 @@ export const anomalyDataChange = function ( // Iterate through the anomaly records, adding anomalyScore properties // to the chartData entries for anomalous buckets. const chartDataForPointSearch = getChartDataForPointSearch(chartData, records[0], chartType); - _.each(records, (record) => { + each(records, (record) => { // Look for a chart point with the same time as the record. // If none found, insert a point for anomalies due to a gap in the data. const recordTime = record[ML_TIME_FIELD_NAME]; @@ -330,13 +335,13 @@ export const anomalyDataChange = function ( chartPoint.actual = record.actual; chartPoint.typical = record.typical; } else { - const causes = _.get(record, 'causes', []); + const causes = get(record, 'causes', []); if (causes.length > 0) { chartPoint.byFieldName = record.by_field_name; chartPoint.numberOfCauses = causes.length; if (causes.length === 1) { // If only a single cause, copy actual and typical values to the top level. - const cause = _.first(record.causes); + const cause = record.causes[0]; chartPoint.actual = cause.actual; chartPoint.typical = cause.typical; } @@ -351,7 +356,7 @@ export const anomalyDataChange = function ( // Add a scheduledEvents property to any points in the chart data set // which correspond to times of scheduled events for the job. if (scheduledEvents !== undefined) { - _.each(scheduledEvents, (events, time) => { + each(scheduledEvents, (events, time) => { const chartPoint = findChartPointForTime(chartDataForPointSearch, Number(time)); if (chartPoint !== undefined) { // Note if the scheduled event coincides with an absence of the underlying metric data, @@ -385,10 +390,10 @@ export const anomalyDataChange = function ( .then((response) => { // calculate an overall min/max for all series const processedData = response.map(processChartData); - const allDataPoints = _.reduce( + const allDataPoints = reduce( processedData, (datapoints, series) => { - _.each(series, (d) => datapoints.push(d)); + each(series, (d) => datapoints.push(d)); return datapoints; }, [] @@ -420,7 +425,7 @@ function processRecordsForDisplay(anomalyRecords) { // Aggregate by job, detector, and analysis fields (partition, by, over). const aggregatedData = {}; - _.each(anomalyRecords, (record) => { + each(anomalyRecords, (record) => { // Check if we can plot a chart for this record, depending on whether the source data // is chartable, and if model plot is enabled for the job. const job = mlJobService.getJob(record.job_id); @@ -524,20 +529,20 @@ function processRecordsForDisplay(anomalyRecords) { let recordsForSeries = []; // Convert to an array of the records with the highest record_score per unique series. - _.each(aggregatedData, (detectorsForJob) => { - _.each(detectorsForJob, (groupsForDetector) => { + each(aggregatedData, (detectorsForJob) => { + each(detectorsForJob, (groupsForDetector) => { if (groupsForDetector.maxScoreRecord !== undefined) { // Detector with no partition / by field. recordsForSeries.push(groupsForDetector.maxScoreRecord); } else { - _.each(groupsForDetector, (valuesForGroup) => { - _.each(valuesForGroup, (dataForGroupValue) => { + each(groupsForDetector, (valuesForGroup) => { + each(valuesForGroup, (dataForGroupValue) => { if (dataForGroupValue.maxScoreRecord !== undefined) { recordsForSeries.push(dataForGroupValue.maxScoreRecord); } else { // Second level of aggregation for partition and by/over. - _.each(dataForGroupValue, (splitsForGroup) => { - _.each(splitsForGroup, (dataForSplitValue) => { + each(dataForGroupValue, (splitsForGroup) => { + each(splitsForGroup, (dataForSplitValue) => { recordsForSeries.push(dataForSplitValue.maxScoreRecord); }); }); @@ -547,7 +552,7 @@ function processRecordsForDisplay(anomalyRecords) { } }); }); - recordsForSeries = _.sortBy(recordsForSeries, 'record_score').reverse(); + recordsForSeries = sortBy(recordsForSeries, 'record_score').reverse(); return recordsForSeries; } @@ -564,7 +569,7 @@ function calculateChartRange( // Calculate the time range for the charts. // Fit in as many points in the available container width plotted at the job bucket span. const midpointMs = Math.ceil((earliestMs + latestMs) / 2); - const maxBucketSpanMs = Math.max.apply(null, _.map(seriesConfigs, 'bucketSpanSeconds')) * 1000; + const maxBucketSpanMs = Math.max.apply(null, map(seriesConfigs, 'bucketSpanSeconds')) * 1000; const pointsToPlotFullSelection = Math.ceil((latestMs - earliestMs) / maxBucketSpanMs); @@ -588,7 +593,7 @@ function calculateChartRange( let minMs = recordsToPlot[0][timeFieldName]; let maxMs = recordsToPlot[0][timeFieldName]; - _.each(recordsToPlot, (record) => { + each(recordsToPlot, (record) => { const diffMs = maxMs - minMs; if (diffMs < maxTimeSpan) { const recordTime = record[timeFieldName]; diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js index 433aa65cc5dd4..a7d422d161108 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import cloneDeep from 'lodash/cloneDeep'; import mockAnomalyChartRecords from './__mocks__/mock_anomaly_chart_records.json'; import mockDetectorsByJob from './__mocks__/mock_detectors_by_job.json'; @@ -24,10 +24,10 @@ import mockSeriesPromisesResponse from './__mocks__/mock_series_promises_respons // suitable responses from the mocked services. The mocked services check against the // provided alternative values and return specific modified mock responses for the test case. -const mockJobConfigClone = _.cloneDeep(mockJobConfig); +const mockJobConfigClone = cloneDeep(mockJobConfig); // adjust mock data to tests against null/0 values -const mockMetricClone = _.cloneDeep(mockSeriesPromisesResponse[0][0]); +const mockMetricClone = cloneDeep(mockSeriesPromisesResponse[0][0]); mockMetricClone.results['1486712700000'] = null; mockMetricClone.results['1486713600000'] = 0; @@ -127,7 +127,7 @@ describe('explorerChartsContainerService', () => { }); test('filtering should skip values of null', (done) => { - const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords).map((d) => { + const mockAnomalyChartRecordsClone = cloneDeep(mockAnomalyChartRecords).map((d) => { d.job_id = 'mock-job-id-distribution'; return d; }); @@ -151,7 +151,7 @@ describe('explorerChartsContainerService', () => { }); test('field value with trailing dot should not throw an error', (done) => { - const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords); + const mockAnomalyChartRecordsClone = cloneDeep(mockAnomalyChartRecords); mockAnomalyChartRecordsClone[1].partition_field_value = 'AAL.'; expect(() => { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx index 2590ab2f1cb23..05e082711f619 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx @@ -10,7 +10,9 @@ import React from 'react'; import './_explorer.scss'; -import _, { isEqual } from 'lodash'; +import isEqual from 'lodash/isEqual'; +import uniq from 'lodash/uniq'; +import get from 'lodash/get'; import d3 from 'd3'; import moment from 'moment'; import DragSelect from 'dragselect'; @@ -176,9 +178,9 @@ export class ExplorerSwimlane extends React.Component { } ); - selectedData.laneLabels = _.uniq(selectedData.laneLabels); - selectedData.times = _.uniq(selectedData.times); - if (_.isEqual(selectedData, previousSelectedData) === false) { + selectedData.laneLabels = uniq(selectedData.laneLabels); + selectedData.times = uniq(selectedData.times); + if (isEqual(selectedData, previousSelectedData) === false) { // If no cells containing anomalies have been selected, // immediately clear the selection, otherwise trigger // a reload with the updated selected cells. @@ -246,7 +248,7 @@ export class ExplorerSwimlane extends React.Component { selectedTimes: d3.extent(times), }; - if (_.isEqual(oldSelection, newSelection)) { + if (isEqual(oldSelection, newSelection)) { triggerNewSelection = false; } @@ -277,8 +279,8 @@ export class ExplorerSwimlane extends React.Component { // Check for selection and reselect the corresponding swimlane cell // if the time range and lane label are still in view. const selectionState = selection; - const selectedType = _.get(selectionState, 'type', undefined); - const selectionViewByFieldName = _.get(selectionState, 'viewByFieldName', ''); + const selectedType = get(selectionState, 'type', undefined); + const selectionViewByFieldName = get(selectionState, 'viewByFieldName', ''); // If a selection was done in the other swimlane, add the "masked" classes // to de-emphasize the swimlane cells. @@ -288,8 +290,8 @@ export class ExplorerSwimlane extends React.Component { } const cellsToSelect: Node[] = []; - const selectedLanes = _.get(selectionState, 'lanes', []); - const selectedTimes = _.get(selectionState, 'times', []); + const selectedLanes = get(selectionState, 'lanes', []); + const selectedTimes = get(selectionState, 'times', []); const selectedTimeExtent = d3.extent(selectedTimes); if ( diff --git a/x-pack/plugins/ml/public/application/services/forecast_service.js b/x-pack/plugins/ml/public/application/services/forecast_service.js index ed5a29ff74a63..57e50387a03ab 100644 --- a/x-pack/plugins/ml/public/application/services/forecast_service.js +++ b/x-pack/plugins/ml/public/application/services/forecast_service.js @@ -6,7 +6,9 @@ // Service for carrying out requests to run ML forecasts and to obtain // data on forecasts that have been performed. -import _ from 'lodash'; +import get from 'lodash/get'; +import find from 'lodash/find'; +import each from 'lodash/each'; import { map } from 'rxjs/operators'; import { ml } from './ml_api_service'; @@ -129,8 +131,8 @@ function getForecastDateRange(job, forecastId) { }, }) .then((resp) => { - obj.earliest = _.get(resp, 'aggregations.earliest.value', null); - obj.latest = _.get(resp, 'aggregations.latest.value', null); + obj.earliest = get(resp, 'aggregations.earliest.value', null); + obj.latest = get(resp, 'aggregations.latest.value', null); if (obj.earliest === null || obj.latest === null) { reject(resp); } else { @@ -157,8 +159,8 @@ function getForecastData( // Extract the partition, by, over fields on which to filter. const criteriaFields = []; const detector = job.analysis_config.detectors[detectorIndex]; - if (_.has(detector, 'partition_field_name')) { - const partitionEntity = _.find(entityFields, { fieldName: detector.partition_field_name }); + if (detector.partition_field_name !== undefined) { + const partitionEntity = find(entityFields, { fieldName: detector.partition_field_name }); if (partitionEntity !== undefined) { criteriaFields.push( { fieldName: 'partition_field_name', fieldValue: partitionEntity.fieldName }, @@ -167,8 +169,8 @@ function getForecastData( } } - if (_.has(detector, 'over_field_name')) { - const overEntity = _.find(entityFields, { fieldName: detector.over_field_name }); + if (detector.over_field_name !== undefined) { + const overEntity = find(entityFields, { fieldName: detector.over_field_name }); if (overEntity !== undefined) { criteriaFields.push( { fieldName: 'over_field_name', fieldValue: overEntity.fieldName }, @@ -177,8 +179,8 @@ function getForecastData( } } - if (_.has(detector, 'by_field_name')) { - const byEntity = _.find(entityFields, { fieldName: detector.by_field_name }); + if (detector.by_field_name !== undefined) { + const byEntity = find(entityFields, { fieldName: detector.by_field_name }); if (byEntity !== undefined) { criteriaFields.push( { fieldName: 'by_field_name', fieldValue: byEntity.fieldName }, @@ -222,7 +224,7 @@ function getForecastData( ]; // Add in term queries for each of the specified criteria. - _.each(criteriaFields, (criteria) => { + each(criteriaFields, (criteria) => { filterCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -281,13 +283,13 @@ function getForecastData( }) .pipe( map((resp) => { - const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, (dataForTime) => { + const aggregationsByTime = get(resp, ['aggregations', 'times', 'buckets'], []); + each(aggregationsByTime, (dataForTime) => { const time = dataForTime.key; obj.results[time] = { - prediction: _.get(dataForTime, ['prediction', 'value']), - forecastUpper: _.get(dataForTime, ['forecastUpper', 'value']), - forecastLower: _.get(dataForTime, ['forecastLower', 'value']), + prediction: get(dataForTime, ['prediction', 'value']), + forecastUpper: get(dataForTime, ['forecastUpper', 'value']), + forecastLower: get(dataForTime, ['forecastLower', 'value']), }; }); @@ -355,7 +357,7 @@ function getForecastRequestStats(job, forecastId) { }) .then((resp) => { if (resp.hits.total !== 0) { - obj.stats = _.first(resp.hits.hits)._source; + obj.stats = resp.hits.hits[0]._source; } resolve(obj); }) diff --git a/x-pack/plugins/ml/public/application/services/job_service.js b/x-pack/plugins/ml/public/application/services/job_service.js index 7e90758ffd7db..704d76059f75c 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.js +++ b/x-pack/plugins/ml/public/application/services/job_service.js @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import cloneDeep from 'lodash/cloneDeep'; +import each from 'lodash/each'; +import find from 'lodash/find'; +import get from 'lodash/get'; +import isNumber from 'lodash/isNumber'; import moment from 'moment'; import { i18n } from '@kbn/i18n'; @@ -135,10 +139,10 @@ class JobService { const jobStats = statsResp.jobs[j]; if (job.job_id === jobStats.job_id) { job.state = jobStats.state; - job.data_counts = _.cloneDeep(jobStats.data_counts); - job.model_size_stats = _.cloneDeep(jobStats.model_size_stats); + job.data_counts = cloneDeep(jobStats.data_counts); + job.model_size_stats = cloneDeep(jobStats.model_size_stats); if (jobStats.node) { - job.node = _.cloneDeep(jobStats.node); + job.node = cloneDeep(jobStats.node); } if (jobStats.open_time) { job.open_time = jobStats.open_time; @@ -212,10 +216,10 @@ class JobService { newJob.state = statsJob.state; newJob.data_counts = {}; newJob.model_size_stats = {}; - newJob.data_counts = _.cloneDeep(statsJob.data_counts); - newJob.model_size_stats = _.cloneDeep(statsJob.model_size_stats); + newJob.data_counts = cloneDeep(statsJob.data_counts); + newJob.model_size_stats = cloneDeep(statsJob.model_size_stats); if (newJob.node) { - newJob.node = _.cloneDeep(statsJob.node); + newJob.node = cloneDeep(statsJob.node); } if (statsJob.open_time) { @@ -352,7 +356,7 @@ class JobService { // create a deep copy of a job object // also remove items from the job which are set by the server and not needed // in the future this formatting could be optional - const tempJob = _.cloneDeep(job); + const tempJob = cloneDeep(job); // remove all of the items which should not be copied // such as counts, state and times @@ -375,7 +379,7 @@ class JobService { delete tempJob.analysis_config.use_per_partition_normalization; - _.each(tempJob.analysis_config.detectors, (d) => { + each(tempJob.analysis_config.detectors, (d) => { delete d.detector_index; }); @@ -469,7 +473,7 @@ class JobService { // find a job based on the id getJob(jobId) { - const job = _.find(jobs, (j) => { + const job = find(jobs, (j) => { return j.job_id === jobId; }); @@ -550,7 +554,7 @@ class JobService { // get fields from detectors if (job.analysis_config.detectors) { - _.each(job.analysis_config.detectors, (dtr) => { + each(job.analysis_config.detectors, (dtr) => { if (dtr.by_field_name) { fields[dtr.by_field_name] = {}; } @@ -568,7 +572,7 @@ class JobService { // get fields from influencers if (job.analysis_config.influencers) { - _.each(job.analysis_config.influencers, (inf) => { + each(job.analysis_config.influencers, (inf) => { fields[inf] = {}; }); } @@ -659,7 +663,7 @@ class JobService { return new Promise((resolve, reject) => { // if the end timestamp is a number, add one ms to it to make it // inclusive of the end of the data - if (_.isNumber(end)) { + if (isNumber(end)) { end++; } @@ -780,7 +784,7 @@ class JobService { }); } }); - _.each(tempGroups, (js, id) => { + each(tempGroups, (js, id) => { groups.push({ id, jobs: js }); }); return groups; @@ -837,9 +841,9 @@ function processBasicJobInfo(localJobService, jobsList) { const customUrlsByJob = {}; // use cloned copy of jobs list so not to alter the original - const jobsListCopy = _.cloneDeep(jobsList); + const jobsListCopy = cloneDeep(jobsList); - _.each(jobsListCopy, (jobObj) => { + each(jobsListCopy, (jobObj) => { const analysisConfig = jobObj.analysis_config; const bucketSpan = parseInterval(analysisConfig.bucket_span); @@ -848,20 +852,20 @@ function processBasicJobInfo(localJobService, jobsList) { bucketSpanSeconds: bucketSpan.asSeconds(), }; - if (_.has(jobObj, 'description') && /^\s*$/.test(jobObj.description) === false) { + if (jobObj.description !== undefined && /^\s*$/.test(jobObj.description) === false) { job.description = jobObj.description; } else { // Just use the id as the description. job.description = jobObj.job_id; } - job.detectors = _.get(analysisConfig, 'detectors', []); + job.detectors = get(analysisConfig, 'detectors', []); detectorsByJob[job.id] = job.detectors; - if (_.has(jobObj, 'custom_settings.custom_urls')) { + if (jobObj.custom_settings !== undefined && jobObj.custom_settings.custom_urls !== undefined) { job.customUrls = []; - _.each(jobObj.custom_settings.custom_urls, (url) => { - if (_.has(url, 'url_name') && _.has(url, 'url_value') && isWebUrl(url.url_value)) { + each(jobObj.custom_settings.custom_urls, (url) => { + if (url.url_name !== undefined && url.url_value !== undefined && isWebUrl(url.url_value)) { // Only make web URLs (i.e. http or https) available in dashboard drilldowns. job.customUrls.push(url); } @@ -897,7 +901,7 @@ function createJobStats(jobsList, jobStats) { const mlNodes = {}; let failedJobs = 0; - _.each(jobsList, (job) => { + each(jobsList, (job) => { if (job.state === 'opened') { jobStats.open.value++; } else if (job.state === 'closed') { diff --git a/x-pack/plugins/ml/public/application/services/mapping_service.js b/x-pack/plugins/ml/public/application/services/mapping_service.js index 52aa5ed7413cb..251bb0bce5690 100644 --- a/x-pack/plugins/ml/public/application/services/mapping_service.js +++ b/x-pack/plugins/ml/public/application/services/mapping_service.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import each from 'lodash/each'; import { ml } from './ml_api_service'; @@ -16,8 +16,8 @@ export function getFieldTypeFromMapping(index, fieldName) { ml.getFieldCaps({ index, fields: [fieldName] }) .then((resp) => { let fieldType = ''; - _.each(resp.fields, (field) => { - _.each(field, (type) => { + each(resp.fields, (field) => { + each(field, (type) => { if (fieldType === '') { fieldType = type.type; } diff --git a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts index d7f016b419377..898ca8894cbda 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts @@ -13,7 +13,8 @@ // Returned response contains a results property containing the requested aggregation. import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; -import _ from 'lodash'; +import each from 'lodash/each'; +import get from 'lodash/get'; import { Dictionary } from '../../../../common/types/common'; import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils'; import { JobId } from '../../../../common/types/anomaly_detection_jobs'; @@ -237,7 +238,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { ]; // Add in term queries for each of the specified criteria. - _.each(criteriaFields, (criteria) => { + each(criteriaFields, (criteria) => { mustCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -316,12 +317,12 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }) .pipe( map((resp) => { - const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, (dataForTime: any) => { + const aggregationsByTime = get(resp, ['aggregations', 'times', 'buckets'], []); + each(aggregationsByTime, (dataForTime: any) => { const time = dataForTime.key; - const modelUpper: number | undefined = _.get(dataForTime, ['modelUpper', 'value']); - const modelLower: number | undefined = _.get(dataForTime, ['modelLower', 'value']); - const actual = _.get(dataForTime, ['actual', 'value']); + const modelUpper: number | undefined = get(dataForTime, ['modelUpper', 'value']); + const modelLower: number | undefined = get(dataForTime, ['modelLower', 'value']); + const actual = get(dataForTime, ['actual', 'value']); obj.results[time] = { actual, @@ -375,7 +376,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -391,7 +392,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { } // Add in term queries for each of the specified criteria. - _.each(criteriaFields, (criteria) => { + each(criteriaFields, (criteria) => { boolCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -428,7 +429,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { .pipe( map((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, (hit: any) => { + each(resp.hits.hits, (hit: any) => { obj.records.push(hit._source); }); } @@ -473,7 +474,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { jobIdFilterStr += `${i > 0 ? ' OR ' : ''}job_id:${jobId}`; }); boolCriteria.push({ @@ -536,15 +537,15 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }) .pipe( map((resp) => { - const dataByJobId = _.get(resp, ['aggregations', 'jobs', 'buckets'], []); - _.each(dataByJobId, (dataForJob: any) => { + const dataByJobId = get(resp, ['aggregations', 'jobs', 'buckets'], []); + each(dataByJobId, (dataForJob: any) => { const jobId: string = dataForJob.key; const resultsForTime: Record = {}; - const dataByTime = _.get(dataForJob, ['times', 'buckets'], []); - _.each(dataByTime, (dataForTime: any) => { + const dataByTime = get(dataForJob, ['times', 'buckets'], []); + each(dataByTime, (dataForTime: any) => { const time: string = dataForTime.key; - const events: object[] = _.get(dataForTime, ['events', 'buckets']); - resultsForTime[time] = _.map(events, 'key'); + const events: any[] = get(dataForTime, ['events', 'buckets']); + resultsForTime[time] = events.map((e) => e.key); }); obj.events[jobId] = resultsForTime; }); diff --git a/x-pack/plugins/ml/public/application/services/results_service/results_service.js b/x-pack/plugins/ml/public/application/services/results_service/results_service.js index 50e2d0a5a2a0b..0c3b2e40c8e26 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/results_service.js +++ b/x-pack/plugins/ml/public/application/services/results_service/results_service.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import each from 'lodash/each'; +import get from 'lodash/get'; import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils'; import { escapeForElasticsearchQuery } from '../../util/string_utils'; @@ -50,7 +51,7 @@ export function resultsServiceProvider(mlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -131,18 +132,18 @@ export function resultsServiceProvider(mlApiServices) { }, }) .then((resp) => { - const dataByJobId = _.get(resp, ['aggregations', 'jobId', 'buckets'], []); - _.each(dataByJobId, (dataForJob) => { + const dataByJobId = get(resp, ['aggregations', 'jobId', 'buckets'], []); + each(dataByJobId, (dataForJob) => { const jobId = dataForJob.key; const resultsForTime = {}; - const dataByTime = _.get(dataForJob, ['byTime', 'buckets'], []); - _.each(dataByTime, (dataForTime) => { - const value = _.get(dataForTime, ['anomalyScore', 'value']); + const dataByTime = get(dataForJob, ['byTime', 'buckets'], []); + each(dataByTime, (dataForTime) => { + const value = get(dataForTime, ['anomalyScore', 'value']); if (value !== undefined) { const time = dataForTime.key; - resultsForTime[time] = _.get(dataForTime, ['anomalyScore', 'value']); + resultsForTime[time] = get(dataForTime, ['anomalyScore', 'value']); } }); obj.results[jobId] = resultsForTime; @@ -198,7 +199,7 @@ export function resultsServiceProvider(mlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -305,17 +306,17 @@ export function resultsServiceProvider(mlApiServices) { }, }) .then((resp) => { - const fieldNameBuckets = _.get( + const fieldNameBuckets = get( resp, ['aggregations', 'influencerFieldNames', 'buckets'], [] ); - _.each(fieldNameBuckets, (nameBucket) => { + each(fieldNameBuckets, (nameBucket) => { const fieldName = nameBucket.key; const fieldValues = []; - const fieldValueBuckets = _.get(nameBucket, ['influencerFieldValues', 'buckets'], []); - _.each(fieldValueBuckets, (valueBucket) => { + const fieldValueBuckets = get(nameBucket, ['influencerFieldValues', 'buckets'], []); + each(fieldValueBuckets, (valueBucket) => { const fieldValueResult = { influencerFieldValue: valueBucket.key, maxAnomalyScore: valueBucket.maxAnomalyScore.value, @@ -360,7 +361,7 @@ export function resultsServiceProvider(mlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -424,8 +425,8 @@ export function resultsServiceProvider(mlApiServices) { }, }) .then((resp) => { - const buckets = _.get(resp, ['aggregations', 'influencerFieldValues', 'buckets'], []); - _.each(buckets, (bucket) => { + const buckets = get(resp, ['aggregations', 'influencerFieldValues', 'buckets'], []); + each(buckets, (bucket) => { const result = { influencerFieldValue: bucket.key, maxAnomalyScore: bucket.maxAnomalyScore.value, @@ -458,9 +459,9 @@ export function resultsServiceProvider(mlApiServices) { end: latestMs, }) .then((resp) => { - const dataByTime = _.get(resp, ['overall_buckets'], []); - _.each(dataByTime, (dataForTime) => { - const value = _.get(dataForTime, ['overall_score']); + const dataByTime = get(resp, ['overall_buckets'], []); + each(dataByTime, (dataForTime) => { + const value = get(dataForTime, ['overall_score']); if (value !== undefined) { obj.results[dataForTime.timestamp] = value; } @@ -517,7 +518,7 @@ export function resultsServiceProvider(mlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -537,7 +538,7 @@ export function resultsServiceProvider(mlApiServices) { if (influencerFieldValues && influencerFieldValues.length > 0) { let influencerFilterStr = ''; - _.each(influencerFieldValues, (value, i) => { + each(influencerFieldValues, (value, i) => { if (i > 0) { influencerFilterStr += ' OR '; } @@ -625,17 +626,17 @@ export function resultsServiceProvider(mlApiServices) { }, }) .then((resp) => { - const fieldValueBuckets = _.get( + const fieldValueBuckets = get( resp, ['aggregations', 'influencerFieldValues', 'buckets'], [] ); - _.each(fieldValueBuckets, (valueBucket) => { + each(fieldValueBuckets, (valueBucket) => { const fieldValue = valueBucket.key; const fieldValues = {}; - const timeBuckets = _.get(valueBucket, ['byTime', 'buckets'], []); - _.each(timeBuckets, (timeBucket) => { + const timeBuckets = get(valueBucket, ['byTime', 'buckets'], []); + each(timeBuckets, (timeBucket) => { const time = timeBucket.key; const score = timeBucket.maxAnomalyScore.value; fieldValues[time] = score; @@ -701,7 +702,7 @@ export function resultsServiceProvider(mlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -744,7 +745,7 @@ export function resultsServiceProvider(mlApiServices) { }) .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, (hit) => { + each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } @@ -797,7 +798,7 @@ export function resultsServiceProvider(mlApiServices) { if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i) => { + each(jobIds, (jobId, i) => { if (i > 0) { jobIdFilterStr += ' OR '; } @@ -875,7 +876,7 @@ export function resultsServiceProvider(mlApiServices) { }) .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, (hit) => { + each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } @@ -1000,7 +1001,7 @@ export function resultsServiceProvider(mlApiServices) { }) .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, (hit) => { + each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } @@ -1079,8 +1080,8 @@ export function resultsServiceProvider(mlApiServices) { }, }) .then((resp) => { - const dataByTimeBucket = _.get(resp, ['aggregations', 'eventRate', 'buckets'], []); - _.each(dataByTimeBucket, (dataForTime) => { + const dataByTimeBucket = get(resp, ['aggregations', 'eventRate', 'buckets'], []); + each(dataByTimeBucket, (dataForTime) => { const time = dataForTime.key; obj.results[time] = dataForTime.doc_count; }); @@ -1227,18 +1228,18 @@ export function resultsServiceProvider(mlApiServices) { // Because of the sampling, results of metricFunctions which use sum or count // can be significantly skewed. Taking into account totalHits we calculate a // a factor to normalize results for these metricFunctions. - const totalHits = _.get(resp, ['hits', 'total'], 0); - const successfulShards = _.get(resp, ['_shards', 'successful'], 0); + const totalHits = get(resp, ['hits', 'total'], 0); + const successfulShards = get(resp, ['_shards', 'successful'], 0); let normalizeFactor = 1; if (totalHits > successfulShards * SAMPLER_TOP_TERMS_SHARD_SIZE) { normalizeFactor = totalHits / (successfulShards * SAMPLER_TOP_TERMS_SHARD_SIZE); } - const dataByTime = _.get(resp, ['aggregations', 'sample', 'byTime', 'buckets'], []); + const dataByTime = get(resp, ['aggregations', 'sample', 'byTime', 'buckets'], []); const data = dataByTime.reduce((d, dataForTime) => { const date = +dataForTime.key; - const entities = _.get(dataForTime, ['entities', 'buckets'], []); + const entities = get(dataForTime, ['entities', 'buckets'], []); entities.forEach((entity) => { let value = metricFunction === 'count' ? entity.doc_count : entity.metric.value; @@ -1291,7 +1292,7 @@ export function resultsServiceProvider(mlApiServices) { { term: { job_id: jobId } }, ]; - _.each(criteriaFields, (criteria) => { + each(criteriaFields, (criteria) => { mustCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -1339,11 +1340,11 @@ export function resultsServiceProvider(mlApiServices) { }, }) .then((resp) => { - const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, (dataForTime) => { + const aggregationsByTime = get(resp, ['aggregations', 'times', 'buckets'], []); + each(aggregationsByTime, (dataForTime) => { const time = dataForTime.key; obj.results[time] = { - score: _.get(dataForTime, ['recordScore', 'value']), + score: get(dataForTime, ['recordScore', 'value']), }; }); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js index 86f12d7ca68c8..d825844ffa14b 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js @@ -9,7 +9,7 @@ */ import PropTypes from 'prop-types'; -import _ from 'lodash'; +import get from 'lodash/get'; import React, { Component } from 'react'; @@ -250,8 +250,8 @@ export class ForecastingModalUI extends Component { .getForecastRequestStats(this.props.job, forecastId) .then((resp) => { // Get the progress (stats value is between 0 and 1). - const progress = _.get(resp, ['stats', 'forecast_progress'], previousProgress); - const status = _.get(resp, ['stats', 'forecast_status']); + const progress = get(resp, ['stats', 'forecast_progress'], previousProgress); + const status = get(resp, ['stats', 'forecast_status']); // The requests for forecast stats can get routed to different shards, // and if these operate at different speeds there is a chance that a @@ -263,7 +263,7 @@ export class ForecastingModalUI extends Component { } // Display any messages returned in the request stats. - let messages = _.get(resp, ['stats', 'forecast_messages'], []); + let messages = get(resp, ['stats', 'forecast_messages'], []); messages = messages.map((message) => ({ message, status: MESSAGE_LEVEL.WARNING })); this.setState({ messages }); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index 190bce1639c4a..7ec59f4acbc51 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -12,9 +12,13 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import useObservable from 'react-use/lib/useObservable'; -import _ from 'lodash'; +import isEqual from 'lodash/isEqual'; +import reduce from 'lodash/reduce'; +import each from 'lodash/each'; +import get from 'lodash/get'; import d3 from 'd3'; import moment from 'moment'; +import { i18n } from '@kbn/i18n'; import { getSeverityWithLow, @@ -49,8 +53,6 @@ import { unhighlightFocusChartAnnotation, } from './timeseries_chart_annotations'; -import { i18n } from '@kbn/i18n'; - const focusZoomPanelHeight = 25; const focusChartHeight = 310; const focusHeight = focusZoomPanelHeight + focusChartHeight; @@ -399,7 +401,7 @@ class TimeseriesChartIntl extends Component { if (zoomFrom) { focusLoadFrom = zoomFrom.getTime(); } else { - focusLoadFrom = _.reduce( + focusLoadFrom = reduce( combinedData, (memo, point) => Math.min(memo, point.date.getTime()), new Date(2099, 12, 31).getTime() @@ -410,11 +412,7 @@ class TimeseriesChartIntl extends Component { if (zoomTo) { focusLoadTo = zoomTo.getTime(); } else { - focusLoadTo = _.reduce( - combinedData, - (memo, point) => Math.max(memo, point.date.getTime()), - 0 - ); + focusLoadTo = reduce(combinedData, (memo, point) => Math.max(memo, point.date.getTime()), 0); } focusLoadTo = Math.min(focusLoadTo, contextXMax); @@ -431,7 +429,7 @@ class TimeseriesChartIntl extends Component { min: moment(new Date(contextXScaleDomain[0])), max: moment(contextXScaleDomain[1]), }; - if (!_.isEqual(newSelectedBounds, this.selectedBounds)) { + if (!isEqual(newSelectedBounds, this.selectedBounds)) { this.selectedBounds = newSelectedBounds; this.setContextBrushExtent( new Date(contextXScaleDomain[0]), @@ -764,7 +762,7 @@ class TimeseriesChartIntl extends Component { }) .attr('class', (d) => { let markerClass = 'metric-value'; - if (_.has(d, 'anomalyScore')) { + if (d.anomalyScore !== undefined) { markerClass += ` anomaly-marker ${getSeverityWithLow(d.anomalyScore).id}`; } return markerClass; @@ -887,14 +885,14 @@ class TimeseriesChartIntl extends Component { ); const zoomOptions = [{ durationMs: autoZoomDuration, label: 'auto' }]; - _.each(ZOOM_INTERVAL_OPTIONS, (option) => { + each(ZOOM_INTERVAL_OPTIONS, (option) => { if (option.duration.asSeconds() > minSecs && option.duration.asSeconds() < boundsSecs) { zoomOptions.push({ durationMs: option.duration.asMilliseconds(), label: option.label }); } }); xPos += zoomLabel.node().getBBox().width + 4; - _.each(zoomOptions, (option) => { + each(zoomOptions, (option) => { const text = zoomGroup .append('a') .attr('data-ms', option.durationMs) @@ -960,7 +958,7 @@ class TimeseriesChartIntl extends Component { const combinedData = contextForecastData === undefined ? data : data.concat(contextForecastData); const valuesRange = { min: Number.MAX_VALUE, max: Number.MIN_VALUE }; - _.each(combinedData, (item) => { + each(combinedData, (item) => { valuesRange.min = Math.min(item.value, valuesRange.min); valuesRange.max = Math.max(item.value, valuesRange.max); }); @@ -973,7 +971,7 @@ class TimeseriesChartIntl extends Component { (contextForecastData !== undefined && contextForecastData.length > 0) ) { const boundsRange = { min: Number.MAX_VALUE, max: Number.MIN_VALUE }; - _.each(combinedData, (item) => { + each(combinedData, (item) => { boundsRange.min = Math.min(item.lower, boundsRange.min); boundsRange.max = Math.max(item.upper, boundsRange.max); }); @@ -1294,7 +1292,7 @@ class TimeseriesChartIntl extends Component { if (swimlaneData !== undefined && swimlaneData.length > 0) { // Adjust the earliest back to the time of the first swimlane point // if this is before the time filter minimum. - earliest = Math.min(_.first(swimlaneData).date.getTime(), bounds.min.valueOf()); + earliest = Math.min(swimlaneData[0].date.getTime(), bounds.min.valueOf()); } const contextAggMs = contextAggregationInterval.asMilliseconds(); @@ -1352,7 +1350,7 @@ class TimeseriesChartIntl extends Component { const formattedDate = formatHumanReadableDateTimeSeconds(marker.date); const tooltipData = [{ label: formattedDate }]; - if (_.has(marker, 'anomalyScore')) { + if (marker.anomalyScore !== undefined) { const score = parseInt(marker.anomalyScore); const displayScore = score > 0 ? score : '< 1'; tooltipData.push({ @@ -1387,7 +1385,7 @@ class TimeseriesChartIntl extends Component { // Show actual/typical when available except for rare detectors. // Rare detectors always have 1 as actual and the probability as typical. // Exposing those values in the tooltip with actual/typical labels might irritate users. - if (_.has(marker, 'actual') && marker.function !== 'rare') { + if (marker.actual !== undefined && marker.function !== 'rare') { // Display the record actual in preference to the chart value, which may be // different depending on the aggregation interval of the chart. tooltipData.push({ @@ -1421,7 +1419,7 @@ class TimeseriesChartIntl extends Component { }, valueAccessor: 'value', }); - if (_.has(marker, 'byFieldName') && _.has(marker, 'numberOfCauses')) { + if (marker.byFieldName !== undefined && marker.numberOfCauses !== undefined) { const numberOfCauses = marker.numberOfCauses; // If numberOfCauses === 1, won't go into this block as actual/typical copied to top level fields. const byFieldName = mlEscape(marker.byFieldName); @@ -1488,7 +1486,7 @@ class TimeseriesChartIntl extends Component { } } else { // TODO - need better formatting for small decimals. - if (_.get(marker, 'isForecast', false) === true) { + if (get(marker, 'isForecast', false) === true) { tooltipData.push({ label: i18n.translate( 'xpack.ml.timeSeriesExplorer.timeSeriesChart.withoutAnomalyScore.predictionLabel', @@ -1548,7 +1546,7 @@ class TimeseriesChartIntl extends Component { } } - if (_.has(marker, 'scheduledEvents')) { + if (marker.scheduledEvents !== undefined) { marker.scheduledEvents.forEach((scheduledEvent, i) => { tooltipData.push({ label: i18n.translate( @@ -1569,7 +1567,7 @@ class TimeseriesChartIntl extends Component { }); } - if (_.has(marker, 'annotation')) { + if (marker.annotation !== undefined) { tooltipData.length = 0; // header tooltipData.push({ diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts index ce5a7565c519b..d1e959b33e5dc 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts @@ -4,7 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import each from 'lodash/each'; +import find from 'lodash/find'; +import get from 'lodash/get'; +import filter from 'lodash/filter'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @@ -35,8 +38,8 @@ function getMetricData( // Extract the partition, by, over fields on which to filter. const criteriaFields = []; const detector = job.analysis_config.detectors[detectorIndex]; - if (_.has(detector, 'partition_field_name')) { - const partitionEntity: any = _.find(entityFields, { + if (detector.partition_field_name !== undefined) { + const partitionEntity: any = find(entityFields, { fieldName: detector.partition_field_name, }); if (partitionEntity !== undefined) { @@ -47,8 +50,8 @@ function getMetricData( } } - if (_.has(detector, 'over_field_name')) { - const overEntity: any = _.find(entityFields, { fieldName: detector.over_field_name }); + if (detector.over_field_name !== undefined) { + const overEntity: any = find(entityFields, { fieldName: detector.over_field_name }); if (overEntity !== undefined) { criteriaFields.push( { fieldName: 'over_field_name', fieldValue: overEntity.fieldName }, @@ -57,8 +60,8 @@ function getMetricData( } } - if (_.has(detector, 'by_field_name')) { - const byEntity: any = _.find(entityFields, { fieldName: detector.by_field_name }); + if (detector.by_field_name !== undefined) { + const byEntity: any = find(entityFields, { fieldName: detector.by_field_name }); if (byEntity !== undefined) { criteriaFields.push( { fieldName: 'by_field_name', fieldValue: byEntity.fieldName }, @@ -97,7 +100,7 @@ function getMetricData( ) .pipe( map((resp) => { - _.each(resp.results, (value, time) => { + each(resp.results, (value, time) => { // @ts-ignore obj.results[time] = { actual: value, @@ -134,7 +137,7 @@ function getChartDetails( } obj.results.functionLabel = functionLabel; - const blankEntityFields = _.filter(entityFields, (entity) => { + const blankEntityFields = filter(entityFields, (entity) => { return entity.fieldValue === null; }); @@ -145,7 +148,7 @@ function getChartDetails( obj.results.entityData.entities = entityFields; resolve(obj); } else { - const entityFieldNames: string[] = _.map(blankEntityFields, 'fieldName'); + const entityFieldNames: string[] = blankEntityFields.map((f) => f.fieldName); ml.getCardinalityOfFields({ index: chartConfig.datafeedConfig.indices, fieldNames: entityFieldNames, @@ -155,12 +158,12 @@ function getChartDetails( latestMs, }) .then((results: any) => { - _.each(blankEntityFields, (field) => { + each(blankEntityFields, (field) => { // results will not contain keys for non-aggregatable fields, // so store as 0 to indicate over all field values. obj.results.entityData.entities.push({ fieldName: field.fieldName, - cardinality: _.get(results, field.fieldName, 0), + cardinality: get(results, field.fieldName, 0), }); }); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/timeseriesexplorer_utils.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/timeseriesexplorer_utils.js index 857db302e664e..7d14bb43ef811 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/timeseriesexplorer_utils.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/timeseriesexplorer_utils.js @@ -10,7 +10,9 @@ * Viewer dashboard. */ -import _ from 'lodash'; +import each from 'lodash/each'; +import get from 'lodash/get'; +import find from 'lodash/find'; import moment from 'moment-timezone'; import { isTimeSeriesViewJob } from '../../../../common/util/job_utils'; @@ -41,7 +43,7 @@ export function createTimeSeriesJobData(jobs) { export function processMetricPlotResults(metricPlotData, modelPlotEnabled) { const metricPlotChartData = []; if (modelPlotEnabled === true) { - _.each(metricPlotData, (dataForTime, time) => { + each(metricPlotData, (dataForTime, time) => { metricPlotChartData.push({ date: new Date(+time), lower: dataForTime.modelLower, @@ -50,7 +52,7 @@ export function processMetricPlotResults(metricPlotData, modelPlotEnabled) { }); }); } else { - _.each(metricPlotData, (dataForTime, time) => { + each(metricPlotData, (dataForTime, time) => { metricPlotChartData.push({ date: new Date(+time), value: dataForTime.actual, @@ -66,7 +68,7 @@ export function processMetricPlotResults(metricPlotData, modelPlotEnabled) { // value, lower and upper keys. export function processForecastResults(forecastData) { const forecastPlotChartData = []; - _.each(forecastData, (dataForTime, time) => { + each(forecastData, (dataForTime, time) => { forecastPlotChartData.push({ date: new Date(+time), isForecast: true, @@ -83,7 +85,7 @@ export function processForecastResults(forecastData) { // i.e. array of Objects with keys date (JavaScript date) and score. export function processRecordScoreResults(scoreData) { const bucketScoreData = []; - _.each(scoreData, (dataForTime, time) => { + each(scoreData, (dataForTime, time) => { bucketScoreData.push({ date: new Date(+time), score: dataForTime.score, @@ -153,7 +155,7 @@ export function processDataForFocusAnomalies( chartPoint.anomalyScore = recordScore; chartPoint.function = record.function; - if (_.has(record, 'actual')) { + if (record.actual !== undefined) { // If cannot match chart point for anomaly time // substitute the value with the record's actual so it won't plot as null/0 if (chartPoint.value === null) { @@ -163,13 +165,13 @@ export function processDataForFocusAnomalies( chartPoint.actual = record.actual; chartPoint.typical = record.typical; } else { - const causes = _.get(record, 'causes', []); + const causes = get(record, 'causes', []); if (causes.length > 0) { chartPoint.byFieldName = record.by_field_name; chartPoint.numberOfCauses = causes.length; if (causes.length === 1) { // If only a single cause, copy actual and typical values to the top level. - const cause = _.first(record.causes); + const cause = record.causes[0]; chartPoint.actual = cause.actual; chartPoint.typical = cause.typical; // substitute the value with the record's actual so it won't plot as null/0 @@ -180,7 +182,7 @@ export function processDataForFocusAnomalies( } } - if (_.has(record, 'multi_bucket_impact')) { + if (record.multi_bucket_impact !== undefined) { chartPoint.multiBucketImpact = record.multi_bucket_impact; } } @@ -194,7 +196,7 @@ export function processDataForFocusAnomalies( // which correspond to times of scheduled events for the job. export function processScheduledEventsForChart(chartData, scheduledEvents) { if (scheduledEvents !== undefined) { - _.each(scheduledEvents, (events, time) => { + each(scheduledEvents, (events, time) => { const chartPoint = findNearestChartPointToTime(chartData, time); if (chartPoint !== undefined) { // Note if the scheduled event coincides with an absence of the underlying metric data, @@ -301,7 +303,7 @@ export function calculateAggregationInterval(bounds, bucketsTarget, jobs, select // Ensure the aggregation interval is always a multiple of the bucket span to avoid strange // behaviour such as adjacent chart buckets holding different numbers of job results. - const bucketSpanSeconds = _.find(jobs, { id: selectedJob.job_id }).bucketSpanSeconds; + const bucketSpanSeconds = find(jobs, { id: selectedJob.job_id }).bucketSpanSeconds; let aggInterval = buckets.getIntervalToNearestMultiple(bucketSpanSeconds); // Set the interval back to the job bucket span if the auto interval is smaller. @@ -324,8 +326,8 @@ export function calculateDefaultFocusRange( const combinedData = isForecastData === false ? contextChartData : contextChartData.concat(contextForecastData); - const earliestDataDate = _.first(combinedData).date; - const latestDataDate = _.last(combinedData).date; + const earliestDataDate = combinedData[0].date; + const latestDataDate = combinedData[combinedData.length - 1].date; let rangeEarliestMs; let rangeLatestMs; @@ -333,8 +335,8 @@ export function calculateDefaultFocusRange( if (isForecastData === true) { // Return a range centred on the start of the forecast range, depending // on the time range of the forecast and data. - const earliestForecastDataDate = _.first(contextForecastData).date; - const latestForecastDataDate = _.last(contextForecastData).date; + const earliestForecastDataDate = contextForecastData[0].date; + const latestForecastDataDate = contextForecastData[contextForecastData.length - 1].date; rangeLatestMs = Math.min( earliestForecastDataDate.getTime() + autoZoomDuration / 2, @@ -379,7 +381,7 @@ export function getAutoZoomDuration(jobs, selectedJob) { // Calculate the 'auto' zoom duration which shows data at bucket span granularity. // Get the minimum bucket span of selected jobs. // TODO - only look at jobs for which data has been returned? - const bucketSpanSeconds = _.find(jobs, { id: selectedJob.job_id }).bucketSpanSeconds; + const bucketSpanSeconds = find(jobs, { id: selectedJob.job_id }).bucketSpanSeconds; // In most cases the duration can be obtained by simply multiplying the points target // Check that this duration returns the bucket span when run back through the diff --git a/x-pack/plugins/ml/public/application/util/chart_config_builder.js b/x-pack/plugins/ml/public/application/util/chart_config_builder.js index 3b09e09d3dd4a..bc63404a106db 100644 --- a/x-pack/plugins/ml/public/application/util/chart_config_builder.js +++ b/x-pack/plugins/ml/public/application/util/chart_config_builder.js @@ -9,7 +9,7 @@ * in the source metric data. */ -import _ from 'lodash'; +import get from 'lodash/get'; import { mlFunctionToESAggregation } from '../../../common/util/job_utils'; @@ -44,15 +44,16 @@ export function buildConfigFromDetector(job, detectorIndex) { // aggregations//aggregations//cardinality/field // or aggs//aggs//cardinality/field let cardinalityField = undefined; - const topAgg = _.get(job.datafeed_config, 'aggregations') || _.get(job.datafeed_config, 'aggs'); - if (topAgg !== undefined && _.values(topAgg).length > 0) { + const topAgg = get(job.datafeed_config, 'aggregations') || get(job.datafeed_config, 'aggs'); + if (topAgg !== undefined && Object.values(topAgg).length > 0) { cardinalityField = - _.get(_.values(topAgg)[0], [ + get(Object.values(topAgg)[0], [ 'aggregations', summaryCountFieldName, 'cardinality', 'field', - ]) || _.get(_.values(topAgg)[0], ['aggs', summaryCountFieldName, 'cardinality', 'field']); + ]) || + get(Object.values(topAgg)[0], ['aggs', summaryCountFieldName, 'cardinality', 'field']); } if (detector.function === 'non_zero_count' && cardinalityField !== undefined) { diff --git a/x-pack/plugins/ml/public/application/util/inherits.js b/x-pack/plugins/ml/public/application/util/inherits.js deleted file mode 100644 index bf16e573117d9..0000000000000 --- a/x-pack/plugins/ml/public/application/util/inherits.js +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - */ - -// create a property descriptor for properties -// that won't change -function describeConst(val) { - return { - writable: false, - enumerable: false, - configurable: false, - value: val, - }; -} - -/** - * Apply inheritance in the legacy `_.class(SubClass).inherits(SuperClass)` - * @param {Function} SubClass class that should inherit SuperClass - * @param {Function} SuperClass - * @return {Function} - */ -export function inherits(SubClass, SuperClass) { - const prototype = Object.create(SuperClass.prototype, { - constructor: describeConst(SubClass), - superConstructor: describeConst(SuperClass), - }); - - Object.defineProperties(SubClass, { - prototype: describeConst(prototype), - Super: describeConst(SuperClass), - }); - - return SubClass; -} diff --git a/x-pack/plugins/ml/public/application/util/time_buckets.js b/x-pack/plugins/ml/public/application/util/time_buckets.js index 19d499faf6c8d..15b8f24804ec8 100644 --- a/x-pack/plugins/ml/public/application/util/time_buckets.js +++ b/x-pack/plugins/ml/public/application/util/time_buckets.js @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import isPlainObject from 'lodash/isPlainObject'; +import isString from 'lodash/isString'; +import ary from 'lodash/ary'; +import sortBy from 'lodash/sortBy'; +import assign from 'lodash/assign'; import moment from 'moment'; import dateMath from '@elastic/datemath'; @@ -80,16 +84,16 @@ TimeBuckets.prototype.setBounds = function (input) { if (!input) return this.clearBounds(); let bounds; - if (_.isPlainObject(input)) { + if (isPlainObject(input)) { // accept the response from timefilter.getActiveBounds() bounds = [input.min, input.max]; } else { bounds = Array.isArray(input) ? input : []; } - const moments = _(bounds).map(_.ary(moment, 1)).sortBy(Number); + const moments = sortBy(bounds.map(ary(moment, 1)), Number); - const valid = moments.size() === 2 && moments.every(isValidMoment); + const valid = moments.length === 2 && moments.every(isValidMoment); if (!valid) { this.clearBounds(); throw new Error('invalid bounds set: ' + input); @@ -175,7 +179,7 @@ TimeBuckets.prototype.setInterval = function (input) { return; } - if (_.isString(interval)) { + if (isString(interval)) { input = interval; interval = parseInterval(interval); if (+interval === 0) { @@ -256,7 +260,7 @@ TimeBuckets.prototype.getInterval = function () { if (+scaled === +interval) return interval; decorateInterval(interval, duration); - return _.assign(scaled, { + return assign(scaled, { preScaled: interval, scale: interval / scaled, scaled: true, @@ -287,7 +291,7 @@ TimeBuckets.prototype.getIntervalToNearestMultiple = function (divisorSecs) { decorateInterval(nearestMultipleInt, this.getDuration()); // Check to see if the new interval is scaled compared to the original. - const preScaled = _.get(interval, 'preScaled'); + const preScaled = interval.preScaled; if (preScaled !== undefined && preScaled < nearestMultipleInt) { nearestMultipleInt.preScaled = preScaled; nearestMultipleInt.scale = preScaled / nearestMultipleInt; diff --git a/x-pack/plugins/ml/server/lib/telemetry/telemetry.ts b/x-pack/plugins/ml/server/lib/telemetry/telemetry.ts index f2162ff2c3d30..d9ebccd554733 100644 --- a/x-pack/plugins/ml/server/lib/telemetry/telemetry.ts +++ b/x-pack/plugins/ml/server/lib/telemetry/telemetry.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import isEmpty from 'lodash/isEmpty'; import { ISavedObjectsRepository } from 'kibana/server'; import { getInternalRepository } from './internal_repository'; @@ -58,7 +58,7 @@ export async function updateTelemetry(internalRepo?: ISavedObjectsRepository) { let telemetry = await getTelemetry(internalRepository); // Create if doesn't exist - if (telemetry === null || _.isEmpty(telemetry)) { + if (telemetry === null || isEmpty(telemetry)) { const newTelemetrySavedObject = await internalRepository.create( TELEMETRY_DOC_ID, initTelemetry(), diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts index 8094689abf3e5..a585449db0a25 100644 --- a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts @@ -5,7 +5,8 @@ */ import Boom from 'boom'; -import _ from 'lodash'; +import each from 'lodash/each'; +import get from 'lodash/get'; import { ILegacyScopedClusterClient } from 'kibana/server'; import { ANNOTATION_EVENT_USER, ANNOTATION_TYPE } from '../../../common/constants/annotations'; @@ -190,7 +191,7 @@ export function annotationProvider({ callAsInternalUser }: ILegacyScopedClusterC if (jobIds && jobIds.length > 0 && !(jobIds.length === 1 && jobIds[0] === '*')) { let jobIdFilterStr = ''; - _.each(jobIds, (jobId, i: number) => { + each(jobIds, (jobId, i: number) => { jobIdFilterStr += `${i! > 0 ? ' OR ' : ''}job_id:${jobId}`; }); boolCriteria.push({ @@ -293,7 +294,7 @@ export function annotationProvider({ callAsInternalUser }: ILegacyScopedClusterC throw new Error(`Annotations couldn't be retrieved from Elasticsearch.`); } - const docs: Annotations = _.get(resp, ['hits', 'hits'], []).map((d: EsResult) => { + const docs: Annotations = get(resp, ['hits', 'hits'], []).map((d: EsResult) => { // get the original source document and the document id, we need it // to identify the annotation when editing/deleting it. // if original `event` is undefined then substitute with 'user` by default @@ -305,7 +306,7 @@ export function annotationProvider({ callAsInternalUser }: ILegacyScopedClusterC } as Annotation; }); - const aggregations = _.get(resp, ['aggregations'], {}) as EsAggregationResult; + const aggregations = get(resp, ['aggregations'], {}) as EsAggregationResult; if (fields) { obj.aggregations = aggregations; } diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js index 3758547779403..381c615051e3b 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import cloneDeep from 'lodash/cloneDeep'; +import each from 'lodash/each'; +import remove from 'lodash/remove'; +import sortBy from 'lodash/sortBy'; +import get from 'lodash/get'; import { mlLog } from '../../client/log'; @@ -91,7 +95,7 @@ export function estimateBucketSpanFactory(mlClusterClient) { } else { // loop over partition values for (let j = 0; j < this.splitFieldValues.length; j++) { - const queryCopy = _.cloneDeep(this.query); + const queryCopy = cloneDeep(this.query); // add a term to the query to filter on the partition value queryCopy.bool.must.push({ term: { @@ -151,7 +155,7 @@ export function estimateBucketSpanFactory(mlClusterClient) { } }; - _.each(this.checkers, (check) => { + each(this.checkers, (check) => { check.check .run() .then((interval) => { @@ -174,7 +178,7 @@ export function estimateBucketSpanFactory(mlClusterClient) { } processResults() { - const allResults = _.map(this.checkers, 'result'); + const allResults = this.checkers.map((c) => c.result); let reducedResults = []; const numberOfSplitFields = this.splitFieldValues.length || 1; @@ -185,8 +189,8 @@ export function estimateBucketSpanFactory(mlClusterClient) { const pos = i * numberOfSplitFields; let resultsSubset = allResults.slice(pos, pos + numberOfSplitFields); // remove results of tests which have failed - resultsSubset = _.remove(resultsSubset, (res) => res !== null); - resultsSubset = _.sortBy(resultsSubset, (r) => r.ms); + resultsSubset = remove(resultsSubset, (res) => res !== null); + resultsSubset = sortBy(resultsSubset, (r) => r.ms); const tempMedian = this.findMedian(resultsSubset); if (tempMedian !== null) { @@ -194,7 +198,7 @@ export function estimateBucketSpanFactory(mlClusterClient) { } } - reducedResults = _.sortBy(reducedResults, (r) => r.ms); + reducedResults = sortBy(reducedResults, (r) => r.ms); return this.findMedian(reducedResults); } @@ -256,7 +260,7 @@ export function estimateBucketSpanFactory(mlClusterClient) { }, }) .then((resp) => { - const value = _.get(resp, ['aggregations', 'field_count', 'value'], 0); + const value = get(resp, ['aggregations', 'field_count', 'value'], 0); resolve(value); }) .catch((resp) => { @@ -293,9 +297,10 @@ export function estimateBucketSpanFactory(mlClusterClient) { }, }) .then((partitionResp) => { - if (_.has(partitionResp, 'aggregations.fields_bucket_counts.buckets')) { + // eslint-disable-next-line camelcase + if (partitionResp.aggregations?.fields_bucket_counts?.buckets !== undefined) { const buckets = partitionResp.aggregations.fields_bucket_counts.buckets; - fieldValues = _.map(buckets, (b) => b.key); + fieldValues = buckets.map((b) => b.key); } resolve(fieldValues); }) diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js index 347843e276c36..d3bbd59f3cf9b 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js @@ -10,7 +10,7 @@ * And a minimum bucket span */ -import _ from 'lodash'; +import get from 'lodash/get'; export function polledDataCheckerFactory({ callAsCurrentUser }) { class PolledDataChecker { @@ -29,7 +29,7 @@ export function polledDataCheckerFactory({ callAsCurrentUser }) { const interval = { name: '1m', ms: 60000 }; this.performSearch(interval.ms) .then((resp) => { - const fullBuckets = _.get(resp, 'aggregations.non_empty_buckets.buckets', []); + const fullBuckets = get(resp, 'aggregations.non_empty_buckets.buckets', []); const result = this.isPolledData(fullBuckets, interval); if (result.pass) { // data is polled, return a flag and the minimumBucketSpan which should be diff --git a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts index 7f19f32373e07..838315d8d272c 100644 --- a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts +++ b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts @@ -5,7 +5,10 @@ */ import { ILegacyScopedClusterClient } from 'kibana/server'; -import _ from 'lodash'; +import get from 'lodash/get'; +import each from 'lodash/each'; +import last from 'lodash/last'; +import find from 'lodash/find'; import { KBN_FIELD_TYPES } from '../../../../../../src/plugins/data/server'; import { ML_JOB_FIELD_TYPES } from '../../../common/constants/field_types'; import { getSafeAggregationName } from '../../../common/util/job_utils'; @@ -216,7 +219,7 @@ const getAggIntervals = async ( const aggsPath = getSamplerAggregationsResponsePath(samplerShardSize); const aggregations = - aggsPath.length > 0 ? _.get(respStats.aggregations, aggsPath) : respStats.aggregations; + aggsPath.length > 0 ? get(respStats.aggregations, aggsPath) : respStats.aggregations; return Object.keys(aggregations).reduce((p, aggName) => { const stats = [aggregations[aggName].min, aggregations[aggName].max]; @@ -300,9 +303,7 @@ export const getHistogramsForFields = async ( const aggsPath = getSamplerAggregationsResponsePath(samplerShardSize); const aggregations = - aggsPath.length > 0 - ? _.get(respChartsData.aggregations, aggsPath) - : respChartsData.aggregations; + aggsPath.length > 0 ? get(respChartsData.aggregations, aggsPath) : respChartsData.aggregations; const chartsData: ChartData[] = fields.map( (field): ChartData => { @@ -382,8 +383,8 @@ export class DataVisualizer { // To avoid checking for the existence of too many aggregatable fields in one request, // split the check into multiple batches (max 200 fields per request). const batches: string[][] = [[]]; - _.each(aggregatableFields, (field) => { - let lastArray: string[] = _.last(batches) as string[]; + each(aggregatableFields, (field) => { + let lastArray: string[] = last(batches) as string[]; if (lastArray.length === AGGREGATABLE_EXISTS_REQUEST_BATCH_SIZE) { lastArray = []; batches.push(lastArray); @@ -475,7 +476,7 @@ export class DataVisualizer { // Batch up fields by type, getting stats for multiple fields at a time. const batches: Field[][] = []; const batchedFields: { [key: string]: Field[][] } = {}; - _.each(fields, (field) => { + each(fields, (field) => { if (field.fieldName === undefined) { // undefined fieldName is used for a document count request. // getDocumentCountStats requires timeField - don't add to batched requests if not defined @@ -487,7 +488,7 @@ export class DataVisualizer { if (batchedFields[fieldType] === undefined) { batchedFields[fieldType] = [[]]; } - let lastArray: Field[] = _.last(batchedFields[fieldType]) as Field[]; + let lastArray: Field[] = last(batchedFields[fieldType]) as Field[]; if (lastArray.length === FIELDS_REQUEST_BATCH_SIZE) { lastArray = []; batchedFields[fieldType].push(lastArray); @@ -496,7 +497,7 @@ export class DataVisualizer { } }); - _.each(batchedFields, (lists) => { + each(batchedFields, (lists) => { batches.push(...lists); }); @@ -636,7 +637,7 @@ export class DataVisualizer { body, }); const aggregations = resp.aggregations; - const totalCount = _.get(resp, ['hits', 'total'], 0); + const totalCount = get(resp, ['hits', 'total'], 0); const stats = { totalCount, aggregatableExistsFields: [] as FieldData[], @@ -645,12 +646,12 @@ export class DataVisualizer { const aggsPath = getSamplerAggregationsResponsePath(samplerShardSize); const sampleCount = - samplerShardSize > 0 ? _.get(aggregations, ['sample', 'doc_count'], 0) : totalCount; + samplerShardSize > 0 ? get(aggregations, ['sample', 'doc_count'], 0) : totalCount; aggregatableFields.forEach((field, i) => { const safeFieldName = getSafeAggregationName(field, i); - const count = _.get(aggregations, [...aggsPath, `${safeFieldName}_count`, 'doc_count'], 0); + const count = get(aggregations, [...aggsPath, `${safeFieldName}_count`, 'doc_count'], 0); if (count > 0) { - const cardinality = _.get( + const cardinality = get( aggregations, [...aggsPath, `${safeFieldName}_cardinality`, 'value'], 0 @@ -745,12 +746,12 @@ export class DataVisualizer { }); const buckets: { [key: string]: number } = {}; - const dataByTimeBucket: Array<{ key: string; doc_count: number }> = _.get( + const dataByTimeBucket: Array<{ key: string; doc_count: number }> = get( resp, ['aggregations', 'eventRate', 'buckets'], [] ); - _.each(dataByTimeBucket, (dataForTime) => { + each(dataByTimeBucket, (dataForTime) => { const time = dataForTime.key; buckets[time] = dataForTime.doc_count; }); @@ -851,12 +852,12 @@ export class DataVisualizer { const batchStats: NumericFieldStats[] = []; fields.forEach((field, i) => { const safeFieldName = getSafeAggregationName(field.fieldName, i); - const docCount = _.get( + const docCount = get( aggregations, [...aggsPath, `${safeFieldName}_field_stats`, 'doc_count'], 0 ); - const fieldStatsResp = _.get( + const fieldStatsResp = get( aggregations, [...aggsPath, `${safeFieldName}_field_stats`, 'actual_stats'], {} @@ -867,20 +868,20 @@ export class DataVisualizer { topAggsPath.push('top'); } - const topValues: Bucket[] = _.get(aggregations, [...topAggsPath, 'buckets'], []); + const topValues: Bucket[] = get(aggregations, [...topAggsPath, 'buckets'], []); const stats: NumericFieldStats = { fieldName: field.fieldName, count: docCount, - min: _.get(fieldStatsResp, 'min', 0), - max: _.get(fieldStatsResp, 'max', 0), - avg: _.get(fieldStatsResp, 'avg', 0), + min: get(fieldStatsResp, 'min', 0), + max: get(fieldStatsResp, 'max', 0), + avg: get(fieldStatsResp, 'avg', 0), isTopValuesSampled: field.cardinality >= SAMPLER_TOP_TERMS_THRESHOLD || samplerShardSize > 0, topValues, topValuesSampleSize: topValues.reduce( (acc, curr) => acc + curr.doc_count, - _.get(aggregations, [...topAggsPath, 'sum_other_doc_count'], 0) + get(aggregations, [...topAggsPath, 'sum_other_doc_count'], 0) ), topValuesSamplerShardSize: field.cardinality >= SAMPLER_TOP_TERMS_THRESHOLD @@ -889,12 +890,12 @@ export class DataVisualizer { }; if (stats.count > 0) { - const percentiles = _.get( + const percentiles = get( aggregations, [...aggsPath, `${safeFieldName}_percentiles`, 'values'], [] ); - const medianPercentile: { value: number; key: number } | undefined = _.find(percentiles, { + const medianPercentile: { value: number; key: number } | undefined = find(percentiles, { key: 50, }); stats.median = medianPercentile !== undefined ? medianPercentile!.value : 0; @@ -978,7 +979,7 @@ export class DataVisualizer { topAggsPath.push('top'); } - const topValues: Bucket[] = _.get(aggregations, [...topAggsPath, 'buckets'], []); + const topValues: Bucket[] = get(aggregations, [...topAggsPath, 'buckets'], []); const stats = { fieldName: field.fieldName, @@ -987,7 +988,7 @@ export class DataVisualizer { topValues, topValuesSampleSize: topValues.reduce( (acc, curr) => acc + curr.doc_count, - _.get(aggregations, [...topAggsPath, 'sum_other_doc_count'], 0) + get(aggregations, [...topAggsPath, 'sum_other_doc_count'], 0) ), topValuesSamplerShardSize: field.cardinality >= SAMPLER_TOP_TERMS_THRESHOLD @@ -1046,12 +1047,12 @@ export class DataVisualizer { const batchStats: DateFieldStats[] = []; fields.forEach((field, i) => { const safeFieldName = getSafeAggregationName(field.fieldName, i); - const docCount = _.get( + const docCount = get( aggregations, [...aggsPath, `${safeFieldName}_field_stats`, 'doc_count'], 0 ); - const fieldStatsResp = _.get( + const fieldStatsResp = get( aggregations, [...aggsPath, `${safeFieldName}_field_stats`, 'actual_stats'], {} @@ -1059,8 +1060,8 @@ export class DataVisualizer { batchStats.push({ fieldName: field.fieldName, count: docCount, - earliest: _.get(fieldStatsResp, 'min', 0), - latest: _.get(fieldStatsResp, 'max', 0), + earliest: get(fieldStatsResp, 'min', 0), + latest: get(fieldStatsResp, 'max', 0), }); }); @@ -1115,17 +1116,17 @@ export class DataVisualizer { const safeFieldName = getSafeAggregationName(field.fieldName, i); const stats: BooleanFieldStats = { fieldName: field.fieldName, - count: _.get(aggregations, [...aggsPath, `${safeFieldName}_value_count`, 'doc_count'], 0), + count: get(aggregations, [...aggsPath, `${safeFieldName}_value_count`, 'doc_count'], 0), trueCount: 0, falseCount: 0, }; - const valueBuckets: Array<{ [key: string]: number }> = _.get( + const valueBuckets: Array<{ [key: string]: number }> = get( aggregations, [...aggsPath, `${safeFieldName}_values`, 'buckets'], [] ); - _.forEach(valueBuckets, (bucket) => { + valueBuckets.forEach((bucket) => { stats[`${bucket.key_as_string}Count`] = bucket.doc_count; }); @@ -1182,8 +1183,8 @@ export class DataVisualizer { // If the field is not in the _source (as will happen if the // field is populated using copy_to in the index mapping), // there will be no example to add. - // Use lodash _.get() to support field names containing dots. - const example: any = _.get(hits[i]._source, field); + // Use lodash get() to support field names containing dots. + const example: any = get(hits[i]._source, field); if (example !== undefined && stats.examples.indexOf(example) === -1) { stats.examples.push(example); if (stats.examples.length === maxExamples) { @@ -1216,7 +1217,7 @@ export class DataVisualizer { // Look ahead to the last percentiles and process these too if // they don't add more than 50% to the value range. - const lastValue = (_.last(percentileBuckets) as any).value; + const lastValue = (last(percentileBuckets) as any).value; const upperBound = lowerBound + 1.5 * (lastValue - lowerBound); const filteredLength = percentileBuckets.length; for (let i = filteredLength; i < percentiles.length; i++) { @@ -1237,7 +1238,7 @@ export class DataVisualizer { // Add in 0-5 and 95-100% if they don't add more // than 25% to the value range at either end. - const lastValue: number = (_.last(percentileBuckets) as any).value; + const lastValue: number = (last(percentileBuckets) as any).value; const maxDiff = 0.25 * (lastValue - lowerBound); if (lowerBound - dataMin < maxDiff) { percentileBuckets.splice(0, 0, percentiles[0]); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts index 92933877e2836..16ee70ad9efde 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import cloneDeep from 'lodash/cloneDeep'; import { ILegacyScopedClusterClient } from 'kibana/server'; @@ -145,7 +145,7 @@ describe('ML - validateCardinality', () => { test: (ids: string[]) => void ) => { const job = getJobConfig(fieldName); - const mockCardinality = _.cloneDeep(mockResponses); + const mockCardinality = cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; return validateCardinality( mlClusterClientFactory(mockCardinality), @@ -250,7 +250,7 @@ describe('ML - validateCardinality', () => { it(`disabled model_plot, over field cardinality of ${cardinality} doesn't trigger a warning`, () => { const job = (getJobConfig('over_field_name') as unknown) as CombinedJob; job.model_plot_config = { enabled: false }; - const mockCardinality = _.cloneDeep(mockResponses); + const mockCardinality = cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; return validateCardinality(mlClusterClientFactory(mockCardinality), job).then((messages) => { const ids = messages.map((m) => m.id); @@ -261,7 +261,7 @@ describe('ML - validateCardinality', () => { it(`enabled model_plot, over field cardinality of ${cardinality} triggers a model plot warning`, () => { const job = (getJobConfig('over_field_name') as unknown) as CombinedJob; job.model_plot_config = { enabled: true }; - const mockCardinality = _.cloneDeep(mockResponses); + const mockCardinality = cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; return validateCardinality(mlClusterClientFactory(mockCardinality), job).then((messages) => { const ids = messages.map((m) => m.id); @@ -272,7 +272,7 @@ describe('ML - validateCardinality', () => { it(`disabled model_plot, by field cardinality of ${cardinality} triggers a field cardinality warning`, () => { const job = (getJobConfig('by_field_name') as unknown) as CombinedJob; job.model_plot_config = { enabled: false }; - const mockCardinality = _.cloneDeep(mockResponses); + const mockCardinality = cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; return validateCardinality(mlClusterClientFactory(mockCardinality), job).then((messages) => { const ids = messages.map((m) => m.id); @@ -283,7 +283,7 @@ describe('ML - validateCardinality', () => { it(`enabled model_plot, by field cardinality of ${cardinality} triggers a model plot warning and field cardinality warning`, () => { const job = (getJobConfig('by_field_name') as unknown) as CombinedJob; job.model_plot_config = { enabled: true }; - const mockCardinality = _.cloneDeep(mockResponses); + const mockCardinality = cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; return validateCardinality(mlClusterClientFactory(mockCardinality), job).then((messages) => { const ids = messages.map((m) => m.id); @@ -294,7 +294,7 @@ describe('ML - validateCardinality', () => { it(`enabled model_plot with terms, by field cardinality of ${cardinality} triggers just field cardinality warning`, () => { const job = (getJobConfig('by_field_name') as unknown) as CombinedJob; job.model_plot_config = { enabled: true, terms: 'AAL,AAB' }; - const mockCardinality = _.cloneDeep(mockResponses); + const mockCardinality = cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; return validateCardinality(mlClusterClientFactory(mockCardinality), job).then((messages) => { const ids = messages.map((m) => m.id); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts index f74d8a26ef370..a45be189ba3d8 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import cloneDeep from 'lodash/cloneDeep'; import { ILegacyScopedClusterClient } from 'kibana/server'; @@ -144,7 +144,7 @@ describe('ML - validateTimeRange', () => { }); it('invalid time field', () => { - const mockSearchResponseInvalid = _.cloneDeep(mockSearchResponse); + const mockSearchResponseInvalid = cloneDeep(mockSearchResponse); mockSearchResponseInvalid.fieldCaps = undefined; const duration = { start: 0, end: 1 }; return validateTimeRange( diff --git a/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js index e664a1403d7d6..588e0e10a8d63 100644 --- a/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js +++ b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import sortBy from 'lodash/sortBy'; +import each from 'lodash/each'; import moment from 'moment-timezone'; import { @@ -55,7 +56,7 @@ export function buildAnomalyTableItems(anomalyRecords, aggregationInterval, date if (source.influencers !== undefined) { const influencers = []; - const sourceInfluencers = _.sortBy(source.influencers, 'influencer_field_name'); + const sourceInfluencers = sortBy(source.influencers, 'influencer_field_name'); sourceInfluencers.forEach((influencer) => { const influencerFieldName = influencer.influencer_field_name; influencer.influencer_field_values.forEach((influencerFieldValue) => { @@ -172,10 +173,10 @@ function aggregateAnomalies(anomalyRecords, interval, dateFormatTz) { // Flatten the aggregatedData to give a list of records with // the highest score per bucketed time / jobId / detectorIndex. const summaryRecords = []; - _.each(aggregatedData, (times, roundedTime) => { - _.each(times, (jobIds) => { - _.each(jobIds, (entityDetectors) => { - _.each(entityDetectors, (record) => { + each(aggregatedData, (times, roundedTime) => { + each(times, (jobIds) => { + each(jobIds, (entityDetectors) => { + each(entityDetectors, (record) => { summaryRecords.push({ time: +roundedTime, source: record, diff --git a/x-pack/plugins/ml/server/models/results_service/results_service.ts b/x-pack/plugins/ml/server/models/results_service/results_service.ts index 04997e517bba9..8e71384942b57 100644 --- a/x-pack/plugins/ml/server/models/results_service/results_service.ts +++ b/x-pack/plugins/ml/server/models/results_service/results_service.ts @@ -4,7 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import _ from 'lodash'; +import sortBy from 'lodash/sortBy'; +import slice from 'lodash/slice'; +import get from 'lodash/get'; import moment from 'moment'; import { SearchResponse } from 'elasticsearch'; import { ILegacyScopedClusterClient } from 'kibana/server'; @@ -175,7 +177,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie }); // Sort anomalies in ascending time order. - records = _.sortBy(records, 'timestamp'); + records = sortBy(records, 'timestamp'); tableData.interval = aggregationInterval; if (aggregationInterval === 'auto') { // Determine the actual interval to use if aggregating. @@ -197,7 +199,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie const categoryIdsByJobId: { [key: string]: any } = {}; categoryAnomalies.forEach((anomaly) => { - if (!_.has(categoryIdsByJobId, anomaly.jobId)) { + if (categoryIdsByJobId[anomaly.jobId] === undefined) { categoryIdsByJobId[anomaly.jobId] = []; } if (categoryIdsByJobId[anomaly.jobId].indexOf(anomaly.entityValue) === -1) { @@ -289,7 +291,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie }; const resp = await callAsInternalUser('search', query); - const maxScore = _.get(resp, ['aggregations', 'max_score', 'value'], null); + const maxScore = get(resp, ['aggregations', 'max_score', 'value'], null); return { maxScore }; } @@ -353,7 +355,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie }, }); - const bucketsByJobId: Array<{ key: string; maxTimestamp: { value?: number } }> = _.get( + const bucketsByJobId: Array<{ key: string; maxTimestamp: { value?: number } }> = get( resp, ['aggregations', 'byJobId', 'buckets'], [] @@ -387,7 +389,7 @@ export function resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClie if (resp.hits.total !== 0) { resp.hits.hits.forEach((hit: any) => { if (maxExamples) { - examplesByCategoryId[hit._source.category_id] = _.slice( + examplesByCategoryId[hit._source.category_id] = slice( hit._source.examples, 0, Math.min(hit._source.examples.length, maxExamples) diff --git a/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap b/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap index ddba7842f1199..66c3aea8acc13 100644 --- a/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap +++ b/x-pack/plugins/reporting/public/components/__snapshots__/report_listing.test.tsx.snap @@ -30,6 +30,7 @@ Array [ }, ] } + data-test-page={0} data-test-subj="reportJobListing" isSelectable={true} itemId="id" @@ -56,6 +57,7 @@ Array [ >
@@ -366,6 +368,7 @@ Array [ ,
diff --git a/x-pack/plugins/reporting/public/components/report_listing.tsx b/x-pack/plugins/reporting/public/components/report_listing.tsx index afcae93a8db16..80ef9311fd0e5 100644 --- a/x-pack/plugins/reporting/public/components/report_listing.tsx +++ b/x-pack/plugins/reporting/public/components/report_listing.tsx @@ -513,6 +513,7 @@ class ReportListingUi extends Component { isSelectable={true} onChange={this.onTableChange} data-test-subj="reportJobListing" + data-test-page={this.state.page} /> {this.state.selectedJobs.length > 0 ? this.renderDeleteButton() : null} diff --git a/x-pack/plugins/reporting/server/routes/jobs.ts b/x-pack/plugins/reporting/server/routes/jobs.ts index 4033719b053ba..e8eac9e577beb 100644 --- a/x-pack/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/plugins/reporting/server/routes/jobs.ts @@ -35,7 +35,13 @@ export function registerJobInfoRoutes(reporting: ReportingCore) { router.get( { path: `${MAIN_ENTRY}/list`, - validate: false, + validate: { + query: schema.object({ + page: schema.string({ defaultValue: '0' }), + size: schema.string({ defaultValue: '10' }), + ids: schema.maybe(schema.string()), + }), + }, }, userHandler(async (user, context, req, res) => { // ensure the async dependencies are loaded @@ -50,7 +56,7 @@ export function registerJobInfoRoutes(reporting: ReportingCore) { page: queryPage = '0', size: querySize = '10', ids: queryIds = null, - } = req.query as ListQuery; + } = req.query as ListQuery; // NOTE: type inference is not working here. userHandler breaks it? const page = parseInt(queryPage, 10) || 0; const size = Math.min(100, parseInt(querySize, 10) || 10); const jobIds = queryIds ? queryIds.split(',') : null; diff --git a/x-pack/plugins/security_solution/common/endpoint/models/event.ts b/x-pack/plugins/security_solution/common/endpoint/models/event.ts index 30e11819c0272..a0e9be58911c6 100644 --- a/x-pack/plugins/security_solution/common/endpoint/models/event.ts +++ b/x-pack/plugins/security_solution/common/endpoint/models/event.ts @@ -55,6 +55,25 @@ export function timestampSafeVersion(event: SafeResolverEvent): string | undefin : firstNonNullValue(event?.['@timestamp']); } +/** + * The `@timestamp` for the event, as a `Date` object. + * If `@timestamp` couldn't be parsed as a `Date`, returns `undefined`. + */ +export function timestampAsDateSafeVersion(event: SafeResolverEvent): Date | undefined { + const value = timestampSafeVersion(event); + if (value === undefined) { + return undefined; + } + + const date = new Date(value); + // Check if the date is valid + if (isFinite(date.getTime())) { + return date; + } else { + return undefined; + } +} + export function eventTimestamp(event: ResolverEvent): string | undefined | number { if (isLegacyEvent(event)) { return event.endgame.timestamp_utc; diff --git a/x-pack/plugins/security_solution/public/common/store/actions.ts b/x-pack/plugins/security_solution/public/common/store/actions.ts index f2072aae1936f..cd8836e38bfef 100644 --- a/x-pack/plugins/security_solution/public/common/store/actions.ts +++ b/x-pack/plugins/security_solution/public/common/store/actions.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { HostAction } from '../../management/pages/endpoint_hosts/store/action'; +import { EndpointAction } from '../../management/pages/endpoint_hosts/store/action'; import { PolicyListAction } from '../../management/pages/policy/store/policy_list'; import { PolicyDetailsAction } from '../../management/pages/policy/store/policy_details'; @@ -13,4 +13,4 @@ export { dragAndDropActions } from './drag_and_drop'; export { inputsActions } from './inputs'; import { RoutingAction } from './routing'; -export type AppAction = HostAction | RoutingAction | PolicyListAction | PolicyDetailsAction; +export type AppAction = EndpointAction | RoutingAction | PolicyListAction | PolicyDetailsAction; diff --git a/x-pack/plugins/security_solution/public/management/common/constants.ts b/x-pack/plugins/security_solution/public/management/common/constants.ts index b07c47a398049..88396cc24a5e2 100644 --- a/x-pack/plugins/security_solution/public/management/common/constants.ts +++ b/x-pack/plugins/security_solution/public/management/common/constants.ts @@ -10,7 +10,7 @@ import { SecurityPageName } from '../../app/types'; // --[ ROUTING ]--------------------------------------------------------------------------- export const MANAGEMENT_APP_ID = `${APP_ID}:${SecurityPageName.administration}`; export const MANAGEMENT_ROUTING_ROOT_PATH = ''; -export const MANAGEMENT_ROUTING_HOSTS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.hosts})`; +export const MANAGEMENT_ROUTING_ENDPOINTS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.endpoints})`; export const MANAGEMENT_ROUTING_POLICIES_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.policies})`; export const MANAGEMENT_ROUTING_POLICY_DETAILS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.policies})/:policyId`; @@ -21,5 +21,5 @@ export const MANAGEMENT_STORE_GLOBAL_NAMESPACE: ManagementStoreGlobalNamespace = export const MANAGEMENT_STORE_POLICY_LIST_NAMESPACE = 'policyList'; /** Namespace within the Management state where policy details state is maintained */ export const MANAGEMENT_STORE_POLICY_DETAILS_NAMESPACE = 'policyDetails'; -/** Namespace within the Management state where hosts state is maintained */ -export const MANAGEMENT_STORE_HOSTS_NAMESPACE = 'hosts'; +/** Namespace within the Management state where endpoint-host state is maintained */ +export const MANAGEMENT_STORE_ENDPOINTS_NAMESPACE = 'endpoints'; diff --git a/x-pack/plugins/security_solution/public/management/common/routing.ts b/x-pack/plugins/security_solution/public/management/common/routing.ts index eeb1533f57a67..ea162422abb6f 100644 --- a/x-pack/plugins/security_solution/public/management/common/routing.ts +++ b/x-pack/plugins/security_solution/public/management/common/routing.ts @@ -10,13 +10,13 @@ import { generatePath } from 'react-router-dom'; import querystring from 'querystring'; import { - MANAGEMENT_ROUTING_HOSTS_PATH, + MANAGEMENT_ROUTING_ENDPOINTS_PATH, MANAGEMENT_ROUTING_POLICIES_PATH, MANAGEMENT_ROUTING_POLICY_DETAILS_PATH, } from './constants'; import { AdministrationSubTab } from '../types'; import { appendSearch } from '../../common/components/link_to/helpers'; -import { HostIndexUIQueryParams } from '../pages/endpoint_hosts/types'; +import { EndpointIndexUIQueryParams } from '../pages/endpoint_hosts/types'; // Taken from: https://github.com/microsoft/TypeScript/issues/12936#issuecomment-559034150 type ExactKeys = Exclude extends never ? T1 : never; @@ -31,42 +31,44 @@ const querystringStringify: ( params: Exact ) => string = querystring.stringify; -/** Make `selected_host` required */ -type HostDetailsUrlProps = Omit & - Required>; +/** Make `selected_endpoint` required */ +type EndpointDetailsUrlProps = Omit & + Required>; -export const getHostListPath = ( - props: { name: 'default' | 'hostList' } & HostIndexUIQueryParams, +export const getEndpointListPath = ( + props: { name: 'default' | 'endpointList' } & EndpointIndexUIQueryParams, search?: string ) => { const { name, ...queryParams } = props; - const urlQueryParams = querystringStringify( + const urlQueryParams = querystringStringify( queryParams ); const urlSearch = `${urlQueryParams && !isEmpty(search) ? '&' : ''}${search ?? ''}`; - if (name === 'hostList') { - return `${generatePath(MANAGEMENT_ROUTING_HOSTS_PATH, { - tabName: AdministrationSubTab.hosts, + if (name === 'endpointList') { + return `${generatePath(MANAGEMENT_ROUTING_ENDPOINTS_PATH, { + tabName: AdministrationSubTab.endpoints, })}${appendSearch(`${urlQueryParams ? `${urlQueryParams}${urlSearch}` : urlSearch}`)}`; } return `${appendSearch(`${urlQueryParams ? `${urlQueryParams}${urlSearch}` : urlSearch}`)}`; }; -export const getHostDetailsPath = ( - props: { name: 'hostDetails' | 'hostPolicyResponse' } & HostIndexUIQueryParams & - HostDetailsUrlProps, +export const getEndpointDetailsPath = ( + props: { name: 'endpointDetails' | 'endpointPolicyResponse' } & EndpointIndexUIQueryParams & + EndpointDetailsUrlProps, search?: string ) => { const { name, ...queryParams } = props; - queryParams.show = (props.name === 'hostPolicyResponse' + queryParams.show = (props.name === 'endpointPolicyResponse' ? 'policy_response' - : '') as HostIndexUIQueryParams['show']; - const urlQueryParams = querystringStringify(queryParams); + : '') as EndpointIndexUIQueryParams['show']; + const urlQueryParams = querystringStringify( + queryParams + ); const urlSearch = `${urlQueryParams && !isEmpty(search) ? '&' : ''}${search ?? ''}`; - return `${generatePath(MANAGEMENT_ROUTING_HOSTS_PATH, { - tabName: AdministrationSubTab.hosts, + return `${generatePath(MANAGEMENT_ROUTING_ENDPOINTS_PATH, { + tabName: AdministrationSubTab.endpoints, })}${appendSearch(`${urlQueryParams ? `${urlQueryParams}${urlSearch}` : urlSearch}`)}`; }; diff --git a/x-pack/plugins/security_solution/public/management/common/translations.ts b/x-pack/plugins/security_solution/public/management/common/translations.ts index 70ccf715eaa09..03f6a80ef99a4 100644 --- a/x-pack/plugins/security_solution/public/management/common/translations.ts +++ b/x-pack/plugins/security_solution/public/management/common/translations.ts @@ -6,8 +6,8 @@ import { i18n } from '@kbn/i18n'; -export const HOSTS_TAB = i18n.translate('xpack.securitySolution.hostsTab', { - defaultMessage: 'Hosts', +export const ENDPOINTS_TAB = i18n.translate('xpack.securitySolution.endpointsTab', { + defaultMessage: 'Endpoints', }); export const POLICIES_TAB = i18n.translate('xpack.securitySolution.policiesTab', { diff --git a/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx b/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx index a4518d1a1f493..4617865d6aa6d 100644 --- a/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx +++ b/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx @@ -116,7 +116,7 @@ const PolicyEmptyState = React.memo<{ ); }); -const HostsEmptyState = React.memo<{ +const EndpointsEmptyState = React.memo<{ loading: boolean; onActionClick: (event: MouseEvent) => void; actionDisabled: boolean; @@ -126,14 +126,14 @@ const HostsEmptyState = React.memo<{ const policySteps = useMemo( () => [ { - title: i18n.translate('xpack.securitySolution.endpoint.hostList.stepOneTitle', { + title: i18n.translate('xpack.securitySolution.endpoint.list.stepOneTitle', { defaultMessage: 'Select the integration you want to use', }), children: ( <> @@ -151,7 +151,7 @@ const HostsEmptyState = React.memo<{ return loading ? ( @@ -159,7 +159,7 @@ const HostsEmptyState = React.memo<{ list ) : ( ); @@ -169,7 +169,7 @@ const HostsEmptyState = React.memo<{ ), }, { - title: i18n.translate('xpack.securitySolution.endpoint.hostList.stepTwoTitle', { + title: i18n.translate('xpack.securitySolution.endpoint.list.stepTwoTitle', { defaultMessage: 'Enroll your agents enabled with Endpoint Security through Ingest Manager', }), @@ -179,7 +179,7 @@ const HostsEmptyState = React.memo<{ @@ -211,13 +211,13 @@ const HostsEmptyState = React.memo<{ steps={policySteps} headerComponent={ } bodyComponent={ } @@ -265,7 +265,7 @@ const ManagementEmptyState = React.memo<{ }); PolicyEmptyState.displayName = 'PolicyEmptyState'; -HostsEmptyState.displayName = 'HostsEmptyState'; +EndpointsEmptyState.displayName = 'HostsEmptyState'; ManagementEmptyState.displayName = 'ManagementEmptyState'; -export { PolicyEmptyState, HostsEmptyState }; +export { PolicyEmptyState, EndpointsEmptyState as HostsEmptyState }; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/index.tsx index a970edd4d30f4..23e55301d22cb 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/index.tsx @@ -6,20 +6,20 @@ import { Switch, Route } from 'react-router-dom'; import React, { memo } from 'react'; -import { HostList } from './view'; -import { MANAGEMENT_ROUTING_HOSTS_PATH } from '../../common/constants'; +import { EndpointList } from './view'; +import { MANAGEMENT_ROUTING_ENDPOINTS_PATH } from '../../common/constants'; import { NotFoundPage } from '../../../app/404'; /** * Provides the routing container for the hosts related views */ -export const HostsContainer = memo(() => { +export const EndpointsContainer = memo(() => { return ( - + ); }); -HostsContainer.displayName = 'HostsContainer'; +EndpointsContainer.displayName = 'EndpointsContainer'; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/routes.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/routes.tsx index 3f92358b93d56..727d2715f0974 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/routes.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/routes.tsx @@ -7,12 +7,12 @@ import React from 'react'; import { Route, Switch } from 'react-router-dom'; -import { HostList } from './view'; +import { EndpointList } from './view'; export const EndpointHostsRoutes: React.FC = () => ( - - + + ); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts index 4a4326d5b2919..2e188af41d2d7 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/action.ts @@ -12,35 +12,35 @@ import { import { ServerApiError } from '../../../../common/types'; import { GetPolicyListResponse } from '../../policy/types'; import { GetPackagesResponse } from '../../../../../../ingest_manager/common'; -import { HostState } from '../types'; +import { EndpointState } from '../types'; -interface ServerReturnedHostList { - type: 'serverReturnedHostList'; +interface ServerReturnedEndpointList { + type: 'serverReturnedEndpointList'; payload: HostResultList; } -interface ServerFailedToReturnHostList { - type: 'serverFailedToReturnHostList'; +interface ServerFailedToReturnEndpointList { + type: 'serverFailedToReturnEndpointList'; payload: ServerApiError; } -interface ServerReturnedHostDetails { - type: 'serverReturnedHostDetails'; +interface ServerReturnedEndpointDetails { + type: 'serverReturnedEndpointDetails'; payload: HostInfo; } -interface ServerFailedToReturnHostDetails { - type: 'serverFailedToReturnHostDetails'; +interface ServerFailedToReturnEndpointDetails { + type: 'serverFailedToReturnEndpointDetails'; payload: ServerApiError; } -interface ServerReturnedHostPolicyResponse { - type: 'serverReturnedHostPolicyResponse'; +interface ServerReturnedEndpointPolicyResponse { + type: 'serverReturnedEndpointPolicyResponse'; payload: GetHostPolicyResponse; } -interface ServerFailedToReturnHostPolicyResponse { - type: 'serverFailedToReturnHostPolicyResponse'; +interface ServerFailedToReturnEndpointPolicyResponse { + type: 'serverFailedToReturnEndpointPolicyResponse'; payload: ServerApiError; } @@ -63,8 +63,8 @@ interface UserSelectedEndpointPolicy { }; } -interface ServerCancelledHostListLoading { - type: 'serverCancelledHostListLoading'; +interface ServerCancelledEndpointListLoading { + type: 'serverCancelledEndpointListLoading'; } interface ServerCancelledPolicyItemsLoading { @@ -76,28 +76,28 @@ interface ServerReturnedEndpointPackageInfo { payload: GetPackagesResponse['response'][0]; } -interface ServerReturnedHostNonExistingPolicies { - type: 'serverReturnedHostNonExistingPolicies'; - payload: HostState['nonExistingPolicies']; +interface ServerReturnedEndpointNonExistingPolicies { + type: 'serverReturnedEndpointNonExistingPolicies'; + payload: EndpointState['nonExistingPolicies']; } -interface ServerReturnedHostExistValue { - type: 'serverReturnedHostExistValue'; +interface ServerReturnedEndpointExistValue { + type: 'serverReturnedEndpointExistValue'; payload: boolean; } -export type HostAction = - | ServerReturnedHostList - | ServerFailedToReturnHostList - | ServerReturnedHostDetails - | ServerFailedToReturnHostDetails - | ServerReturnedHostPolicyResponse - | ServerFailedToReturnHostPolicyResponse +export type EndpointAction = + | ServerReturnedEndpointList + | ServerFailedToReturnEndpointList + | ServerReturnedEndpointDetails + | ServerFailedToReturnEndpointDetails + | ServerReturnedEndpointPolicyResponse + | ServerFailedToReturnEndpointPolicyResponse | ServerReturnedPoliciesForOnboarding | ServerFailedToReturnPoliciesForOnboarding | UserSelectedEndpointPolicy - | ServerCancelledHostListLoading - | ServerReturnedHostExistValue + | ServerCancelledEndpointListLoading + | ServerReturnedEndpointExistValue | ServerCancelledPolicyItemsLoading | ServerReturnedEndpointPackageInfo - | ServerReturnedHostNonExistingPolicies; + | ServerReturnedEndpointNonExistingPolicies; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/host_pagination.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts similarity index 80% rename from x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/host_pagination.test.ts rename to x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts index 533b14e50f3dd..0fd970f4bed12 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/host_pagination.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts @@ -13,41 +13,41 @@ import { coreMock } from '../../../../../../../../src/core/public/mocks'; import { HostResultList, AppLocation } from '../../../../../common/endpoint/types'; import { DepsStartMock, depsStartMock } from '../../../../common/mock/endpoint'; -import { hostMiddlewareFactory } from './middleware'; +import { endpointMiddlewareFactory } from './middleware'; -import { hostListReducer } from './reducer'; +import { endpointListReducer } from './reducer'; import { uiQueryParams } from './selectors'; -import { mockHostResultList } from './mock_host_result_list'; -import { HostState, HostIndexUIQueryParams } from '../types'; +import { mockEndpointResultList } from './mock_endpoint_result_list'; +import { EndpointState, EndpointIndexUIQueryParams } from '../types'; import { MiddlewareActionSpyHelper, createSpyMiddleware, } from '../../../../common/store/test_utils'; -import { getHostListPath } from '../../../common/routing'; +import { getEndpointListPath } from '../../../common/routing'; -describe('host list pagination: ', () => { +describe('endpoint list pagination: ', () => { let fakeCoreStart: jest.Mocked; let depsStart: DepsStartMock; let fakeHttpServices: jest.Mocked; let history: History; let store: Store; - let queryParams: () => HostIndexUIQueryParams; + let queryParams: () => EndpointIndexUIQueryParams; let waitForAction: MiddlewareActionSpyHelper['waitForAction']; let actionSpyMiddleware; const getEndpointListApiResponse = (): HostResultList => { - return mockHostResultList({ request_page_size: 1, request_page_index: 1, total: 10 }); + return mockEndpointResultList({ request_page_size: 1, request_page_index: 1, total: 10 }); }; - let historyPush: (params: HostIndexUIQueryParams) => void; + let historyPush: (params: EndpointIndexUIQueryParams) => void; beforeEach(() => { fakeCoreStart = coreMock.createStart(); depsStart = depsStartMock(); fakeHttpServices = fakeCoreStart.http as jest.Mocked; history = createBrowserHistory(); - const middleware = hostMiddlewareFactory(fakeCoreStart, depsStart); - ({ actionSpyMiddleware, waitForAction } = createSpyMiddleware()); - store = createStore(hostListReducer, applyMiddleware(middleware, actionSpyMiddleware)); + const middleware = endpointMiddlewareFactory(fakeCoreStart, depsStart); + ({ actionSpyMiddleware, waitForAction } = createSpyMiddleware()); + store = createStore(endpointListReducer, applyMiddleware(middleware, actionSpyMiddleware)); history.listen((location) => { store.dispatch({ type: 'userChangedUrl', payload: location }); @@ -55,12 +55,12 @@ describe('host list pagination: ', () => { queryParams = () => uiQueryParams(store.getState()); - historyPush = (nextQueryParams: HostIndexUIQueryParams): void => { - return history.push(getHostListPath({ name: 'hostList', ...nextQueryParams })); + historyPush = (nextQueryParams: EndpointIndexUIQueryParams): void => { + return history.push(getEndpointListPath({ name: 'endpointList', ...nextQueryParams })); }; }); - describe('when the user enteres the host list for the first time', () => { + describe('when the user enteres the endpoint list for the first time', () => { it('the api is called with page_index and page_size defaulting to 0 and 10 respectively', async () => { const apiResponse = getEndpointListApiResponse(); fakeHttpServices.post.mockResolvedValue(apiResponse); @@ -70,10 +70,10 @@ describe('host list pagination: ', () => { type: 'userChangedUrl', payload: { ...history.location, - pathname: getHostListPath({ name: 'hostList' }), + pathname: getEndpointListPath({ name: 'endpointList' }), }, }); - await waitForAction('serverReturnedHostList'); + await waitForAction('serverReturnedEndpointList'); expect(fakeHttpServices.post).toHaveBeenCalledWith('/api/endpoint/metadata', { body: JSON.stringify({ paging_properties: [{ page_index: '0' }, { page_size: '10' }], diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts index 8ff4ad5a043b5..b3ab3443809c8 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/index.test.ts @@ -5,24 +5,24 @@ */ import { createStore, Dispatch, Store } from 'redux'; -import { HostState } from '../types'; +import { EndpointState } from '../types'; import { listData } from './selectors'; -import { mockHostResultList } from './mock_host_result_list'; -import { HostAction } from './action'; -import { hostListReducer } from './reducer'; +import { mockEndpointResultList } from './mock_endpoint_result_list'; +import { EndpointAction } from './action'; +import { endpointListReducer } from './reducer'; -describe('HostList store concerns', () => { - let store: Store; - let dispatch: Dispatch; +describe('EndpointList store concerns', () => { + let store: Store; + let dispatch: Dispatch; const createTestStore = () => { - store = createStore(hostListReducer); + store = createStore(endpointListReducer); dispatch = store.dispatch; }; const loadDataToStore = () => { dispatch({ - type: 'serverReturnedHostList', - payload: mockHostResultList({ request_page_size: 1, request_page_index: 1, total: 10 }), + type: 'serverReturnedEndpointList', + payload: mockEndpointResultList({ request_page_size: 1, request_page_index: 1, total: 10 }), }); }; @@ -51,18 +51,18 @@ describe('HostList store concerns', () => { policyItemsLoading: false, endpointPackageInfo: undefined, nonExistingPolicies: {}, - hostsExist: true, + endpointsExist: true, }); }); - test('it handles `serverReturnedHostList', () => { - const payload = mockHostResultList({ + test('it handles `serverReturnedEndpointList', () => { + const payload = mockEndpointResultList({ request_page_size: 1, request_page_index: 1, total: 10, }); dispatch({ - type: 'serverReturnedHostList', + type: 'serverReturnedEndpointList', payload, }); @@ -80,7 +80,7 @@ describe('HostList store concerns', () => { loadDataToStore(); }); - test('it selects `hostListData`', () => { + test('it selects `endpointListData`', () => { const currentState = store.getState(); expect(listData(currentState)).toEqual(currentState.hosts); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts index 1c5c4fbac51ba..77ade5bcc6971 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts @@ -16,36 +16,36 @@ import { } from '../../../../common/store/test_utils'; import { Immutable, HostResultList } from '../../../../../common/endpoint/types'; import { AppAction } from '../../../../common/store/actions'; -import { mockHostResultList } from './mock_host_result_list'; +import { mockEndpointResultList } from './mock_endpoint_result_list'; import { listData } from './selectors'; -import { HostState } from '../types'; -import { hostListReducer } from './reducer'; -import { hostMiddlewareFactory } from './middleware'; -import { getHostListPath } from '../../../common/routing'; +import { EndpointState } from '../types'; +import { endpointListReducer } from './reducer'; +import { endpointMiddlewareFactory } from './middleware'; +import { getEndpointListPath } from '../../../common/routing'; -describe('host list middleware', () => { +describe('endpoint list middleware', () => { let fakeCoreStart: jest.Mocked; let depsStart: DepsStartMock; let fakeHttpServices: jest.Mocked; - type HostListStore = Store, Immutable>; - let store: HostListStore; - let getState: HostListStore['getState']; - let dispatch: HostListStore['dispatch']; + type EndpointListStore = Store, Immutable>; + let store: EndpointListStore; + let getState: EndpointListStore['getState']; + let dispatch: EndpointListStore['dispatch']; let waitForAction: MiddlewareActionSpyHelper['waitForAction']; let actionSpyMiddleware; let history: History; const getEndpointListApiResponse = (): HostResultList => { - return mockHostResultList({ request_page_size: 1, request_page_index: 1, total: 10 }); + return mockEndpointResultList({ request_page_size: 1, request_page_index: 1, total: 10 }); }; beforeEach(() => { fakeCoreStart = coreMock.createStart({ basePath: '/mock' }); depsStart = depsStartMock(); fakeHttpServices = fakeCoreStart.http as jest.Mocked; - ({ actionSpyMiddleware, waitForAction } = createSpyMiddleware()); + ({ actionSpyMiddleware, waitForAction } = createSpyMiddleware()); store = createStore( - hostListReducer, - applyMiddleware(hostMiddlewareFactory(fakeCoreStart, depsStart), actionSpyMiddleware) + endpointListReducer, + applyMiddleware(endpointMiddlewareFactory(fakeCoreStart, depsStart), actionSpyMiddleware) ); getState = store.getState; dispatch = store.dispatch; @@ -60,10 +60,10 @@ describe('host list middleware', () => { type: 'userChangedUrl', payload: { ...history.location, - pathname: getHostListPath({ name: 'hostList' }), + pathname: getEndpointListPath({ name: 'endpointList' }), }, }); - await waitForAction('serverReturnedHostList'); + await waitForAction('serverReturnedEndpointList'); expect(fakeHttpServices.post).toHaveBeenCalledWith('/api/endpoint/metadata', { body: JSON.stringify({ paging_properties: [{ page_index: '0' }, { page_size: '10' }], diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts index 74bebf211258a..fa2dbe084c1a4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts @@ -9,14 +9,14 @@ import { HostInfo, HostResultList } from '../../../../../common/endpoint/types'; import { GetPolicyListResponse } from '../../policy/types'; import { ImmutableMiddlewareFactory } from '../../../../common/store'; import { - isOnHostPage, - hasSelectedHost, + isOnEndpointPage, + hasSelectedEndpoint, uiQueryParams, listData, endpointPackageInfo, nonExistingPolicies, } from './selectors'; -import { HostState } from '../types'; +import { EndpointState } from '../types'; import { sendGetEndpointSpecificPackageConfigs, sendGetEndpointSecurityPackage, @@ -24,16 +24,16 @@ import { } from '../../policy/store/policy_list/services/ingest'; import { AGENT_CONFIG_SAVED_OBJECT_TYPE } from '../../../../../../ingest_manager/common'; -export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (coreStart) => { +export const endpointMiddlewareFactory: ImmutableMiddlewareFactory = (coreStart) => { return ({ getState, dispatch }) => (next) => async (action) => { next(action); const state = getState(); - // Host list + // Endpoint list if ( action.type === 'userChangedUrl' && - isOnHostPage(state) && - hasSelectedHost(state) !== true + isOnEndpointPage(state) && + hasSelectedEndpoint(state) !== true ) { if (!endpointPackageInfo(state)) { sendGetEndpointSecurityPackage(coreStart.http) @@ -50,30 +50,30 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor } const { page_index: pageIndex, page_size: pageSize } = uiQueryParams(state); - let hostResponse; + let endpointResponse; try { - hostResponse = await coreStart.http.post('/api/endpoint/metadata', { + endpointResponse = await coreStart.http.post('/api/endpoint/metadata', { body: JSON.stringify({ paging_properties: [{ page_index: pageIndex }, { page_size: pageSize }], }), }); - hostResponse.request_page_index = Number(pageIndex); + endpointResponse.request_page_index = Number(pageIndex); dispatch({ - type: 'serverReturnedHostList', - payload: hostResponse, + type: 'serverReturnedEndpointList', + payload: endpointResponse, }); - getNonExistingPoliciesForHostsList( + getNonExistingPoliciesForEndpointsList( coreStart.http, - hostResponse.hosts, + endpointResponse.hosts, nonExistingPolicies(state) ) .then((missingPolicies) => { if (missingPolicies !== undefined) { dispatch({ - type: 'serverReturnedHostNonExistingPolicies', + type: 'serverReturnedEndpointNonExistingPolicies', payload: missingPolicies, }); } @@ -83,24 +83,24 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor .catch((error) => console.error(error)); } catch (error) { dispatch({ - type: 'serverFailedToReturnHostList', + type: 'serverFailedToReturnEndpointList', payload: error, }); } - // No hosts, so we should check to see if there are policies for onboarding - if (hostResponse && hostResponse.hosts.length === 0) { + // No endpoints, so we should check to see if there are policies for onboarding + if (endpointResponse && endpointResponse.hosts.length === 0) { const http = coreStart.http; // The original query to the list could have had an invalid param (ex. invalid page_size), - // so we check first if hosts actually do exist before pulling in data for the onboarding + // so we check first if endpoints actually do exist before pulling in data for the onboarding // messages. - if (await doHostsExist(http)) { + if (await doEndpointsExist(http)) { return; } dispatch({ - type: 'serverReturnedHostExistValue', + type: 'serverReturnedEndpointExistValue', payload: false, }); @@ -135,13 +135,13 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor } } - // Host Details - if (action.type === 'userChangedUrl' && hasSelectedHost(state) === true) { + // Endpoint Details + if (action.type === 'userChangedUrl' && hasSelectedEndpoint(state) === true) { dispatch({ type: 'serverCancelledPolicyItemsLoading', }); - // If user navigated directly to a host details page, load the host list + // If user navigated directly to a endpoint details page, load the endpoint list if (listData(state).length === 0) { const { page_index: pageIndex, page_size: pageSize } = uiQueryParams(state); try { @@ -152,11 +152,11 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor }); response.request_page_index = Number(pageIndex); dispatch({ - type: 'serverReturnedHostList', + type: 'serverReturnedEndpointList', payload: response, }); - getNonExistingPoliciesForHostsList( + getNonExistingPoliciesForEndpointsList( coreStart.http, response.hosts, nonExistingPolicies(state) @@ -164,7 +164,7 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor .then((missingPolicies) => { if (missingPolicies !== undefined) { dispatch({ - type: 'serverReturnedHostNonExistingPolicies', + type: 'serverReturnedEndpointNonExistingPolicies', payload: missingPolicies, }); } @@ -174,31 +174,35 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor .catch((error) => console.error(error)); } catch (error) { dispatch({ - type: 'serverFailedToReturnHostList', + type: 'serverFailedToReturnEndpointList', payload: error, }); } } else { dispatch({ - type: 'serverCancelledHostListLoading', + type: 'serverCancelledEndpointListLoading', }); } - // call the host details api - const { selected_host: selectedHost } = uiQueryParams(state); + // call the endpoint details api + const { selected_endpoint: selectedEndpoint } = uiQueryParams(state); try { const response = await coreStart.http.get( - `/api/endpoint/metadata/${selectedHost}` + `/api/endpoint/metadata/${selectedEndpoint}` ); dispatch({ - type: 'serverReturnedHostDetails', + type: 'serverReturnedEndpointDetails', payload: response, }); - getNonExistingPoliciesForHostsList(coreStart.http, [response], nonExistingPolicies(state)) + getNonExistingPoliciesForEndpointsList( + coreStart.http, + [response], + nonExistingPolicies(state) + ) .then((missingPolicies) => { if (missingPolicies !== undefined) { dispatch({ - type: 'serverReturnedHostNonExistingPolicies', + type: 'serverReturnedEndpointNonExistingPolicies', payload: missingPolicies, }); } @@ -208,7 +212,7 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor .catch((error) => console.error(error)); } catch (error) { dispatch({ - type: 'serverFailedToReturnHostDetails', + type: 'serverFailedToReturnEndpointDetails', payload: error, }); } @@ -216,15 +220,15 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor // call the policy response api try { const policyResponse = await coreStart.http.get(`/api/endpoint/policy_response`, { - query: { hostId: selectedHost }, + query: { hostId: selectedEndpoint }, }); dispatch({ - type: 'serverReturnedHostPolicyResponse', + type: 'serverReturnedEndpointPolicyResponse', payload: policyResponse, }); } catch (error) { dispatch({ - type: 'serverFailedToReturnHostPolicyResponse', + type: 'serverFailedToReturnEndpointPolicyResponse', payload: error, }); } @@ -232,11 +236,11 @@ export const hostMiddlewareFactory: ImmutableMiddlewareFactory = (cor }; }; -const getNonExistingPoliciesForHostsList = async ( +const getNonExistingPoliciesForEndpointsList = async ( http: HttpStart, hosts: HostResultList['hosts'], - currentNonExistingPolicies: HostState['nonExistingPolicies'] -): Promise => { + currentNonExistingPolicies: EndpointState['nonExistingPolicies'] +): Promise => { if (hosts.length === 0) { return; } @@ -266,14 +270,14 @@ const getNonExistingPoliciesForHostsList = async ( )})`, }, }) - ).items.reduce((list, agentConfig) => { + ).items.reduce((list, agentConfig) => { (agentConfig.package_configs as string[]).forEach((packageConfig) => { list[packageConfig as string] = true; }); return list; }, {}); - const nonExisting = policyIdsToCheck.reduce( + const nonExisting = policyIdsToCheck.reduce( (list, policyId) => { if (policiesFound[policyId]) { return list; @@ -291,7 +295,7 @@ const getNonExistingPoliciesForHostsList = async ( return nonExisting; }; -const doHostsExist = async (http: HttpStart): Promise => { +const doEndpointsExist = async (http: HttpStart): Promise => { try { return ( ( @@ -304,7 +308,7 @@ const doHostsExist = async (http: HttpStart): Promise => { ); } catch (error) { // eslint-disable-next-line no-console - console.error(`error while trying to check if hosts exist`); + console.error(`error while trying to check if endpoints exist`); // eslint-disable-next-line no-console console.error(error); } diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_host_result_list.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts similarity index 79% rename from x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_host_result_list.ts rename to x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts index b69e5c5cd0e65..2f0b66624f379 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_host_result_list.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts @@ -26,7 +26,7 @@ import { GetPolicyListResponse } from '../../policy/types'; const generator = new EndpointDocGenerator('seed'); -export const mockHostResultList: (options?: { +export const mockEndpointResultList: (options?: { total?: number; request_page_size?: number; request_page_index?: number; @@ -62,7 +62,7 @@ export const mockHostResultList: (options?: { /** * returns a mocked API response for retrieving a single host metadata */ -export const mockHostDetailsApiResult = (): HostInfo => { +export const mockEndpointDetailsApiResult = (): HostInfo => { return { metadata: generator.generateHostMetadata(), host_status: HostStatus.ERROR, @@ -73,14 +73,14 @@ export const mockHostDetailsApiResult = (): HostInfo => { * Mock API handlers used by the Endpoint Host list. It also sets up a list of * API handlers for Host details based on a list of Host results. */ -const hostListApiPathHandlerMocks = ({ - hostsResults = mockHostResultList({ total: 3 }).hosts, +const endpointListApiPathHandlerMocks = ({ + endpointsResults = mockEndpointResultList({ total: 3 }).hosts, epmPackages = [generator.generateEpmPackage()], endpointPackageConfigs = [], policyResponse = generator.generatePolicyResponse(), }: { /** route handlers will be setup for each individual host in this array */ - hostsResults?: HostResultList['hosts']; + endpointsResults?: HostResultList['hosts']; epmPackages?: GetPackagesResponse['response']; endpointPackageConfigs?: GetPolicyListResponse['items']; policyResponse?: HostPolicyResponse; @@ -94,17 +94,17 @@ const hostListApiPathHandlerMocks = ({ }; }, - // host list + // endpoint list '/api/endpoint/metadata': (): HostResultList => { return { - hosts: hostsResults, + hosts: endpointsResults, request_page_size: 10, request_page_index: 0, - total: hostsResults?.length || 0, + total: endpointsResults?.length || 0, }; }, - // Do policies referenced in host list exist + // Do policies referenced in endpoint list exist // just returns 1 single agent config that includes all of the packageConfig IDs provided [INGEST_API_AGENT_CONFIGS]: (): GetAgentConfigsResponse => { const agentConfig = generator.generateAgentConfig(); @@ -137,9 +137,9 @@ const hostListApiPathHandlerMocks = ({ }, }; - // Build a GET route handler for each host details based on the list of Hosts passed on input - if (hostsResults) { - hostsResults.forEach((host) => { + // Build a GET route handler for each endpoint details based on the list of Endpoints passed on input + if (endpointsResults) { + endpointsResults.forEach((host) => { // @ts-expect-error apiHandlers[`/api/endpoint/metadata/${host.metadata.host.id}`] = () => host; }); @@ -149,33 +149,36 @@ const hostListApiPathHandlerMocks = ({ }; /** - * Sets up mock impelementations in support of the Hosts list view + * Sets up mock impelementations in support of the Endpoints list view * * @param mockedHttpService - * @param hostsResults + * @param endpointsResults * @param pathHandlersOptions */ -export const setHostListApiMockImplementation: ( +export const setEndpointListApiMockImplementation: ( mockedHttpService: jest.Mocked, - apiResponses?: Parameters[0] + apiResponses?: Parameters[0] ) => void = ( mockedHttpService, - { hostsResults = mockHostResultList({ total: 3 }).hosts, ...pathHandlersOptions } = {} + { endpointsResults = mockEndpointResultList({ total: 3 }).hosts, ...pathHandlersOptions } = {} ) => { - const apiHandlers = hostListApiPathHandlerMocks({ ...pathHandlersOptions, hostsResults }); + const apiHandlers = endpointListApiPathHandlerMocks({ + ...pathHandlersOptions, + endpointsResults, + }); mockedHttpService.post .mockImplementation(async (...args) => { throw new Error(`un-expected call to http.post: ${args}`); }) - // First time called, return list of hosts + // First time called, return list of endpoints .mockImplementationOnce(async () => { return apiHandlers['/api/endpoint/metadata'](); }); - // If the hosts list results is zero, then mock the second call to `/metadata` to return - // empty list - indicating there are no hosts currently present on the system - if (!hostsResults.length) { + // If the endpoints list results is zero, then mock the second call to `/metadata` to return + // empty list - indicating there are no endpoints currently present on the system + if (!endpointsResults.length) { mockedHttpService.post.mockImplementationOnce(async () => { return apiHandlers['/api/endpoint/metadata'](); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts index e54f7df4d4f75..d4fe3310eac0a 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/reducer.ts @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { isOnHostPage, hasSelectedHost } from './selectors'; -import { HostState } from '../types'; +import { isOnEndpointPage, hasSelectedEndpoint } from './selectors'; +import { EndpointState } from '../types'; import { AppAction } from '../../../../common/store/actions'; import { ImmutableReducer } from '../../../../common/store'; import { Immutable } from '../../../../../common/endpoint/types'; -export const initialHostListState: Immutable = { +export const initialEndpointListState: Immutable = { hosts: [], pageSize: 10, pageIndex: 0, @@ -29,15 +29,15 @@ export const initialHostListState: Immutable = { policyItemsLoading: false, endpointPackageInfo: undefined, nonExistingPolicies: {}, - hostsExist: true, + endpointsExist: true, }; /* eslint-disable-next-line complexity */ -export const hostListReducer: ImmutableReducer = ( - state = initialHostListState, +export const endpointListReducer: ImmutableReducer = ( + state = initialEndpointListState, action ) => { - if (action.type === 'serverReturnedHostList') { + if (action.type === 'serverReturnedEndpointList') { const { hosts, total, @@ -53,13 +53,13 @@ export const hostListReducer: ImmutableReducer = ( loading: false, error: undefined, }; - } else if (action.type === 'serverFailedToReturnHostList') { + } else if (action.type === 'serverFailedToReturnEndpointList') { return { ...state, error: action.payload, loading: false, }; - } else if (action.type === 'serverReturnedHostNonExistingPolicies') { + } else if (action.type === 'serverReturnedEndpointNonExistingPolicies') { return { ...state, nonExistingPolicies: { @@ -67,14 +67,14 @@ export const hostListReducer: ImmutableReducer = ( ...action.payload, }, }; - } else if (action.type === 'serverReturnedHostDetails') { + } else if (action.type === 'serverReturnedEndpointDetails') { return { ...state, details: action.payload.metadata, detailsLoading: false, detailsError: undefined, }; - } else if (action.type === 'serverFailedToReturnHostDetails') { + } else if (action.type === 'serverFailedToReturnEndpointDetails') { return { ...state, detailsError: action.payload, @@ -92,14 +92,14 @@ export const hostListReducer: ImmutableReducer = ( error: action.payload, policyItemsLoading: false, }; - } else if (action.type === 'serverReturnedHostPolicyResponse') { + } else if (action.type === 'serverReturnedEndpointPolicyResponse') { return { ...state, policyResponse: action.payload.policy_response, policyResponseLoading: false, policyResponseError: undefined, }; - } else if (action.type === 'serverFailedToReturnHostPolicyResponse') { + } else if (action.type === 'serverFailedToReturnEndpointPolicyResponse') { return { ...state, policyResponseError: action.payload, @@ -111,7 +111,7 @@ export const hostListReducer: ImmutableReducer = ( selectedPolicyId: action.payload.selectedPolicyId, policyResponseLoading: false, }; - } else if (action.type === 'serverCancelledHostListLoading') { + } else if (action.type === 'serverCancelledEndpointListLoading') { return { ...state, loading: false, @@ -126,22 +126,22 @@ export const hostListReducer: ImmutableReducer = ( ...state, endpointPackageInfo: action.payload, }; - } else if (action.type === 'serverReturnedHostExistValue') { + } else if (action.type === 'serverReturnedEndpointExistValue') { return { ...state, - hostsExist: action.payload, + endpointsExist: action.payload, }; } else if (action.type === 'userChangedUrl') { - const newState: Immutable = { + const newState: Immutable = { ...state, location: action.payload, }; - const isCurrentlyOnListPage = isOnHostPage(newState) && !hasSelectedHost(newState); - const wasPreviouslyOnListPage = isOnHostPage(state) && !hasSelectedHost(state); - const isCurrentlyOnDetailsPage = isOnHostPage(newState) && hasSelectedHost(newState); - const wasPreviouslyOnDetailsPage = isOnHostPage(state) && hasSelectedHost(state); + const isCurrentlyOnListPage = isOnEndpointPage(newState) && !hasSelectedEndpoint(newState); + const wasPreviouslyOnListPage = isOnEndpointPage(state) && !hasSelectedEndpoint(state); + const isCurrentlyOnDetailsPage = isOnEndpointPage(newState) && hasSelectedEndpoint(newState); + const wasPreviouslyOnDetailsPage = isOnEndpointPage(state) && hasSelectedEndpoint(state); - // if on the host list page for the first time, return new location and load list + // if on the endpoint list page for the first time, return new location and load list if (isCurrentlyOnListPage) { if (!wasPreviouslyOnListPage) { return { @@ -154,7 +154,7 @@ export const hostListReducer: ImmutableReducer = ( }; } } else if (isCurrentlyOnDetailsPage) { - // if previous page was the list or another host details page, load host details only + // if previous page was the list or another endpoint details page, load endpoint details only if (wasPreviouslyOnDetailsPage || wasPreviouslyOnListPage) { return { ...state, @@ -166,7 +166,7 @@ export const hostListReducer: ImmutableReducer = ( policyResponseError: undefined, }; } else { - // if previous page was not host list or host details, load both list and details + // if previous page was not endpoint list or endpoint details, load both list and details return { ...state, location: action.payload, @@ -180,14 +180,14 @@ export const hostListReducer: ImmutableReducer = ( }; } } - // otherwise we are not on a host list or details page + // otherwise we are not on a endpoint list or details page return { ...state, location: action.payload, error: undefined, detailsError: undefined, policyResponseError: undefined, - hostsExist: true, + endpointsExist: true, }; } return state; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts index ca006f21c29ac..2c6fc6d5a75e1 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/selectors.ts @@ -14,36 +14,36 @@ import { HostPolicyResponseConfiguration, HostPolicyResponseActionStatus, } from '../../../../../common/endpoint/types'; -import { HostState, HostIndexUIQueryParams } from '../types'; -import { MANAGEMENT_ROUTING_HOSTS_PATH } from '../../../common/constants'; +import { EndpointState, EndpointIndexUIQueryParams } from '../types'; +import { MANAGEMENT_ROUTING_ENDPOINTS_PATH } from '../../../common/constants'; const PAGE_SIZES = Object.freeze([10, 20, 50]); -export const listData = (state: Immutable) => state.hosts; +export const listData = (state: Immutable) => state.hosts; -export const pageIndex = (state: Immutable): number => state.pageIndex; +export const pageIndex = (state: Immutable): number => state.pageIndex; -export const pageSize = (state: Immutable): number => state.pageSize; +export const pageSize = (state: Immutable): number => state.pageSize; -export const totalHits = (state: Immutable): number => state.total; +export const totalHits = (state: Immutable): number => state.total; -export const listLoading = (state: Immutable): boolean => state.loading; +export const listLoading = (state: Immutable): boolean => state.loading; -export const listError = (state: Immutable) => state.error; +export const listError = (state: Immutable) => state.error; -export const detailsData = (state: Immutable) => state.details; +export const detailsData = (state: Immutable) => state.details; -export const detailsLoading = (state: Immutable): boolean => state.detailsLoading; +export const detailsLoading = (state: Immutable): boolean => state.detailsLoading; -export const detailsError = (state: Immutable) => state.detailsError; +export const detailsError = (state: Immutable) => state.detailsError; -export const policyItems = (state: Immutable) => state.policyItems; +export const policyItems = (state: Immutable) => state.policyItems; -export const policyItemsLoading = (state: Immutable) => state.policyItemsLoading; +export const policyItemsLoading = (state: Immutable) => state.policyItemsLoading; -export const selectedPolicyId = (state: Immutable) => state.selectedPolicyId; +export const selectedPolicyId = (state: Immutable) => state.selectedPolicyId; -export const endpointPackageInfo = (state: Immutable) => state.endpointPackageInfo; +export const endpointPackageInfo = (state: Immutable) => state.endpointPackageInfo; export const endpointPackageVersion = createSelector( endpointPackageInfo, @@ -53,14 +53,14 @@ export const endpointPackageVersion = createSelector( /** * Returns the full policy response from the endpoint after a user modifies a policy. */ -const detailsPolicyAppliedResponse = (state: Immutable) => +const detailsPolicyAppliedResponse = (state: Immutable) => state.policyResponse && state.policyResponse.Endpoint.policy.applied; /** * Returns the response configurations from the endpoint after a user modifies a policy. */ export const policyResponseConfigurations: ( - state: Immutable + state: Immutable ) => undefined | Immutable = createSelector( detailsPolicyAppliedResponse, (applied) => { @@ -72,7 +72,7 @@ export const policyResponseConfigurations: ( * Returns a map of the number of failed and warning policy response actions per configuration. */ export const policyResponseFailedOrWarningActionCount: ( - state: Immutable + state: Immutable ) => Map = createSelector(detailsPolicyAppliedResponse, (applied) => { const failureOrWarningByConfigType = new Map(); if (applied?.response?.configurations !== undefined && applied?.actions !== undefined) { @@ -98,7 +98,7 @@ export const policyResponseFailedOrWarningActionCount: ( * Returns the actions taken by the endpoint for each response configuration after a user modifies a policy. */ export const policyResponseActions: ( - state: Immutable + state: Immutable ) => undefined | Immutable = createSelector( detailsPolicyAppliedResponse, (applied) => { @@ -106,32 +106,32 @@ export const policyResponseActions: ( } ); -export const policyResponseLoading = (state: Immutable): boolean => +export const policyResponseLoading = (state: Immutable): boolean => state.policyResponseLoading; -export const policyResponseError = (state: Immutable) => state.policyResponseError; +export const policyResponseError = (state: Immutable) => state.policyResponseError; -export const isOnHostPage = (state: Immutable) => { +export const isOnEndpointPage = (state: Immutable) => { return ( matchPath(state.location?.pathname ?? '', { - path: MANAGEMENT_ROUTING_HOSTS_PATH, + path: MANAGEMENT_ROUTING_ENDPOINTS_PATH, exact: true, }) !== null ); }; export const uiQueryParams: ( - state: Immutable -) => Immutable = createSelector( - (state: Immutable) => state.location, - (location: Immutable['location']) => { - const data: HostIndexUIQueryParams = { page_index: '0', page_size: '10' }; + state: Immutable +) => Immutable = createSelector( + (state: Immutable) => state.location, + (location: Immutable['location']) => { + const data: EndpointIndexUIQueryParams = { page_index: '0', page_size: '10' }; if (location) { // Removes the `?` from the beginning of query string if it exists const query = querystring.parse(location.search.slice(1)); - const keys: Array = [ - 'selected_host', + const keys: Array = [ + 'selected_endpoint', 'page_size', 'page_index', 'show', @@ -171,15 +171,15 @@ export const uiQueryParams: ( } ); -export const hasSelectedHost: (state: Immutable) => boolean = createSelector( +export const hasSelectedEndpoint: (state: Immutable) => boolean = createSelector( uiQueryParams, - ({ selected_host: selectedHost }) => { - return selectedHost !== undefined; + ({ selected_endpoint: selectedEndpoint }) => { + return selectedEndpoint !== undefined; } ); /** What policy details panel view to show */ -export const showView: (state: HostState) => 'policy_response' | 'details' = createSelector( +export const showView: (state: EndpointState) => 'policy_response' | 'details' = createSelector( uiQueryParams, (searchParams) => { return searchParams.show === 'policy_response' ? 'policy_response' : 'details'; @@ -189,7 +189,7 @@ export const showView: (state: HostState) => 'policy_response' | 'details' = cre /** * Returns the Policy Response overall status */ -export const policyResponseStatus: (state: Immutable) => string = createSelector( +export const policyResponseStatus: (state: Immutable) => string = createSelector( (state) => state.policyResponse, (policyResponse) => { return (policyResponse && policyResponse?.Endpoint?.policy?.applied?.status) || ''; @@ -197,15 +197,16 @@ export const policyResponseStatus: (state: Immutable) => string = cre ); /** - * returns the list of known non-existing polices that may have been in the Host API response. + * returns the list of known non-existing polices that may have been in the Endpoint API response. * @param state */ export const nonExistingPolicies: ( - state: Immutable -) => Immutable = (state) => state.nonExistingPolicies; + state: Immutable +) => Immutable = (state) => state.nonExistingPolicies; /** - * Return boolean that indicates whether hosts exist + * Return boolean that indicates whether endpoints exist * @param state */ -export const hostsExist: (state: Immutable) => boolean = (state) => state.hostsExist; +export const endpointsExist: (state: Immutable) => boolean = (state) => + state.endpointsExist; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts index 6c949e9700b9a..7e75285560bd3 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/types.ts @@ -15,7 +15,7 @@ import { import { ServerApiError } from '../../../common/types'; import { GetPackagesResponse } from '../../../../../ingest_manager/common'; -export interface HostState { +export interface EndpointState { /** list of host **/ hosts: HostInfo[]; /** number of items per page */ @@ -53,15 +53,15 @@ export interface HostState { /** tracks the list of policies IDs used in Host metadata that may no longer exist */ nonExistingPolicies: Record; /** Tracks whether hosts exist and helps control if onboarding should be visible */ - hostsExist: boolean; + endpointsExist: boolean; } /** * Query params on the host page parsed from the URL */ -export interface HostIndexUIQueryParams { - /** Selected host id shows host details flyout */ - selected_host?: string; +export interface EndpointIndexUIQueryParams { + /** Selected endpoint id shows host details flyout */ + selected_endpoint?: string; /** How many items to show in list */ page_size?: string; /** Which page to show */ diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/host_policy_link.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/endpoint_policy_link.tsx similarity index 89% rename from x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/host_policy_link.tsx rename to x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/endpoint_policy_link.tsx index ec4d7e87b721d..2b6132aca4108 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/host_policy_link.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/endpoint_policy_link.tsx @@ -6,7 +6,7 @@ import React, { memo, useMemo } from 'react'; import { EuiLink, EuiLinkAnchorProps } from '@elastic/eui'; -import { useHostSelector } from '../hooks'; +import { useEndpointSelector } from '../hooks'; import { nonExistingPolicies } from '../../store/selectors'; import { getPolicyDetailPath } from '../../../../common/routing'; import { useFormatUrl } from '../../../../../common/components/link_to'; @@ -18,12 +18,12 @@ import { useNavigateByRouterEventHandler } from '../../../../../common/hooks/end * the `nonExistingPolicies` value in the store. If it does not exist, then regular * text is returned. */ -export const HostPolicyLink = memo< +export const EndpointPolicyLink = memo< Omit & { policyId: string; } >(({ policyId, children, onClick, ...otherProps }) => { - const missingPolicies = useHostSelector(nonExistingPolicies); + const missingPolicies = useEndpointSelector(nonExistingPolicies); const { formatUrl } = useFormatUrl(SecurityPageName.administration); const { toRoutePath, toRouteUrl } = useMemo(() => { const toPath = getPolicyDetailPath(policyId); @@ -50,4 +50,4 @@ export const HostPolicyLink = memo< ); }); -HostPolicyLink.displayName = 'HostPolicyLink'; +EndpointPolicyLink.displayName = 'EndpointPolicyLink'; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx similarity index 76% rename from x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx rename to x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx index 6a0a0cbb1014e..bd499ee6abb24 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx @@ -19,18 +19,18 @@ import React, { memo, useMemo } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { HostMetadata } from '../../../../../../common/endpoint/types'; -import { useHostSelector, useAgentDetailsIngestUrl } from '../hooks'; +import { useEndpointSelector, useAgentDetailsIngestUrl } from '../hooks'; import { useNavigateToAppEventHandler } from '../../../../../common/hooks/endpoint/use_navigate_to_app_event_handler'; import { policyResponseStatus, uiQueryParams } from '../../store/selectors'; import { POLICY_STATUS_TO_HEALTH_COLOR } from '../host_constants'; import { FormattedDateAndTime } from '../../../../../common/components/endpoint/formatted_date_time'; import { useNavigateByRouterEventHandler } from '../../../../../common/hooks/endpoint/use_navigate_by_router_event_handler'; import { LinkToApp } from '../../../../../common/components/endpoint/link_to_app'; -import { getHostDetailsPath } from '../../../../common/routing'; +import { getEndpointDetailsPath } from '../../../../common/routing'; import { SecurityPageName } from '../../../../../app/types'; import { useFormatUrl } from '../../../../../common/components/link_to'; import { AgentDetailsReassignConfigAction } from '../../../../../../../ingest_manager/public'; -import { HostPolicyLink } from '../components/host_policy_link'; +import { EndpointPolicyLink } from '../components/endpoint_policy_link'; const HostIds = styled(EuiListGroupItem)` margin-top: 0; @@ -51,15 +51,15 @@ const LinkToExternalApp = styled.div` const openReassignFlyoutSearch = '?openReassignFlyout=true'; -export const HostDetails = memo(({ details }: { details: HostMetadata }) => { +export const EndpointDetails = memo(({ details }: { details: HostMetadata }) => { const agentId = details.elastic.agent.id; const { url: agentDetailsUrl, appId: ingestAppId, appPath: agentDetailsAppPath, } = useAgentDetailsIngestUrl(agentId); - const queryParams = useHostSelector(uiQueryParams); - const policyStatus = useHostSelector( + const queryParams = useEndpointSelector(uiQueryParams); + const policyStatus = useEndpointSelector( policyResponseStatus ) as keyof typeof POLICY_STATUS_TO_HEALTH_COLOR; const { formatUrl } = useFormatUrl(SecurityPageName.administration); @@ -67,13 +67,13 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { const detailsResultsUpper = useMemo(() => { return [ { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.os', { + title: i18n.translate('xpack.securitySolution.endpoint.details.os', { defaultMessage: 'OS', }), description: details.host.os.full, }, { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.lastSeen', { + title: i18n.translate('xpack.securitySolution.endpoint.details.lastSeen', { defaultMessage: 'Last Seen', }), description: , @@ -83,19 +83,19 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { const [policyResponseUri, policyResponseRoutePath] = useMemo(() => { // eslint-disable-next-line @typescript-eslint/naming-convention - const { selected_host, show, ...currentUrlParams } = queryParams; + const { selected_endpoint, show, ...currentUrlParams } = queryParams; return [ formatUrl( - getHostDetailsPath({ - name: 'hostPolicyResponse', + getEndpointDetailsPath({ + name: 'endpointPolicyResponse', ...currentUrlParams, - selected_host: details.host.id, + selected_endpoint: details.host.id, }) ), - getHostDetailsPath({ - name: 'hostPolicyResponse', + getEndpointDetailsPath({ + name: 'endpointPolicyResponse', ...currentUrlParams, - selected_host: details.host.id, + selected_endpoint: details.host.id, }), ]; }, [details.host.id, formatUrl, queryParams]); @@ -110,7 +110,10 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { onDoneNavigateTo: [ 'securitySolution:administration', { - path: getHostDetailsPath({ name: 'hostDetails', selected_host: details.host.id }), + path: getEndpointDetailsPath({ + name: 'endpointDetails', + selected_endpoint: details.host.id, + }), }, ], }, @@ -121,22 +124,22 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { const detailsResultsPolicy = useMemo(() => { return [ { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.policy', { + title: i18n.translate('xpack.securitySolution.endpoint.details.policy', { defaultMessage: 'Integration', }), description: ( <> - {details.Endpoint.policy.applied.name} - + ), }, { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.policyStatus', { + title: i18n.translate('xpack.securitySolution.endpoint.details.policyStatus', { defaultMessage: 'Configuration response', }), description: ( @@ -152,7 +155,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { > @@ -166,7 +169,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { const detailsResultsLower = useMemo(() => { return [ { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.ipAddress', { + title: i18n.translate('xpack.securitySolution.endpoint.details.ipAddress', { defaultMessage: 'IP Address', }), description: ( @@ -178,13 +181,13 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { ), }, { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.hostname', { + title: i18n.translate('xpack.securitySolution.endpoint.details.hostname', { defaultMessage: 'Hostname', }), description: details.host.hostname, }, { - title: i18n.translate('xpack.securitySolution.endpoint.host.details.endpointVersion', { + title: i18n.translate('xpack.securitySolution.endpoint.details.endpointVersion', { defaultMessage: 'Endpoint Version', }), description: details.agent.version, @@ -197,13 +200,13 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { { appPath={agentDetailsWithFlyoutPath} href={agentDetailsWithFlyoutUrl} onClick={handleReassignEndpointsClick} - data-test-subj="hostDetailsLinkToIngest" + data-test-subj="endpointDetailsLinkToIngest" > @@ -225,10 +228,10 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { ); }); -HostDetails.displayName = 'HostDetails'; +EndpointDetails.displayName = 'EndpointDetails'; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx index 69dabeeb616a0..40227ec24a9e4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx @@ -19,7 +19,7 @@ import { useHistory } from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { useToasts } from '../../../../../common/lib/kibana'; -import { useHostSelector } from '../hooks'; +import { useEndpointSelector } from '../hooks'; import { urlFromQueryParams } from '../url_from_query_params'; import { uiQueryParams, @@ -33,36 +33,39 @@ import { policyResponseError, policyResponseLoading, } from '../../store/selectors'; -import { HostDetails } from './host_details'; +import { EndpointDetails } from './endpoint_details'; import { PolicyResponse } from './policy_response'; import { HostMetadata } from '../../../../../../common/endpoint/types'; import { FlyoutSubHeader, FlyoutSubHeaderProps } from './components/flyout_sub_header'; import { useNavigateByRouterEventHandler } from '../../../../../common/hooks/endpoint/use_navigate_by_router_event_handler'; -import { getHostListPath } from '../../../../common/routing'; +import { getEndpointListPath } from '../../../../common/routing'; import { SecurityPageName } from '../../../../../app/types'; import { useFormatUrl } from '../../../../../common/components/link_to'; -export const HostDetailsFlyout = memo(() => { +export const EndpointDetailsFlyout = memo(() => { const history = useHistory(); const toasts = useToasts(); - const queryParams = useHostSelector(uiQueryParams); - const { selected_host: selectedHost, ...queryParamsWithoutSelectedHost } = queryParams; - const details = useHostSelector(detailsData); - const loading = useHostSelector(detailsLoading); - const error = useHostSelector(detailsError); - const show = useHostSelector(showView); + const queryParams = useEndpointSelector(uiQueryParams); + const { + selected_endpoint: selectedEndpoint, + ...queryParamsWithoutSelectedEndpoint + } = queryParams; + const details = useEndpointSelector(detailsData); + const loading = useEndpointSelector(detailsLoading); + const error = useEndpointSelector(detailsError); + const show = useEndpointSelector(showView); const handleFlyoutClose = useCallback(() => { - history.push(urlFromQueryParams(queryParamsWithoutSelectedHost)); - }, [history, queryParamsWithoutSelectedHost]); + history.push(urlFromQueryParams(queryParamsWithoutSelectedEndpoint)); + }, [history, queryParamsWithoutSelectedEndpoint]); useEffect(() => { if (error !== undefined) { toasts.addDanger({ - title: i18n.translate('xpack.securitySolution.endpoint.host.details.errorTitle', { + title: i18n.translate('xpack.securitySolution.endpoint.details.errorTitle', { defaultMessage: 'Could not find host', }), - text: i18n.translate('xpack.securitySolution.endpoint.host.details.errorBody', { + text: i18n.translate('xpack.securitySolution.endpoint.details.errorBody', { defaultMessage: 'Please exit the flyout and select an available host.', }), }); @@ -73,12 +76,12 @@ export const HostDetailsFlyout = memo(() => { -

+

{loading ? : details?.host?.hostname}

@@ -93,8 +96,8 @@ export const HostDetailsFlyout = memo(() => { <> {show === 'details' && ( <> - - + + )} @@ -105,31 +108,31 @@ export const HostDetailsFlyout = memo(() => { ); }); -HostDetailsFlyout.displayName = 'HostDetailsFlyout'; +EndpointDetailsFlyout.displayName = 'EndpointDetailsFlyout'; const PolicyResponseFlyoutPanel = memo<{ hostMeta: HostMetadata; }>(({ hostMeta }) => { - const { show, ...queryParams } = useHostSelector(uiQueryParams); - const responseConfig = useHostSelector(policyResponseConfigurations); - const responseActions = useHostSelector(policyResponseActions); - const responseAttentionCount = useHostSelector(policyResponseFailedOrWarningActionCount); - const loading = useHostSelector(policyResponseLoading); - const error = useHostSelector(policyResponseError); + const { show, ...queryParams } = useEndpointSelector(uiQueryParams); + const responseConfig = useEndpointSelector(policyResponseConfigurations); + const responseActions = useEndpointSelector(policyResponseActions); + const responseAttentionCount = useEndpointSelector(policyResponseFailedOrWarningActionCount); + const loading = useEndpointSelector(policyResponseLoading); + const error = useEndpointSelector(policyResponseError); const { formatUrl } = useFormatUrl(SecurityPageName.administration); const [detailsUri, detailsRoutePath] = useMemo( () => [ formatUrl( - getHostListPath({ - name: 'hostList', + getEndpointListPath({ + name: 'endpointList', ...queryParams, - selected_host: hostMeta.host.id, + selected_endpoint: hostMeta.host.id, }) ), - getHostListPath({ - name: 'hostList', + getEndpointListPath({ + name: 'endpointList', ...queryParams, - selected_host: hostMeta.host.id, + selected_endpoint: hostMeta.host.id, }), ], [hostMeta.host.id, formatUrl, queryParams] @@ -137,7 +140,7 @@ const PolicyResponseFlyoutPanel = memo<{ const backToDetailsClickHandler = useNavigateByRouterEventHandler(detailsRoutePath); const backButtonProp = useMemo((): FlyoutSubHeaderProps['backButton'] => { return { - title: i18n.translate('xpack.securitySolution.endpoint.host.policyResponse.backLinkTitle', { + title: i18n.translate('xpack.securitySolution.endpoint.policyResponse.backLinkTitle', { defaultMessage: 'Endpoint Details', }), href: detailsUri, @@ -149,13 +152,13 @@ const PolicyResponseFlyoutPanel = memo<{ <> - - + +

@@ -164,7 +167,7 @@ const PolicyResponseFlyoutPanel = memo<{ } diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx index 3a1dd180405e0..231e301a93aab 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx @@ -90,7 +90,7 @@ const ResponseActions = memo(

{formatResponse(key)}

@@ -162,7 +162,7 @@ export const PolicyResponse = memo( attentionCount > 0 && ( {attentionCount} diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response_friendly_names.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response_friendly_names.ts index 020e8c9e38ad5..07ab38fd52776 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response_friendly_names.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response_friendly_names.ts @@ -9,198 +9,189 @@ import { i18n } from '@kbn/i18n'; const policyResponses: Array<[string, string]> = [ [ 'configure_dns_events', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_dns_events', - { defaultMessage: 'Configure DNS Events' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.configure_dns_events', { + defaultMessage: 'Configure DNS Events', + }), ], [ 'configure_elasticsearch_connection', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_elasticsearch_connection', + 'xpack.securitySolution.endpoint.details.policyResponse.configure_elasticsearch_connection', { defaultMessage: 'Configure Elastic Search Connection' } ), ], [ 'configure_file_events', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_file_events', - { defaultMessage: 'Configure File Events' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.configure_file_events', { + defaultMessage: 'Configure File Events', + }), ], [ 'configure_imageload_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_imageload_events', + 'xpack.securitySolution.endpoint.details.policyResponse.configure_imageload_events', { defaultMessage: 'Configure Image Load Events' } ), ], [ 'configure_kernel', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_kernel', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.configure_kernel', { defaultMessage: 'Configure Kernel', }), ], [ 'configure_logging', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_logging', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.configure_logging', { defaultMessage: 'Configure Logging', }), ], [ 'configure_malware', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_malware', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.configure_malware', { defaultMessage: 'Configure Malware', }), ], [ 'configure_network_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_network_events', + 'xpack.securitySolution.endpoint.details.policyResponse.configure_network_events', { defaultMessage: 'Configure Network Events' } ), ], [ 'configure_process_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_process_events', + 'xpack.securitySolution.endpoint.details.policyResponse.configure_process_events', { defaultMessage: 'Configure Process Events' } ), ], [ 'configure_registry_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_registry_events', + 'xpack.securitySolution.endpoint.details.policyResponse.configure_registry_events', { defaultMessage: 'Configure Registry Events' } ), ], [ 'configure_security_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_security_events', + 'xpack.securitySolution.endpoint.details.policyResponse.configure_security_events', { defaultMessage: 'Configure Security Events' } ), ], [ 'connect_kernel', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.connect_kernel', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.connect_kernel', { defaultMessage: 'Connect Kernel', }), ], [ 'detect_async_image_load_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_async_image_load_events', + 'xpack.securitySolution.endpoint.details.policyResponse.detect_async_image_load_events', { defaultMessage: 'Detect Async Image Load Events' } ), ], [ 'detect_file_open_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_file_open_events', + 'xpack.securitySolution.endpoint.details.policyResponse.detect_file_open_events', { defaultMessage: 'Detect File Open Events' } ), ], [ 'detect_file_write_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_file_write_events', + 'xpack.securitySolution.endpoint.details.policyResponse.detect_file_write_events', { defaultMessage: 'Detect File Write Events' } ), ], [ 'detect_network_events', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_network_events', - { defaultMessage: 'Detect Network Events' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.detect_network_events', { + defaultMessage: 'Detect Network Events', + }), ], [ 'detect_process_events', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_process_events', - { defaultMessage: 'Detect Process Events' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.detect_process_events', { + defaultMessage: 'Detect Process Events', + }), ], [ 'detect_registry_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_registry_events', + 'xpack.securitySolution.endpoint.details.policyResponse.detect_registry_events', { defaultMessage: 'Detect Registry Events' } ), ], [ 'detect_sync_image_load_events', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_sync_image_load_events', + 'xpack.securitySolution.endpoint.details.policyResponse.detect_sync_image_load_events', { defaultMessage: 'Detect Sync Image Load Events' } ), ], [ 'download_global_artifacts', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.download_global_artifacts', + 'xpack.securitySolution.endpoint.details.policyResponse.download_global_artifacts', { defaultMessage: 'Download Global Artifacts' } ), ], [ 'download_user_artifacts', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.download_user_artifacts', + 'xpack.securitySolution.endpoint.details.policyResponse.download_user_artifacts', { defaultMessage: 'Download User Artifacts' } ), ], [ 'load_config', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.load_config', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.load_config', { defaultMessage: 'Load Config', }), ], [ 'load_malware_model', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.load_malware_model', - { defaultMessage: 'Load Malware Model' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.load_malware_model', { + defaultMessage: 'Load Malware Model', + }), ], [ 'read_elasticsearch_config', i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.read_elasticsearch_config', + 'xpack.securitySolution.endpoint.details.policyResponse.read_elasticsearch_config', { defaultMessage: 'Read ElasticSearch Config' } ), ], [ 'read_events_config', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.read_events_config', - { defaultMessage: 'Read Events Config' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.read_events_config', { + defaultMessage: 'Read Events Config', + }), ], [ 'read_kernel_config', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.read_kernel_config', - { defaultMessage: 'Read Kernel Config' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.read_kernel_config', { + defaultMessage: 'Read Kernel Config', + }), ], [ 'read_logging_config', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.read_logging_config', - { defaultMessage: 'Read Logging Config' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.read_logging_config', { + defaultMessage: 'Read Logging Config', + }), ], [ 'read_malware_config', - i18n.translate( - 'xpack.securitySolution.endpoint.hostDetails.policyResponse.read_malware_config', - { defaultMessage: 'Read Malware Config' } - ), + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.read_malware_config', { + defaultMessage: 'Read Malware Config', + }), ], [ 'workflow', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.workflow', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.workflow', { defaultMessage: 'Workflow', }), ], @@ -211,43 +202,43 @@ const responseMap = new Map(policyResponses); // Additional values used in the Policy Response UI responseMap.set( 'success', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.success', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.success', { defaultMessage: 'Success', }) ); responseMap.set( 'warning', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.warning', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.warning', { defaultMessage: 'Warning', }) ); responseMap.set( 'failure', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.failed', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.failed', { defaultMessage: 'Failed', }) ); responseMap.set( 'logging', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.logging', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.logging', { defaultMessage: 'Logging', }) ); responseMap.set( 'streaming', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.streaming', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.streaming', { defaultMessage: 'Streaming', }) ); responseMap.set( 'malware', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.malware', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.malware', { defaultMessage: 'Malware', }) ); responseMap.set( 'events', - i18n.translate('xpack.securitySolution.endpoint.hostDetails.policyResponse.events', { + i18n.translate('xpack.securitySolution.endpoint.details.policyResponse.events', { defaultMessage: 'Events', }) ); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks.ts index d11335df875e9..a9c84678c88a9 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/hooks.ts @@ -7,16 +7,18 @@ import { useSelector } from 'react-redux'; import { useMemo } from 'react'; import { useKibana } from '../../../../common/lib/kibana'; -import { HostState } from '../types'; +import { EndpointState } from '../types'; import { - MANAGEMENT_STORE_HOSTS_NAMESPACE, + MANAGEMENT_STORE_ENDPOINTS_NAMESPACE, MANAGEMENT_STORE_GLOBAL_NAMESPACE, } from '../../../common/constants'; import { State } from '../../../../common/store'; -export function useHostSelector(selector: (state: HostState) => TSelected) { +export function useEndpointSelector(selector: (state: EndpointState) => TSelected) { return useSelector(function (state: State) { return selector( - state[MANAGEMENT_STORE_GLOBAL_NAMESPACE][MANAGEMENT_STORE_HOSTS_NAMESPACE] as HostState + state[MANAGEMENT_STORE_GLOBAL_NAMESPACE][ + MANAGEMENT_STORE_ENDPOINTS_NAMESPACE + ] as EndpointState ); }); } diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx index bb6003f73714d..09df6d6ece042 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx @@ -7,12 +7,12 @@ import React from 'react'; import * as reactTestingLibrary from '@testing-library/react'; -import { HostList } from './index'; +import { EndpointList } from './index'; import { - mockHostDetailsApiResult, - mockHostResultList, - setHostListApiMockImplementation, -} from '../store/mock_host_result_list'; + mockEndpointDetailsApiResult, + mockEndpointResultList, + setEndpointListApiMockImplementation, +} from '../store/mock_endpoint_result_list'; import { AppContextTestRender, createAppRootMockRenderer } from '../../../../common/mock/endpoint'; import { HostInfo, @@ -27,7 +27,7 @@ import { mockPolicyResultList } from '../../policy/store/policy_list/test_mock_u jest.mock('../../../../common/components/link_to'); -describe('when on the hosts page', () => { +describe('when on the list page', () => { const docGenerator = new EndpointDocGenerator(); let render: () => ReturnType; let history: AppContextTestRender['history']; @@ -38,9 +38,9 @@ describe('when on the hosts page', () => { beforeEach(() => { const mockedContext = createAppRootMockRenderer(); ({ history, store, coreStart, middlewareSpy } = mockedContext); - render = () => mockedContext.render(); + render = () => mockedContext.render(); reactTestingLibrary.act(() => { - history.push('/hosts'); + history.push('/endpoints'); }); }); @@ -50,10 +50,10 @@ describe('when on the hosts page', () => { expect(timelineFlyout).toBeNull(); }); - describe('when there are no hosts or polices', () => { + describe('when there are no endpoints or polices', () => { beforeEach(() => { - setHostListApiMockImplementation(coreStart.http, { - hostsResults: [], + setEndpointListApiMockImplementation(coreStart.http, { + endpointsResults: [], }); }); @@ -70,8 +70,8 @@ describe('when on the hosts page', () => { describe('when there are policies, but no hosts', () => { beforeEach(async () => { - setHostListApiMockImplementation(coreStart.http, { - hostsResults: [], + setEndpointListApiMockImplementation(coreStart.http, { + endpointsResults: [], endpointPackageConfigs: mockPolicyResultList({ total: 3 }).items, }); }); @@ -111,7 +111,7 @@ describe('when on the hosts page', () => { it('should not show the flyout', () => { const renderResult = render(); expect.assertions(1); - return renderResult.findByTestId('hostDetailsFlyout').catch((e) => { + return renderResult.findByTestId('endpointDetailsFlyout').catch((e) => { expect(e).not.toBeNull(); }); }); @@ -122,7 +122,7 @@ describe('when on the hosts page', () => { let firstPolicyID: string; beforeEach(() => { reactTestingLibrary.act(() => { - const hostListData = mockHostResultList({ total: 4 }).hosts; + const hostListData = mockEndpointResultList({ total: 4 }).hosts; firstPolicyID = hostListData[0].metadata.Endpoint.policy.applied.id; @@ -142,8 +142,8 @@ describe('when on the hosts page', () => { const ingestPackageConfigs = mockPolicyResultList({ total: 1 }).items; ingestPackageConfigs[0].id = firstPolicyID; - setHostListApiMockImplementation(coreStart.http, { - hostsResults: hostListData, + setEndpointListApiMockImplementation(coreStart.http, { + endpointsResults: hostListData, endpointPackageConfigs: ingestPackageConfigs, }); }); @@ -152,7 +152,7 @@ describe('when on the hosts page', () => { it('should display rows in the table', async () => { const renderResult = render(); await reactTestingLibrary.act(async () => { - await middlewareSpy.waitForAction('serverReturnedHostList'); + await middlewareSpy.waitForAction('serverReturnedEndpointList'); }); const rows = await renderResult.findAllByRole('row'); expect(rows).toHaveLength(5); @@ -160,15 +160,15 @@ describe('when on the hosts page', () => { it('should show total', async () => { const renderResult = render(); await reactTestingLibrary.act(async () => { - await middlewareSpy.waitForAction('serverReturnedHostList'); + await middlewareSpy.waitForAction('serverReturnedEndpointList'); }); - const total = await renderResult.findByTestId('hostListTableTotal'); + const total = await renderResult.findByTestId('endpointListTableTotal'); expect(total.textContent).toEqual('4 Hosts'); }); it('should display correct status', async () => { const renderResult = render(); await reactTestingLibrary.act(async () => { - await middlewareSpy.waitForAction('serverReturnedHostList'); + await middlewareSpy.waitForAction('serverReturnedEndpointList'); }); const hostStatuses = await renderResult.findAllByTestId('rowHostStatus'); @@ -194,7 +194,7 @@ describe('when on the hosts page', () => { it('should display correct policy status', async () => { const renderResult = render(); await reactTestingLibrary.act(async () => { - await middlewareSpy.waitForAction('serverReturnedHostList'); + await middlewareSpy.waitForAction('serverReturnedEndpointList'); }); const policyStatuses = await renderResult.findAllByTestId('rowPolicyStatus'); @@ -213,7 +213,7 @@ describe('when on the hosts page', () => { it('should display policy name as a link', async () => { const renderResult = render(); await reactTestingLibrary.act(async () => { - await middlewareSpy.waitForAction('serverReturnedHostList'); + await middlewareSpy.waitForAction('serverReturnedEndpointList'); }); const firstPolicyName = (await renderResult.findAllByTestId('policyNameCellLink'))[0]; expect(firstPolicyName).not.toBeNull(); @@ -225,7 +225,7 @@ describe('when on the hosts page', () => { beforeEach(async () => { renderResult = render(); await reactTestingLibrary.act(async () => { - await middlewareSpy.waitForAction('serverReturnedHostList'); + await middlewareSpy.waitForAction('serverReturnedEndpointList'); }); const hostNameLinks = await renderResult.findAllByTestId('hostnameCellLink'); if (hostNameLinks.length) { @@ -234,7 +234,7 @@ describe('when on the hosts page', () => { }); it('should show the flyout', () => { - return renderResult.findByTestId('hostDetailsFlyout').then((flyout) => { + return renderResult.findByTestId('endpointDetailsFlyout').then((flyout) => { expect(flyout).not.toBeNull(); }); }); @@ -298,12 +298,12 @@ describe('when on the hosts page', () => { return policyResponse; }; - const dispatchServerReturnedHostPolicyResponse = ( + const dispatchServerReturnedEndpointPolicyResponse = ( overallStatus: HostPolicyResponseActionStatus = HostPolicyResponseActionStatus.success ) => { reactTestingLibrary.act(() => { store.dispatch({ - type: 'serverReturnedHostPolicyResponse', + type: 'serverReturnedEndpointPolicyResponse', payload: { policy_response: createPolicyResponse(overallStatus), }, @@ -316,7 +316,7 @@ describe('when on the hosts page', () => { // eslint-disable-next-line @typescript-eslint/naming-convention host_status, metadata: { host, ...details }, - } = mockHostDetailsApiResult(); + } = mockEndpointDetailsApiResult(); hostDetails = { host_status, @@ -334,18 +334,18 @@ describe('when on the hosts page', () => { const policy = docGenerator.generatePolicyPackageConfig(); policy.id = hostDetails.metadata.Endpoint.policy.applied.id; - setHostListApiMockImplementation(coreStart.http, { - hostsResults: [hostDetails], + setEndpointListApiMockImplementation(coreStart.http, { + endpointsResults: [hostDetails], endpointPackageConfigs: [policy], }); reactTestingLibrary.act(() => { - history.push('/hosts?selected_host=1'); + history.push('/endpoints?selected_endpoint=1'); }); renderAndWaitForData = async () => { const renderResult = render(); - await middlewareSpy.waitForAction('serverReturnedHostDetails'); + await middlewareSpy.waitForAction('serverReturnedEndpointDetails'); return renderResult; }; }); @@ -355,7 +355,7 @@ describe('when on the hosts page', () => { it('should show the flyout', async () => { const renderResult = await renderAndWaitForData(); - return renderResult.findByTestId('hostDetailsFlyout').then((flyout) => { + return renderResult.findByTestId('endpointDetailsFlyout').then((flyout) => { expect(flyout).not.toBeNull(); }); }); @@ -387,7 +387,7 @@ describe('when on the hosts page', () => { const policyStatusLink = await renderResult.findByTestId('policyStatusValue'); expect(policyStatusLink).not.toBeNull(); expect(policyStatusLink.getAttribute('href')).toEqual( - '/hosts?page_index=0&page_size=10&selected_host=1&show=policy_response' + '/endpoints?page_index=0&page_size=10&selected_endpoint=1&show=policy_response' ); }); @@ -400,14 +400,14 @@ describe('when on the hosts page', () => { }); const changedUrlAction = await userChangedUrlChecker; expect(changedUrlAction.payload.search).toEqual( - '?page_index=0&page_size=10&selected_host=1&show=policy_response' + '?page_index=0&page_size=10&selected_endpoint=1&show=policy_response' ); }); it('should display Success overall policy status', async () => { const renderResult = await renderAndWaitForData(); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse(HostPolicyResponseActionStatus.success); + dispatchServerReturnedEndpointPolicyResponse(HostPolicyResponseActionStatus.success); }); const policyStatusLink = await renderResult.findByTestId('policyStatusValue'); expect(policyStatusLink.textContent).toEqual('Success'); @@ -421,7 +421,7 @@ describe('when on the hosts page', () => { it('should display Warning overall policy status', async () => { const renderResult = await renderAndWaitForData(); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse(HostPolicyResponseActionStatus.warning); + dispatchServerReturnedEndpointPolicyResponse(HostPolicyResponseActionStatus.warning); }); const policyStatusLink = await renderResult.findByTestId('policyStatusValue'); expect(policyStatusLink.textContent).toEqual('Warning'); @@ -435,7 +435,7 @@ describe('when on the hosts page', () => { it('should display Failed overall policy status', async () => { const renderResult = await renderAndWaitForData(); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse(HostPolicyResponseActionStatus.failure); + dispatchServerReturnedEndpointPolicyResponse(HostPolicyResponseActionStatus.failure); }); const policyStatusLink = await renderResult.findByTestId('policyStatusValue'); expect(policyStatusLink.textContent).toEqual('Failed'); @@ -449,7 +449,7 @@ describe('when on the hosts page', () => { it('should display Unknown overall policy status', async () => { const renderResult = await renderAndWaitForData(); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse('' as HostPolicyResponseActionStatus); + dispatchServerReturnedEndpointPolicyResponse('' as HostPolicyResponseActionStatus); }); const policyStatusLink = await renderResult.findByTestId('policyStatusValue'); expect(policyStatusLink.textContent).toEqual('Unknown'); @@ -463,7 +463,7 @@ describe('when on the hosts page', () => { it('should include the link to reassignment in Ingest', async () => { coreStart.application.getUrlForApp.mockReturnValue('/app/ingestManager'); const renderResult = await renderAndWaitForData(); - const linkToReassign = await renderResult.findByTestId('hostDetailsLinkToIngest'); + const linkToReassign = await renderResult.findByTestId('endpointDetailsLinkToIngest'); expect(linkToReassign).not.toBeNull(); expect(linkToReassign.textContent).toEqual('Reassign Configuration'); expect(linkToReassign.getAttribute('href')).toEqual( @@ -475,7 +475,7 @@ describe('when on the hosts page', () => { beforeEach(async () => { coreStart.application.getUrlForApp.mockReturnValue('/app/ingestManager'); const renderResult = await renderAndWaitForData(); - const linkToReassign = await renderResult.findByTestId('hostDetailsLinkToIngest'); + const linkToReassign = await renderResult.findByTestId('endpointDetailsLinkToIngest'); reactTestingLibrary.act(() => { reactTestingLibrary.fireEvent.click(linkToReassign); }); @@ -491,7 +491,7 @@ describe('when on the hosts page', () => { beforeEach(async () => { coreStart.http.post.mockImplementation(async (requestOptions) => { if (requestOptions.path === '/api/endpoint/metadata') { - return mockHostResultList({ total: 0 }); + return mockEndpointResultList({ total: 0 }); } throw new Error(`POST to '${requestOptions.path}' does not have a mock response!`); }); @@ -502,44 +502,44 @@ describe('when on the hosts page', () => { reactTestingLibrary.fireEvent.click(policyStatusLink); }); await userChangedUrlChecker; - await middlewareSpy.waitForAction('serverReturnedHostPolicyResponse'); + await middlewareSpy.waitForAction('serverReturnedEndpointPolicyResponse'); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse(); + dispatchServerReturnedEndpointPolicyResponse(); }); }); afterEach(reactTestingLibrary.cleanup); it('should hide the host details panel', async () => { - const hostDetailsFlyout = await renderResult.queryByTestId('hostDetailsFlyoutBody'); - expect(hostDetailsFlyout).toBeNull(); + const endpointDetailsFlyout = await renderResult.queryByTestId('endpointDetailsFlyoutBody'); + expect(endpointDetailsFlyout).toBeNull(); }); it('should display policy response sub-panel', async () => { expect( - await renderResult.findByTestId('hostDetailsPolicyResponseFlyoutHeader') + await renderResult.findByTestId('endpointDetailsPolicyResponseFlyoutHeader') ).not.toBeNull(); expect( - await renderResult.findByTestId('hostDetailsPolicyResponseFlyoutBody') + await renderResult.findByTestId('endpointDetailsPolicyResponseFlyoutBody') ).not.toBeNull(); }); it('should include the sub-panel title', async () => { expect( - (await renderResult.findByTestId('hostDetailsPolicyResponseFlyoutTitle')).textContent + (await renderResult.findByTestId('endpointDetailsPolicyResponseFlyoutTitle')).textContent ).toBe('Configuration Response'); }); it('should show a configuration section for each protection', async () => { const configAccordions = await renderResult.findAllByTestId( - 'hostDetailsPolicyResponseConfigAccordion' + 'endpointDetailsPolicyResponseConfigAccordion' ); expect(configAccordions).not.toBeNull(); }); it('should show an actions section for each configuration', async () => { const actionAccordions = await renderResult.findAllByTestId( - 'hostDetailsPolicyResponseActionsAccordion' + 'endpointDetailsPolicyResponseActionsAccordion' ); const action = await renderResult.findAllByTestId('policyResponseAction'); const statusHealth = await renderResult.findAllByTestId('policyResponseStatusHealth'); @@ -557,14 +557,14 @@ describe('when on the hosts page', () => { ); reactTestingLibrary.act(() => { store.dispatch({ - type: 'serverReturnedHostPolicyResponse', + type: 'serverReturnedEndpointPolicyResponse', payload: { policy_response: policyResponse, }, }); }); return renderResult - .findAllByTestId('hostDetailsPolicyResponseAttentionBadge') + .findAllByTestId('endpointDetailsPolicyResponseAttentionBadge') .catch((e) => { expect(e).not.toBeNull(); }); @@ -572,28 +572,28 @@ describe('when on the hosts page', () => { it('should show a numbered badge if at least one action failed', async () => { const policyResponseActionDispatched = middlewareSpy.waitForAction( - 'serverReturnedHostPolicyResponse' + 'serverReturnedEndpointPolicyResponse' ); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse(HostPolicyResponseActionStatus.failure); + dispatchServerReturnedEndpointPolicyResponse(HostPolicyResponseActionStatus.failure); }); await policyResponseActionDispatched; const attentionBadge = await renderResult.findAllByTestId( - 'hostDetailsPolicyResponseAttentionBadge' + 'endpointDetailsPolicyResponseAttentionBadge' ); expect(attentionBadge).not.toBeNull(); }); it('should show a numbered badge if at least one action has a warning', async () => { const policyResponseActionDispatched = middlewareSpy.waitForAction( - 'serverReturnedHostPolicyResponse' + 'serverReturnedEndpointPolicyResponse' ); reactTestingLibrary.act(() => { - dispatchServerReturnedHostPolicyResponse(HostPolicyResponseActionStatus.warning); + dispatchServerReturnedEndpointPolicyResponse(HostPolicyResponseActionStatus.warning); }); await policyResponseActionDispatched; const attentionBadge = await renderResult.findAllByTestId( - 'hostDetailsPolicyResponseAttentionBadge' + 'endpointDetailsPolicyResponseAttentionBadge' ); expect(attentionBadge).not.toBeNull(); }); @@ -602,7 +602,7 @@ describe('when on the hosts page', () => { const subHeaderBackLink = await renderResult.findByTestId('flyoutSubHeaderBackButton'); expect(subHeaderBackLink.textContent).toBe('Endpoint Details'); expect(subHeaderBackLink.getAttribute('href')).toBe( - '/hosts?page_index=0&page_size=10&selected_host=1' + '/endpoints?page_index=0&page_size=10&selected_endpoint=1' ); }); @@ -614,7 +614,7 @@ describe('when on the hosts page', () => { }); const changedUrlAction = await userChangedUrlChecker; expect(changedUrlAction.payload.search).toEqual( - '?page_index=0&page_size=10&selected_host=1' + '?page_index=0&page_size=10&selected_endpoint=1' ); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx index cdea4bfcf9f86..a923d49012d70 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx @@ -25,9 +25,9 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { createStructuredSelector } from 'reselect'; import { useDispatch } from 'react-redux'; -import { HostDetailsFlyout } from './details'; +import { EndpointDetailsFlyout } from './details'; import * as selectors from '../store/selectors'; -import { useHostSelector } from './hooks'; +import { useEndpointSelector } from './hooks'; import { HOST_STATUS_TO_HEALTH_COLOR, POLICY_STATUS_TO_HEALTH_COLOR, @@ -46,12 +46,12 @@ import { AgentConfigDetailsDeployAgentAction, } from '../../../../../../ingest_manager/public'; import { SecurityPageName } from '../../../../app/types'; -import { getHostListPath, getHostDetailsPath } from '../../../common/routing'; +import { getEndpointListPath, getEndpointDetailsPath } from '../../../common/routing'; import { useFormatUrl } from '../../../../common/components/link_to'; -import { HostAction } from '../store/action'; -import { HostPolicyLink } from './components/host_policy_link'; +import { EndpointAction } from '../store/action'; +import { EndpointPolicyLink } from './components/endpoint_policy_link'; -const HostListNavLink = memo<{ +const EndpointListNavLink = memo<{ name: string; href: string; route: string; @@ -71,10 +71,10 @@ const HostListNavLink = memo<{ ); }); -HostListNavLink.displayName = 'HostListNavLink'; +EndpointListNavLink.displayName = 'EndpointListNavLink'; const selector = (createStructuredSelector as CreateStructuredSelector)(selectors); -export const HostList = () => { +export const EndpointList = () => { const history = useHistory(); const { listData, @@ -84,16 +84,16 @@ export const HostList = () => { listLoading: loading, listError, uiQueryParams: queryParams, - hasSelectedHost, + hasSelectedEndpoint, policyItems, selectedPolicyId, policyItemsLoading, endpointPackageVersion, - hostsExist, - } = useHostSelector(selector); + endpointsExist, + } = useEndpointSelector(selector); const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); - const dispatch = useDispatch<(a: HostAction) => void>(); + const dispatch = useDispatch<(a: EndpointAction) => void>(); const paginationSetup = useMemo(() => { return { @@ -108,10 +108,10 @@ export const HostList = () => { const onTableChange = useCallback( ({ page }: { page: { index: number; size: number } }) => { const { index, size } = page; - // FIXME: PT: if host details is open, table is not displaying correct number of rows + // FIXME: PT: if endpoint details is open, table is not displaying correct number of rows history.push( - getHostListPath({ - name: 'hostList', + getEndpointListPath({ + name: 'endpointList', ...queryParams, page_index: JSON.stringify(index), page_size: JSON.stringify(size), @@ -130,12 +130,12 @@ export const HostList = () => { state: { onCancelNavigateTo: [ 'securitySolution:administration', - { path: getHostListPath({ name: 'hostList' }) }, + { path: getEndpointListPath({ name: 'endpointList' }) }, ], - onCancelUrl: formatUrl(getHostListPath({ name: 'hostList' })), + onCancelUrl: formatUrl(getEndpointListPath({ name: 'endpointList' })), onSaveNavigateTo: [ 'securitySolution:administration', - { path: getHostListPath({ name: 'hostList' }) }, + { path: getEndpointListPath({ name: 'endpointList' }) }, ], }, } @@ -148,7 +148,7 @@ export const HostList = () => { state: { onDoneNavigateTo: [ 'securitySolution:administration', - { path: getHostListPath({ name: 'hostList' }) }, + { path: getEndpointListPath({ name: 'endpointList' }) }, ], }, }); @@ -183,28 +183,28 @@ export const HostList = () => { ); const columns: Array>> = useMemo(() => { - const lastActiveColumnName = i18n.translate('xpack.securitySolution.endpointList.lastActive', { + const lastActiveColumnName = i18n.translate('xpack.securitySolution.endpoint.list.lastActive', { defaultMessage: 'Last Active', }); return [ { field: 'metadata.host', - name: i18n.translate('xpack.securitySolution.endpointList.hostname', { + name: i18n.translate('xpack.securitySolution.endpoint.list.hostname', { defaultMessage: 'Hostname', }), render: ({ hostname, id }: HostInfo['metadata']['host']) => { - const toRoutePath = getHostDetailsPath( + const toRoutePath = getEndpointDetailsPath( { ...queryParams, - name: 'hostDetails', - selected_host: id, + name: 'endpointDetails', + selected_endpoint: id, }, search ); const toRouteUrl = formatUrl(toRoutePath); return ( - { }, { field: 'host_status', - name: i18n.translate('xpack.securitySolution.endpointList.hostStatus', { - defaultMessage: 'Host Status', + name: i18n.translate('xpack.securitySolution.endpoint.list.hostStatus', { + defaultMessage: 'Agent Status', }), // eslint-disable-next-line react/display-name render: (hostStatus: HostInfo['host_status']) => { @@ -227,7 +227,7 @@ export const HostList = () => { className="eui-textTruncate" > @@ -237,33 +237,33 @@ export const HostList = () => { }, { field: 'metadata.Endpoint.policy.applied', - name: i18n.translate('xpack.securitySolution.endpointList.policy', { + name: i18n.translate('xpack.securitySolution.endpoint.list.policy', { defaultMessage: 'Integration', }), truncateText: true, // eslint-disable-next-line react/display-name render: (policy: HostInfo['metadata']['Endpoint']['policy']['applied']) => { return ( - {policy.name} - + ); }, }, { field: 'metadata.Endpoint.policy.applied', - name: i18n.translate('xpack.securitySolution.endpointList.policyStatus', { + name: i18n.translate('xpack.securitySolution.endpoint.list.policyStatus', { defaultMessage: 'Configuration Status', }), render: (policy: HostInfo['metadata']['Endpoint']['policy']['applied'], item: HostInfo) => { - const toRoutePath = getHostDetailsPath({ - name: 'hostPolicyResponse', + const toRoutePath = getEndpointDetailsPath({ + name: 'endpointPolicyResponse', ...queryParams, - selected_host: item.metadata.host.id, + selected_endpoint: item.metadata.host.id, }); const toRouteUrl = formatUrl(toRoutePath); return ( @@ -272,7 +272,7 @@ export const HostList = () => { className="eui-textTruncate" data-test-subj="rowPolicyStatus" > - { }, { field: 'metadata.host.os.name', - name: i18n.translate('xpack.securitySolution.endpointList.os', { + name: i18n.translate('xpack.securitySolution.endpoint.list.os', { defaultMessage: 'Operating System', }), truncateText: true, }, { field: 'metadata.host.ip', - name: i18n.translate('xpack.securitySolution.endpointList.ip', { + name: i18n.translate('xpack.securitySolution.endpoint.list.ip', { defaultMessage: 'IP Address', }), // eslint-disable-next-line react/display-name @@ -309,7 +309,7 @@ export const HostList = () => { }, { field: 'metadata.agent.version', - name: i18n.translate('xpack.securitySolution.endpointList.endpointVersion', { + name: i18n.translate('xpack.securitySolution.endpoint.list.endpointVersion', { defaultMessage: 'Version', }), }, @@ -330,10 +330,10 @@ export const HostList = () => { }, [formatUrl, queryParams, search]); const renderTableOrEmptyState = useMemo(() => { - if (hostsExist) { + if (endpointsExist) { return ( { } }, [ loading, - hostsExist, + endpointsExist, policyItemsLoading, policyItems, listData, @@ -377,7 +377,7 @@ export const HostList = () => { return ( @@ -385,15 +385,15 @@ export const HostList = () => {

@@ -403,7 +403,7 @@ export const HostList = () => {

@@ -411,12 +411,12 @@ export const HostList = () => { } > - {hasSelectedHost && } + {hasSelectedEndpoint && } {listData && listData.length > 0 && ( <> - + diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/url_from_query_params.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/url_from_query_params.ts index a14f1d0d0dd6c..c421f513556f4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/url_from_query_params.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/url_from_query_params.ts @@ -7,10 +7,10 @@ // eslint-disable-next-line import/no-nodejs-modules import querystring from 'querystring'; -import { HostIndexUIQueryParams } from '../types'; +import { EndpointIndexUIQueryParams } from '../types'; import { AppLocation } from '../../../../../common/endpoint/types'; -export function urlFromQueryParams(queryParams: HostIndexUIQueryParams): Partial { +export function urlFromQueryParams(queryParams: EndpointIndexUIQueryParams): Partial { const search = querystring.stringify(queryParams); return { search, diff --git a/x-pack/plugins/security_solution/public/management/pages/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/index.test.tsx index 5ec42671ec3d2..9e496ce6c0b50 100644 --- a/x-pack/plugins/security_solution/public/management/pages/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/index.test.tsx @@ -30,7 +30,7 @@ describe('when in the Admistration tab', () => { it('should display the Management view when Ingest is ON', async () => { (useIngestEnabledCheck as jest.Mock).mockReturnValue({ allEnabled: true }); const renderResult = render(); - const hostPage = await renderResult.findByTestId('hostPage'); - expect(hostPage).not.toBeNull(); + const endpointPage = await renderResult.findByTestId('endpointPage'); + expect(endpointPage).not.toBeNull(); }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/index.tsx b/x-pack/plugins/security_solution/public/management/pages/index.tsx index 3e1c0743fb4f1..c20a3dd31d6a4 100644 --- a/x-pack/plugins/security_solution/public/management/pages/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/index.tsx @@ -13,24 +13,24 @@ import { EuiText, EuiEmptyPrompt } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { PolicyContainer } from './policy'; import { - MANAGEMENT_ROUTING_HOSTS_PATH, + MANAGEMENT_ROUTING_ENDPOINTS_PATH, MANAGEMENT_ROUTING_POLICIES_PATH, MANAGEMENT_ROUTING_ROOT_PATH, } from '../common/constants'; import { NotFoundPage } from '../../app/404'; -import { HostsContainer } from './endpoint_hosts'; -import { getHostListPath } from '../common/routing'; +import { EndpointsContainer } from './endpoint_hosts'; +import { getEndpointListPath } from '../common/routing'; import { APP_ID, SecurityPageName } from '../../../common/constants'; import { GetUrlForApp } from '../../common/components/navigation/types'; import { AdministrationRouteSpyState } from '../../common/utils/route/types'; import { ADMINISTRATION } from '../../app/home/translations'; import { AdministrationSubTab } from '../types'; -import { HOSTS_TAB, POLICIES_TAB } from '../common/translations'; +import { ENDPOINTS_TAB, POLICIES_TAB } from '../common/translations'; import { SpyRoute } from '../../common/utils/route/spy_routes'; import { useIngestEnabledCheck } from '../../common/hooks/endpoint/ingest_enabled'; const TabNameMappedToI18nKey: Record = { - [AdministrationSubTab.hosts]: HOSTS_TAB, + [AdministrationSubTab.endpoints]: ENDPOINTS_TAB, [AdministrationSubTab.policies]: POLICIES_TAB, }; @@ -102,13 +102,13 @@ export const ManagementContainer = memo(() => { return ( - + { - history.replace(getHostListPath({ name: 'hostList' })); + history.replace(getEndpointListPath({ name: 'endpointList' })); return null; }} /> diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/agents_summary.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/agents_summary.tsx index 921493e239c0f..5dbd1b6ff4919 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/agents_summary.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/agents_summary.tsx @@ -34,7 +34,7 @@ export const AgentsSummary = memo((props) => { title: i18n.translate( 'xpack.securitySolution.endpoint.policyDetails.agentsSummary.totalTitle', { - defaultMessage: 'Hosts', + defaultMessage: 'Endpoints', } ), health: '', diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx index c81ffb0060c88..c934cfb94fc7e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx @@ -10,7 +10,7 @@ import { mount } from 'enzyme'; import { PolicyDetails } from './policy_details'; import { EndpointDocGenerator } from '../../../../../common/endpoint/generate_data'; import { AppContextTestRender, createAppRootMockRenderer } from '../../../../common/mock/endpoint'; -import { getPolicyDetailPath, getHostListPath } from '../../../common/routing'; +import { getPolicyDetailPath, getEndpointListPath } from '../../../common/routing'; import { policyListApiPathHandlers } from '../store/policy_list/test_mock_utils'; jest.mock('../../../../common/components/link_to'); @@ -19,7 +19,7 @@ describe('Policy Details', () => { type FindReactWrapperResponse = ReturnType['find']>; const policyDetailsPathUrl = getPolicyDetailPath('1'); - const hostListPath = getHostListPath({ name: 'hostList' }); + const endpointListPath = getEndpointListPath({ name: 'endpointList' }); const sleep = (ms = 100) => new Promise((wakeup) => setTimeout(wakeup, ms)); const generator = new EndpointDocGenerator(); let history: AppContextTestRender['history']; @@ -129,7 +129,7 @@ describe('Policy Details', () => { const backToListButton = pageHeaderLeft.find('EuiButtonEmpty'); expect(backToListButton.prop('iconType')).toBe('arrowLeft'); - expect(backToListButton.prop('href')).toBe(hostListPath); + expect(backToListButton.prop('href')).toBe(endpointListPath); expect(backToListButton.text()).toBe('Back to endpoint hosts'); const pageTitle = pageHeaderLeft.find('[data-test-subj="pageViewHeaderLeftTitle"]'); @@ -143,7 +143,7 @@ describe('Policy Details', () => { ); expect(history.location.pathname).toEqual(policyDetailsPathUrl); backToListButton.simulate('click', { button: 0 }); - expect(history.location.pathname).toEqual(hostListPath); + expect(history.location.pathname).toEqual(endpointListPath); }); it('should display agent stats', async () => { await asyncActions; @@ -153,7 +153,7 @@ describe('Policy Details', () => { ); const agentsSummary = headerRight.find('EuiFlexGroup[data-test-subj="policyAgentsSummary"]'); expect(agentsSummary).toHaveLength(1); - expect(agentsSummary.text()).toBe('Hosts5Online3Offline1Error1'); + expect(agentsSummary.text()).toBe('Endpoints5Online3Offline1Error1'); }); it('should display cancel button', async () => { await asyncActions; @@ -175,7 +175,7 @@ describe('Policy Details', () => { const navigateToAppMockedCalls = coreStart.application.navigateToApp.mock.calls; expect(navigateToAppMockedCalls[navigateToAppMockedCalls.length - 1]).toEqual([ 'securitySolution:administration', - { path: hostListPath }, + { path: endpointListPath }, ]); }); it('should display save button', async () => { diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx index d309faf59d044..e54e684d788c0 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx @@ -43,7 +43,7 @@ import { PageViewHeaderTitle } from '../../../../common/components/endpoint/page import { ManagementPageView } from '../../../components/management_page_view'; import { SpyRoute } from '../../../../common/utils/route/spy_routes'; import { SecurityPageName } from '../../../../app/types'; -import { getHostListPath } from '../../../common/routing'; +import { getEndpointListPath } from '../../../common/routing'; import { useFormatUrl } from '../../../../common/components/link_to'; import { useNavigateToAppEventHandler } from '../../../../common/hooks/endpoint/use_navigate_to_app_event_handler'; import { MANAGEMENT_APP_ID } from '../../../common/constants'; @@ -71,7 +71,7 @@ export const PolicyDetails = React.memo(() => { const [showConfirm, setShowConfirm] = useState(false); const [routeState, setRouteState] = useState(); const policyName = policyItem?.name ?? ''; - const hostListRouterPath = getHostListPath({ name: 'hostList' }); + const hostListRouterPath = getEndpointListPath({ name: 'endpointList' }); // Handle showing update statuses useEffect(() => { diff --git a/x-pack/plugins/security_solution/public/management/store/middleware.ts b/x-pack/plugins/security_solution/public/management/store/middleware.ts index a29da9bef5875..c7a7d2cad0623 100644 --- a/x-pack/plugins/security_solution/public/management/store/middleware.ts +++ b/x-pack/plugins/security_solution/public/management/store/middleware.ts @@ -12,19 +12,19 @@ import { import { policyListMiddlewareFactory } from '../pages/policy/store/policy_list'; import { policyDetailsMiddlewareFactory } from '../pages/policy/store/policy_details'; import { - MANAGEMENT_STORE_HOSTS_NAMESPACE, + MANAGEMENT_STORE_ENDPOINTS_NAMESPACE, MANAGEMENT_STORE_GLOBAL_NAMESPACE, MANAGEMENT_STORE_POLICY_DETAILS_NAMESPACE, MANAGEMENT_STORE_POLICY_LIST_NAMESPACE, } from '../common/constants'; -import { hostMiddlewareFactory } from '../pages/endpoint_hosts/store/middleware'; +import { endpointMiddlewareFactory } from '../pages/endpoint_hosts/store/middleware'; const policyListSelector = (state: State) => state[MANAGEMENT_STORE_GLOBAL_NAMESPACE][MANAGEMENT_STORE_POLICY_LIST_NAMESPACE]; const policyDetailsSelector = (state: State) => state[MANAGEMENT_STORE_GLOBAL_NAMESPACE][MANAGEMENT_STORE_POLICY_DETAILS_NAMESPACE]; const endpointsSelector = (state: State) => - state[MANAGEMENT_STORE_GLOBAL_NAMESPACE][MANAGEMENT_STORE_HOSTS_NAMESPACE]; + state[MANAGEMENT_STORE_GLOBAL_NAMESPACE][MANAGEMENT_STORE_ENDPOINTS_NAMESPACE]; export const managementMiddlewareFactory: SecuritySubPluginMiddlewareFactory = ( coreStart, @@ -39,6 +39,6 @@ export const managementMiddlewareFactory: SecuritySubPluginMiddlewareFactory = ( policyDetailsSelector, policyDetailsMiddlewareFactory(coreStart, depsStart) ), - substateMiddlewareFactory(endpointsSelector, hostMiddlewareFactory(coreStart, depsStart)), + substateMiddlewareFactory(endpointsSelector, endpointMiddlewareFactory(coreStart, depsStart)), ]; }; diff --git a/x-pack/plugins/security_solution/public/management/store/reducer.ts b/x-pack/plugins/security_solution/public/management/store/reducer.ts index f3c470fb1e8a3..eafd69c875ff1 100644 --- a/x-pack/plugins/security_solution/public/management/store/reducer.ts +++ b/x-pack/plugins/security_solution/public/management/store/reducer.ts @@ -14,14 +14,17 @@ import { initialPolicyListState, } from '../pages/policy/store/policy_list/reducer'; import { - MANAGEMENT_STORE_HOSTS_NAMESPACE, + MANAGEMENT_STORE_ENDPOINTS_NAMESPACE, MANAGEMENT_STORE_POLICY_DETAILS_NAMESPACE, MANAGEMENT_STORE_POLICY_LIST_NAMESPACE, } from '../common/constants'; import { ImmutableCombineReducers } from '../../common/store'; import { Immutable } from '../../../common/endpoint/types'; import { ManagementState } from '../types'; -import { hostListReducer, initialHostListState } from '../pages/endpoint_hosts/store/reducer'; +import { + endpointListReducer, + initialEndpointListState, +} from '../pages/endpoint_hosts/store/reducer'; const immutableCombineReducers: ImmutableCombineReducers = combineReducers; @@ -31,7 +34,7 @@ const immutableCombineReducers: ImmutableCombineReducers = combineReducers; export const mockManagementState: Immutable = { [MANAGEMENT_STORE_POLICY_LIST_NAMESPACE]: initialPolicyListState(), [MANAGEMENT_STORE_POLICY_DETAILS_NAMESPACE]: initialPolicyDetailsState(), - [MANAGEMENT_STORE_HOSTS_NAMESPACE]: initialHostListState, + [MANAGEMENT_STORE_ENDPOINTS_NAMESPACE]: initialEndpointListState, }; /** @@ -40,5 +43,5 @@ export const mockManagementState: Immutable = { export const managementReducer = immutableCombineReducers({ [MANAGEMENT_STORE_POLICY_LIST_NAMESPACE]: policyListReducer, [MANAGEMENT_STORE_POLICY_DETAILS_NAMESPACE]: policyDetailsReducer, - [MANAGEMENT_STORE_HOSTS_NAMESPACE]: hostListReducer, + [MANAGEMENT_STORE_ENDPOINTS_NAMESPACE]: endpointListReducer, }); diff --git a/x-pack/plugins/security_solution/public/management/types.ts b/x-pack/plugins/security_solution/public/management/types.ts index 86959caaba4f4..c35c9277b4488 100644 --- a/x-pack/plugins/security_solution/public/management/types.ts +++ b/x-pack/plugins/security_solution/public/management/types.ts @@ -7,7 +7,7 @@ import { CombinedState } from 'redux'; import { SecurityPageName } from '../app/types'; import { PolicyListState, PolicyDetailsState } from './pages/policy/types'; -import { HostState } from './pages/endpoint_hosts/types'; +import { EndpointState } from './pages/endpoint_hosts/types'; /** * The type for the management store global namespace. Used mostly internally to reference @@ -18,14 +18,14 @@ export type ManagementStoreGlobalNamespace = 'management'; export type ManagementState = CombinedState<{ policyList: PolicyListState; policyDetails: PolicyDetailsState; - hosts: HostState; + endpoints: EndpointState; }>; /** * The management list of sub-tabs. Changes to these will impact the Router routes. */ export enum AdministrationSubTab { - hosts = 'hosts', + endpoints = 'endpoints', policies = 'policy', } diff --git a/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx b/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx index 1d726a7dbd901..8b73253157edc 100644 --- a/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx @@ -7,13 +7,13 @@ import React, { memo } from 'react'; import { EuiCallOut, EuiButton, EuiButtonEmpty } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { getHostListPath } from '../../../management/common/routing'; +import { getEndpointListPath } from '../../../management/common/routing'; import { useNavigateToAppEventHandler } from '../../../common/hooks/endpoint/use_navigate_to_app_event_handler'; import { useManagementFormatUrl } from '../../../management/components/hooks/use_management_format_url'; import { MANAGEMENT_APP_ID } from '../../../management/common/constants'; export const EndpointNotice = memo<{ onDismiss: () => void }>(({ onDismiss }) => { - const endpointsPath = getHostListPath({ name: 'hostList' }); + const endpointsPath = getEndpointListPath({ name: 'endpointList' }); const endpointsLink = useManagementFormatUrl(endpointsPath); const handleGetStartedClick = useNavigateToAppEventHandler(MANAGEMENT_APP_ID, { path: endpointsPath, diff --git a/x-pack/plugins/security_solution/public/resolver/mocks/endpoint_event.ts b/x-pack/plugins/security_solution/public/resolver/mocks/endpoint_event.ts index c822fdf647c16..083f6b8baa59f 100644 --- a/x-pack/plugins/security_solution/public/resolver/mocks/endpoint_event.ts +++ b/x-pack/plugins/security_solution/public/resolver/mocks/endpoint_event.ts @@ -15,12 +15,14 @@ export function mockEndpointEvent({ parentEntityId, timestamp, lifecycleType, + pid = 0, }: { entityID: string; name: string; parentEntityId?: string; timestamp: number; lifecycleType?: string; + pid?: number; }): EndpointEvent { return { '@timestamp': timestamp, @@ -45,7 +47,7 @@ export function mockEndpointEvent({ executable: 'executable', args: 'args', name, - pid: 0, + pid, hash: { md5: 'hash.md5', }, diff --git a/x-pack/plugins/security_solution/public/resolver/mocks/resolver_tree.ts b/x-pack/plugins/security_solution/public/resolver/mocks/resolver_tree.ts index 5d2cbb2eab0dc..7edf4f8071ed8 100644 --- a/x-pack/plugins/security_solution/public/resolver/mocks/resolver_tree.ts +++ b/x-pack/plugins/security_solution/public/resolver/mocks/resolver_tree.ts @@ -175,18 +175,21 @@ export function mockTreeWithNoAncestorsAnd2Children({ secondChildID: string; }): ResolverTree { const origin: ResolverEvent = mockEndpointEvent({ + pid: 0, entityID: originID, name: 'c', parentEntityId: 'none', timestamp: 0, }); const firstChild: ResolverEvent = mockEndpointEvent({ + pid: 1, entityID: firstChildID, name: 'd', parentEntityId: originID, timestamp: 1, }); const secondChild: ResolverEvent = mockEndpointEvent({ + pid: 2, entityID: secondChildID, name: 'e', parentEntityId: originID, diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/connect_enzyme_wrapper_and_store.ts b/x-pack/plugins/security_solution/public/resolver/test_utilities/connect_enzyme_wrapper_and_store.ts deleted file mode 100644 index 3a4a1f7d634d1..0000000000000 --- a/x-pack/plugins/security_solution/public/resolver/test_utilities/connect_enzyme_wrapper_and_store.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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 { Store } from 'redux'; -import { ReactWrapper } from 'enzyme'; - -/** - * We use the full-DOM emulation mode of `enzyme` via `mount`. Even though we use `react-redux`, `enzyme` - * does not update the DOM after state transitions. This subscribes to the `redux` store and after any state - * transition it asks `enzyme` to update the DOM to match the React state. - */ -export function connectEnzymeWrapperAndStore(store: Store, wrapper: ReactWrapper): void { - store.subscribe(() => { - // See https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/update.html - return wrapper.update(); - }); -} diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx b/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx index 6f44c5aee7cac..cae6a18576ebd 100644 --- a/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/simulator/index.tsx @@ -10,7 +10,6 @@ import { mount, ReactWrapper } from 'enzyme'; import { createMemoryHistory, History as HistoryPackageHistoryInterface } from 'history'; import { CoreStart } from '../../../../../../../src/core/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; -import { connectEnzymeWrapperAndStore } from '../connect_enzyme_wrapper_and_store'; import { spyMiddlewareFactory } from '../spy_middleware_factory'; import { resolverMiddlewareFactory } from '../../store/middleware'; import { resolverReducer } from '../../store/reducer'; @@ -48,6 +47,7 @@ export class Simulator { dataAccessLayer, resolverComponentInstanceID, databaseDocumentID, + history, }: { /** * A (mock) data access layer that will be used to create the Resolver store. @@ -61,6 +61,7 @@ export class Simulator { * a databaseDocumentID to pass to Resolver. Resolver will use this in requests to the mock data layer. */ databaseDocumentID?: string; + history?: HistoryPackageHistoryInterface; }) { this.resolverComponentInstanceID = resolverComponentInstanceID; // create the spy middleware (for debugging tests) @@ -79,8 +80,9 @@ export class Simulator { // Create a redux store w/ the top level Resolver reducer and the enhancer that includes the Resolver middleware and the `spyMiddleware` this.store = createStore(resolverReducer, middlewareEnhancer); - // Create a fake 'history' instance that Resolver will use to read and write query string values - this.history = createMemoryHistory(); + // If needed, create a fake 'history' instance. + // Resolver will use to read and write query string values. + this.history = history ?? createMemoryHistory(); // Used for `KibanaContextProvider` const coreStart: CoreStart = coreMock.createStart(); @@ -95,9 +97,6 @@ export class Simulator { databaseDocumentID={databaseDocumentID} /> ); - - // Update the enzyme wrapper after each state transition - connectEnzymeWrapperAndStore(this.store, this.wrapper); } /** @@ -112,6 +111,16 @@ export class Simulator { return this.spyMiddleware.debugActions(); } + /** + * EUI uses a component called `AutoSizer` that won't render its children unless it has sufficient size. + * This forces any `AutoSizer` instances to have a large size. + */ + private forceAutoSizerOpen() { + this.wrapper + .find('AutoSizer') + .forEach((wrapper) => wrapper.setState({ width: 10000, height: 10000 })); + } + /** * Yield the result of `mapper` over and over, once per event-loop cycle. * After 10 times, quit. @@ -124,6 +133,7 @@ export class Simulator { yield mapper(); await new Promise((resolve) => { setTimeout(() => { + this.forceAutoSizerOpen(); this.wrapper.update(); resolve(); }, 0); @@ -174,6 +184,13 @@ export class Simulator { ); } + /** + * The items in the submenu that is opened by expanding a node in the map. + */ + public processNodeSubmenuItems(): ReactWrapper { + return this.domNodes('[data-test-subj="resolver:map:node-submenu-item"]'); + } + /** * Return the selected node query string values. */ @@ -206,38 +223,38 @@ export class Simulator { } /** - * An element with a list of all nodes. + * The titles of the links that select a node in the node list view. */ - public nodeListElement(): ReactWrapper { - return this.domNodes('[data-test-subj="resolver:node-list"]'); + public nodeListNodeLinkText(): ReactWrapper { + return this.domNodes('[data-test-subj="resolver:node-list:node-link:title"]'); } /** - * Return the items in the node list (the default panel view.) + * The icons in the links that select a node in the node list view. */ - public nodeListItems(): ReactWrapper { - return this.domNodes('[data-test-subj="resolver:node-list:item"]'); + public nodeListNodeLinkIcons(): ReactWrapper { + return this.domNodes('[data-test-subj="resolver:node-list:node-link:icon"]'); } /** - * The element containing the details for the selected node. + * Link rendered in the breadcrumbs of the node detail view. Takes the user to the node list. */ - public nodeDetailElement(): ReactWrapper { - return this.domNodes('[data-test-subj="resolver:node-detail"]'); + public nodeDetailBreadcrumbNodeListLink(): ReactWrapper { + return this.domNodes('[data-test-subj="resolver:node-detail:breadcrumbs:node-list-link"]'); } /** - * The details of the selected node are shown in a description list. This returns the title elements of the description list. + * The title element for the node detail view. */ - private nodeDetailEntryTitle(): ReactWrapper { - return this.domNodes('[data-test-subj="resolver:node-detail:entry-title"]'); + public nodeDetailViewTitle(): ReactWrapper { + return this.domNodes('[data-test-subj="resolver:node-detail:title"]'); } /** - * The details of the selected node are shown in a description list. This returns the description elements of the description list. + * The icon element for the node detail title. */ - private nodeDetailEntryDescription(): ReactWrapper { - return this.domNodes('[data-test-subj="resolver:node-detail:entry-description"]'); + public nodeDetailViewTitleIcon(): ReactWrapper { + return this.domNodes('[data-test-subj="resolver:node-detail:title-icon"]'); } /** @@ -253,8 +270,14 @@ export class Simulator { * The titles and descriptions (as text) from the node detail panel. */ public nodeDetailDescriptionListEntries(): Array<[string, string]> { - const titles = this.nodeDetailEntryTitle(); - const descriptions = this.nodeDetailEntryDescription(); + /** + * The details of the selected node are shown in a description list. This returns the title elements of the description list. + */ + const titles = this.domNodes('[data-test-subj="resolver:node-detail:entry-title"]'); + /** + * The details of the selected node are shown in a description list. This returns the description elements of the description list. + */ + const descriptions = this.domNodes('[data-test-subj="resolver:node-detail:entry-description"]'); const entries: Array<[string, string]> = []; for (let index = 0; index < Math.min(titles.length, descriptions.length); index++) { const title = titles.at(index).text(); diff --git a/x-pack/plugins/security_solution/public/resolver/test_utilities/url_search.ts b/x-pack/plugins/security_solution/public/resolver/test_utilities/url_search.ts new file mode 100644 index 0000000000000..1a26e29d22da7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/test_utilities/url_search.ts @@ -0,0 +1,26 @@ +/* + * 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. + */ + +interface Options { + /** + * The entity_id of the selected node. + */ + selectedEntityID?: string; +} + +/** + * Calculate the expected URL search based on options. + */ +export function urlSearch(resolverComponentInstanceID: string, options?: Options): string { + if (!options) { + return ''; + } + const params = new URLSearchParams(); + if (options.selectedEntityID !== undefined) { + params.set(`resolver-${resolverComponentInstanceID}-id`, options.selectedEntityID); + } + return params.toString(); +} diff --git a/x-pack/plugins/security_solution/public/resolver/view/assets.tsx b/x-pack/plugins/security_solution/public/resolver/view/assets.tsx index fc4a9daf17ad1..6962d300f7072 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/assets.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/assets.tsx @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +/* eslint-disable react/display-name */ + import React, { memo } from 'react'; import euiThemeAmsterdamDark from '@elastic/eui/dist/eui_theme_amsterdam_dark.json'; import euiThemeAmsterdamLight from '@elastic/eui/dist/eui_theme_amsterdam_light.json'; @@ -11,7 +13,7 @@ import { htmlIdGenerator, ButtonColor } from '@elastic/eui'; import styled from 'styled-components'; import { i18n } from '@kbn/i18n'; import { useUiSetting } from '../../common/lib/kibana'; -import { DEFAULT_DARK_MODE } from '../../../common/constants'; +import { DEFAULT_DARK_MODE as defaultDarkMode } from '../../../common/constants'; import { ResolverProcessType } from '../types'; type ResolverColorNames = @@ -141,8 +143,6 @@ const PaintServers = memo(({ isDarkMode }: { isDarkMode: boolean }) => ( )); -PaintServers.displayName = 'PaintServers'; - /** * Ids of symbols to be linked by elements */ @@ -376,8 +376,6 @@ const SymbolsAndShapes = memo(({ isDarkMode }: { isDarkMode: boolean }) => ( )); -SymbolsAndShapes.displayName = 'SymbolsAndShapes'; - /** * This `` element is used to define the reusable assets for the Resolver * It confers several advantages, including but not limited to: @@ -386,7 +384,7 @@ SymbolsAndShapes.displayName = 'SymbolsAndShapes'; * 3. `` elements can be handled by compositor (faster) */ const SymbolDefinitionsComponent = memo(({ className }: { className?: string }) => { - const isDarkMode = useUiSetting(DEFAULT_DARK_MODE); + const isDarkMode = useUiSetting(defaultDarkMode); return ( @@ -397,8 +395,6 @@ const SymbolDefinitionsComponent = memo(({ className }: { className?: string }) ); }); -SymbolDefinitionsComponent.displayName = 'SymbolDefinitions'; - export const SymbolDefinitions = styled(SymbolDefinitionsComponent)` position: absolute; left: 100%; @@ -424,7 +420,7 @@ export const useResolverTheme = (): { nodeAssets: NodeStyleMap; cubeAssetsForNode: (isProcessTerimnated: boolean, isProcessTrigger: boolean) => NodeStyleConfig; } => { - const isDarkMode = useUiSetting(DEFAULT_DARK_MODE); + const isDarkMode = useUiSetting(defaultDarkMode); const theme = isDarkMode ? euiThemeAmsterdamDark : euiThemeAmsterdamLight; const getThemedOption = (lightOption: string, darkOption: string): string => { diff --git a/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx index 98ea235d3524f..296e5b253c0b9 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/clickthrough.test.tsx @@ -71,8 +71,9 @@ describe('Resolver, when analyzing a tree that has no ancestors and 2 children', }); }); - it(`should show the node list`, async () => { - await expect(simulator.map(() => simulator.nodeListElement().length)).toYieldEqualTo(1); + it(`should show links to the 3 nodes (with icons) in the node list.`, async () => { + await expect(simulator.map(() => simulator.nodeListNodeLinkText().length)).toYieldEqualTo(3); + await expect(simulator.map(() => simulator.nodeListNodeLinkIcons().length)).toYieldEqualTo(3); }); describe("when the second child node's first button has been clicked", () => { @@ -152,5 +153,20 @@ describe('Resolver, when analyzing a tree that has two related events for the or relatedEventButtons: 1, }); }); + describe('when the related events button is clicked', () => { + beforeEach(async () => { + const button = await simulator.resolveWrapper(() => + simulator.processNodeRelatedEventButton(entityIDs.origin) + ); + if (button) { + button.simulate('click'); + } + }); + it('should open the submenu', async () => { + await expect( + simulator.map(() => simulator.processNodeSubmenuItems().map((node) => node.text())) + ).toYieldEqualTo(['2 registry']); + }); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/resolver/view/map.tsx b/x-pack/plugins/security_solution/public/resolver/view/map.tsx deleted file mode 100644 index bbff2388af8b7..0000000000000 --- a/x-pack/plugins/security_solution/public/resolver/view/map.tsx +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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. - */ - -/* eslint-disable react/display-name */ - -import React, { useContext } from 'react'; -import { useSelector } from 'react-redux'; -import { useEffectOnce } from 'react-use'; -import { EuiLoadingSpinner } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; -import * as selectors from '../store/selectors'; -import { EdgeLine } from './edge_line'; -import { GraphControls } from './graph_controls'; -import { ProcessEventDot } from './process_event_dot'; -import { useCamera } from './use_camera'; -import { SymbolDefinitions, useResolverTheme } from './assets'; -import { useStateSyncingActions } from './use_state_syncing_actions'; -import { useResolverQueryParams } from './use_resolver_query_params'; -import { StyledMapContainer, StyledPanel, GraphContainer } from './styles'; -import { entityIDSafeVersion } from '../../../common/endpoint/models/event'; -import { SideEffectContext } from './side_effect_context'; - -/** - * The highest level connected Resolver component. Needs a `Provider` in its ancestry to work. - */ -export const ResolverMap = React.memo(function ({ - className, - databaseDocumentID, - resolverComponentInstanceID, -}: { - /** - * Used by `styled-components`. - */ - className?: string; - /** - * The `_id` value of an event in ES. - * Used as the origin of the Resolver graph. - */ - databaseDocumentID?: string; - /** - * A string literal describing where in the app resolver is located, - * used to prevent collisions in things like query params - */ - resolverComponentInstanceID: string; -}) { - /** - * This is responsible for dispatching actions that include any external data. - * `databaseDocumentID` - */ - useStateSyncingActions({ databaseDocumentID, resolverComponentInstanceID }); - - const { timestamp } = useContext(SideEffectContext); - - // use this for the entire render in order to keep things in sync - const timeAtRender = timestamp(); - - const { processNodePositions, connectingEdgeLineSegments } = useSelector( - selectors.visibleNodesAndEdgeLines - )(timeAtRender); - const terminatedProcesses = useSelector(selectors.terminatedProcesses); - const { projectionMatrix, ref, onMouseDown } = useCamera(); - const isLoading = useSelector(selectors.isLoading); - const hasError = useSelector(selectors.hasError); - const activeDescendantId = useSelector(selectors.ariaActiveDescendant); - const { colorMap } = useResolverTheme(); - const { cleanUpQueryParams } = useResolverQueryParams(); - - useEffectOnce(() => { - return () => cleanUpQueryParams(); - }); - - return ( - - {isLoading ? ( -
- -
- ) : hasError ? ( -
-
- {' '} - -
-
- ) : ( - - {connectingEdgeLineSegments.map(({ points: [startPosition, endPosition], metadata }) => ( - - ))} - {[...processNodePositions].map(([processEvent, position]) => { - const processEntityId = entityIDSafeVersion(processEvent); - return ( - - ); - })} - - )} - - - - - ); -}); diff --git a/x-pack/plugins/security_solution/public/resolver/view/panel.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/panel.test.tsx index 78e5fd79bea13..4d391a6c9ce59 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panel.test.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panel.test.tsx @@ -4,47 +4,143 @@ * you may not use this file except in compliance with the Elastic License. */ +import { createMemoryHistory, History as HistoryPackageHistoryInterface } from 'history'; + import { noAncestorsTwoChildren } from '../data_access_layer/mocks/no_ancestors_two_children'; import { Simulator } from '../test_utilities/simulator'; // Extend jest with a custom matcher import '../test_utilities/extend_jest'; +import { urlSearch } from '../test_utilities/url_search'; + +// the resolver component instance ID, used by the react code to distinguish piece of global state from those used by other resolver instances +const resolverComponentInstanceID = 'resolverComponentInstanceID'; -describe('Resolver: when analyzing a tree with no ancestors and two children', () => { - let simulator: Simulator; - let databaseDocumentID: string; +describe(`Resolver: when analyzing a tree with no ancestors and two children, and when the component instance ID is ${resolverComponentInstanceID}`, () => { + /** + * Get (or lazily create and get) the simulator. + */ + let simulator: () => Simulator; + /** lazily populated by `simulator`. */ + let simulatorInstance: Simulator | undefined; + let memoryHistory: HistoryPackageHistoryInterface; - // the resolver component instance ID, used by the react code to distinguish piece of global state from those used by other resolver instances - const resolverComponentInstanceID = 'resolverComponentInstanceID'; + // node IDs used by the generator + let entityIDs: { + origin: string; + firstChild: string; + secondChild: string; + }; - beforeEach(async () => { + beforeEach(() => { // create a mock data access layer const { metadata: dataAccessLayerMetadata, dataAccessLayer } = noAncestorsTwoChildren(); - // save a reference to the `_id` supported by the mock data layer - databaseDocumentID = dataAccessLayerMetadata.databaseDocumentID; + entityIDs = dataAccessLayerMetadata.entityIDs; + + memoryHistory = createMemoryHistory(); // create a resolver simulator, using the data access layer and an arbitrary component instance ID - simulator = new Simulator({ databaseDocumentID, dataAccessLayer, resolverComponentInstanceID }); + simulator = () => { + if (simulatorInstance) { + return simulatorInstance; + } else { + simulatorInstance = new Simulator({ + databaseDocumentID: dataAccessLayerMetadata.databaseDocumentID, + dataAccessLayer, + resolverComponentInstanceID, + history: memoryHistory, + }); + return simulatorInstance; + } + }; }); - it('should show the node list', async () => { - await expect(simulator.map(() => simulator.nodeListElement().length)).toYieldEqualTo(1); + afterEach(() => { + simulatorInstance = undefined; }); - it('should have 3 nodes in the node list', async () => { - await expect(simulator.map(() => simulator.nodeListItems().length)).toYieldEqualTo(3); + const queryStringWithOriginSelected = urlSearch(resolverComponentInstanceID, { + selectedEntityID: 'origin', }); - describe('when there is an item in the node list and it has been clicked', () => { + + describe(`when the URL query string is ${queryStringWithOriginSelected}`, () => { + beforeEach(() => { + memoryHistory.push({ + search: queryStringWithOriginSelected, + }); + }); + it('should show the node details for the origin', async () => { + await expect( + simulator().map(() => { + const titleWrapper = simulator().nodeDetailViewTitle(); + const titleIconWrapper = simulator().nodeDetailViewTitleIcon(); + return { + title: titleWrapper.exists() ? titleWrapper.text() : null, + titleIcon: titleIconWrapper.exists() ? titleIconWrapper.text() : null, + detailEntries: simulator().nodeDetailDescriptionListEntries(), + }; + }) + ).toYieldEqualTo({ + title: 'c', + titleIcon: 'Running Process', + detailEntries: [ + ['process.executable', 'executable'], + ['process.pid', '0'], + ['user.name', 'user.name'], + ['user.domain', 'user.domain'], + ['process.parent.pid', '0'], + ['process.hash.md5', 'hash.md5'], + ['process.args', 'args'], + ], + }); + }); + }); + + const queryStringWithFirstChildSelected = urlSearch(resolverComponentInstanceID, { + selectedEntityID: 'firstChild', + }); + + describe(`when the URL query string is ${queryStringWithFirstChildSelected}`, () => { + beforeEach(() => { + memoryHistory.push({ + search: queryStringWithFirstChildSelected, + }); + }); + it('should show the node details for the first child', async () => { + await expect( + simulator().map(() => simulator().nodeDetailDescriptionListEntries()) + ).toYieldEqualTo([ + ['process.executable', 'executable'], + ['process.pid', '1'], + ['user.name', 'user.name'], + ['user.domain', 'user.domain'], + ['process.parent.pid', '0'], + ['process.hash.md5', 'hash.md5'], + ['process.args', 'args'], + ]); + }); + }); + + it('should have 3 nodes (with icons) in the node list', async () => { + await expect(simulator().map(() => simulator().nodeListNodeLinkText().length)).toYieldEqualTo( + 3 + ); + await expect(simulator().map(() => simulator().nodeListNodeLinkIcons().length)).toYieldEqualTo( + 3 + ); + }); + + describe('when there is an item in the node list and its text has been clicked', () => { beforeEach(async () => { - const nodeListItems = await simulator.resolveWrapper(() => simulator.nodeListItems()); - expect(nodeListItems && nodeListItems.length).toBeTruthy(); - if (nodeListItems) { - nodeListItems.first().find('button').simulate('click'); + const nodeLinks = await simulator().resolveWrapper(() => simulator().nodeListNodeLinkText()); + expect(nodeLinks).toBeTruthy(); + if (nodeLinks) { + nodeLinks.first().simulate('click'); } }); it('should show the details for the first node', async () => { await expect( - simulator.map(() => simulator.nodeDetailDescriptionListEntries()) + simulator().map(() => simulator().nodeDetailDescriptionListEntries()) ).toYieldEqualTo([ ['process.executable', 'executable'], ['process.pid', '0'], @@ -55,5 +151,29 @@ describe('Resolver: when analyzing a tree with no ancestors and two children', ( ['process.args', 'args'], ]); }); + it("should have the first node's ID in the query string", async () => { + await expect(simulator().map(() => simulator().queryStringValues())).toYieldEqualTo({ + selectedNode: [entityIDs.origin], + }); + }); + describe('and when the node list link has been clicked', () => { + beforeEach(async () => { + const nodeListLink = await simulator().resolveWrapper(() => + simulator().nodeDetailBreadcrumbNodeListLink() + ); + if (nodeListLink) { + nodeListLink.simulate('click'); + } + }); + it('should show the list of nodes with links to each node', async () => { + await expect( + simulator().map(() => { + return simulator() + .nodeListNodeLinkText() + .map((node) => node.text()); + }) + ).toYieldEqualTo(['c', 'd', 'e']); + }); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx index 0d8f65b4e39e6..b7c8ed0dfd7db 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/cube_for_process.tsx @@ -4,42 +4,55 @@ * you may not use this file except in compliance with the Elastic License. */ +import styled from 'styled-components'; + +import { i18n } from '@kbn/i18n'; + +/* eslint-disable react/display-name */ + import React, { memo } from 'react'; import { useResolverTheme } from '../assets'; /** - * During user testing, one user indicated they wanted to see stronger visual relationships between - * Nodes on the graph and what's in the table. Using the same symbol in both places (as below) could help with that. + * Icon representing a process node. */ -export const CubeForProcess = memo(function CubeForProcess({ - isProcessTerminated, +export const CubeForProcess = memo(function ({ + running, + 'data-test-subj': dataTestSubj, }: { - isProcessTerminated: boolean; + 'data-test-subj'?: string; + /** + * True if the process represented by the node is still running. + */ + running: boolean; }) { const { cubeAssetsForNode } = useResolverTheme(); - const { cubeSymbol, descriptionText } = cubeAssetsForNode(isProcessTerminated, false); + const { cubeSymbol } = cubeAssetsForNode(!running, false); return ( - <> - - {descriptionText} - - - + + + {i18n.translate('xpack.securitySolution.resolver.node_icon', { + defaultMessage: '{running, select, true {Running Process} false {Terminated Process}}', + values: { running }, + })} + + + ); }); + +const StyledSVG = styled.svg` + position: relative; + top: 0.4em; + margin-right: 0.25em; +`; diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx index 7e7e8b757baf7..b3c4eefe5fae7 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/index.tsx @@ -220,7 +220,7 @@ PanelContent.displayName = 'PanelContent'; export const Panel = memo(function Event({ className }: { className?: string }) { return ( - + ); diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/process_details.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/process_details.tsx index 112a3400c4947..adfcc4cc44d1f 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/process_details.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/process_details.tsx @@ -129,6 +129,7 @@ export const ProcessDetails = memo(function ProcessDetails({ defaultMessage: 'Events', } ), + 'data-test-subj': 'resolver:node-detail:breadcrumbs:node-list-link', onClick: () => { pushToQueryParams({ crumbId: '', crumbEvent: '' }); }, @@ -155,20 +156,23 @@ export const ProcessDetails = memo(function ProcessDetails({ return cubeAssetsForNode(isProcessTerminated, false); }, [processEvent, cubeAssetsForNode, isProcessTerminated]); - const titleId = useMemo(() => htmlIdGenerator('resolverTable')(), []); + const titleID = useMemo(() => htmlIdGenerator('resolverTable')(), []); return ( <> -

- - {processName} +

+ + {processName}

- {descriptionText} + {descriptionText} diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/process_list_with_counts.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/process_list_with_counts.tsx index 11f005f8acbcd..1be4b4b055243 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/process_list_with_counts.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/process_list_with_counts.tsx @@ -111,8 +111,11 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ }); }} > - - {name} + + {name} ); }, @@ -150,18 +153,10 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ const processTableView: ProcessTableView[] = useMemo( () => [...processNodePositions.keys()].map((processEvent) => { - let dateTime: Date | undefined; - const eventTime = event.timestampSafeVersion(processEvent); const name = event.processNameSafeVersion(processEvent); - if (eventTime) { - const date = new Date(eventTime); - if (isFinite(date.getTime())) { - dateTime = date; - } - } return { name, - timestamp: dateTime, + timestamp: event.timestampAsDateSafeVersion(processEvent), event: processEvent, }; }), @@ -172,12 +167,9 @@ export const ProcessListWithCounts = memo(function ProcessListWithCounts({ const crumbs = useMemo(() => { return [ { - text: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.panel.processListWithCounts.events', - { - defaultMessage: 'All Process Events', - } - ), + text: i18n.translate('xpack.securitySolution.resolver.panel.nodeList.title', { + defaultMessage: 'All Process Events', + }), onClick: () => {}, }, ]; diff --git a/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx b/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx index 7f0ba244146fd..359a4e2dafd2e 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/submenu.tsx @@ -4,8 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ +/* eslint-disable no-duplicate-imports */ + +/* eslint-disable react/display-name */ + import { i18n } from '@kbn/i18n'; -import React, { ReactNode, useState, useMemo, useCallback, useRef, useLayoutEffect } from 'react'; +import React, { useState, useMemo, useCallback, useRef, useLayoutEffect } from 'react'; import { EuiI18nNumber, EuiSelectable, @@ -15,6 +19,7 @@ import { htmlIdGenerator, } from '@elastic/eui'; import styled from 'styled-components'; +import { EuiSelectableOption } from '@elastic/eui'; import { Matrix3 } from '../types'; /** @@ -59,21 +64,21 @@ const OptionList = React.memo( subMenuOptions: ResolverSubmenuOptionList; isLoading: boolean; }) => { - const [options, setOptions] = useState(() => + const [options, setOptions] = useState(() => typeof subMenuOptions !== 'object' ? [] - : subMenuOptions.map((opt: ResolverSubmenuOption): { - label: string; - prepend?: ReactNode; - } => { - return opt.prefix + : subMenuOptions.map((option: ResolverSubmenuOption) => { + const dataTestSubj = 'resolver:map:node-submenu-item'; + return option.prefix ? { - label: opt.optionTitle, - prepend: {opt.prefix} , + label: option.optionTitle, + prepend: {option.prefix} , + 'data-test-subj': dataTestSubj, } : { - label: opt.optionTitle, + label: option.optionTitle, prepend: , + 'data-test-subj': dataTestSubj, }; }) ); @@ -88,11 +93,10 @@ const OptionList = React.memo( }, {}); }, [subMenuOptions]); - type ChangeOptions = Array<{ label: string; prepend?: ReactNode; checked?: string }>; const selectableProps = useMemo(() => { return { listProps: { showIcons: true, bordered: true }, - onChange: (newOptions: ChangeOptions) => { + onChange: (newOptions: EuiSelectableOption[]) => { const selectedOption = newOptions.find((opt) => opt.checked === 'on'); if (selectedOption) { const { label } = selectedOption; @@ -119,8 +123,6 @@ const OptionList = React.memo( } ); -OptionList.displayName = 'OptionList'; - /** * A Submenu to be displayed in one of two forms: * 1) Provided a collection of `optionsWithActions`: it will call `menuAction` then - if and when menuData becomes available - display each item with an optional prefix and call the supplied action for the options when that option is clicked. @@ -259,8 +261,6 @@ const NodeSubMenuComponents = React.memo( } ); -NodeSubMenuComponents.displayName = 'NodeSubMenu'; - export const NodeSubMenu = styled(NodeSubMenuComponents)` margin: 2px 0 0 0; padding: 0; diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 720ec2892093b..f2aeed63d6eea 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -4283,7 +4283,6 @@ "visTypeVega.vegaParser.dataExceedsSomeParamsUseTimesLimitErrorMessage": "データには {urlParam}、{valuesParam}、 {sourceParam} の内複数を含めることができません", "visTypeVega.vegaParser.hostConfigIsDeprecatedWarningMessage": "{deprecatedConfigName} は廃止されました。代わりに {newConfigName} を使用してください。", "visTypeVega.vegaParser.hostConfigValueTypeErrorMessage": "{configName} が含まれている場合、オブジェクトでなければなりません", - "visTypeVega.vegaParser.inputSpecDoesNotSpecifySchemaWarningMessage": "インプット仕様で {schemaParam} が指定されていないため、デフォルトで {defaultSchema} になります", "visTypeVega.vegaParser.invalidVegaSpecErrorMessage": "無効な Vega 仕様", "visTypeVega.vegaParser.kibanaConfigValueTypeErrorMessage": "{configName} が含まれている場合、オブジェクトでなければなりません", "visTypeVega.vegaParser.mapStyleValueTypeWarningMessage": "{mapStyleConfigName} は {mapStyleConfigFirstAllowedValue} か {mapStyleConfigSecondAllowedValue} のどちらかです", @@ -16233,65 +16232,65 @@ "xpack.securitySolution.editDataProvider.valuePlaceholder": "値", "xpack.securitySolution.emptyMessage": "Elastic セキュリティは無料かつオープンのElastic SIEMに、Elastic Endpointを搭載。脅威の防御と検知、脅威への対応を支援します。開始するには、セキュリティソリューション関連データをElastic Stackに追加する必要があります。詳細については、ご覧ください ", "xpack.securitySolution.emptyString.emptyStringDescription": "空の文字列", - "xpack.securitySolution.endpoint.host.details.endpointVersion": "エンドポイントバージョン", - "xpack.securitySolution.endpoint.host.details.errorBody": "フライアウトを終了して、利用可能なホストを選択してください。", - "xpack.securitySolution.endpoint.host.details.errorTitle": "ホストが見つかりませんでした", - "xpack.securitySolution.endpoint.host.details.hostname": "ホスト名", - "xpack.securitySolution.endpoint.host.details.ipAddress": "IP アドレス", - "xpack.securitySolution.endpoint.host.details.lastSeen": "前回の認識", - "xpack.securitySolution.endpoint.host.details.linkToIngestTitle": "ポリシーの再割り当て", - "xpack.securitySolution.endpoint.host.details.os": "OS", - "xpack.securitySolution.endpoint.host.details.policy": "ポリシー", - "xpack.securitySolution.endpoint.host.details.policyStatus": "ポリシーステータス", - "xpack.securitySolution.endpoint.host.details.policyStatusValue": "{policyStatus, select, success {成功} warning {警告} failure {失敗} other {不明}}", - "xpack.securitySolution.endpoint.host.policyResponse.backLinkTitle": "エンドポイント詳細", - "xpack.securitySolution.endpoint.host.policyResponse.title": "ポリシー応答", - "xpack.securitySolution.endpoint.hostDetails.noPolicyResponse": "ポリシー応答がありません", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_dns_events": "DNSイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_elasticsearch_connection": "Elastic Search接続の構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_file_events": "ファイルイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_imageload_events": "画像読み込みイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_kernel": "カーネルの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_logging": "ロギングの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_malware": "マルウェアの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_network_events": "ネットワークイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_process_events": "プロセスイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_registry_events": "レジストリイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_security_events": "セキュリティイベントの構成", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.connect_kernel": "カーネルを接続", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_async_image_load_events": "非同期画像読み込みイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_file_open_events": "ファイルオープンイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_file_write_events": "ファイル書き込みイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_network_events": "ネットワークイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_process_events": "プロセスイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_registry_events": "レジストリイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_sync_image_load_events": "同期画像読み込みイベントを検出", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.download_global_artifacts": "グローバルアーチファクトをダウンロード", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.download_user_artifacts": "ユーザーアーチファクトをダウンロード", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.events": "イベント", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.failed": "失敗", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.load_config": "構成の読み込み", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.load_malware_model": "マルウェアモデルの読み込み", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.logging": "ログ", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.malware": "マルウェア", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_elasticsearch_config": "Elasticsearch構成を読み取る", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_events_config": "イベント構成を読み取る", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_kernel_config": "カーネル構成を読み取る", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_logging_config": "ロギング構成を読み取る", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_malware_config": "マルウェア構成を読み取る", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.streaming": "ストリーム中…", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.success": "成功", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.warning": "警告", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.workflow": "ワークフロー", - "xpack.securitySolution.endpoint.hostList.beta": "ベータ", - "xpack.securitySolution.endpoint.hostList.loadingPolicies": "ポリシー構成を読み込んでいます…", - "xpack.securitySolution.endpoint.hostList.noEndpointsInstructions": "セキュリティポリシーを作成しました。以下のステップに従い、エージェントでElastic Endpoint Security機能を有効にする必要があります。", - "xpack.securitySolution.endpoint.hostList.noEndpointsPrompt": "エージェントでElastic Endpoint Securityを有効にする", - "xpack.securitySolution.endpoint.hostList.noPolicies": "ポリシーがありません。", - "xpack.securitySolution.endpoint.hostList.stepOne": "既存のポリシーは以下のリストのとおりです。これは後から変更できます。", - "xpack.securitySolution.endpoint.hostList.stepOneTitle": "ホストの保護で使用するポリシーを選択", - "xpack.securitySolution.endpoint.hostList.stepTwo": "開始するために必要なコマンドが提供されます。", - "xpack.securitySolution.endpoint.hostList.stepTwoTitle": "Ingest Manager経由でEndpoint Securityによって有効にされたエージェントを登録", + "xpack.securitySolution.endpoint.details.endpointVersion": "エンドポイントバージョン", + "xpack.securitySolution.endpoint.details.errorBody": "フライアウトを終了して、利用可能なホストを選択してください。", + "xpack.securitySolution.endpoint.details.errorTitle": "ホストが見つかりませんでした", + "xpack.securitySolution.endpoint.details.hostname": "ホスト名", + "xpack.securitySolution.endpoint.details.ipAddress": "IP アドレス", + "xpack.securitySolution.endpoint.details.lastSeen": "前回の認識", + "xpack.securitySolution.endpoint.details.linkToIngestTitle": "ポリシーの再割り当て", + "xpack.securitySolution.endpoint.details.os": "OS", + "xpack.securitySolution.endpoint.details.policy": "ポリシー", + "xpack.securitySolution.endpoint.details.policyStatus": "ポリシーステータス", + "xpack.securitySolution.endpoint.details.policyStatusValue": "{policyStatus, select, success {成功} warning {警告} failure {失敗} other {不明}}", + "xpack.securitySolution.endpoint.policyResponse.backLinkTitle": "エンドポイント詳細", + "xpack.securitySolution.endpoint.policyResponse.title": "ポリシー応答", + "xpack.securitySolution.endpoint.details.noPolicyResponse": "ポリシー応答がありません", + "xpack.securitySolution.endpoint.details.policyResponse.configure_dns_events": "DNSイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_elasticsearch_connection": "Elastic Search接続の構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_file_events": "ファイルイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_imageload_events": "画像読み込みイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_kernel": "カーネルの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_logging": "ロギングの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_malware": "マルウェアの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_network_events": "ネットワークイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_process_events": "プロセスイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_registry_events": "レジストリイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.configure_security_events": "セキュリティイベントの構成", + "xpack.securitySolution.endpoint.details.policyResponse.connect_kernel": "カーネルを接続", + "xpack.securitySolution.endpoint.details.policyResponse.detect_async_image_load_events": "非同期画像読み込みイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.detect_file_open_events": "ファイルオープンイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.detect_file_write_events": "ファイル書き込みイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.detect_network_events": "ネットワークイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.detect_process_events": "プロセスイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.detect_registry_events": "レジストリイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.detect_sync_image_load_events": "同期画像読み込みイベントを検出", + "xpack.securitySolution.endpoint.details.policyResponse.download_global_artifacts": "グローバルアーチファクトをダウンロード", + "xpack.securitySolution.endpoint.details.policyResponse.download_user_artifacts": "ユーザーアーチファクトをダウンロード", + "xpack.securitySolution.endpoint.details.policyResponse.events": "イベント", + "xpack.securitySolution.endpoint.details.policyResponse.failed": "失敗", + "xpack.securitySolution.endpoint.details.policyResponse.load_config": "構成の読み込み", + "xpack.securitySolution.endpoint.details.policyResponse.load_malware_model": "マルウェアモデルの読み込み", + "xpack.securitySolution.endpoint.details.policyResponse.logging": "ログ", + "xpack.securitySolution.endpoint.details.policyResponse.malware": "マルウェア", + "xpack.securitySolution.endpoint.details.policyResponse.read_elasticsearch_config": "Elasticsearch構成を読み取る", + "xpack.securitySolution.endpoint.details.policyResponse.read_events_config": "イベント構成を読み取る", + "xpack.securitySolution.endpoint.details.policyResponse.read_kernel_config": "カーネル構成を読み取る", + "xpack.securitySolution.endpoint.details.policyResponse.read_logging_config": "ロギング構成を読み取る", + "xpack.securitySolution.endpoint.details.policyResponse.read_malware_config": "マルウェア構成を読み取る", + "xpack.securitySolution.endpoint.details.policyResponse.streaming": "ストリーム中…", + "xpack.securitySolution.endpoint.details.policyResponse.success": "成功", + "xpack.securitySolution.endpoint.details.policyResponse.warning": "警告", + "xpack.securitySolution.endpoint.details.policyResponse.workflow": "ワークフロー", + "xpack.securitySolution.endpoint.list.beta": "ベータ", + "xpack.securitySolution.endpoint.list.loadingPolicies": "ポリシー構成を読み込んでいます…", + "xpack.securitySolution.endpoint.list.noEndpointsInstructions": "セキュリティポリシーを作成しました。以下のステップに従い、エージェントでElastic Endpoint Security機能を有効にする必要があります。", + "xpack.securitySolution.endpoint.list.noEndpointsPrompt": "エージェントでElastic Endpoint Securityを有効にする", + "xpack.securitySolution.endpoint.list.noPolicies": "ポリシーがありません。", + "xpack.securitySolution.endpoint.list.stepOne": "既存のポリシーは以下のリストのとおりです。これは後から変更できます。", + "xpack.securitySolution.endpoint.list.stepOneTitle": "ホストの保護で使用するポリシーを選択", + "xpack.securitySolution.endpoint.list.stepTwo": "開始するために必要なコマンドが提供されます。", + "xpack.securitySolution.endpoint.list.stepTwoTitle": "Ingest Manager経由でEndpoint Securityによって有効にされたエージェントを登録", "xpack.securitySolution.endpoint.ingestManager.createPackageConfig.endpointConfiguration": "このエージェント構成を使用するすべてのエージェントは基本ポリシーを使用します。セキュリティアプリでこのポリシーを変更できます。Fleetはこれらの変更をエージェントにデプロイします。", "xpack.securitySolution.endpoint.ingestToastMessage": "Ingest Managerが設定中に失敗しました。", "xpack.securitySolution.endpoint.ingestToastTitle": "アプリを初期化できませんでした", @@ -16381,7 +16380,7 @@ "xpack.securitySolution.endpoint.resolver.panel.processEventListByType.eventDescriptiveName": "{descriptor} {subject}", "xpack.securitySolution.endpoint.resolver.panel.processEventListByType.events": "イベント", "xpack.securitySolution.endpoint.resolver.panel.processEventListByType.wait": "イベントを待機しています...", - "xpack.securitySolution.endpoint.resolver.panel.processListWithCounts.events": "すべてのプロセスイベント", + "xpack.securitySolution.resolver.panel.nodeList.title": "すべてのプロセスイベント", "xpack.securitySolution.endpoint.resolver.panel.relatedCounts.numberOfEventsInCrumb": "{totalCount}件のイベント", "xpack.securitySolution.endpoint.resolver.panel.relatedDetail.missing": "関連イベントが見つかりません。", "xpack.securitySolution.endpoint.resolver.panel.relatedDetail.wait": "イベントを待機しています...", @@ -16412,16 +16411,16 @@ "xpack.securitySolution.endpoint.resolver.runningTrigger": "トリガーの実行中", "xpack.securitySolution.endpoint.resolver.terminatedProcess": "プロセスを中断しました", "xpack.securitySolution.endpoint.resolver.terminatedTrigger": "トリガーを中断しました", - "xpack.securitySolution.endpointList.endpointVersion": "バージョン", - "xpack.securitySolution.endpointList.hostname": "ホスト名", - "xpack.securitySolution.endpointList.hostStatus": "ホストステータス", - "xpack.securitySolution.endpointList.hostStatusValue": "{hostStatus, select, online {オンライン} error {エラー} other {オフライン}}", - "xpack.securitySolution.endpointList.ip": "IP アドレス", - "xpack.securitySolution.endpointList.lastActive": "前回のアーカイブ", - "xpack.securitySolution.endpointList.os": "オペレーティングシステム", - "xpack.securitySolution.endpointList.policy": "ポリシー", - "xpack.securitySolution.endpointList.policyStatus": "ポリシーステータス", - "xpack.securitySolution.endpointList.totalCount": "{totalItemCount, plural, one {# ホスト} other {# ホスト}}", + "xpack.securitySolution.endpoint.list.endpointVersion": "バージョン", + "xpack.securitySolution.endpoint.list.hostname": "ホスト名", + "xpack.securitySolution.endpoint.list.hostStatus": "ホストステータス", + "xpack.securitySolution.endpoint.list.hostStatusValue": "{hostStatus, select, online {オンライン} error {エラー} other {オフライン}}", + "xpack.securitySolution.endpoint.list.ip": "IP アドレス", + "xpack.securitySolution.endpoint.list.lastActive": "前回のアーカイブ", + "xpack.securitySolution.endpoint.list.os": "オペレーティングシステム", + "xpack.securitySolution.endpoint.list.policy": "ポリシー", + "xpack.securitySolution.endpoint.list.policyStatus": "ポリシーステータス", + "xpack.securitySolution.endpoint.list.totalCount": "{totalItemCount, plural, one {# ホスト} other {# ホスト}}", "xpack.securitySolution.endpointManagement.noPermissionsSubText": "Ingest Managerが無効である可能性があります。この機能を使用するには、Ingest Managerを有効にする必要があります。Ingest Managerを有効にする権限がない場合は、Kibana管理者に連絡してください。", "xpack.securitySolution.endpointManagemnet.noPermissionsText": "Elastic Security Administrationを使用するために必要なKibana権限がありません。", "xpack.securitySolution.enpdoint.resolver.panelutils.betaBadgeLabel": "BETA", @@ -16610,8 +16609,8 @@ "xpack.securitySolution.host.details.overview.platformTitle": "プラットフォーム", "xpack.securitySolution.host.details.overview.regionTitle": "地域", "xpack.securitySolution.host.details.versionLabel": "バージョン", - "xpack.securitySolution.hostList.pageSubTitle": "Elastic Endpoint Securityを実行しているホスト", - "xpack.securitySolution.hostList.pageTitle": "ホスト", + "xpack.securitySolution.endpoint.list.pageSubTitle": "Elastic Endpoint Securityを実行しているホスト", + "xpack.securitySolution.endpoint.list.pageTitle": "ホスト", "xpack.securitySolution.hosts.kqlPlaceholder": "例:host.name: \"foo\"", "xpack.securitySolution.hosts.navigation.alertsTitle": "外部アラート", "xpack.securitySolution.hosts.navigation.allHostsTitle": "すべてのホスト", @@ -16623,7 +16622,7 @@ "xpack.securitySolution.hosts.navigaton.matrixHistogram.errorFetchingAuthenticationsData": "認証データをクエリできませんでした", "xpack.securitySolution.hosts.navigaton.matrixHistogram.errorFetchingEventsData": "イベントデータをクエリできませんでした", "xpack.securitySolution.hosts.pageTitle": "ホスト", - "xpack.securitySolution.hostsTab": "ホスト", + "xpack.securitySolution.endpointsTab": "ホスト", "xpack.securitySolution.hostsTable.firstLastSeenToolTip": "選択された日付範囲との相関付けです", "xpack.securitySolution.hostsTable.hostsTitle": "すべてのホスト", "xpack.securitySolution.hostsTable.lastSeenTitle": "前回の認識", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 69820834cad5d..82a6b128ad619 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -4284,7 +4284,6 @@ "visTypeVega.vegaParser.dataExceedsSomeParamsUseTimesLimitErrorMessage": "数据不得包含 {urlParam}、{valuesParam} 和 {sourceParam} 中的多个值", "visTypeVega.vegaParser.hostConfigIsDeprecatedWarningMessage": "{deprecatedConfigName} 已弃用。请改用 {newConfigName}。", "visTypeVega.vegaParser.hostConfigValueTypeErrorMessage": "如果存在,{configName} 必须为对象", - "visTypeVega.vegaParser.inputSpecDoesNotSpecifySchemaWarningMessage": "输入规范未指定 {schemaParam},其默认值为 {defaultSchema}", "visTypeVega.vegaParser.invalidVegaSpecErrorMessage": "Vega 规范无效", "visTypeVega.vegaParser.kibanaConfigValueTypeErrorMessage": "如果存在,{configName} 必须为对象", "visTypeVega.vegaParser.mapStyleValueTypeWarningMessage": "{mapStyleConfigName} 可能为 {mapStyleConfigFirstAllowedValue} 或 {mapStyleConfigSecondAllowedValue}", @@ -16238,65 +16237,65 @@ "xpack.securitySolution.editDataProvider.valuePlaceholder": "值", "xpack.securitySolution.emptyMessage": "Elastic Security 将免费且开放的 Elastic SIEM 和 Elastic Endpoint Security 整合在一起,从而防御、检测并响应威胁。首先,您需要将安全解决方案相关数据添加到 Elastic Stack。有关更多信息,请查看我们的 ", "xpack.securitySolution.emptyString.emptyStringDescription": "空字符串", - "xpack.securitySolution.endpoint.host.details.endpointVersion": "Endpoint 版本", - "xpack.securitySolution.endpoint.host.details.errorBody": "请退出浮出控件并选择可用主机。", - "xpack.securitySolution.endpoint.host.details.errorTitle": "找不到主机", - "xpack.securitySolution.endpoint.host.details.hostname": "主机名", - "xpack.securitySolution.endpoint.host.details.ipAddress": "IP 地址", - "xpack.securitySolution.endpoint.host.details.lastSeen": "最后看到时间", - "xpack.securitySolution.endpoint.host.details.linkToIngestTitle": "重新分配策略", - "xpack.securitySolution.endpoint.host.details.os": "OS", - "xpack.securitySolution.endpoint.host.details.policy": "政策", - "xpack.securitySolution.endpoint.host.details.policyStatus": "策略状态", - "xpack.securitySolution.endpoint.host.details.policyStatusValue": "{policyStatus, select, success {成功} warning {警告} failure {失败} other {未知}}", - "xpack.securitySolution.endpoint.host.policyResponse.backLinkTitle": "终端详情", - "xpack.securitySolution.endpoint.host.policyResponse.title": "策略响应", - "xpack.securitySolution.endpoint.hostDetails.noPolicyResponse": "没有可用的策略响应", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_dns_events": "配置 DNS 事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_elasticsearch_connection": "配置 Elastic 搜索连接", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_file_events": "配置文件事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_imageload_events": "配置映像加载事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_kernel": "配置内核", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_logging": "配置日志记录", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_malware": "配置恶意软件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_network_events": "配置网络事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_process_events": "配置进程事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_registry_events": "配置注册表事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.configure_security_events": "配置安全事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.connect_kernel": "连接内核", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_async_image_load_events": "检测异步映像加载事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_file_open_events": "检测文件打开事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_file_write_events": "检测文件写入事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_network_events": "检测网络事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_process_events": "检测进程事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_registry_events": "检测注册表事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.detect_sync_image_load_events": "检测同步映像加载事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.download_global_artifacts": "下载全局项目", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.download_user_artifacts": "下面用户项目", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.events": "事件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.failed": "失败", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.load_config": "加载配置", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.load_malware_model": "加载恶意软件模型", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.logging": "日志", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.malware": "恶意软件", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_elasticsearch_config": "读取 ElasticSearch 配置", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_events_config": "读取时间配置", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_kernel_config": "读取内核配置", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_logging_config": "读取日志配置", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.read_malware_config": "读取恶意软件配置", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.streaming": "流式传输", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.success": "成功", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.warning": "警告", - "xpack.securitySolution.endpoint.hostDetails.policyResponse.workflow": "工作流", - "xpack.securitySolution.endpoint.hostList.beta": "公测版", - "xpack.securitySolution.endpoint.hostList.loadingPolicies": "正在加载政策配置", - "xpack.securitySolution.endpoint.hostList.noEndpointsInstructions": "您已创建安全策略。现在您需要按照下面的步骤在代理上启用 Elastic Endpoint Security 功能。", - "xpack.securitySolution.endpoint.hostList.noEndpointsPrompt": "在您的代理上启用 Elastic Endpoint Security", - "xpack.securitySolution.endpoint.hostList.noPolicies": "没有策略。", - "xpack.securitySolution.endpoint.hostList.stepOne": "现有策略在下面列出。之后可以对其进行更改。", - "xpack.securitySolution.endpoint.hostList.stepOneTitle": "选择要用于保护主机的策略", - "xpack.securitySolution.endpoint.hostList.stepTwo": "为了让您入门,将会为您提供必要的命令。", - "xpack.securitySolution.endpoint.hostList.stepTwoTitle": "通过采集管理器注册启用 Endpoint Security 的代理", + "xpack.securitySolution.endpoint.details.endpointVersion": "Endpoint 版本", + "xpack.securitySolution.endpoint.details.errorBody": "请退出浮出控件并选择可用主机。", + "xpack.securitySolution.endpoint.details.errorTitle": "找不到主机", + "xpack.securitySolution.endpoint.details.hostname": "主机名", + "xpack.securitySolution.endpoint.details.ipAddress": "IP 地址", + "xpack.securitySolution.endpoint.details.lastSeen": "最后看到时间", + "xpack.securitySolution.endpoint.details.linkToIngestTitle": "重新分配策略", + "xpack.securitySolution.endpoint.details.os": "OS", + "xpack.securitySolution.endpoint.details.policy": "政策", + "xpack.securitySolution.endpoint.details.policyStatus": "策略状态", + "xpack.securitySolution.endpoint.details.policyStatusValue": "{policyStatus, select, success {成功} warning {警告} failure {失败} other {未知}}", + "xpack.securitySolution.endpoint.policyResponse.backLinkTitle": "终端详情", + "xpack.securitySolution.endpoint.policyResponse.title": "策略响应", + "xpack.securitySolution.endpoint.details.noPolicyResponse": "没有可用的策略响应", + "xpack.securitySolution.endpoint.details.policyResponse.configure_dns_events": "配置 DNS 事件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_elasticsearch_connection": "配置 Elastic 搜索连接", + "xpack.securitySolution.endpoint.details.policyResponse.configure_file_events": "配置文件事件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_imageload_events": "配置映像加载事件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_kernel": "配置内核", + "xpack.securitySolution.endpoint.details.policyResponse.configure_logging": "配置日志记录", + "xpack.securitySolution.endpoint.details.policyResponse.configure_malware": "配置恶意软件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_network_events": "配置网络事件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_process_events": "配置进程事件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_registry_events": "配置注册表事件", + "xpack.securitySolution.endpoint.details.policyResponse.configure_security_events": "配置安全事件", + "xpack.securitySolution.endpoint.details.policyResponse.connect_kernel": "连接内核", + "xpack.securitySolution.endpoint.details.policyResponse.detect_async_image_load_events": "检测异步映像加载事件", + "xpack.securitySolution.endpoint.details.policyResponse.detect_file_open_events": "检测文件打开事件", + "xpack.securitySolution.endpoint.details.policyResponse.detect_file_write_events": "检测文件写入事件", + "xpack.securitySolution.endpoint.details.policyResponse.detect_network_events": "检测网络事件", + "xpack.securitySolution.endpoint.details.policyResponse.detect_process_events": "检测进程事件", + "xpack.securitySolution.endpoint.details.policyResponse.detect_registry_events": "检测注册表事件", + "xpack.securitySolution.endpoint.details.policyResponse.detect_sync_image_load_events": "检测同步映像加载事件", + "xpack.securitySolution.endpoint.details.policyResponse.download_global_artifacts": "下载全局项目", + "xpack.securitySolution.endpoint.details.policyResponse.download_user_artifacts": "下面用户项目", + "xpack.securitySolution.endpoint.details.policyResponse.events": "事件", + "xpack.securitySolution.endpoint.details.policyResponse.failed": "失败", + "xpack.securitySolution.endpoint.details.policyResponse.load_config": "加载配置", + "xpack.securitySolution.endpoint.details.policyResponse.load_malware_model": "加载恶意软件模型", + "xpack.securitySolution.endpoint.details.policyResponse.logging": "日志", + "xpack.securitySolution.endpoint.details.policyResponse.malware": "恶意软件", + "xpack.securitySolution.endpoint.details.policyResponse.read_elasticsearch_config": "读取 ElasticSearch 配置", + "xpack.securitySolution.endpoint.details.policyResponse.read_events_config": "读取时间配置", + "xpack.securitySolution.endpoint.details.policyResponse.read_kernel_config": "读取内核配置", + "xpack.securitySolution.endpoint.details.policyResponse.read_logging_config": "读取日志配置", + "xpack.securitySolution.endpoint.details.policyResponse.read_malware_config": "读取恶意软件配置", + "xpack.securitySolution.endpoint.details.policyResponse.streaming": "流式传输", + "xpack.securitySolution.endpoint.details.policyResponse.success": "成功", + "xpack.securitySolution.endpoint.details.policyResponse.warning": "警告", + "xpack.securitySolution.endpoint.details.policyResponse.workflow": "工作流", + "xpack.securitySolution.endpoint.list.beta": "公测版", + "xpack.securitySolution.endpoint.list.loadingPolicies": "正在加载政策配置", + "xpack.securitySolution.endpoint.list.noEndpointsInstructions": "您已创建安全策略。现在您需要按照下面的步骤在代理上启用 Elastic Endpoint Security 功能。", + "xpack.securitySolution.endpoint.list.noEndpointsPrompt": "在您的代理上启用 Elastic Endpoint Security", + "xpack.securitySolution.endpoint.list.noPolicies": "没有策略。", + "xpack.securitySolution.endpoint.list.stepOne": "现有策略在下面列出。之后可以对其进行更改。", + "xpack.securitySolution.endpoint.list.stepOneTitle": "选择要用于保护主机的策略", + "xpack.securitySolution.endpoint.list.stepTwo": "为了让您入门,将会为您提供必要的命令。", + "xpack.securitySolution.endpoint.list.stepTwoTitle": "通过采集管理器注册启用 Endpoint Security 的代理", "xpack.securitySolution.endpoint.ingestManager.createPackageConfig.endpointConfiguration": "使用此代理配置的任何代理都会使用基本策略。可以在 Security 应用中对此策略进行更改,Fleet 会将这些更改部署到代理。", "xpack.securitySolution.endpoint.ingestToastMessage": "采集管理器在其设置期间失败。", "xpack.securitySolution.endpoint.ingestToastTitle": "应用无法初始化", @@ -16387,7 +16386,7 @@ "xpack.securitySolution.endpoint.resolver.panel.processEventListByType.eventDescriptiveName": "{descriptor} {subject}", "xpack.securitySolution.endpoint.resolver.panel.processEventListByType.events": "事件", "xpack.securitySolution.endpoint.resolver.panel.processEventListByType.wait": "等候事件......", - "xpack.securitySolution.endpoint.resolver.panel.processListWithCounts.events": "所有进程事件", + "xpack.securitySolution.resolver.panel.nodeList.title": "所有进程事件", "xpack.securitySolution.endpoint.resolver.panel.relatedCounts.numberOfEventsInCrumb": "{totalCount} 个事件", "xpack.securitySolution.endpoint.resolver.panel.relatedDetail.missing": "找不到相关事件。", "xpack.securitySolution.endpoint.resolver.panel.relatedDetail.wait": "等候事件......", @@ -16418,16 +16417,16 @@ "xpack.securitySolution.endpoint.resolver.runningTrigger": "正在运行的触发器", "xpack.securitySolution.endpoint.resolver.terminatedProcess": "已终止进程", "xpack.securitySolution.endpoint.resolver.terminatedTrigger": "已终止触发器", - "xpack.securitySolution.endpointList.endpointVersion": "版本", - "xpack.securitySolution.endpointList.hostname": "主机名", - "xpack.securitySolution.endpointList.hostStatus": "主机状态", - "xpack.securitySolution.endpointList.hostStatusValue": "{hostStatus, select, online {联机} error {错误} other {脱机}}", - "xpack.securitySolution.endpointList.ip": "IP 地址", - "xpack.securitySolution.endpointList.lastActive": "上次活动时间", - "xpack.securitySolution.endpointList.os": "操作系统", - "xpack.securitySolution.endpointList.policy": "政策", - "xpack.securitySolution.endpointList.policyStatus": "策略状态", - "xpack.securitySolution.endpointList.totalCount": "{totalItemCount, plural, one {# 个主机} other {# 个主机}}", + "xpack.securitySolution.endpoint.list.endpointVersion": "版本", + "xpack.securitySolution.endpoint.list.hostname": "主机名", + "xpack.securitySolution.endpoint.list.hostStatus": "主机状态", + "xpack.securitySolution.endpoint.list.hostStatusValue": "{hostStatus, select, online {联机} error {错误} other {脱机}}", + "xpack.securitySolution.endpoint.list.ip": "IP 地址", + "xpack.securitySolution.endpoint.list.lastActive": "上次活动时间", + "xpack.securitySolution.endpoint.list.os": "操作系统", + "xpack.securitySolution.endpoint.list.policy": "政策", + "xpack.securitySolution.endpoint.list.policyStatus": "策略状态", + "xpack.securitySolution.endpoint.list.totalCount": "{totalItemCount, plural, one {# 个主机} other {# 个主机}}", "xpack.securitySolution.endpointManagement.noPermissionsSubText": "似乎采集管理器已禁用。必须启用采集管理器,才能使用此功能。如果您无权启用采集管理器,请联系您的 Kibana 管理员。", "xpack.securitySolution.endpointManagemnet.noPermissionsText": "您没有所需的 Kibana 权限,无法使用 Elastic Security 管理", "xpack.securitySolution.enpdoint.resolver.panelutils.betaBadgeLabel": "公测版", @@ -16616,8 +16615,8 @@ "xpack.securitySolution.host.details.overview.platformTitle": "平台", "xpack.securitySolution.host.details.overview.regionTitle": "地区", "xpack.securitySolution.host.details.versionLabel": "版本", - "xpack.securitySolution.hostList.pageSubTitle": "运行 Elastic Endpoint Security 的主机", - "xpack.securitySolution.hostList.pageTitle": "主机", + "xpack.securitySolution.endpoint.list.pageSubTitle": "运行 Elastic Endpoint Security 的主机", + "xpack.securitySolution.endpoint.list.pageTitle": "主机", "xpack.securitySolution.hosts.kqlPlaceholder": "例如 host.name:“foo”", "xpack.securitySolution.hosts.navigation.alertsTitle": "外部告警", "xpack.securitySolution.hosts.navigation.allHostsTitle": "所有主机", @@ -16629,7 +16628,7 @@ "xpack.securitySolution.hosts.navigaton.matrixHistogram.errorFetchingAuthenticationsData": "无法查询身份验证数据", "xpack.securitySolution.hosts.navigaton.matrixHistogram.errorFetchingEventsData": "无法查询事件数据", "xpack.securitySolution.hosts.pageTitle": "主机", - "xpack.securitySolution.hostsTab": "主机", + "xpack.securitySolution.endpointsTab": "主机", "xpack.securitySolution.hostsTable.firstLastSeenToolTip": "相对于选定日期范围", "xpack.securitySolution.hostsTable.hostsTitle": "所有主机", "xpack.securitySolution.hostsTable.lastSeenTitle": "最后看到时间", diff --git a/x-pack/test/functional/apps/dashboard/reporting/screenshots.ts b/x-pack/test/functional/apps/dashboard/reporting/screenshots.ts index da1131d051581..cf70e5a7b8b6c 100644 --- a/x-pack/test/functional/apps/dashboard/reporting/screenshots.ts +++ b/x-pack/test/functional/apps/dashboard/reporting/screenshots.ts @@ -16,12 +16,13 @@ const mkdirAsync = promisify(fs.mkdir); const REPORTS_FOLDER = path.resolve(__dirname, 'reports'); -export default function ({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const PageObjects = getPageObjects(['reporting', 'common', 'dashboard']); const esArchiver = getService('esArchiver'); const browser = getService('browser'); const log = getService('log'); const config = getService('config'); - const PageObjects = getPageObjects(['reporting', 'common', 'dashboard']); + const es = getService('es'); describe('Screenshots', () => { before('initialize tests', async () => { @@ -33,6 +34,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { after('clean up archives', async () => { await esArchiver.unload('reporting/ecommerce'); await esArchiver.unload('reporting/ecommerce_kibana'); + await es.deleteByQuery({ + index: '.reporting-*', + refresh: true, + body: { query: { match_all: {} } }, + }); }); describe('Print PDF button', () => { diff --git a/x-pack/test/functional/apps/discover/reporting.ts b/x-pack/test/functional/apps/discover/reporting.ts index 32ccc59913dbc..7181bf0c74271 100644 --- a/x-pack/test/functional/apps/discover/reporting.ts +++ b/x-pack/test/functional/apps/discover/reporting.ts @@ -9,6 +9,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { const log = getService('log'); + const es = getService('es'); const esArchiver = getService('esArchiver'); const browser = getService('browser'); const PageObjects = getPageObjects(['reporting', 'common', 'discover']); @@ -22,6 +23,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { }); after('clean up archives', async () => { await esArchiver.unload('reporting/ecommerce'); + await es.deleteByQuery({ + index: '.reporting-*', + refresh: true, + body: { query: { match_all: {} } }, + }); }); describe('Generate CSV button', () => { diff --git a/x-pack/test/functional/apps/lens/lens_reporting.ts b/x-pack/test/functional/apps/lens/lens_reporting.ts index 3e3d217b9d8d7..4974b63be6f72 100644 --- a/x-pack/test/functional/apps/lens/lens_reporting.ts +++ b/x-pack/test/functional/apps/lens/lens_reporting.ts @@ -9,6 +9,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'dashboard', 'reporting']); + const es = getService('es'); const esArchiver = getService('esArchiver'); const listingTable = getService('listingTable'); @@ -19,6 +20,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { after(async () => { await esArchiver.unload('lens/reporting'); + await es.deleteByQuery({ + index: '.reporting-*', + refresh: true, + body: { query: { match_all: {} } }, + }); }); it('should not cause PDF reports to fail', async () => { diff --git a/x-pack/test/functional/apps/reporting_management/index.ts b/x-pack/test/functional/apps/reporting_management/index.ts index f44d5858d53a1..8606c46053ab0 100644 --- a/x-pack/test/functional/apps/reporting_management/index.ts +++ b/x-pack/test/functional/apps/reporting_management/index.ts @@ -9,6 +9,6 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default ({ loadTestFile }: FtrProviderContext) => { describe('reporting management app', function () { this.tags('ciGroup7'); - loadTestFile(require.resolve('./report_delete_pagination')); + loadTestFile(require.resolve('./report_listing')); }); }; diff --git a/x-pack/test/functional/apps/reporting_management/report_delete_pagination.ts b/x-pack/test/functional/apps/reporting_management/report_delete_pagination.ts deleted file mode 100644 index 488314030085f..0000000000000 --- a/x-pack/test/functional/apps/reporting_management/report_delete_pagination.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../ftr_provider_context'; - -export default ({ getPageObjects, getService }: FtrProviderContext) => { - const pageObjects = getPageObjects(['common', 'reporting']); - const log = getService('log'); - const retry = getService('retry'); - const security = getService('security'); - - const testSubjects = getService('testSubjects'); - const esArchiver = getService('esArchiver'); - - describe('Delete reports', function () { - before(async () => { - await security.testUser.setRoles(['kibana_admin', 'reporting_user']); - await esArchiver.load('empty_kibana'); - await esArchiver.load('reporting/archived_reports'); - await pageObjects.common.navigateToApp('reporting'); - await testSubjects.existOrFail('reportJobListing', { timeout: 200000 }); - }); - - after(async () => { - await esArchiver.unload('empty_kibana'); - await esArchiver.unload('reporting/archived_reports'); - await security.testUser.restoreDefaults(); - }); - - it('Confirm single report deletion works', async () => { - log.debug('Checking for reports.'); - await retry.try(async () => { - await testSubjects.click('checkboxSelectRow-k9a9xlwl0gpe1457b10rraq3'); - }); - const deleteButton = await testSubjects.find('deleteReportButton'); - await retry.waitFor('delete button to become enabled', async () => { - return await deleteButton.isEnabled(); - }); - await deleteButton.click(); - await testSubjects.exists('confirmModalBodyText'); - await testSubjects.click('confirmModalConfirmButton'); - await retry.try(async () => { - await testSubjects.waitForDeleted('checkboxSelectRow-k9a9xlwl0gpe1457b10rraq3'); - }); - }); - - // functional test for report pagination: https://github.com/elastic/kibana/pull/62881 - it('Report pagination', async () => { - const previousButton = await testSubjects.find('pagination-button-previous'); - expect(await previousButton.getAttribute('disabled')).to.be('true'); - await testSubjects.click('pagination-button-1'); - expect(await previousButton.getAttribute('disabled')).to.be(null); - }); - }); -}; diff --git a/x-pack/test/functional/apps/reporting_management/report_listing.ts b/x-pack/test/functional/apps/reporting_management/report_listing.ts new file mode 100644 index 0000000000000..5bb36103fc6f6 --- /dev/null +++ b/x-pack/test/functional/apps/reporting_management/report_listing.ts @@ -0,0 +1,121 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { WebElementWrapper } from 'test/functional/services/lib/web_element_wrapper'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +const getTableTextFromElement = async (tableEl: WebElementWrapper) => { + const rows = await tableEl.findAllByCssSelector('tbody tr'); + return ( + await Promise.all( + rows.map(async (row) => { + return await row.getVisibleText(); + }) + ) + ).join('\n'); +}; + +export default ({ getPageObjects, getService }: FtrProviderContext) => { + const pageObjects = getPageObjects(['common', 'reporting']); + const log = getService('log'); + const retry = getService('retry'); + const security = getService('security'); + + const testSubjects = getService('testSubjects'); + const findInstance = getService('find'); + const esArchiver = getService('esArchiver'); + + describe('Listing of Reports', function () { + before(async () => { + await security.testUser.setRoles(['kibana_admin', 'reporting_user']); + await esArchiver.load('empty_kibana'); + }); + + beforeEach(async () => { + // to reset the data after deletion testing + await esArchiver.load('reporting/archived_reports'); + await pageObjects.common.navigateToApp('reporting'); + await testSubjects.existOrFail('reportJobListing', { timeout: 200000 }); + }); + + after(async () => { + await esArchiver.unload('empty_kibana'); + await security.testUser.restoreDefaults(); + }); + + afterEach(async () => { + await esArchiver.unload('reporting/archived_reports'); + }); + + it('Confirm single report deletion works', async () => { + log.debug('Checking for reports.'); + await retry.try(async () => { + await testSubjects.click('checkboxSelectRow-k9a9xlwl0gpe1457b10rraq3'); + }); + const deleteButton = await testSubjects.find('deleteReportButton'); + await retry.waitFor('delete button to become enabled', async () => { + return await deleteButton.isEnabled(); + }); + await deleteButton.click(); + await testSubjects.exists('confirmModalBodyText'); + await testSubjects.click('confirmModalConfirmButton'); + await retry.try(async () => { + await testSubjects.waitForDeleted('checkboxSelectRow-k9a9xlwl0gpe1457b10rraq3'); + }); + }); + + it('Paginates content', async () => { + const previousButton = await testSubjects.find('pagination-button-previous'); + + // previous CAN NOT be clicked + expect(await previousButton.getAttribute('disabled')).to.be('true'); + + // scan page 1 + let tableText = await getTableTextFromElement(await testSubjects.find('reportJobListing')); + const PAGE_CONTENT_1 = `[Logs] File Type Scatter Plot\nvisualization\n2020-04-21 @ 07:01 PM\ntest_user\nCompleted at 2020-04-21 @ 07:02 PM +[Logs] File Type Scatter Plot\nvisualization\n2020-04-21 @ 07:01 PM\ntest_user\nCompleted at 2020-04-21 @ 07:02 PM +[Logs] Heatmap\nvisualization\n2020-04-21 @ 07:00 PM\ntest_user\nCompleted at 2020-04-21 @ 07:01 PM +[Logs] Heatmap\nvisualization\n2020-04-21 @ 07:00 PM\ntest_user\nCompleted at 2020-04-21 @ 07:01 PM +[Flights] Flight Delays\nvisualization\n2020-04-21 @ 07:00 PM\ntest_user\nCompleted at 2020-04-21 @ 07:01 PM +[Flights] Flight Delays\nvisualization\n2020-04-21 @ 07:00 PM\ntest_user\nCompleted at 2020-04-21 @ 07:01 PM +pdf\ndashboard\n2020-04-21 @ 07:00 PM\ntest_user\nCompleted at 2020-04-21 @ 07:00 PM +pdf\ndashboard\n2020-04-21 @ 07:00 PM\ntest_user\nCompleted at 2020-04-21 @ 07:00 PM +[Flights] Flight Cancellations\nvisualization\n2020-04-21 @ 06:59 PM\ntest_user\nCompleted at 2020-04-21 @ 07:00 PM +[Flights] Markdown Instructions\nvisualization\n2020-04-21 @ 06:59 PM\ntest_user\nCompleted at 2020-04-21 @ 07:00 PM`; + expect(tableText).to.be(PAGE_CONTENT_1); + + // click page 2 + await testSubjects.click('pagination-button-1'); + await findInstance.byCssSelector('[data-test-page="1"]'); + + // previous CAN be clicked + expect(await previousButton.getAttribute('disabled')).to.be(null); + + // scan page 2 + tableText = await getTableTextFromElement(await testSubjects.find('reportJobListing')); + const PAGE_CONTENT_2 = `[eCommerce] Revenue Tracking\ncanvas workpad\n2020-04-21 @ 06:58 PM\ntest_user\nCompleted at 2020-04-21 @ 06:59 PM +[Logs] Web Traffic\ncanvas workpad\n2020-04-21 @ 06:58 PM\ntest_user\nCompleted at 2020-04-21 @ 06:59 PM +[Flights] Overview\ncanvas workpad\n2020-04-21 @ 06:58 PM\ntest_user\nCompleted at 2020-04-21 @ 06:59 PM +[eCommerce] Revenue Dashboard\ndashboard\n2020-04-21 @ 06:57 PM\ntest_user\nCompleted at 2020-04-21 @ 06:58 PM +[Logs] Web Traffic\ndashboard\n2020-04-21 @ 06:57 PM\ntest_user\nCompleted at 2020-04-21 @ 06:58 PM +[Flights] Global Flight Dashboard\ndashboard\n2020-04-21 @ 06:56 PM\ntest_user\nCompleted at 2020-04-21 @ 06:57 PM +[Flights] Global Flight Dashboard\ndashboard\n2020-04-21 @ 06:56 PM\ntest_user\nCompleted at 2020-04-21 @ 06:57 PM +report4csv\n2020-04-21 @ 06:55 PM\ntest_user\nCompleted at 2020-04-21 @ 06:56 PM - Max size reached\nreport3csv\n2020-04-21 @ 06:55 PM +test_user\nCompleted at 2020-04-21 @ 06:55 PM - Max size reached\nreport2csv\n2020-04-21 @ 06:54 PM\ntest_user\nCompleted at 2020-04-21 @ 06:55 PM - Max size reached`; + expect(tableText).to.be(PAGE_CONTENT_2); + + // click page 3 + await testSubjects.click('pagination-button-2'); + await findInstance.byCssSelector('[data-test-page="2"]'); + + // scan page 3 + tableText = await getTableTextFromElement(await testSubjects.find('reportJobListing')); + const PAGE_CONTENT_3 = `report1csv\n2020-04-21 @ 06:54 PM\ntest_user\nCompleted at 2020-04-21 @ 06:54 PM - Max size reached`; + expect(tableText).to.be(PAGE_CONTENT_3); + }); + }); +}; diff --git a/x-pack/test/functional/apps/visualize/reporting.ts b/x-pack/test/functional/apps/visualize/reporting.ts index 02fd74e9480f7..d1cea5a4481b1 100644 --- a/x-pack/test/functional/apps/visualize/reporting.ts +++ b/x-pack/test/functional/apps/visualize/reporting.ts @@ -8,6 +8,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { + const es = getService('es'); const esArchiver = getService('esArchiver'); const browser = getService('browser'); const log = getService('log'); @@ -29,6 +30,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { after('clean up archives', async () => { await esArchiver.unload('reporting/ecommerce'); await esArchiver.unload('reporting/ecommerce_kibana'); + await es.deleteByQuery({ + index: '.reporting-*', + refresh: true, + body: { query: { match_all: {} } }, + }); }); describe('Print PDF button', () => { diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts index 85d0e56231643..0037c39b8fed2 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts @@ -13,14 +13,14 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const esArchiver = getService('esArchiver'); const testSubjects = getService('testSubjects'); - describe('host list', function () { + describe('endpoint list', function () { this.tags('ciGroup7'); const sleep = (ms = 100) => new Promise((resolve) => setTimeout(resolve, ms)); describe('when there is data,', () => { before(async () => { await esArchiver.load('endpoint/metadata/api_feature', { useCreate: true }); - await pageObjects.endpoint.navigateToHostList(); + await pageObjects.endpoint.navigateToEndpointList(); }); after(async () => { await deleteMetadataStream(getService); @@ -28,14 +28,14 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { it('finds page title', async () => { const title = await testSubjects.getVisibleText('pageViewHeaderLeftTitle'); - expect(title).to.equal('Hosts'); + expect(title).to.equal('Endpoints'); }); it('displays table data', async () => { const expectedData = [ [ 'Hostname', - 'Host Status', + 'Agent Status', 'Integration', 'Configuration Status', 'Operating System', @@ -74,70 +74,76 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { 'Jan 24, 2020 @ 16:06:09.541', ], ]; - const tableData = await pageObjects.endpointPageUtils.tableData('hostListTable'); + const tableData = await pageObjects.endpointPageUtils.tableData('endpointListTable'); expect(tableData).to.eql(expectedData); }); it('does not show the details flyout initially', async () => { - await testSubjects.missingOrFail('hostDetailsFlyout'); + await testSubjects.missingOrFail('endpointDetailsFlyout'); }); describe('when the hostname is clicked on,', () => { it('display the details flyout', async () => { await (await testSubjects.find('hostnameCellLink')).click(); - await testSubjects.existOrFail('hostDetailsUpperList'); - await testSubjects.existOrFail('hostDetailsLowerList'); + await testSubjects.existOrFail('endpointDetailsUpperList'); + await testSubjects.existOrFail('endpointDetailsLowerList'); }); it('updates the details flyout when a new hostname is selected from the list', async () => { - // display flyout for the first host in the list + // display flyout for the first endpoint in the list await (await testSubjects.findAll('hostnameCellLink'))[0].click(); - await testSubjects.existOrFail('hostDetailsFlyoutTitle'); - const hostDetailTitle0 = await testSubjects.getVisibleText('hostDetailsFlyoutTitle'); - // select the 2nd host in the host list + await testSubjects.existOrFail('endpointDetailsFlyoutTitle'); + const endpointDetailTitle0 = await testSubjects.getVisibleText( + 'endpointDetailsFlyoutTitle' + ); + // select the 2nd endpoint in the endpoint list await (await testSubjects.findAll('hostnameCellLink'))[1].click(); await pageObjects.endpoint.waitForVisibleTextToChange( - 'hostDetailsFlyoutTitle', - hostDetailTitle0 + 'endpointDetailsFlyoutTitle', + endpointDetailTitle0 + ); + const endpointDetailTitle1 = await testSubjects.getVisibleText( + 'endpointDetailsFlyoutTitle' ); - const hostDetailTitle1 = await testSubjects.getVisibleText('hostDetailsFlyoutTitle'); - expect(hostDetailTitle1).to.not.eql(hostDetailTitle0); + expect(endpointDetailTitle1).to.not.eql(endpointDetailTitle0); }); it('has the same flyout info when the same hostname is selected', async () => { - // display flyout for the first host in the list + // display flyout for the first endpoint in the list await (await testSubjects.findAll('hostnameCellLink'))[1].click(); - await testSubjects.existOrFail('hostDetailsFlyoutTitle'); - const hostDetailTitleInitial = await testSubjects.getVisibleText( - 'hostDetailsFlyoutTitle' + await testSubjects.existOrFail('endpointDetailsFlyoutTitle'); + const endpointDetailTitleInitial = await testSubjects.getVisibleText( + 'endpointDetailsFlyoutTitle' ); - // select the same host in the host list + // select the same endpoint in the endpoint list await (await testSubjects.findAll('hostnameCellLink'))[1].click(); await sleep(500); // give page time to refresh and verify it did not change - const hostDetailTitleNew = await testSubjects.getVisibleText('hostDetailsFlyoutTitle'); - expect(hostDetailTitleNew).to.equal(hostDetailTitleInitial); + const endpointDetailTitleNew = await testSubjects.getVisibleText( + 'endpointDetailsFlyoutTitle' + ); + expect(endpointDetailTitleNew).to.equal(endpointDetailTitleInitial); }); // The integration does not work properly yet. Skipping this test for now. it.skip('navigates to ingest fleet when the Reassign Configuration link is clicked', async () => { await (await testSubjects.find('hostnameCellLink')).click(); - await (await testSubjects.find('hostDetailsLinkToIngest')).click(); + await (await testSubjects.find('endpointDetailsLinkToIngest')).click(); await testSubjects.existOrFail('fleetAgentListTable'); }); }); // This set of tests fails the flyout does not open in the before() and will be fixed in soon - describe.skip('has a url with a host id', () => { + describe.skip("has a url with an endpoint host's id", () => { before(async () => { - await pageObjects.endpoint.navigateToHostList( + await pageObjects.endpoint.navigateToEndpointList( 'selected_host=fc0ff548-feba-41b6-8367-65e8790d0eaf' ); }); it('shows a flyout', async () => { - await testSubjects.existOrFail('hostDetailsFlyoutBody'); - await testSubjects.existOrFail('hostDetailsUpperList'); - await testSubjects.existOrFail('hostDetailsLowerList'); + await testSubjects.existOrFail('endpointDetailsFlyoutBody'); + await testSubjects.existOrFail('endpointDetailsUpperList'); + await testSubjects.existOrFail('endpointDetailsLowerList'); }); it('displays details row headers', async () => { @@ -151,13 +157,15 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { 'Hostname', 'Sensor Version', ]; - const keys = await pageObjects.endpoint.hostFlyoutDescriptionKeys('hostDetailsFlyout'); + const keys = await pageObjects.endpoint.endpointFlyoutDescriptionKeys( + 'endpointDetailsFlyout' + ); expect(keys).to.eql(expectedData); }); it('displays details row descriptions', async () => { - const values = await pageObjects.endpoint.hostFlyoutDescriptionValues( - 'hostDetailsFlyout' + const values = await pageObjects.endpoint.endpointFlyoutDescriptionValues( + 'endpointDetailsFlyout' ); expect(values).to.eql([ @@ -178,7 +186,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { // clear out the data and reload the page await deleteMetadataStream(getService); - await pageObjects.endpoint.navigateToHostList(); + await pageObjects.endpoint.navigateToEndpointList(); }); it('displays empty Policy Table page.', async () => { await testSubjects.existOrFail('emptyPolicyTable'); diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts index 02f893029f819..1119906ba5cfa 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts @@ -81,7 +81,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.policy.confirmAndSave(); await testSubjects.existOrFail('policyDetailsSuccessMessage'); - await pageObjects.endpoint.navigateToHostList(); + await pageObjects.endpoint.navigateToEndpointList(); await pageObjects.policy.navigateToPolicyDetails(policyInfo.packageConfig.id); expect(await (await testSubjects.find('policyWindowsEvent_process')).isSelected()).to.equal( diff --git a/x-pack/test/security_solution_endpoint/page_objects/endpoint_page.ts b/x-pack/test/security_solution_endpoint/page_objects/endpoint_page.ts index ae4320fc5395f..f89ee5fe2729b 100644 --- a/x-pack/test/security_solution_endpoint/page_objects/endpoint_page.ts +++ b/x-pack/test/security_solution_endpoint/page_objects/endpoint_page.ts @@ -14,12 +14,12 @@ export function EndpointPageProvider({ getService, getPageObjects }: FtrProvider return { /** - * Navigate to the Hosts list page + * Navigate to the Endpoints list page */ - async navigateToHostList(searchParams?: string) { + async navigateToEndpointList(searchParams?: string) { await pageObjects.common.navigateToUrlWithBrowserHistory( 'securitySolutionManagement', - `/hosts${searchParams ? `?${searchParams}` : ''}` + `/endpoints${searchParams ? `?${searchParams}` : ''}` ); await pageObjects.header.waitUntilLoadingHasFinished(); }, @@ -51,7 +51,7 @@ export function EndpointPageProvider({ getService, getPageObjects }: FtrProvider }); }, - async hostFlyoutDescriptionKeys(dataTestSubj: string) { + async endpointFlyoutDescriptionKeys(dataTestSubj: string) { await testSubjects.exists(dataTestSubj); const detailsData: WebElementWrapper = await testSubjects.find(dataTestSubj); const $ = await detailsData.parseDomContent(); @@ -65,7 +65,7 @@ export function EndpointPageProvider({ getService, getPageObjects }: FtrProvider ); }, - async hostFlyoutDescriptionValues(dataTestSubj: string) { + async endpointFlyoutDescriptionValues(dataTestSubj: string) { await testSubjects.exists(dataTestSubj); const detailsData: WebElementWrapper = await testSubjects.find(dataTestSubj); const $ = await detailsData.parseDomContent(); diff --git a/yarn.lock b/yarn.lock index 101f735355f0b..7731d2f7a8ea1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3026,10 +3026,10 @@ resolved "https://registry.yarnpkg.com/@mapbox/geojson-types/-/geojson-types-1.0.2.tgz#9aecf642cb00eab1080a57c4f949a65b4a5846d6" integrity sha512-e9EBqHHv3EORHrSfbR9DqecPNn+AmuAoQxV6aL8Xu30bJMJR1o8PZLZzpk1Wq7/NfCbuhmakHTPYRhoqLsXRnw== -"@mapbox/geojsonhint@^2.0.0": - version "2.2.0" - resolved "https://registry.yarnpkg.com/@mapbox/geojsonhint/-/geojsonhint-2.2.0.tgz#75ca94706e9a56e6debf4e1c78fabdc67978b883" - integrity sha512-8qQYRB+/2z2JsN5s6D0WAnpo69+3V3nvJsSFLwMB1dsaWz1V4oZeuoje9srbYAxxL8PXCwIywfhYa3GxOkBv5Q== +"@mapbox/geojsonhint@3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/geojsonhint/-/geojsonhint-3.0.0.tgz#42448232ce4236cb89c1b69c36b0cadeac99e02e" + integrity sha512-zHcyh1rDHYnEBd6NvOWoeHLuvazlDkIjvz9MJx4cKwcKTlfrqgxVnTv1QLnVJnsSU5neJnhQJcgscR/Zl4uYgw== dependencies: concat-stream "^1.6.1" jsonlint-lines "1.7.1" @@ -3042,16 +3042,17 @@ resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz#ce56e539f83552b58d10d672ea4d6fc9adc7b234" integrity sha1-zlblOfg1UrWNENZy6k1vya3HsjQ= -"@mapbox/mapbox-gl-draw@^1.1.2": - version "1.1.2" - resolved "https://registry.yarnpkg.com/@mapbox/mapbox-gl-draw/-/mapbox-gl-draw-1.1.2.tgz#247b3f0727db34c2641ab718df5eebeee69a2585" - integrity sha512-DWtATUAnJaGZYoH/y2O+QTRybxrp5y3w3eV5FXHFNVcKsCAojKEMB8ALKUG2IsiCKqV/JCAguK9AlPWR7Bjafw== +"@mapbox/mapbox-gl-draw@^1.2.0": + version "1.2.0" + resolved "https://registry.yarnpkg.com/@mapbox/mapbox-gl-draw/-/mapbox-gl-draw-1.2.0.tgz#b6e5278afef65bd5d7d92366034997768e478ad9" + integrity sha512-gMrP2zn8PzDtrs72FMJTPytCumX5vUn9R7IK38qBOVy9UfqbdWr56KYuNA/2X+jKn4FIOpmWf8CWkKpOaQkv7w== dependencies: "@mapbox/geojson-area" "^0.2.1" "@mapbox/geojson-extent" "^0.3.2" "@mapbox/geojson-normalize" "0.0.1" - "@mapbox/geojsonhint" "^2.0.0" + "@mapbox/geojsonhint" "3.0.0" "@mapbox/point-geometry" "0.1.0" + eslint-plugin-import "^2.19.1" hat "0.0.3" lodash.isequal "^4.2.0" xtend "^4.0.1"