diff --git a/docs/setup/install/auto-enroll.asciidoc b/docs/setup/install/auto-enroll.asciidoc new file mode 100644 index 0000000000000..0f9f9e2d8a929 --- /dev/null +++ b/docs/setup/install/auto-enroll.asciidoc @@ -0,0 +1,21 @@ +[role="exclude"] + +If this is the first time you're starting {kib}, this command generates a +unique link in your terminal to enroll your {kib} instance with {es}. + +. In your terminal, click the generated link to open {kib} in your browser. + +. In your browser, paste the enrollment token that was generated in the terminal +when you started {es}, and then click the button to connect your {kib} instance with {es}. + +. Log in to {kib} as the `elastic` user with the password that was +generated when you started {es}. + +[NOTE] +==== +If you need to reset the password for the `elastic` user or other +built-in users, run the {ref}/reset-password.html[`elasticsearch-reset-password`] tool. To generate new enrollment tokens for +{kib} or {es} nodes, run the +{ref}/create-enrollment-token.html[`elasticsearch-create-enrollment-token`] tool. +These tools are available in the {es} `bin` directory. +==== \ No newline at end of file diff --git a/docs/setup/install/deb.asciidoc b/docs/setup/install/deb.asciidoc index a229426185200..3f600d7c2bdbc 100644 --- a/docs/setup/install/deb.asciidoc +++ b/docs/setup/install/deb.asciidoc @@ -122,6 +122,30 @@ sudo dpkg -i kibana-{version}-amd64.deb endif::[] +[[deb-enroll]] +==== Start {es} and generate an enrollment token for {kib} +++++ +Generate an enrollment token +++++ + +When you start {es} for the first time, the following security configuration +occurs automatically: + +* Authentication and authorization are enabled, and a password is generated for the `elastic` built-in superuser. +* Certificates and keys for TLS are generated for the transport and HTTP layer, and TLS is enabled and configured with these keys and certificates. + +The password and certificate and keys are output to your terminal. + +You can then generate an enrollment token for {kib} with the +{ref}/create-enrollment-token.html[`elasticsearch-create-enrollment-token`] tool: + +[source,sh] +---- +bin/elasticsearch-create-enrollment-token -s kibana +---- + +Start {kib} and enter the enrollment token to securely connect {kib} with {es}. + [[deb-running-systemd]] include::systemd.asciidoc[] diff --git a/docs/setup/install/rpm.asciidoc b/docs/setup/install/rpm.asciidoc index a87d2f89b6ddb..329af9af0ccf7 100644 --- a/docs/setup/install/rpm.asciidoc +++ b/docs/setup/install/rpm.asciidoc @@ -115,6 +115,30 @@ sudo rpm --install kibana-{version}-x86_64.rpm endif::[] +[[rpm-enroll]] +==== Start {es} and generate an enrollment token for {kib} +++++ +Generate an enrollment token +++++ + +When you start {es} for the first time, the following security configuration +occurs automatically: + +* Authentication and authorization are enabled, and a password is generated for the `elastic` built-in superuser. +* Certificates and keys for TLS are generated for the transport and HTTP layer, and TLS is enabled and configured with these keys and certificates. + +The password and certificate and keys are output to your terminal. + +You can then generate an enrollment token for {kib} with the +{ref}/create-enrollment-token.html[`elasticsearch-create-enrollment-token`] tool: + +[source,sh] +---- +bin/elasticsearch-create-enrollment-token -s kibana +---- + +Start {kib} and enter the enrollment token to securely connect {kib} with {es}. + [[rpm-running-systemd]] include::systemd.asciidoc[] diff --git a/docs/setup/install/start-es-and-enroll.asciidoc b/docs/setup/install/start-es-and-enroll.asciidoc new file mode 100644 index 0000000000000..25541ec4aa993 --- /dev/null +++ b/docs/setup/install/start-es-and-enroll.asciidoc @@ -0,0 +1,16 @@ +==== Start {es} and generate an enrollment token for {kib} +++++ +Generate an enrollment token +++++ + +When you start {es} for the first time, the following security configuration +occurs automatically: + +* {ref}/configuring-stack-security.html#stack-security-certificates[Certificates and keys] for TLS are +generated for the transport and HTTP layers. +* The TLS configuration settings are written to `elasticsearch.yml`. +* A password is generated for the `elastic` user. +* An enrollment token is generated for {kib}. + +You can then start {kib} and enter the enrollment token to securely connect +{kib} with {es}. The enrollment token is valid for 30 minutes. \ No newline at end of file diff --git a/docs/setup/install/systemd.asciidoc b/docs/setup/install/systemd.asciidoc index 6fcb82217affc..125626e314241 100644 --- a/docs/setup/install/systemd.asciidoc +++ b/docs/setup/install/systemd.asciidoc @@ -1,6 +1,6 @@ ==== Run {kib} with `systemd` -To configure Kibana to start automatically when the system boots up, +To configure {kib} to start automatically when the system starts, run the following commands: [source,sh] @@ -9,7 +9,7 @@ sudo /bin/systemctl daemon-reload sudo /bin/systemctl enable kibana.service -------------------------------------------------- -Kibana can be started and stopped as follows: +{kib} can be started and stopped as follows: [source,sh] -------------------------------------------- @@ -17,6 +17,6 @@ sudo systemctl start kibana.service sudo systemctl stop kibana.service -------------------------------------------- -These commands provide no feedback as to whether Kibana was started +These commands provide no feedback as to whether {kib} was started successfully or not. Log information can be accessed via -`journalctl -u kibana.service`. +`journalctl -u kibana.service`. \ No newline at end of file diff --git a/docs/setup/install/targz-running.asciidoc b/docs/setup/install/targz-running.asciidoc index d3813d9811b13..40a2626cdd73a 100644 --- a/docs/setup/install/targz-running.asciidoc +++ b/docs/setup/install/targz-running.asciidoc @@ -9,3 +9,5 @@ Kibana can be started from the command line as follows: By default, Kibana runs in the foreground, prints its logs to the standard output (`stdout`), and can be stopped by pressing *Ctrl-C*. + +include::auto-enroll.asciidoc[] diff --git a/docs/setup/install/targz.asciidoc b/docs/setup/install/targz.asciidoc index 104ac335b5232..d9849811a7455 100644 --- a/docs/setup/install/targz.asciidoc +++ b/docs/setup/install/targz.asciidoc @@ -90,6 +90,8 @@ cd kibana-{version}/ <2> endif::[] +[[targz-enroll]] +include::start-es-and-enroll.asciidoc[] [[targz-running]] include::targz-running.asciidoc[] diff --git a/docs/setup/install/windows-running.asciidoc b/docs/setup/install/windows-running.asciidoc index 832284edc8f39..aabde22d66d16 100644 --- a/docs/setup/install/windows-running.asciidoc +++ b/docs/setup/install/windows-running.asciidoc @@ -9,3 +9,5 @@ Kibana can be started from the command line as follows: By default, Kibana runs in the foreground, prints its logs to `STDOUT`, and can be stopped by pressing *Ctrl-C*. + +include::auto-enroll.asciidoc[] \ No newline at end of file diff --git a/docs/setup/install/windows.asciidoc b/docs/setup/install/windows.asciidoc index 4138fc1886a6c..352a327e61195 100644 --- a/docs/setup/install/windows.asciidoc +++ b/docs/setup/install/windows.asciidoc @@ -40,6 +40,9 @@ CD c:\kibana-{version}-windows-x86_64 endif::[] +[[windows-enroll]] +include::start-es-and-enroll.asciidoc[] + [[windows-running]] include::windows-running.asciidoc[] diff --git a/docs/user/alerting/alerting-getting-started.asciidoc b/docs/user/alerting/alerting-getting-started.asciidoc index b53788b518fa0..80ad1bb630f53 100644 --- a/docs/user/alerting/alerting-getting-started.asciidoc +++ b/docs/user/alerting/alerting-getting-started.asciidoc @@ -24,7 +24,7 @@ This section describes all of these elements and how they operate together. [float] === Rules -A rule specifies a background task that runs on the {kib} server to check for specific conditions. {kib} provides two types of rules: stack rules that are built into {kib} and domain rules that are registered by Kibana apps. Refer to <> for more information. +A rule specifies a background task that runs on the {kib} server to check for specific conditions. {kib} provides two types of rules: stack rules that are built into {kib} and the rules that are registered by Kibana apps. Refer to <> for more information. A rule consists of three main parts: @@ -53,7 +53,7 @@ to control the details of the conditions to detect. For example, an <> lets you specify the index to query, an aggregation field, and a time window, but the details of the underlying {es} query are hidden. -See <> and <> for the types of rules provided by {kib} and how they express their conditions. +See <> for the rules provided by {kib} and how they express their conditions. [float] [[alerting-concepts-scheduling]] diff --git a/docs/user/alerting/rule-types.asciidoc b/docs/user/alerting/rule-types.asciidoc index ab2349f2fb102..324347f3b2648 100644 --- a/docs/user/alerting/rule-types.asciidoc +++ b/docs/user/alerting/rule-types.asciidoc @@ -2,7 +2,8 @@ [[rule-types]] == Rule types -A rule is a set of <>, <>, and <> that enable notifications. {kib} provides two types of rules: rules specific to the Elastic Stack and rules specific to a domain. +A rule is a set of <>, <>, and <> that enable notifications. {kib} provides rules built into the Elastic Stack and rules registered by one of the {kib} apps. +You can create most rules types in < Rules and Connectors>>. For information on creating security rules, refer to {security-guide}/rules-ui-create.html[Create a detection rule]. [NOTE] ============================================== @@ -15,45 +16,64 @@ see {subscriptions}[the subscription page]. [[stack-rules]] === Stack rules -<> are built into {kib}. To access the *Stack Rules* feature and create and edit rules, users require the `all` privilege. See <> for more information. +<> are built into {kib}. To access the *Stack Rules* feature and create and edit rules, users require the `all` privilege. See <> for more information. [cols="2*<"] |=== -| <> -| Aggregate field values from documents using {es} queries, compare them to threshold values, and schedule actions to run when the thresholds are met. - | <> | Run a user-configured {es} query, compare the number of matches to a configured threshold, and schedule actions to run when the threshold condition is met. -| {ref}/transform-alerts.html[{transform-cap} rules] beta:[] +| <> +| Aggregate field values from documents using {es} queries, compare them to threshold values, and schedule actions to run when the thresholds are met. + +| {ref}/transform-alerts.html[{transform-cap} rules] | beta:[] Run scheduled checks on a {ctransform} to check its health. If a {ctransform} meets the conditions, an alert is created and the associated action is triggered. +| <> +| Run an {es} query to determine if any documents are currently contained in any boundaries from a specified boundary index and generate alerts when a rule's conditions are met. + |=== [float] -[[domain-specific-rules]] -=== Domain rules +[[observability-rules]] +=== Observability rules -Domain rules are registered by *Observability*, *Security*, <> and <>. +Observability rules are categorized into APM and User Experience, Logs, Metrics, Stack Monitoring, and Uptime. [cols="2*<"] |=== -| {observability-guide}/create-alerts.html[Observability rules] -| Detect complex conditions in the *Logs*, *Metrics*, and *Uptime* apps. -| {security-guide}/prebuilt-rules.html[Security rules] -| Detect suspicious source events with pre-built or custom rules and create alerts when a rule’s conditions are met. +| <> +| Detect complex conditions in *APM* data and trigger built-in actions when the conditions are met. -| <> -| Run an {es} query to determine if any documents are currently contained in any boundaries from a specified boundary index and generate alerts when a rule's conditions are met. +| {observability-guide}/create-alerts.html[Logs rules] +| Detect complex conditions in the *Logs* app. -| {ml-docs}/ml-configuring-alerts.html[{ml-cap} rules] beta:[] -| beta:[] Run scheduled checks on an {anomaly-job} to detect anomalies with certain conditions. If an anomaly meets the conditions, an alert is created and the associated action is triggered. +| {observability-guide}/create-alerts.html[Metrics rules] +| Detect complex conditions in the *Metrics* app. + +| <> +| Provide {kib} Alerting rules out-of-the box to notify you of potential issues in the Elastic Stack. + +| {observability-guide}/create-alerts.html[Uptime rules] +| Detect complex conditions in the *Uptime* app. |=== +[float] +[[ml-rules]] +=== Machine learning rules + +beta:[] {ml-docs}/ml-configuring-alerts.html[{ml-cap} rules] run scheduled checks on an {anomaly-job} to detect anomalies with certain conditions. If an anomaly meets the conditions, an alert is created and the associated action is triggered. + +[float] +[[security-rules]] +=== Security rules + +Security rules detect suspicious source events with pre-built or custom rules and create alerts when a rule’s conditions are met. For more information, refer to {security-guide}/prebuilt-rules.html[Security rules]. + include::rule-types/index-threshold.asciidoc[] include::rule-types/es-query.asciidoc[] include::rule-types/geo-rule-types.asciidoc[] diff --git a/examples/expressions_explorer/kibana.json b/examples/expressions_explorer/kibana.json index 770ce91143d99..dea706d024941 100644 --- a/examples/expressions_explorer/kibana.json +++ b/examples/expressions_explorer/kibana.json @@ -10,5 +10,5 @@ }, "requiredPlugins": ["expressions", "inspector", "uiActions", "developerExamples"], "optionalPlugins": [], - "requiredBundles": [] + "requiredBundles": ["kibanaReact"] } diff --git a/examples/expressions_explorer/public/app.tsx b/examples/expressions_explorer/public/app.tsx index 260c529650bdb..631b60f4dc566 100644 --- a/examples/expressions_explorer/public/app.tsx +++ b/examples/expressions_explorer/public/app.tsx @@ -18,7 +18,7 @@ import { EuiText, EuiLink, } from '@elastic/eui'; -import { AppMountParameters } from '../../../src/core/public'; +import { AppMountParameters, IUiSettingsClient } from '../../../src/core/public'; import { ExpressionsStart } from '../../../src/plugins/expressions/public'; import { Start as InspectorStart } from '../../../src/plugins/inspector/public'; import { RunExpressionsExample } from './run_expressions'; @@ -26,53 +26,58 @@ import { RenderExpressionsExample } from './render_expressions'; import { ActionsExpressionsExample } from './actions_and_expressions'; import { UiActionsStart } from '../../../src/plugins/ui_actions/public'; import { ActionsExpressionsExample2 } from './actions_and_expressions2'; +import { createKibanaReactContext } from '../../../src/plugins/kibana_react/public'; interface Props { expressions: ExpressionsStart; inspector: InspectorStart; actions: UiActionsStart; + uiSettings: IUiSettingsClient; } -const ExpressionsExplorer = ({ expressions, inspector, actions }: Props) => { +const ExpressionsExplorer = ({ expressions, inspector, actions, uiSettings }: Props) => { + const { Provider: KibanaReactContextProvider } = createKibanaReactContext({ uiSettings }); return ( - - - Expressions Explorer - - - -

- There are a couple of ways to run the expressions. Below some of the options are - demonstrated. You can read more about it{' '} - - here - -

-
+ + + + Expressions Explorer + + + +

+ There are a couple of ways to run the expressions. Below some of the options are + demonstrated. You can read more about it{' '} + + here + +

+
- + - + - + - + - + - + - + - -
-
-
-
+ +
+
+
+
+ ); }; diff --git a/examples/expressions_explorer/public/editor/expression_editor.tsx b/examples/expressions_explorer/public/editor/expression_editor.tsx index 16370c2ece281..79c5a296981db 100644 --- a/examples/expressions_explorer/public/editor/expression_editor.tsx +++ b/examples/expressions_explorer/public/editor/expression_editor.tsx @@ -7,7 +7,7 @@ */ import React from 'react'; -import { EuiCodeEditor } from '@elastic/eui'; +import { CodeEditor } from '../../../../src/plugins/kibana_react/public'; interface Props { value: string; @@ -16,19 +16,17 @@ interface Props { export function ExpressionEditor({ value, onChange }: Props) { return ( - {}} aria-label="Code Editor" /> ); diff --git a/examples/expressions_explorer/public/plugin.tsx b/examples/expressions_explorer/public/plugin.tsx index 329dcfbb11d45..07f0526c3461d 100644 --- a/examples/expressions_explorer/public/plugin.tsx +++ b/examples/expressions_explorer/public/plugin.tsx @@ -59,6 +59,7 @@ export class ExpressionsExplorerPlugin implements Plugin = ({ filter, stateContainer }) => { <>
- + All - + Completed @@ -76,7 +76,7 @@ const TodoApp: React.FC = ({ filter, stateContainer }) => { to={{ ...location, pathname: '/not-completed' }} data-test-subj={'filterLinkNotCompleted'} > - + Not Completed diff --git a/package.json b/package.json index d1639068c1cd4..53d9e1ac15dba 100644 --- a/package.json +++ b/package.json @@ -99,11 +99,11 @@ "@elastic/apm-rum": "^5.9.1", "@elastic/apm-rum-react": "^1.3.1", "@elastic/apm-synthtrace": "link:bazel-bin/packages/elastic-apm-synthtrace", - "@elastic/charts": "39.0.1", + "@elastic/charts": "39.0.2", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath", "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.35", "@elastic/ems-client": "8.0.0", - "@elastic/eui": "40.1.0", + "@elastic/eui": "41.0.0", "@elastic/filesaver": "1.1.2", "@elastic/maki": "6.3.0", "@elastic/node-crypto": "1.2.1", @@ -511,6 +511,7 @@ "@types/deep-freeze-strict": "^1.1.0", "@types/delete-empty": "^2.0.0", "@types/ejs": "^3.0.6", + "@types/elastic__apm-synthtrace": "link:bazel-bin/packages/elastic-apm-synthtrace/npm_module_types", "@types/elastic__datemath": "link:bazel-bin/packages/elastic-datemath/npm_module_types", "@types/elasticsearch": "^5.0.33", "@types/enzyme": "^3.10.8", diff --git a/packages/BUILD.bazel b/packages/BUILD.bazel index b96fea80f027b..74c28790ae06e 100644 --- a/packages/BUILD.bazel +++ b/packages/BUILD.bazel @@ -74,6 +74,7 @@ filegroup( filegroup( name = "build_pkg_types", srcs = [ + "//packages/elastic-apm-synthtrace:build_types", "//packages/elastic-datemath:build_types", ], ) diff --git a/packages/elastic-apm-synthtrace/BUILD.bazel b/packages/elastic-apm-synthtrace/BUILD.bazel index 8ae1632ffee4c..7fb188de435b6 100644 --- a/packages/elastic-apm-synthtrace/BUILD.bazel +++ b/packages/elastic-apm-synthtrace/BUILD.bazel @@ -1,9 +1,10 @@ -load("@npm//@bazel/typescript:index.bzl", "ts_config", "ts_project") -load("@build_bazel_rules_nodejs//:index.bzl", "js_library", "pkg_npm") -load("//src/dev/bazel:index.bzl", "jsts_transpiler") +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") PKG_BASE_NAME = "elastic-apm-synthtrace" PKG_REQUIRE_NAME = "@elastic/apm-synthtrace" +TYPES_PKG_REQUIRE_NAME = "@types/elastic__apm-synthtrace" SOURCE_FILES = glob( [ @@ -31,21 +32,18 @@ RUNTIME_DEPS = [ "@npm//moment", "@npm//object-hash", "@npm//p-limit", - "@npm//utility-types", - "@npm//uuid", "@npm//yargs", ] TYPES_DEPS = [ "//packages/elastic-datemath:npm_module_types", "@npm//@elastic/elasticsearch", - "@npm//moment", - "@npm//p-limit", "@npm//@types/jest", "@npm//@types/lodash", "@npm//@types/node", - "@npm//@types/uuid", "@npm//@types/object-hash", + "@npm//moment", + "@npm//p-limit", ] jsts_transpiler( @@ -75,12 +73,13 @@ ts_project( root_dir = "src", source_map = True, tsconfig = ":tsconfig", + validate = False, ) js_library( name = PKG_BASE_NAME, srcs = NPM_MODULE_EXTRA_FILES, - deps = RUNTIME_DEPS + [":target_node", ":tsc_types"], + deps = RUNTIME_DEPS + [":target_node"], package_name = PKG_REQUIRE_NAME, visibility = ["//visibility:public"], ) @@ -99,3 +98,20 @@ filegroup( ], visibility = ["//visibility:public"], ) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = TYPES_PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [ + ":npm_module_types", + ], + visibility = ["//visibility:public"], +) diff --git a/packages/elastic-apm-synthtrace/package.json b/packages/elastic-apm-synthtrace/package.json index 43699e4795586..d2f2016a891b3 100644 --- a/packages/elastic-apm-synthtrace/package.json +++ b/packages/elastic-apm-synthtrace/package.json @@ -4,6 +4,5 @@ "description": "Elastic APM trace data generator", "license": "SSPL-1.0 OR Elastic License 2.0", "main": "./target_node/index.js", - "types": "./target_types/index.d.ts", "private": true } diff --git a/packages/elastic-apm-synthtrace/src/index.ts b/packages/elastic-apm-synthtrace/src/index.ts index 70105438ff5ae..931215c75fde4 100644 --- a/packages/elastic-apm-synthtrace/src/index.ts +++ b/packages/elastic-apm-synthtrace/src/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +export type { Exception } from './lib/entity'; export { service } from './lib/service'; export { browser } from './lib/browser'; export { timerange } from './lib/timerange'; diff --git a/packages/kbn-apm-config-loader/src/index.ts b/packages/kbn-apm-config-loader/src/index.ts index b16f6dcfd418f..381eb895b7eec 100644 --- a/packages/kbn-apm-config-loader/src/index.ts +++ b/packages/kbn-apm-config-loader/src/index.ts @@ -8,4 +8,5 @@ export { getConfiguration } from './config_loader'; export { initApm } from './init_apm'; +export { shouldInstrumentClient } from './rum_agent_configuration'; export type { ApmConfiguration } from './config'; diff --git a/packages/kbn-apm-config-loader/src/rum_agent_configuration.test.ts b/packages/kbn-apm-config-loader/src/rum_agent_configuration.test.ts new file mode 100644 index 0000000000000..be4619578b5a4 --- /dev/null +++ b/packages/kbn-apm-config-loader/src/rum_agent_configuration.test.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { shouldInstrumentClient } from './rum_agent_configuration'; +describe('shouldInstrumentClient', () => { + it('returns false if apm is disabled', () => { + expect(shouldInstrumentClient({ active: false })).toBe(false); + }); + + it('returns false if apm is enabled with contextPropagationOnly: true', () => { + expect(shouldInstrumentClient({ active: true, contextPropagationOnly: true })).toBe(false); + }); + + it('returns false if apm is enabled with disableSend: true', () => { + expect(shouldInstrumentClient({ active: true, disableSend: true })).toBe(false); + }); + + it('returns true if apm is enabled', () => { + expect(shouldInstrumentClient({ active: true })).toBe(true); + expect(shouldInstrumentClient({ active: true, contextPropagationOnly: false })).toBe(true); + expect(shouldInstrumentClient({ active: true, disableSend: false })).toBe(true); + }); +}); diff --git a/packages/kbn-apm-config-loader/src/rum_agent_configuration.ts b/packages/kbn-apm-config-loader/src/rum_agent_configuration.ts new file mode 100644 index 0000000000000..5a73c95e21135 --- /dev/null +++ b/packages/kbn-apm-config-loader/src/rum_agent_configuration.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import type { AgentConfigOptions } from 'elastic-apm-node'; + +export function shouldInstrumentClient(config?: AgentConfigOptions): boolean { + return Boolean( + config?.active === true && config.contextPropagationOnly !== true && config.disableSend !== true + ); +} diff --git a/packages/kbn-es-query/src/filters/build_filters/query_string_filter.ts b/packages/kbn-es-query/src/filters/build_filters/query_string_filter.ts index a18347c77cfc9..69f10efd97d66 100644 --- a/packages/kbn-es-query/src/filters/build_filters/query_string_filter.ts +++ b/packages/kbn-es-query/src/filters/build_filters/query_string_filter.ts @@ -16,6 +16,7 @@ export type QueryStringFilter = Filter & { query?: { query_string?: { query: string; + fields?: string[]; }; }; }; diff --git a/packages/kbn-ui-shared-deps-npm/BUILD.bazel b/packages/kbn-ui-shared-deps-npm/BUILD.bazel index 416a4d4799b7b..490aa91f30680 100644 --- a/packages/kbn-ui-shared-deps-npm/BUILD.bazel +++ b/packages/kbn-ui-shared-deps-npm/BUILD.bazel @@ -46,6 +46,7 @@ RUNTIME_DEPS = [ "@npm//moment-timezone", "@npm//moment", "@npm//raw-loader", + "@npm//react-ace", "@npm//react-dom", "@npm//react-intl", "@npm//react-is", diff --git a/packages/kbn-ui-shared-deps-npm/webpack.config.js b/packages/kbn-ui-shared-deps-npm/webpack.config.js index 80043bd0857ee..a6e7180e88123 100644 --- a/packages/kbn-ui-shared-deps-npm/webpack.config.js +++ b/packages/kbn-ui-shared-deps-npm/webpack.config.js @@ -82,6 +82,7 @@ module.exports = (_, argv) => { 'moment-timezone/moment-timezone', 'moment-timezone/data/packed/latest.json', 'moment', + 'react-ace', 'react-beautiful-dnd', 'react-dom', 'react-dom/server', diff --git a/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap b/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap index 0ed784ef680f7..7682a848b0b17 100644 --- a/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap +++ b/src/core/public/core_app/status/components/__snapshots__/server_status.test.tsx.snap @@ -3,7 +3,7 @@ exports[`ServerStatus renders correctly for green state 2`] = ` @@ -36,7 +36,7 @@ exports[`ServerStatus renders correctly for green state 2`] = ` exports[`ServerStatus renders correctly for red state 2`] = ` diff --git a/src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap b/src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap index 5b0e831286aad..c30637ed85a57 100644 --- a/src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap +++ b/src/core/public/core_app/status/components/__snapshots__/status_table.test.tsx.snap @@ -30,7 +30,7 @@ exports[`StatusTable renders when statuses is provided 1`] = ` "id": "available", "message": "Ready", "title": "green", - "uiColor": "secondary", + "uiColor": "success", }, }, ] diff --git a/src/core/public/core_app/status/components/server_status.test.tsx b/src/core/public/core_app/status/components/server_status.test.tsx index 3aa41827ff40f..e4fa84d317dd6 100644 --- a/src/core/public/core_app/status/components/server_status.test.tsx +++ b/src/core/public/core_app/status/components/server_status.test.tsx @@ -14,7 +14,7 @@ import { FormattedStatus } from '../lib'; const getStatus = (parts: Partial = {}): FormattedStatus['state'] => ({ id: 'available', title: 'Green', - uiColor: 'secondary', + uiColor: 'success', message: '', ...parts, }); diff --git a/src/core/public/core_app/status/components/status_table.test.tsx b/src/core/public/core_app/status/components/status_table.test.tsx index af7d33bee5ed6..3cb5d1126ef31 100644 --- a/src/core/public/core_app/status/components/status_table.test.tsx +++ b/src/core/public/core_app/status/components/status_table.test.tsx @@ -12,7 +12,7 @@ import { StatusTable } from './status_table'; const state = { id: 'available' as const, - uiColor: 'secondary', + uiColor: 'success', message: 'Ready', title: 'green', }; diff --git a/src/core/public/core_app/status/lib/load_status.test.ts b/src/core/public/core_app/status/lib/load_status.test.ts index 73c697c3d55aa..b6e7ba9b91e97 100644 --- a/src/core/public/core_app/status/lib/load_status.test.ts +++ b/src/core/public/core_app/status/lib/load_status.test.ts @@ -174,7 +174,7 @@ describe('response processing', () => { id: 'available', title: 'Green', message: 'Elasticsearch is available', - uiColor: 'secondary', + uiColor: 'success', }, }, { @@ -183,12 +183,12 @@ describe('response processing', () => { id: 'available', title: 'Green', message: 'SavedObjects service has completed migrations and is available', - uiColor: 'secondary', + uiColor: 'success', }, }, { id: 'plugin:1', - state: { id: 'available', title: 'Green', message: 'Ready', uiColor: 'secondary' }, + state: { id: 'available', title: 'Green', message: 'Ready', uiColor: 'success' }, }, { id: 'plugin:2', diff --git a/src/core/public/core_app/status/lib/load_status.ts b/src/core/public/core_app/status/lib/load_status.ts index e65764771f0fc..0baa67d4e793c 100644 --- a/src/core/public/core_app/status/lib/load_status.ts +++ b/src/core/public/core_app/status/lib/load_status.ts @@ -128,7 +128,7 @@ const STATUS_LEVEL_UI_ATTRS: Record = { title: i18n.translate('core.status.greenTitle', { defaultMessage: 'Green', }), - uiColor: 'secondary', + uiColor: 'success', }, }; diff --git a/src/core/public/doc_links/doc_links_service.ts b/src/core/public/doc_links/doc_links_service.ts index a9330ce499cac..6b6ceeddee68e 100644 --- a/src/core/public/doc_links/doc_links_service.ts +++ b/src/core/public/doc_links/doc_links_service.ts @@ -156,7 +156,7 @@ export class DocLinksService { luceneExpressions: `${ELASTICSEARCH_DOCS}modules-scripting-expression.html`, }, indexPatterns: { - introduction: `${KIBANA_DOCS}index-patterns.html`, + introduction: `${KIBANA_DOCS}data-views.html`, fieldFormattersNumber: `${KIBANA_DOCS}numeral.html`, fieldFormattersString: `${KIBANA_DOCS}field-formatters-string.html`, runtimeFields: `${KIBANA_DOCS}managing-data-views.html#runtime-fields`, diff --git a/src/core/public/i18n/__snapshots__/i18n_service.test.tsx.snap b/src/core/public/i18n/__snapshots__/i18n_service.test.tsx.snap index 197714df7f207..e93ef34c38025 100644 --- a/src/core/public/i18n/__snapshots__/i18n_service.test.tsx.snap +++ b/src/core/public/i18n/__snapshots__/i18n_service.test.tsx.snap @@ -26,10 +26,6 @@ exports[`#start() returns \`Context\` component 1`] = ` "euiCodeBlock.copyButton": "Copy", "euiCodeBlock.fullscreenCollapse": "Collapse", "euiCodeBlock.fullscreenExpand": "Expand", - "euiCodeEditor.startEditing": "Press Enter to start editing.", - "euiCodeEditor.startInteracting": "Press Enter to start interacting with the code.", - "euiCodeEditor.stopEditing": "When you're done, press Escape to stop editing.", - "euiCodeEditor.stopInteracting": "When you're done, press Escape to stop interacting with the code.", "euiCollapsedItemActions.allActions": "All actions", "euiColorPicker.alphaLabel": "Alpha channel (opacity) value", "euiColorPicker.closeLabel": "Press the down key to open a popover containing color options", diff --git a/src/core/public/i18n/i18n_eui_mapping.tsx b/src/core/public/i18n/i18n_eui_mapping.tsx index f28add25056ee..79180575129ea 100644 --- a/src/core/public/i18n/i18n_eui_mapping.tsx +++ b/src/core/public/i18n/i18n_eui_mapping.tsx @@ -127,22 +127,6 @@ export const getEuiContextMapping = (): EuiTokensObject => { defaultMessage: 'Expand', description: 'ARIA label for a button that enters fullscreen view', }), - 'euiCodeEditor.startEditing': i18n.translate('core.euiCodeEditor.startEditing', { - defaultMessage: 'Press Enter to start editing.', - description: 'Screen reader text to prompt editing', - }), - 'euiCodeEditor.startInteracting': i18n.translate('core.euiCodeEditor.startInteracting', { - defaultMessage: 'Press Enter to start interacting with the code.', - description: 'Screen reader text to prompt interaction', - }), - 'euiCodeEditor.stopEditing': i18n.translate('core.euiCodeEditor.stopEditing', { - defaultMessage: "When you're done, press Escape to stop editing.", - description: 'Screen reader text to describe ending editing', - }), - 'euiCodeEditor.stopInteracting': i18n.translate('core.euiCodeEditor.stopInteracting', { - defaultMessage: "When you're done, press Escape to stop interacting with the code.", - description: 'Screen reader text to describe ending interactions', - }), 'euiCollapsedItemActions.allActions': i18n.translate( 'core.euiCollapsedItemActions.allActions', { diff --git a/src/core/server/http_resources/get_apm_config.test.mocks.ts b/src/core/server/http_resources/get_apm_config.test.mocks.ts index 8c3fa180a04f0..03d1a2575ba53 100644 --- a/src/core/server/http_resources/get_apm_config.test.mocks.ts +++ b/src/core/server/http_resources/get_apm_config.test.mocks.ts @@ -7,8 +7,10 @@ */ export const getConfigurationMock = jest.fn(); +export const shouldInstrumentClientMock = jest.fn(() => true); jest.doMock('@kbn/apm-config-loader', () => ({ getConfiguration: getConfigurationMock, + shouldInstrumentClient: shouldInstrumentClientMock, })); export const agentMock = {} as Record; diff --git a/src/core/server/http_resources/get_apm_config.test.ts b/src/core/server/http_resources/get_apm_config.test.ts index bd867375f46d6..9552a91da97b1 100644 --- a/src/core/server/http_resources/get_apm_config.test.ts +++ b/src/core/server/http_resources/get_apm_config.test.ts @@ -6,7 +6,11 @@ * Side Public License, v 1. */ -import { getConfigurationMock, agentMock } from './get_apm_config.test.mocks'; +import { + getConfigurationMock, + agentMock, + shouldInstrumentClientMock, +} from './get_apm_config.test.mocks'; import { getApmConfig } from './get_apm_config'; const defaultApmConfig = { @@ -17,6 +21,7 @@ const defaultApmConfig = { describe('getApmConfig', () => { beforeEach(() => { getConfigurationMock.mockReturnValue(defaultApmConfig); + shouldInstrumentClientMock.mockReturnValue(true); }); afterEach(() => { @@ -25,12 +30,7 @@ describe('getApmConfig', () => { }); it('returns null if apm is disabled', () => { - getConfigurationMock.mockReturnValue({ - active: false, - }); - expect(getApmConfig('/path')).toBeNull(); - - getConfigurationMock.mockReturnValue(undefined); + shouldInstrumentClientMock.mockReturnValue(false); expect(getApmConfig('/path')).toBeNull(); }); diff --git a/src/core/server/http_resources/get_apm_config.ts b/src/core/server/http_resources/get_apm_config.ts index 6ea172b162d28..3e7be65f96652 100644 --- a/src/core/server/http_resources/get_apm_config.ts +++ b/src/core/server/http_resources/get_apm_config.ts @@ -7,11 +7,11 @@ */ import agent from 'elastic-apm-node'; -import { getConfiguration } from '@kbn/apm-config-loader'; +import { getConfiguration, shouldInstrumentClient } from '@kbn/apm-config-loader'; export const getApmConfig = (requestPath: string) => { const baseConfig = getConfiguration('kibana-frontend'); - if (!baseConfig?.active) { + if (!shouldInstrumentClient(baseConfig)) { return null; } diff --git a/src/core/server/status/legacy_status.test.ts b/src/core/server/status/legacy_status.test.ts index 8f1193cfcbd33..61c356e514e5f 100644 --- a/src/core/server/status/legacy_status.test.ts +++ b/src/core/server/status/legacy_status.test.ts @@ -37,7 +37,7 @@ describe('calculateLegacyStatus', () => { title: 'Green', nickname: 'Looking good', icon: 'success', - uiColor: 'secondary', + uiColor: 'success', since: expect.any(String), }); }); @@ -80,7 +80,7 @@ describe('calculateLegacyStatus', () => { message: 'Available', since: expect.any(String), state: 'green', - uiColor: 'secondary', + uiColor: 'success', }, { icon: 'danger', diff --git a/src/core/server/status/legacy_status.ts b/src/core/server/status/legacy_status.ts index 1b3d139b1345e..654427781ba9e 100644 --- a/src/core/server/status/legacy_status.ts +++ b/src/core/server/status/legacy_status.ts @@ -37,7 +37,7 @@ interface LegacyStatusOverall { type LegacyStatusState = 'green' | 'yellow' | 'red'; type LegacyStatusIcon = 'danger' | 'warning' | 'success'; -type LegacyStatusUiColor = 'secondary' | 'warning' | 'danger'; +type LegacyStatusUiColor = 'success' | 'warning' | 'danger'; interface LegacyStateAttr { id: LegacyStatusState; @@ -141,7 +141,7 @@ const STATUS_LEVEL_LEGACY_ATTRS = deepFreeze>({ defaultMessage: 'Green', }), icon: 'success', - uiColor: 'secondary', + uiColor: 'success', nickname: 'Looking good', }, }); diff --git a/src/core/server/status/routes/integration_tests/status.test.ts b/src/core/server/status/routes/integration_tests/status.test.ts index df840f5d7c059..df203675725a8 100644 --- a/src/core/server/status/routes/integration_tests/status.test.ts +++ b/src/core/server/status/routes/integration_tests/status.test.ts @@ -164,7 +164,7 @@ describe('GET /api/status', () => { since: expect.any(String), state: 'green', title: 'Green', - uiColor: 'secondary', + uiColor: 'success', }, statuses: [ { @@ -173,7 +173,7 @@ describe('GET /api/status', () => { message: 'Service is working', since: expect.any(String), state: 'green', - uiColor: 'secondary', + uiColor: 'success', }, { icon: 'success', @@ -181,7 +181,7 @@ describe('GET /api/status', () => { message: 'Service is working', since: expect.any(String), state: 'green', - uiColor: 'secondary', + uiColor: 'success', }, { icon: 'success', @@ -189,7 +189,7 @@ describe('GET /api/status', () => { message: 'a is available', since: expect.any(String), state: 'green', - uiColor: 'secondary', + uiColor: 'success', }, { icon: 'warning', diff --git a/src/dev/license_checker/config.ts b/src/dev/license_checker/config.ts index f23456bbaca07..078786abb8c64 100644 --- a/src/dev/license_checker/config.ts +++ b/src/dev/license_checker/config.ts @@ -75,6 +75,6 @@ export const LICENSE_OVERRIDES = { 'jsts@1.6.2': ['Eclipse Distribution License - v 1.0'], // cf. https://github.com/bjornharrtell/jsts '@mapbox/jsonlint-lines-primitives@2.0.2': ['MIT'], // license in readme https://github.com/tmcw/jsonlint '@elastic/ems-client@8.0.0': ['Elastic License 2.0'], - '@elastic/eui@40.1.0': ['SSPL-1.0 OR Elastic License 2.0'], + '@elastic/eui@41.0.0': ['SSPL-1.0 OR Elastic License 2.0'], 'language-subtag-registry@0.3.21': ['CC-BY-4.0'], // retired ODC‑By license https://github.com/mattcg/language-subtag-registry }; diff --git a/src/plugins/advanced_settings/public/management_app/components/field/field.tsx b/src/plugins/advanced_settings/public/management_app/components/field/field.tsx index 745452a31ff9c..5e4d047b2c701 100644 --- a/src/plugins/advanced_settings/public/management_app/components/field/field.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/field/field.tsx @@ -8,6 +8,7 @@ import React, { PureComponent, Fragment } from 'react'; import classNames from 'classnames'; +import 'react-ace'; import 'brace/theme/textmate'; import 'brace/mode/markdown'; import 'brace/mode/json'; diff --git a/src/plugins/advanced_settings/public/management_app/components/form/form.tsx b/src/plugins/advanced_settings/public/management_app/components/form/form.tsx index 0b08a317e87c9..2356cc7690c7c 100644 --- a/src/plugins/advanced_settings/public/management_app/components/form/form.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/form/form.tsx @@ -368,7 +368,7 @@ export class Form extends PureComponent { { } if (statusCode <= 299) { - return 'secondary'; + return 'success'; } if (statusCode <= 399) { diff --git a/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts b/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts index dfa263f2f1e65..fc9e66e17685c 100644 --- a/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts +++ b/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts @@ -79,6 +79,34 @@ const rules = { }, }, }, + boxplot: { + __template: { + field: '', + }, + field: '{field}', + compression: 100, + missing: 0, + }, + t_test: { + a: { + field: '{field}', + filter: { __scope_link: 'GLOBAL.filter' }, + }, + b: { + field: '{field}', + filter: { __scope_link: 'GLOBAL.filter' }, + }, + type: { __one_of: ['paired', 'homoscedastic', 'heteroscedastic'] }, + __template: { + a: { + field: '', + }, + b: { + field: '', + }, + type: '', + }, + }, adjacency_matrix: { filters: {}, }, diff --git a/src/plugins/console/server/lib/spec_definitions/json/overrides/logstash.put_pipeline.json b/src/plugins/console/server/lib/spec_definitions/json/overrides/logstash.put_pipeline.json new file mode 100644 index 0000000000000..224def4d5bf13 --- /dev/null +++ b/src/plugins/console/server/lib/spec_definitions/json/overrides/logstash.put_pipeline.json @@ -0,0 +1,66 @@ +{ + "logstash.put_pipeline": { + "data_autocomplete_rules": { + "__template": { + "last_modified": "", + "pipeline": "", + "pipeline_metadata": {}, + "pipeline_settings": {}, + "username": "" + }, + "last_modified": "", + "pipeline_metadata": {}, + "username": "", + "pipeline": "", + "pipeline_settings": { + "pipeline.id": "main", + "pipeline.workers": 0, + "pipeline.batch.size": 125, + "pipeline.batch.delay": 50, + "pipeline.unsafe_shutdown": false, + "pipeline.plugin_classloaders": false, + "pipeline.ordered": "auto", + "pipeline.ecs_compatibility": "disabled", + "pipeline.separate_logs": false, + "queue.type": "memory", + "queue.page_capacity": "64mb", + "queue.max_events": 0, + "queue.max_bytes": "1024mb", + "queue.checkpoint.acks": 1024, + "queue.checkpoint.writes": 1024, + "queue.checkpoint.retry": false, + "queue.max_bytes.number": 0, + "queue.max_bytes.units": "", + "queue.drain": false, + "api.enabled": true, + "api.environment": "production", + "api.http.host": "127.0.0.1", + "api.http.port": "9600-9700", + "api.ssl.enabled": false, + "api.ssl.keystore.path": "", + "api.ssl.keystore.password": "", + "api.auth.type": "none", + "api.auth.basic.username": "", + "api.auth.basic.password": "", + "log.level": "info", + "log.format": "plain", + "path.logs": "LOGSTASH_HOME/logs", + "path.plugins": "PATH/logstash/TYPE/NAME.rb", + "path.queue": "path.data/queue", + "path.data": "LOGSTASH_HOME/data", + "path.config": "/usr/share/logstash/pipeline", + "path.dead_letter_queue": "path.data/dead_letter_queue", + "dead_letter_queue.max_bytes": "1024mb", + "dead_letter_queue.enable": false, + "config.support_escapes": false, + "config.debug": false, + "config.reload.interval": "3s", + "config.reload.automatic": false, + "config.test_and_exit": false, + "config.string": "", + "node.name": "" + }, + "description": "" + } + } +} \ No newline at end of file diff --git a/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx b/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx index 8391edd30d8ee..8e24e9ea595dc 100644 --- a/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx +++ b/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx @@ -502,7 +502,7 @@ export function DashboardTopNav({ { 'data-test-subj': 'dashboardUnsavedChangesBadge', badgeText: unsavedChangesBadge.getUnsavedChangedBadgeText(), - color: 'secondary', + color: 'success', }, ] : undefined; diff --git a/src/plugins/data/public/ui/typeahead/_suggestion.scss b/src/plugins/data/public/ui/typeahead/_suggestion.scss index 67ff17d017053..345c7493dc293 100644 --- a/src/plugins/data/public/ui/typeahead/_suggestion.scss +++ b/src/plugins/data/public/ui/typeahead/_suggestion.scss @@ -1,7 +1,7 @@ // These are the various types in the dropdown, they each get a color $kbnTypeaheadTypes: ( field: $euiColorWarning, - value: $euiColorSecondary, + value: $euiColorSuccess, operator: $euiColorPrimary, conjunction: $euiColorVis3, ); diff --git a/src/plugins/dev_tools/public/application.tsx b/src/plugins/dev_tools/public/application.tsx index 1eb4a5f4e99e8..9351cdcdf54bf 100644 --- a/src/plugins/dev_tools/public/application.tsx +++ b/src/plugins/dev_tools/public/application.tsx @@ -10,20 +10,27 @@ import React, { useEffect, useRef } from 'react'; import { Observable } from 'rxjs'; import ReactDOM from 'react-dom'; import { HashRouter as Router, Switch, Route, Redirect } from 'react-router-dom'; -import { EuiTab, EuiTabs, EuiToolTip } from '@elastic/eui'; +import { EuiTab, EuiTabs, EuiToolTip, EuiBetaBadge } from '@elastic/eui'; import { I18nProvider } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { euiThemeVars } from '@kbn/ui-shared-deps-src/theme'; import { ApplicationStart, ChromeStart, ScopedHistory, CoreTheme } from 'src/core/public'; +import type { DocTitleService, BreadcrumbService } from './services'; import { DevToolApp } from './dev_tool'; +export interface AppServices { + docTitleService: DocTitleService; + breadcrumbService: BreadcrumbService; +} + interface DevToolsWrapperProps { devTools: readonly DevToolApp[]; activeDevTool: DevToolApp; updateRoute: (newRoute: string) => void; theme$: Observable; + appServices: AppServices; } interface MountedDevToolDescriptor { @@ -32,7 +39,14 @@ interface MountedDevToolDescriptor { unmountHandler: () => void; } -function DevToolsWrapper({ devTools, activeDevTool, updateRoute, theme$ }: DevToolsWrapperProps) { +function DevToolsWrapper({ + devTools, + activeDevTool, + updateRoute, + theme$, + appServices, +}: DevToolsWrapperProps) { + const { docTitleService, breadcrumbService } = appServices; const mountedTool = useRef(null); useEffect( @@ -44,6 +58,11 @@ function DevToolsWrapper({ devTools, activeDevTool, updateRoute, theme$ }: DevTo [] ); + useEffect(() => { + docTitleService.setTitle(activeDevTool.title); + breadcrumbService.setBreadcrumbs(activeDevTool.title); + }, [activeDevTool, docTitleService, breadcrumbService]); + return (
@@ -59,7 +78,21 @@ function DevToolsWrapper({ devTools, activeDevTool, updateRoute, theme$ }: DevTo }} > - {currentDevTool.title} + + {currentDevTool.title}{' '} + {currentDevTool.isBeta && ( + + )} + ))} @@ -127,40 +160,20 @@ function setBadge(application: ApplicationStart, chrome: ChromeStart) { }); } -function setTitle(chrome: ChromeStart) { - chrome.docTitle.change( - i18n.translate('devTools.pageTitle', { - defaultMessage: 'Dev Tools', - }) - ); -} - -function setBreadcrumbs(chrome: ChromeStart) { - chrome.setBreadcrumbs([ - { - text: i18n.translate('devTools.k7BreadcrumbsDevToolsLabel', { - defaultMessage: 'Dev Tools', - }), - href: '#/', - }, - ]); -} - export function renderApp( element: HTMLElement, application: ApplicationStart, chrome: ChromeStart, history: ScopedHistory, theme$: Observable, - devTools: readonly DevToolApp[] + devTools: readonly DevToolApp[], + appServices: AppServices ) { if (redirectOnMissingCapabilities(application)) { return () => {}; } setBadge(application, chrome); - setBreadcrumbs(chrome); - setTitle(chrome); ReactDOM.render( @@ -180,6 +193,7 @@ export function renderApp( activeDevTool={devTool} devTools={devTools} theme$={theme$} + appServices={appServices} /> )} /> diff --git a/src/plugins/dev_tools/public/constants/texts.ts b/src/plugins/dev_tools/public/constants/texts.ts new file mode 100644 index 0000000000000..12f27c5904efd --- /dev/null +++ b/src/plugins/dev_tools/public/constants/texts.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18n } from '@kbn/i18n'; + +export const i18Texts = { + breadcrumbs: { + home: i18n.translate('devTools.breadcrumb.homeLabel', { + defaultMessage: 'Dev Tools', + }), + }, +}; diff --git a/src/plugins/dev_tools/public/dev_tool.ts b/src/plugins/dev_tools/public/dev_tool.ts index 8adfd4c76482d..a2e32d43a60c7 100644 --- a/src/plugins/dev_tools/public/dev_tool.ts +++ b/src/plugins/dev_tools/public/dev_tool.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { ReactNode } from 'react'; import { AppMount } from 'src/core/public'; /** @@ -29,9 +28,14 @@ export class DevToolApp { * This will be used as a label in the tab above the actual tool. * May also be a ReactNode. */ - public readonly title: ReactNode; + public readonly title: string; public readonly mount: AppMount; + /** + * Mark the navigation tab as beta. + */ + public readonly isBeta?: boolean; + /** * Flag indicating to disable the tab of this dev tool. Navigating to a * disabled dev tool will be treated as the navigation to an unknown route @@ -57,12 +61,13 @@ export class DevToolApp { constructor( id: string, - title: ReactNode, + title: string, mount: AppMount, enableRouting: boolean, order: number, toolTipContent = '', - disabled = false + disabled = false, + isBeta?: boolean ) { this.id = id; this.title = title; @@ -71,6 +76,7 @@ export class DevToolApp { this.order = order; this.tooltipContent = toolTipContent; this.disabled = disabled; + this.isBeta = isBeta; } public enable() { @@ -94,5 +100,6 @@ export const createDevToolApp = ({ order, tooltipContent, disabled, + isBeta, }: CreateDevToolArgs) => - new DevToolApp(id, title, mount, enableRouting, order, tooltipContent, disabled); + new DevToolApp(id, title, mount, enableRouting, order, tooltipContent, disabled, isBeta); diff --git a/src/plugins/dev_tools/public/index.scss b/src/plugins/dev_tools/public/index.scss index 4bec602ea42db..a00084972c0ea 100644 --- a/src/plugins/dev_tools/public/index.scss +++ b/src/plugins/dev_tools/public/index.scss @@ -21,3 +21,7 @@ flex-direction: column; flex-grow: 1; } + +.devApp__tabBeta { + vertical-align: middle; +} diff --git a/src/plugins/dev_tools/public/plugin.ts b/src/plugins/dev_tools/public/plugin.ts index e45e73c4b1b40..1876bf278513e 100644 --- a/src/plugins/dev_tools/public/plugin.ts +++ b/src/plugins/dev_tools/public/plugin.ts @@ -15,6 +15,7 @@ import { sortBy } from 'lodash'; import { AppNavLinkStatus, DEFAULT_APP_CATEGORIES } from '../../../core/public'; import { UrlForwardingSetup } from '../../url_forwarding/public'; import { CreateDevToolArgs, DevToolApp, createDevToolApp } from './dev_tool'; +import { DocTitleService, BreadcrumbService } from './services'; import './index.scss'; @@ -36,6 +37,9 @@ export class DevToolsPlugin implements Plugin { private readonly devTools = new Map(); private appStateUpdater = new BehaviorSubject(() => ({})); + private breadcrumbService = new BreadcrumbService(); + private docTitleService = new DocTitleService(); + private getSortedDevTools(): readonly DevToolApp[] { return sortBy([...this.devTools.values()], 'order'); } @@ -59,8 +63,24 @@ export class DevToolsPlugin implements Plugin { const [core] = await getStartServices(); const { application, chrome } = core; + this.docTitleService.setup(chrome.docTitle.change); + this.breadcrumbService.setup(chrome.setBreadcrumbs); + + const appServices = { + breadcrumbService: this.breadcrumbService, + docTitleService: this.docTitleService, + }; + const { renderApp } = await import('./application'); - return renderApp(element, application, chrome, history, theme$, this.getSortedDevTools()); + return renderApp( + element, + application, + chrome, + history, + theme$, + this.getSortedDevTools(), + appServices + ); }, }); diff --git a/src/plugins/dev_tools/public/services/breadcrumb.ts b/src/plugins/dev_tools/public/services/breadcrumb.ts new file mode 100644 index 0000000000000..c12aa7e8ceef2 --- /dev/null +++ b/src/plugins/dev_tools/public/services/breadcrumb.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ManagementAppMountParams } from '../../../management/public'; +import { i18Texts } from '../constants/texts'; + +export type SetBreadcrumbs = ManagementAppMountParams['setBreadcrumbs']; + +export class BreadcrumbService { + private setBreadcrumbsHandler?: SetBreadcrumbs; + + public setup(setBreadcrumbsHandler: SetBreadcrumbs): void { + this.setBreadcrumbsHandler = setBreadcrumbsHandler; + } + + public setBreadcrumbs(page: string): void { + if (!this.setBreadcrumbsHandler) { + throw new Error('Breadcrumb service has not been initialized'); + } + + if (!page || page === 'home') { + this.setBreadcrumbsHandler([{ text: i18Texts.breadcrumbs.home }]); + } else { + this.setBreadcrumbsHandler([{ text: i18Texts.breadcrumbs.home, href: '#/' }, { text: page }]); + } + } +} diff --git a/src/plugins/dev_tools/public/services/doc_title.ts b/src/plugins/dev_tools/public/services/doc_title.ts new file mode 100644 index 0000000000000..abe9b1ece6b24 --- /dev/null +++ b/src/plugins/dev_tools/public/services/doc_title.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { i18Texts } from '../constants/texts'; + +type ChangeDocTitleHandler = (newTitle: string | string[]) => void; + +export class DocTitleService { + private changeDocTitleHandler: ChangeDocTitleHandler = () => {}; + + public setup(_changeDocTitleHandler: ChangeDocTitleHandler): void { + this.changeDocTitleHandler = _changeDocTitleHandler; + } + + public setTitle(page: string): void { + if (!this.changeDocTitleHandler) { + throw new Error('DocTitle service has not been initialized'); + } + + if (!page || page === 'home') { + this.changeDocTitleHandler(i18Texts.breadcrumbs.home); + } else { + this.changeDocTitleHandler(`${page} - ${i18Texts.breadcrumbs.home}`); + } + } +} diff --git a/src/plugins/dev_tools/public/services/index.ts b/src/plugins/dev_tools/public/services/index.ts new file mode 100644 index 0000000000000..283ec44e41097 --- /dev/null +++ b/src/plugins/dev_tools/public/services/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export { DocTitleService } from './doc_title'; +export { BreadcrumbService } from './breadcrumb'; diff --git a/src/plugins/dev_tools/tsconfig.json b/src/plugins/dev_tools/tsconfig.json index bbb33ac5b2f99..df16711f6ea50 100644 --- a/src/plugins/dev_tools/tsconfig.json +++ b/src/plugins/dev_tools/tsconfig.json @@ -9,6 +9,7 @@ "include": ["public/**/*"], "references": [ { "path": "../../core/tsconfig.json" }, - { "path": "../url_forwarding/tsconfig.json" } + { "path": "../url_forwarding/tsconfig.json" }, + { "path": "../../../src/plugins/management/tsconfig.json" } ] } diff --git a/src/plugins/discover/public/application/main/components/sidebar/discover_field_bucket.tsx b/src/plugins/discover/public/application/main/components/sidebar/discover_field_bucket.tsx index 9b0134bf19406..54c5bccaf6041 100644 --- a/src/plugins/discover/public/application/main/components/sidebar/discover_field_bucket.tsx +++ b/src/plugins/discover/public/application/main/components/sidebar/discover_field_bucket.tsx @@ -55,7 +55,7 @@ export function DiscoverFieldBucket({ field, bucket, onAddFilter }: Props) { - + {bucket.percent}% diff --git a/src/plugins/discover/public/application/main/components/sidebar/string_progress_bar.tsx b/src/plugins/discover/public/application/main/components/sidebar/string_progress_bar.tsx index a3f6c70c23a6e..34bcbfcaf113e 100644 --- a/src/plugins/discover/public/application/main/components/sidebar/string_progress_bar.tsx +++ b/src/plugins/discover/public/application/main/components/sidebar/string_progress_bar.tsx @@ -18,7 +18,5 @@ interface Props { export function StringFieldProgressBar({ value, percent, count }: Props) { const ariaLabel = `${value}: ${count} (${percent}%)`; - return ( - - ); + return ; } diff --git a/src/plugins/discover/public/components/discover_grid/discover_grid_expand_button.tsx b/src/plugins/discover/public/components/discover_grid/discover_grid_expand_button.tsx index 3453a535f98dd..372fe03666d03 100644 --- a/src/plugins/discover/public/components/discover_grid/discover_grid_expand_button.tsx +++ b/src/plugins/discover/public/components/discover_grid/discover_grid_expand_button.tsx @@ -50,7 +50,7 @@ export const ExpandButton = ({ rowIndex, setCellProps }: EuiDataGridCellValueEle aria-label={buttonLabel} data-test-subj="docTableExpandToggleColumn" onClick={() => setExpanded(isCurrentRowExpanded ? undefined : current)} - color={isCurrentRowExpanded ? 'primary' : 'subdued'} + color={isCurrentRowExpanded ? 'primary' : 'text'} iconType={isCurrentRowExpanded ? 'minimize' : 'expand'} isSelected={isCurrentRowExpanded} /> diff --git a/src/plugins/es_ui_shared/public/components/code_editor/code_editor.tsx b/src/plugins/es_ui_shared/public/components/code_editor/code_editor.tsx index 6299b473f68df..5f172d010b836 100644 --- a/src/plugins/es_ui_shared/public/components/code_editor/code_editor.tsx +++ b/src/plugins/es_ui_shared/public/components/code_editor/code_editor.tsx @@ -9,9 +9,7 @@ import React, { Component, AriaAttributes } from 'react'; import classNames from 'classnames'; import AceEditor, { IAceEditorProps } from 'react-ace'; -import { EuiI18n } from '@elastic/eui'; -// @ts-ignore -import { htmlIdGenerator, keys } from '@elastic/eui/lib/services'; +import { EuiI18n, htmlIdGenerator, keys } from '@elastic/eui'; import './_index.scss'; diff --git a/src/plugins/es_ui_shared/static/forms/components/index.ts b/src/plugins/es_ui_shared/static/forms/components/index.ts index 95b92d205c8cd..7dc1ce16a6824 100644 --- a/src/plugins/es_ui_shared/static/forms/components/index.ts +++ b/src/plugins/es_ui_shared/static/forms/components/index.ts @@ -9,7 +9,7 @@ /* @TODO -The brace/mode/json import below is loaded eagerly - before this plugin is explicitly loaded by users. This makes +The react-ace and brace/mode/json imports below are loaded eagerly - before this plugin is explicitly loaded by users. This makes the brace JSON mode, used for JSON syntax highlighting and grammar checking, available across all of Kibana plugins. This is not ideal because we are loading JS that is not necessary for Kibana to start, but the alternative @@ -19,6 +19,7 @@ EuiCodeEditor (for instance, explicitly). Importing here is a way of preventing a more sophisticated solution to this problem since we want to, eventually, migrate all code editors over to Monaco. Once that is done, we should remove this import. */ +import 'react-ace'; import 'brace/mode/json'; export * from './field'; diff --git a/src/plugins/home/public/application/components/__snapshots__/synopsis.test.js.snap b/src/plugins/home/public/application/components/__snapshots__/synopsis.test.js.snap index 8e04e70ed92b6..68bb6022d093b 100644 --- a/src/plugins/home/public/application/components/__snapshots__/synopsis.test.js.snap +++ b/src/plugins/home/public/application/components/__snapshots__/synopsis.test.js.snap @@ -2,7 +2,11 @@ exports[`props iconType 1`] = ` diff --git a/src/plugins/home/public/application/components/synopsis.js b/src/plugins/home/public/application/components/synopsis.js index b450ec8d15d2a..73113c48107d2 100644 --- a/src/plugins/home/public/application/components/synopsis.js +++ b/src/plugins/home/public/application/components/synopsis.js @@ -22,7 +22,7 @@ export function Synopsis({ id, description, iconUrl, iconType, title, url, onCli return ( `; exports[`Table should render the boolean template (true) 1`] = ` `; diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/components/table/table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/components/table/table.tsx index e3e59a4093334..aed985f062cd9 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/components/table/table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/components/table/table.tsx @@ -225,7 +225,7 @@ export const renderFieldName = (field: IndexedFieldItem, timeFieldName?: string) export class Table extends PureComponent { renderBooleanTemplate(value: string, arialLabel: string) { - return value ? : ; + return value ? : ; } renderFieldType(type: string, isConflict: boolean) { diff --git a/src/plugins/inspector/public/views/requests/components/request_selector.tsx b/src/plugins/inspector/public/views/requests/components/request_selector.tsx index 04fac0bd93b7e..539abd3d14372 100644 --- a/src/plugins/inspector/public/views/requests/components/request_selector.tsx +++ b/src/plugins/inspector/public/views/requests/components/request_selector.tsx @@ -114,7 +114,7 @@ export class RequestSelector extends Component { } > ); diff --git a/src/plugins/kibana_react/public/code_editor/editor_theme.ts b/src/plugins/kibana_react/public/code_editor/editor_theme.ts index 6c2727b123de8..517fe4cf61a08 100644 --- a/src/plugins/kibana_react/public/code_editor/editor_theme.ts +++ b/src/plugins/kibana_react/public/code_editor/editor_theme.ts @@ -35,7 +35,7 @@ export function createTheme( { token: 'strong', fontStyle: 'bold' }, { token: 'variable', foreground: euiTheme.euiColorPrimary }, - { token: 'variable.predefined', foreground: euiTheme.euiColorSecondary }, + { token: 'variable.predefined', foreground: euiTheme.euiColorSuccess }, { token: 'constant', foreground: euiTheme.euiColorAccent }, { token: 'comment', foreground: euiTheme.euiColorMediumShade }, { token: 'number', foreground: euiTheme.euiColorAccent }, @@ -52,7 +52,7 @@ export function createTheme( { token: 'tag.id.jade', foreground: euiTheme.euiColorPrimary }, { token: 'tag.class.jade', foreground: euiTheme.euiColorPrimary }, { token: 'meta.scss', foreground: euiTheme.euiColorAccent }, - { token: 'metatag', foreground: euiTheme.euiColorSecondary }, + { token: 'metatag', foreground: euiTheme.euiColorSuccess }, { token: 'metatag.content.html', foreground: euiTheme.euiColorDanger }, { token: 'metatag.html', foreground: euiTheme.euiColorMediumShade }, { token: 'metatag.xml', foreground: euiTheme.euiColorMediumShade }, @@ -63,7 +63,7 @@ export function createTheme( { token: 'string.value.json', foreground: euiTheme.euiColorPrimary }, { token: 'attribute.name', foreground: euiTheme.euiColorDanger }, - { token: 'attribute.name.css', foreground: euiTheme.euiColorSecondary }, + { token: 'attribute.name.css', foreground: euiTheme.euiColorSuccess }, { token: 'attribute.value', foreground: euiTheme.euiColorPrimary }, { token: 'attribute.value.number', foreground: euiTheme.euiColorWarning }, { token: 'attribute.value.unit', foreground: euiTheme.euiColorWarning }, diff --git a/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/__snapshots__/elastic_agent_card.test.tsx.snap b/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/__snapshots__/elastic_agent_card.test.tsx.snap index 8e1d0cb92e006..f6dcf46b27d8c 100644 --- a/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/__snapshots__/elastic_agent_card.test.tsx.snap +++ b/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/__snapshots__/elastic_agent_card.test.tsx.snap @@ -13,6 +13,11 @@ exports[`ElasticAgentCard props button 1`] = ` } > = ({ description={i18n.translate('kibana-react.noDataPage.elasticAgentCard.description', { defaultMessage: `Use Elastic Agent for a simple, unified way to collect data from your machines.`, })} - betaBadgeLabel={recommended ? NO_DATA_RECOMMENDED : undefined} + betaBadgeProps={{ label: recommended ? NO_DATA_RECOMMENDED : undefined }} footer={footer} layout={layout as 'vertical' | undefined} {...cardRest} diff --git a/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/no_data_card.tsx b/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/no_data_card.tsx index 9cc38cc5f6038..2d7335a1740a0 100644 --- a/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/no_data_card.tsx +++ b/src/plugins/kibana_react/public/page_template/no_data_page/no_data_card/no_data_card.tsx @@ -33,7 +33,7 @@ export const NoDataCard: FunctionComponent = ({ description={i18n.translate('kibana-react.noDataPage.noDataCard.description', { defaultMessage: `Proceed without collecting data`, })} - betaBadgeLabel={recommended ? NO_DATA_RECOMMENDED : undefined} + betaBadgeProps={{ label: recommended ? NO_DATA_RECOMMENDED : undefined }} footer={footer} layout={layout as 'vertical' | undefined} {...cardRest} diff --git a/src/plugins/management/public/application.tsx b/src/plugins/management/public/application.tsx index 8e3e7da41c394..3e2c4f7c04e40 100644 --- a/src/plugins/management/public/application.tsx +++ b/src/plugins/management/public/application.tsx @@ -13,11 +13,16 @@ import { AppMountParameters } from 'kibana/public'; import { ManagementApp, ManagementAppDependencies } from './components/management_app'; export const renderApp = async ( - { history, appBasePath, element }: AppMountParameters, + { history, appBasePath, element, theme$ }: AppMountParameters, dependencies: ManagementAppDependencies ) => { ReactDOM.render( - , + , element ); diff --git a/src/plugins/management/public/components/management_app/management_app.tsx b/src/plugins/management/public/components/management_app/management_app.tsx index 23d0a29083747..ac9739cc54578 100644 --- a/src/plugins/management/public/components/management_app/management_app.tsx +++ b/src/plugins/management/public/components/management_app/management_app.tsx @@ -25,6 +25,7 @@ import { SectionsServiceStart } from '../../types'; interface ManagementAppProps { appBasePath: string; history: AppMountParameters['history']; + theme$: AppMountParameters['theme$']; dependencies: ManagementAppDependencies; } @@ -34,7 +35,7 @@ export interface ManagementAppDependencies { setBreadcrumbs: (newBreadcrumbs: ChromeBreadcrumb[]) => void; } -export const ManagementApp = ({ dependencies, history }: ManagementAppProps) => { +export const ManagementApp = ({ dependencies, history, theme$ }: ManagementAppProps) => { const { setBreadcrumbs } = dependencies; const [selectedId, setSelectedId] = useState(''); const [sections, setSections] = useState(); @@ -93,6 +94,7 @@ export const ManagementApp = ({ dependencies, history }: ManagementAppProps) => > void; onAppMounted: (id: string) => void; @@ -23,7 +24,14 @@ interface ManagementRouterProps { } export const ManagementRouter = memo( - ({ dependencies, history, setBreadcrumbs, onAppMounted, sections }: ManagementRouterProps) => ( + ({ + dependencies, + history, + setBreadcrumbs, + onAppMounted, + sections, + theme$, + }: ManagementRouterProps) => ( {sections.map((section) => @@ -38,6 +46,7 @@ export const ManagementRouter = memo( setBreadcrumbs={setBreadcrumbs} onAppMounted={onAppMounted} history={history} + theme$={theme$} /> )} /> diff --git a/src/plugins/management/public/components/management_app_wrapper/management_app_wrapper.tsx b/src/plugins/management/public/components/management_app_wrapper/management_app_wrapper.tsx index 72bfe609c141a..57de84ec5aec6 100644 --- a/src/plugins/management/public/components/management_app_wrapper/management_app_wrapper.tsx +++ b/src/plugins/management/public/components/management_app_wrapper/management_app_wrapper.tsx @@ -19,6 +19,7 @@ interface ManagementSectionWrapperProps { setBreadcrumbs: (crumbs?: ChromeBreadcrumb[], history?: ScopedHistory) => void; onAppMounted: (id: string) => void; history: AppMountParameters['history']; + theme$: AppMountParameters['theme$']; } export class ManagementAppWrapper extends Component { @@ -26,7 +27,7 @@ export class ManagementAppWrapper extends Component(); componentDidMount() { - const { setBreadcrumbs, app, onAppMounted, history } = this.props; + const { setBreadcrumbs, app, onAppMounted, history, theme$ } = this.props; const { mount, basePath } = app; const appHistory = history.createSubHistory(app.basePath); @@ -35,6 +36,7 @@ export class ManagementAppWrapper extends Component setBreadcrumbs(crumbs, appHistory), element: this.mountElementRef.current!, history: appHistory, + theme$, }); onAppMounted(app.id); diff --git a/src/plugins/management/public/types.ts b/src/plugins/management/public/types.ts index 6a165c812b474..87b336928db91 100644 --- a/src/plugins/management/public/types.ts +++ b/src/plugins/management/public/types.ts @@ -6,10 +6,11 @@ * Side Public License, v 1. */ +import { Observable } from 'rxjs'; import { ScopedHistory, Capabilities } from 'kibana/public'; import type { LocatorPublic } from 'src/plugins/share/common'; import { ManagementSection, RegisterManagementSectionArgs } from './utils'; -import { ChromeBreadcrumb } from '../../../core/public/'; +import { ChromeBreadcrumb, CoreTheme } from '../../../core/public/'; import type { ManagementAppLocatorParams } from '../common/locator'; export interface ManagementSetup { @@ -63,6 +64,7 @@ export interface ManagementAppMountParams { element: HTMLElement; // element the section should render into setBreadcrumbs: (crumbs: ChromeBreadcrumb[]) => void; history: ScopedHistory; + theme$: Observable; } export interface CreateManagementItemArgs { diff --git a/src/plugins/presentation_util/public/components/controls/control_group/component/control_group_component.tsx b/src/plugins/presentation_util/public/components/controls/control_group/component/control_group_component.tsx index 22b97b6f6b0da..9b5e5588373db 100644 --- a/src/plugins/presentation_util/public/components/controls/control_group/component/control_group_component.tsx +++ b/src/plugins/presentation_util/public/components/controls/control_group/component/control_group_component.tsx @@ -174,7 +174,7 @@ export const ControlGroup = () => { { const flyoutInstance = openFlyout( diff --git a/src/plugins/presentation_util/public/components/controls/control_types/options_list/options_list_popover_component.tsx b/src/plugins/presentation_util/public/components/controls/control_types/options_list/options_list_popover_component.tsx index 90f92e30c32c9..a84d0460e9299 100644 --- a/src/plugins/presentation_util/public/components/controls/control_types/options_list/options_list_popover_component.tsx +++ b/src/plugins/presentation_util/public/components/controls/control_types/options_list/options_list_popover_component.tsx @@ -92,7 +92,7 @@ export const OptionsListPopover = ({ size="s" iconType="list" aria-pressed={showOnlySelected} - color={showOnlySelected ? 'primary' : 'subdued'} + color={showOnlySelected ? 'primary' : 'text'} display={showOnlySelected ? 'base' : 'empty'} aria-label={OptionsListStrings.popover.getClearAllSelectionsButtonTitle()} onClick={() => setShowOnlySelected(!showOnlySelected)} diff --git a/src/plugins/presentation_util/public/components/labs/project_list_item.scss b/src/plugins/presentation_util/public/components/labs/project_list_item.scss index 898770f7811a1..75c0018989fa0 100644 --- a/src/plugins/presentation_util/public/components/labs/project_list_item.scss +++ b/src/plugins/presentation_util/public/components/labs/project_list_item.scss @@ -10,7 +10,7 @@ left: 4px; bottom: $euiSizeL; width: 4px; - background: $euiColorSecondary; + background: $euiColorSuccess; content: ''; } diff --git a/src/plugins/presentation_util/public/components/labs/project_list_item.tsx b/src/plugins/presentation_util/public/components/labs/project_list_item.tsx index 994059c9789ec..909e8434f77f1 100644 --- a/src/plugins/presentation_util/public/components/labs/project_list_item.tsx +++ b/src/plugins/presentation_util/public/components/labs/project_list_item.tsx @@ -58,7 +58,7 @@ export const ProjectListItem = ({ project, onStatusChange }: Props) => { content={strings.getOverriddenIconTipLabel()} position="top" type="dot" - color="secondary" + color="success" /> ) : null} diff --git a/src/plugins/telemetry/schema/oss_plugins.json b/src/plugins/telemetry/schema/oss_plugins.json index d40bf9aa5d610..cd5d3818bcdec 100644 --- a/src/plugins/telemetry/schema/oss_plugins.json +++ b/src/plugins/telemetry/schema/oss_plugins.json @@ -9250,11 +9250,37 @@ "description": "Number of TSVB visualizations using \"last value\" as a time range" } }, + "timeseries_use_es_indices_total": { + "type": "long", + "_meta": { "description": "Number of TSVB visualizations using elasticsearch indices" } + }, "timeseries_table_use_aggregate_function": { "type": "long", "_meta": { "description": "Number of TSVB table visualizations using aggregate function" } + }, + "timeseries_types": { + "properties": { + "table": { + "type": "long" + }, + "gauge": { + "type": "long" + }, + "markdown": { + "type": "long" + }, + "top_n": { + "type": "long" + }, + "timeseries": { + "type": "long" + }, + "metric": { + "type": "long" + } + } } } }, diff --git a/src/plugins/vis_types/timeseries/kibana.json b/src/plugins/vis_types/timeseries/kibana.json index 5cc425e4edf71..63cabc70a9587 100644 --- a/src/plugins/vis_types/timeseries/kibana.json +++ b/src/plugins/vis_types/timeseries/kibana.json @@ -5,7 +5,7 @@ "server": true, "ui": true, "requiredPlugins": ["charts", "data", "expressions", "visualizations", "visualize"], - "optionalPlugins": ["usageCollection"], + "optionalPlugins": ["home","usageCollection"], "requiredBundles": ["kibanaUtils", "kibanaReact", "fieldFormats"], "owner": { "name": "Vis Editors", diff --git a/src/plugins/vis_types/timeseries/public/application/components/splits/filter.js b/src/plugins/vis_types/timeseries/public/application/components/splits/filter.js index 6324fff859d44..a53dc291fb6f0 100644 --- a/src/plugins/vis_types/timeseries/public/application/components/splits/filter.js +++ b/src/plugins/vis_types/timeseries/public/application/components/splits/filter.js @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { createSelectHandler } from '../lib/create_select_handler'; import { GroupBySelect } from './group_by_select'; import PropTypes from 'prop-types'; import React from 'react'; @@ -15,12 +14,16 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { getDefaultQueryLanguage } from '../lib/get_default_query_language'; import { QueryBarWrapper } from '../query_bar_wrapper'; +const RESET_STATE = { + filter: undefined, +}; + export const SplitByFilter = (props) => { const { onChange, uiRestrictions, indexPattern } = props; const defaults = { filter: { language: getDefaultQueryLanguage(), query: '' } }; const model = { ...defaults, ...props.model }; const htmlId = htmlIdGenerator(); - const handleSelectChange = createSelectHandler(onChange); + return ( @@ -35,7 +38,12 @@ export const SplitByFilter = (props) => { > { + onChange({ + split_mode: newSplitMode, + ...RESET_STATE, + }); + }} uiRestrictions={uiRestrictions} /> diff --git a/src/plugins/vis_types/timeseries/public/application/components/splits/filters.js b/src/plugins/vis_types/timeseries/public/application/components/splits/filters.js index 8c91d057ae341..edb1ce5927939 100644 --- a/src/plugins/vis_types/timeseries/public/application/components/splits/filters.js +++ b/src/plugins/vis_types/timeseries/public/application/components/splits/filters.js @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { createSelectHandler } from '../lib/create_select_handler'; import { GroupBySelect } from './group_by_select'; import { FilterItems } from './filter_items'; import PropTypes from 'prop-types'; @@ -14,10 +13,13 @@ import React from 'react'; import { htmlIdGenerator, EuiFlexGroup, EuiFlexItem, EuiFormRow } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +const RESET_STATE = { + split_filters: undefined, +}; + export const SplitByFilters = (props) => { const { onChange, model, uiRestrictions, indexPattern } = props; const htmlId = htmlIdGenerator(); - const handleSelectChange = createSelectHandler(onChange); return (
@@ -33,7 +35,12 @@ export const SplitByFilters = (props) => { > { + onChange({ + split_mode: newSplitMode, + ...RESET_STATE, + }); + }} uiRestrictions={uiRestrictions} /> diff --git a/src/plugins/vis_types/timeseries/public/application/components/splits/terms.js b/src/plugins/vis_types/timeseries/public/application/components/splits/terms.js index b32af037533f7..8a85c9826e937 100644 --- a/src/plugins/vis_types/timeseries/public/application/components/splits/terms.js +++ b/src/plugins/vis_types/timeseries/public/application/components/splits/terms.js @@ -30,6 +30,14 @@ import { STACKED_OPTIONS } from '../../visualizations/constants'; import { getIndexPatternKey } from '../../../../common/index_patterns_utils'; const DEFAULTS = { terms_direction: 'desc', terms_size: 10, terms_order_by: '_count' }; +const RESET_STATE = { + terms_field: undefined, + terms_include: undefined, + terms_exclude: undefined, + terms_direction: undefined, + terms_size: undefined, + terms_order_by: undefined, +}; export const SplitByTermsUI = ({ onChange, @@ -106,7 +114,12 @@ export const SplitByTermsUI = ({ > { + onChange({ + split_mode: newSplitMode, + ...RESET_STATE, + }); + }} uiRestrictions={uiRestrictions} /> diff --git a/src/plugins/vis_types/timeseries/server/plugin.ts b/src/plugins/vis_types/timeseries/server/plugin.ts index 5347d9ab7bfbc..248016f1a9836 100644 --- a/src/plugins/vis_types/timeseries/server/plugin.ts +++ b/src/plugins/vis_types/timeseries/server/plugin.ts @@ -21,6 +21,7 @@ import { first, map } from 'rxjs/operators'; import { VisTypeTimeseriesConfig } from './config'; import { getVisData } from './lib/get_vis_data'; import { UsageCollectionSetup } from '../../../usage_collection/server'; +import { HomeServerPluginSetup } from '../../../home/server'; import { PluginStart } from '../../../data/server'; import { IndexPatternsService } from '../../../data/common'; import { visDataRoutes } from './routes/vis'; @@ -47,6 +48,7 @@ export interface LegacySetup { interface VisTypeTimeseriesPluginSetupDependencies { usageCollection?: UsageCollectionSetup; + home?: HomeServerPluginSetup; } interface VisTypeTimeseriesPluginStartDependencies { @@ -128,7 +130,7 @@ export class VisTypeTimeseriesPlugin implements Plugin { fieldsRoutes(router, framework); if (plugins.usageCollection) { - registerTimeseriesUsageCollector(plugins.usageCollection); + registerTimeseriesUsageCollector(plugins.usageCollection, plugins.home); } return { diff --git a/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.test.ts b/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.test.ts index 3f3a204d29263..573c6c0e00fe2 100644 --- a/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.test.ts +++ b/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.test.ts @@ -22,7 +22,9 @@ const mockedSavedObject = { type: 'metrics', title: 'TSVB visualization 1', params: { + type: 'gauge', time_range_mode: TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE, + use_kibana_indexes: true, }, }), }, @@ -33,7 +35,9 @@ const mockedSavedObject = { type: 'metrics', title: 'TSVB visualization 2', params: { + type: 'top_n', time_range_mode: TIME_RANGE_DATA_MODES.LAST_VALUE, + use_kibana_indexes: false, }, }), }, @@ -44,7 +48,9 @@ const mockedSavedObject = { type: 'metrics', title: 'TSVB visualization 3', params: { + type: 'markdown', time_range_mode: undefined, + use_kibana_indexes: false, }, }), }, @@ -78,7 +84,9 @@ const mockedSavedObjectsByValue = [ savedVis: { type: 'metrics', params: { + type: 'markdown', time_range_mode: TIME_RANGE_DATA_MODES.LAST_VALUE, + use_kibana_indexes: false, }, }, }, @@ -93,7 +101,9 @@ const mockedSavedObjectsByValue = [ savedVis: { type: 'metrics', params: { + type: 'timeseries', time_range_mode: TIME_RANGE_DATA_MODES.ENTIRE_TIME_RANGE, + use_kibana_indexes: true, }, }, }, @@ -115,6 +125,7 @@ const mockedSavedObjectsByValue = [ aggregate_function: 'sum', }, ], + use_kibana_indexes: true, }, }, }, @@ -241,7 +252,16 @@ describe('Timeseries visualization usage collector', () => { expect(result).toStrictEqual({ timeseries_use_last_value_mode_total: 5, + timeseries_use_es_indices_total: 4, timeseries_table_use_aggregate_function: 2, + timeseries_types: { + gauge: 1, + markdown: 2, + metric: 0, + table: 2, + timeseries: 1, + top_n: 1, + }, }); }); }); diff --git a/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.ts b/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.ts index 58f0c9c7f1459..cc08b8789d368 100644 --- a/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.ts +++ b/src/plugins/vis_types/timeseries/server/usage_collector/get_usage_collector.ts @@ -14,12 +14,22 @@ import type { ISavedObjectsRepository, SavedObjectsFindResult, } from '../../../../../core/server'; +import type { HomeServerPluginSetup } from '../../../../home/server'; import type { SavedVisState } from '../../../../visualizations/common'; import type { Panel } from '../../common/types'; export interface TimeseriesUsage { timeseries_use_last_value_mode_total: number; + timeseries_use_es_indices_total: number; timeseries_table_use_aggregate_function: number; + timeseries_types: { + table: number; + gauge: number; + markdown: number; + top_n: number; + timeseries: number; + metric: number; + }; } const doTelemetryFoVisualizations = async ( @@ -59,31 +69,80 @@ const doTelemetryForByValueVisualizations = async ( } }; +const getDefaultTSVBVisualizations = (home?: HomeServerPluginSetup) => { + const titles: string[] = []; + const sampleDataSets = home?.sampleData.getSampleDatasets() ?? []; + + sampleDataSets.forEach((sampleDataSet) => + sampleDataSet.savedObjects.forEach((savedObject) => { + try { + if (savedObject.type === 'visualization') { + const visState = JSON.parse(savedObject.attributes?.visState); + + if (visState.type === 'metrics') { + titles.push(visState.title); + } + } + } catch (e) { + // Let it go, visState is invalid and we'll don't need to handle it + } + }) + ); + + return titles; +}; + export const getStats = async ( - soClient: SavedObjectsClientContract | ISavedObjectsRepository + soClient: SavedObjectsClientContract | ISavedObjectsRepository, + home?: HomeServerPluginSetup ): Promise => { const timeseriesUsage = { timeseries_use_last_value_mode_total: 0, + timeseries_use_es_indices_total: 0, timeseries_table_use_aggregate_function: 0, + timeseries_types: { + gauge: 0, + markdown: 0, + metric: 0, + table: 0, + timeseries: 0, + top_n: 0, + }, }; + // we want to exclude the TSVB Sample Data visualizations from the stats + // in order to have more accurate results + const excludedFromStatsVisualizations = getDefaultTSVBVisualizations(home); + function telemetryUseLastValueMode(visState: SavedVisState) { if ( visState.type === 'metrics' && visState.params.type !== 'timeseries' && (!visState.params.time_range_mode || - visState.params.time_range_mode === TIME_RANGE_DATA_MODES.LAST_VALUE) + visState.params.time_range_mode === TIME_RANGE_DATA_MODES.LAST_VALUE) && + !excludedFromStatsVisualizations.includes(visState.title) ) { timeseriesUsage.timeseries_use_last_value_mode_total++; } } + function telemetryUseESIndices(visState: SavedVisState) { + if ( + visState.type === 'metrics' && + !visState.params.use_kibana_indexes && + !excludedFromStatsVisualizations.includes(visState.title) + ) { + timeseriesUsage.timeseries_use_es_indices_total++; + } + } + function telemetryTableAggFunction(visState: SavedVisState) { if ( visState.type === 'metrics' && visState.params.type === 'table' && visState.params.series && - visState.params.series.length > 0 + visState.params.series.length > 0 && + !excludedFromStatsVisualizations.includes(visState.title) ) { const usesAggregateFunction = visState.params.series.some( (s) => s.aggregate_by && s.aggregate_function @@ -94,17 +153,30 @@ export const getStats = async ( } } + function telemetryPanelTypes(visState: SavedVisState) { + if (visState.type === 'metrics' && !excludedFromStatsVisualizations.includes(visState.title)) { + timeseriesUsage.timeseries_types[visState.params.type]++; + } + } await Promise.all([ // last value usage telemetry doTelemetryFoVisualizations(soClient, telemetryUseLastValueMode), doTelemetryForByValueVisualizations(soClient, telemetryUseLastValueMode), + // elasticsearch indices usage telemetry + doTelemetryFoVisualizations(soClient, telemetryUseESIndices), + doTelemetryForByValueVisualizations(soClient, telemetryUseESIndices), // table aggregate function telemetry doTelemetryFoVisualizations(soClient, telemetryTableAggFunction), doTelemetryForByValueVisualizations(soClient, telemetryTableAggFunction), + // panel types usage telemetry + doTelemetryFoVisualizations(soClient, telemetryPanelTypes), + doTelemetryForByValueVisualizations(soClient, telemetryPanelTypes), ]); return timeseriesUsage.timeseries_use_last_value_mode_total || - timeseriesUsage.timeseries_table_use_aggregate_function + timeseriesUsage.timeseries_use_es_indices_total || + timeseriesUsage.timeseries_table_use_aggregate_function || + Object.values(timeseriesUsage.timeseries_types).some((visualizationCount) => visualizationCount) ? timeseriesUsage : undefined; }; diff --git a/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.test.ts b/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.test.ts index 26a74821fe5ae..3714cc6b30c45 100644 --- a/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.test.ts +++ b/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.test.ts @@ -46,7 +46,7 @@ describe('registerTimeseriesUsageCollector', () => { const mockedCollectorFetchContext = createCollectorFetchContextMock(); const fetchResult = await usageCollector.fetch(mockedCollectorFetchContext); expect(mockGetStats).toBeCalledTimes(1); - expect(mockGetStats).toBeCalledWith(mockedCollectorFetchContext.soClient); + expect(mockGetStats).toBeCalledWith(mockedCollectorFetchContext.soClient, undefined); expect(fetchResult).toBe(mockStats); }); }); diff --git a/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.ts b/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.ts index b96d6ce4c5da8..e8fd666fb28d1 100644 --- a/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.ts +++ b/src/plugins/vis_types/timeseries/server/usage_collector/register_timeseries_collector.ts @@ -8,8 +8,12 @@ import { getStats, TimeseriesUsage } from './get_usage_collector'; import type { UsageCollectionSetup } from '../../../../usage_collection/server'; +import type { HomeServerPluginSetup } from '../../../../home/server'; -export function registerTimeseriesUsageCollector(collectorSet: UsageCollectionSetup) { +export function registerTimeseriesUsageCollector( + collectorSet: UsageCollectionSetup, + home?: HomeServerPluginSetup +) { const collector = collectorSet.makeUsageCollector({ type: 'vis_type_timeseries', isReady: () => true, @@ -18,12 +22,24 @@ export function registerTimeseriesUsageCollector(collectorSet: UsageCollectionSe type: 'long', _meta: { description: 'Number of TSVB visualizations using "last value" as a time range' }, }, + timeseries_use_es_indices_total: { + type: 'long', + _meta: { description: 'Number of TSVB visualizations using elasticsearch indices' }, + }, timeseries_table_use_aggregate_function: { type: 'long', _meta: { description: 'Number of TSVB table visualizations using aggregate function' }, }, + timeseries_types: { + table: { type: 'long' }, + gauge: { type: 'long' }, + markdown: { type: 'long' }, + top_n: { type: 'long' }, + timeseries: { type: 'long' }, + metric: { type: 'long' }, + }, }, - fetch: async ({ soClient }) => await getStats(soClient), + fetch: async ({ soClient }) => await getStats(soClient, home), }); collectorSet.registerCollector(collector); diff --git a/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.tsx b/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.tsx index ff3b05f0bd994..acbe226155397 100644 --- a/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.tsx +++ b/src/plugins/visualizations/public/wizard/agg_based_selection/agg_based_selection.tsx @@ -137,7 +137,7 @@ class AggBasedSelection extends React.Component} + icon={} className="aggBasedDialog__card" /> diff --git a/src/plugins/visualizations/public/wizard/group_selection/group_selection.tsx b/src/plugins/visualizations/public/wizard/group_selection/group_selection.tsx index b28d980424ebf..3866bce796c22 100644 --- a/src/plugins/visualizations/public/wizard/group_selection/group_selection.tsx +++ b/src/plugins/visualizations/public/wizard/group_selection/group_selection.tsx @@ -110,7 +110,7 @@ function GroupSelection(props: GroupSelectionProps) { 'Use our classic visualize library to create charts based on aggregations.', } )} - icon={} + icon={} className="visNewVisDialog__groupsCard" > { } layout="horizontal" - icon={} + icon={} className="visNewVisDialog__groupsCard" /> diff --git a/test/functional/services/remote/network_profiles.ts b/test/functional/services/remote/network_profiles.ts new file mode 100644 index 0000000000000..c27bafa4f8dcb --- /dev/null +++ b/test/functional/services/remote/network_profiles.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +interface NetworkOptions { + DOWNLOAD: number; + UPLOAD: number; + LATENCY: number; +} + +const sec = 1_000; +const kB = 1024; + +// Download (kb/s) Upload (kb/s) Latency (ms) +// https://gist.github.com/theodorosploumis/fd4086ee58369b68aea6b0782dc96a2e +export const NETWORK_PROFILES: { [key: string]: NetworkOptions } = { + DEFAULT: { DOWNLOAD: 5 * kB * sec, UPLOAD: 1 * kB * sec, LATENCY: 0.1 * sec }, + GPRS: { DOWNLOAD: 0.05 * kB * sec, UPLOAD: 0.02 * kB * sec, LATENCY: 0.5 * sec }, + MOBILE_EDGE: { DOWNLOAD: 0.24 * kB * sec, UPLOAD: 0.2 * kB * sec, LATENCY: 0.84 * sec }, + '2G_REGULAR': { DOWNLOAD: 0.25 * kB * sec, UPLOAD: 0.05 * kB * sec, LATENCY: 0.3 * sec }, + '2G_GOOD': { DOWNLOAD: 0.45 * kB * sec, UPLOAD: 0.15 * kB * sec, LATENCY: 0.15 * sec }, + '3G_SLOW': { DOWNLOAD: 0.78 * kB * sec, UPLOAD: 0.33 * kB * sec, LATENCY: 0.2 * sec }, + '3G_REGULAR': { DOWNLOAD: 0.75 * kB * sec, UPLOAD: 0.25 * kB * sec, LATENCY: 0.1 * sec }, + '3G_GOOD': { DOWNLOAD: 1.5 * kB * sec, UPLOAD: 0.75 * kB * sec, LATENCY: 0.04 * sec }, + '4G_REGULAR': { DOWNLOAD: 4 * kB * sec, UPLOAD: 3 * kB * sec, LATENCY: 0.02 * sec }, + DSL: { DOWNLOAD: 2 * kB * sec, UPLOAD: 1 * kB * sec, LATENCY: 0.005 * sec }, + CABLE_5MBPS: { DOWNLOAD: 5 * kB * sec, UPLOAD: 1 * kB * sec, LATENCY: 0.28 * sec }, + CABLE_8MBPS: { DOWNLOAD: 8 * kB * sec, UPLOAD: 2 * kB * sec, LATENCY: 0.1 * sec }, + WIFI: { DOWNLOAD: 30 * kB * sec, UPLOAD: 15 * kB * sec, LATENCY: 0.002 * sec }, +}; diff --git a/test/functional/services/remote/webdriver.ts b/test/functional/services/remote/webdriver.ts index 9ae848d95473a..84dfdf3c845f7 100644 --- a/test/functional/services/remote/webdriver.ts +++ b/test/functional/services/remote/webdriver.ts @@ -32,6 +32,7 @@ import { createStdoutSocket } from './create_stdout_stream'; import { preventParallelCalls } from './prevent_parallel_calls'; import { Browsers } from './browsers'; +import { NETWORK_PROFILES } from './network_profiles'; const throttleOption: string = process.env.TEST_THROTTLE_NETWORK as string; const headlessBrowser: string = process.env.TEST_BROWSER_HEADLESS as string; @@ -290,14 +291,30 @@ async function attemptToCreateCommand( const { session, consoleLog$ } = await buildDriverInstance(); if (throttleOption === '1' && browserType === 'chrome') { + const { KBN_NETWORK_TEST_PROFILE = 'DEFAULT' } = process.env; + + const profile = + KBN_NETWORK_TEST_PROFILE in Object.keys(NETWORK_PROFILES) + ? KBN_NETWORK_TEST_PROFILE + : 'DEFAULT'; + + const { + DOWNLOAD: downloadThroughput, + UPLOAD: uploadThroughput, + LATENCY: latency, + } = NETWORK_PROFILES[`${profile}`]; + // Only chrome supports this option. - log.debug('NETWORK THROTTLED: 768k down, 256k up, 100ms latency.'); + log.debug( + `NETWORK THROTTLED with profile ${profile}: ${downloadThroughput}kbps down, ${uploadThroughput}kbps up, ${latency} ms latency.` + ); - (session as any).setNetworkConditions({ + // @ts-expect-error + session.setNetworkConditions({ offline: false, - latency: 100, // Additional latency (ms). - download_throughput: 768 * 1024, // These speeds are in bites per second, not kilobytes. - upload_throughput: 256 * 1024, + latency, + download_throughput: downloadThroughput, + upload_throughput: uploadThroughput, }); } diff --git a/x-pack/examples/alerting_example/public/components/view_alert.tsx b/x-pack/examples/alerting_example/public/components/view_alert.tsx index 5f3581871e2bd..0269654806c51 100644 --- a/x-pack/examples/alerting_example/public/components/view_alert.tsx +++ b/x-pack/examples/alerting_example/public/components/view_alert.tsx @@ -9,7 +9,7 @@ import React, { useState, useEffect, Fragment } from 'react'; import { EuiText, - EuiLoadingKibana, + EuiLoadingLogo, EuiCallOut, EuiTextColor, EuiDescriptionList, @@ -106,6 +106,6 @@ export const ViewAlertPage = withRouter(({ http, id }: Props) => { )} ) : ( - + ); }); diff --git a/x-pack/examples/alerting_example/public/components/view_astros_alert.tsx b/x-pack/examples/alerting_example/public/components/view_astros_alert.tsx index 1bab422c2bcf0..44ca8f624c197 100644 --- a/x-pack/examples/alerting_example/public/components/view_astros_alert.tsx +++ b/x-pack/examples/alerting_example/public/components/view_astros_alert.tsx @@ -9,7 +9,7 @@ import React, { useState, useEffect, Fragment } from 'react'; import { EuiText, - EuiLoadingKibana, + EuiLoadingLogo, EuiCallOut, EuiTextColor, EuiDescriptionList, @@ -114,6 +114,6 @@ export const ViewPeopleInSpaceAlertPage = withRouter(({ http, id }: Props) => { )} ) : ( - + ); }); diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/containers/drilldowns_without_embeddable_example/drilldowns_without_embeddable_example.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/containers/drilldowns_without_embeddable_example/drilldowns_without_embeddable_example.tsx index a0e1f38543c29..0941c1e2c8148 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/containers/drilldowns_without_embeddable_example/drilldowns_without_embeddable_example.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/containers/drilldowns_without_embeddable_example/drilldowns_without_embeddable_example.tsx @@ -101,7 +101,7 @@ export const DrilldownsWithoutEmbeddableExample: React.FC = () => { {openManagerButton} { ({ id, + includeLegacyId, }: { id: string; + includeLegacyId?: boolean; }): Promise> { const { saved_object: result, ...resolveResponse } = await this.unsecuredSavedObjectsClient.resolve('alert', id); @@ -483,7 +485,8 @@ export class RulesClient { result.id, result.attributes.alertTypeId, result.attributes, - result.references + result.references, + includeLegacyId ); return { @@ -1202,44 +1205,51 @@ export class RulesClient { } if (this.eventLogger && attributes.scheduledTaskId) { - const { state } = taskInstanceToAlertTaskInstance( - await this.taskManager.get(attributes.scheduledTaskId), - attributes as unknown as SanitizedAlert - ); + try { + const { state } = taskInstanceToAlertTaskInstance( + await this.taskManager.get(attributes.scheduledTaskId), + attributes as unknown as SanitizedAlert + ); - const recoveredAlertInstances = mapValues, AlertInstance>( - state.alertInstances ?? {}, - (rawAlertInstance) => new AlertInstance(rawAlertInstance) - ); - const recoveredAlertInstanceIds = Object.keys(recoveredAlertInstances); - - for (const instanceId of recoveredAlertInstanceIds) { - const { group: actionGroup, subgroup: actionSubgroup } = - recoveredAlertInstances[instanceId].getLastScheduledActions() ?? {}; - const instanceState = recoveredAlertInstances[instanceId].getState(); - const message = `instance '${instanceId}' has recovered due to the rule was disabled`; - - const event = createAlertEventLogRecordObject({ - ruleId: id, - ruleName: attributes.name, - ruleType: this.ruleTypeRegistry.get(attributes.alertTypeId), - instanceId, - action: EVENT_LOG_ACTIONS.recoveredInstance, - message, - state: instanceState, - group: actionGroup, - subgroup: actionSubgroup, - namespace: this.namespace, - savedObjects: [ - { - id, - type: 'alert', - typeId: attributes.alertTypeId, - relation: SAVED_OBJECT_REL_PRIMARY, - }, - ], - }); - this.eventLogger.logEvent(event); + const recoveredAlertInstances = mapValues, AlertInstance>( + state.alertInstances ?? {}, + (rawAlertInstance) => new AlertInstance(rawAlertInstance) + ); + const recoveredAlertInstanceIds = Object.keys(recoveredAlertInstances); + + for (const instanceId of recoveredAlertInstanceIds) { + const { group: actionGroup, subgroup: actionSubgroup } = + recoveredAlertInstances[instanceId].getLastScheduledActions() ?? {}; + const instanceState = recoveredAlertInstances[instanceId].getState(); + const message = `instance '${instanceId}' has recovered due to the rule was disabled`; + + const event = createAlertEventLogRecordObject({ + ruleId: id, + ruleName: attributes.name, + ruleType: this.ruleTypeRegistry.get(attributes.alertTypeId), + instanceId, + action: EVENT_LOG_ACTIONS.recoveredInstance, + message, + state: instanceState, + group: actionGroup, + subgroup: actionSubgroup, + namespace: this.namespace, + savedObjects: [ + { + id, + type: 'alert', + typeId: attributes.alertTypeId, + relation: SAVED_OBJECT_REL_PRIMARY, + }, + ], + }); + this.eventLogger.logEvent(event); + } + } catch (error) { + // this should not block the rest of the disable process + this.logger.warn( + `rulesClient.disable('${id}') - Could not write recovery events - ${error.message}` + ); } } try { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts index c518d385dd747..a5b9f1d928e81 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/disable.test.ts @@ -350,6 +350,65 @@ describe('disable()', () => { }); }); + test('disables the rule even if unable to retrieve task manager doc to generate recovery event log events', async () => { + unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ + id: '1', + type: 'api_key_pending_invalidation', + attributes: { + apiKeyId: '123', + createdAt: '2019-02-12T21:01:22.479Z', + }, + references: [], + }); + taskManager.get.mockRejectedValueOnce(new Error('Fail')); + await rulesClient.disable({ id: '1' }); + expect(unsecuredSavedObjectsClient.get).not.toHaveBeenCalled(); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { + namespace: 'default', + }); + expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledWith( + 'alert', + '1', + { + consumer: 'myApp', + schedule: { interval: '10s' }, + alertTypeId: 'myType', + enabled: false, + meta: { + versionApiKeyLastmodified: kibanaVersion, + }, + scheduledTaskId: null, + apiKey: null, + apiKeyOwner: null, + updatedAt: '2019-02-12T21:01:22.479Z', + updatedBy: 'elastic', + actions: [ + { + group: 'default', + id: '1', + actionTypeId: '1', + actionRef: '1', + params: { + foo: true, + }, + }, + ], + }, + { + version: '123', + } + ); + expect(taskManager.removeIfExists).toHaveBeenCalledWith('task-123'); + expect( + (unsecuredSavedObjectsClient.create.mock.calls[0][1] as InvalidatePendingApiKey).apiKeyId + ).toBe('123'); + + expect(eventLogger.logEvent).toHaveBeenCalledTimes(0); + expect(rulesClientParams.logger.warn).toHaveBeenCalledWith( + `rulesClient.disable('1') - Could not write recovery events - Fail` + ); + }); + test('falls back when getDecryptedAsInternalUser throws an error', async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); unsecuredSavedObjectsClient.create.mockResolvedValueOnce({ diff --git a/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts index 537d890217cfb..8102dcedbd780 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/resolve.test.ts @@ -125,6 +125,80 @@ describe('resolve()', () => { `); }); + test('calls saved objects client with id and includeLegacyId params', async () => { + const rulesClient = new RulesClient(rulesClientParams); + unsecuredSavedObjectsClient.resolve.mockResolvedValueOnce({ + saved_object: { + id: '1', + type: 'alert', + attributes: { + legacyId: 'some-legacy-id', + alertTypeId: '123', + schedule: { interval: '10s' }, + params: { + bar: true, + }, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + actions: [ + { + group: 'default', + actionRef: 'action_0', + params: { + foo: true, + }, + }, + ], + notifyWhen: 'onActiveAlert', + }, + references: [ + { + name: 'action_0', + type: 'action', + id: '1', + }, + ], + }, + outcome: 'aliasMatch', + alias_target_id: '2', + }); + const result = await rulesClient.resolve({ id: '1', includeLegacyId: true }); + expect(result).toMatchInlineSnapshot(` + Object { + "actions": Array [ + Object { + "group": "default", + "id": "1", + "params": Object { + "foo": true, + }, + }, + ], + "alertTypeId": "123", + "alias_target_id": "2", + "createdAt": 2019-02-12T21:01:22.479Z, + "id": "1", + "legacyId": "some-legacy-id", + "notifyWhen": "onActiveAlert", + "outcome": "aliasMatch", + "params": Object { + "bar": true, + }, + "schedule": Object { + "interval": "10s", + }, + "updatedAt": 2019-02-12T21:01:22.479Z, + } + `); + expect(unsecuredSavedObjectsClient.resolve).toHaveBeenCalledTimes(1); + expect(unsecuredSavedObjectsClient.resolve.mock.calls[0]).toMatchInlineSnapshot(` + Array [ + "alert", + "1", + ] + `); + }); + test('should call useSavedObjectReferences.injectReferences if defined for rule type', async () => { const injectReferencesFn = jest.fn().mockReturnValue({ bar: true, diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx index 35c6fb3c634cc..74d9ccdcda8d8 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/PercentileAnnotations.tsx @@ -35,7 +35,7 @@ export function PercentileAnnotations({ percentiles }: Props) { const style: Partial = { line: { strokeWidth: 1, - stroke: euiLightVars.euiColorSecondary, + stroke: euiLightVars.euiColorSuccess, opacity: 1, }, }; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/render_option.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/render_option.tsx index 4a4d8e9d3e191..3293760ef7128 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/render_option.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/render_option.tsx @@ -11,7 +11,7 @@ import styled from 'styled-components'; import { euiLightVars } from '@kbn/ui-shared-deps-src/theme'; const StyledSpan = styled.span` - color: ${euiLightVars.euiColorSecondaryText}; + color: ${euiLightVars.euiColorSuccessText}; font-weight: 500; :not(:last-of-type)::after { content: '•'; diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx index 7623e467aaa2d..8789bbd772319 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx @@ -224,7 +224,7 @@ export function SettingsPage({ fill isLoading={isSaving} isDisabled={!isFormValid} - color="secondary" + color="success" iconType="check" > {i18n.translate( diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx index f320123ce0723..5c41a1b4db7e6 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx @@ -97,7 +97,7 @@ export function ServiceContents({ - + {i18n.translate('xpack.apm.serviceMap.focusMapButtonText', { defaultMessage: 'Focus map', })} diff --git a/x-pack/plugins/apm/public/components/shared/charts/breakdown_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/breakdown_chart/index.tsx index 7f7c163ff1ea1..78bfd8911c351 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/breakdown_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/breakdown_chart/index.tsx @@ -81,7 +81,7 @@ export function BreakdownChart({ const xFormatter = niceTimeFormatter([min, max]); - const annotationColor = theme.eui.euiColorSecondary; + const annotationColor = theme.eui.euiColorSuccess; const isEmpty = isTimeseriesEmpty(timeseries); diff --git a/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx b/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx index bcdfff2678cda..29ef524508b02 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx @@ -105,7 +105,7 @@ export function TimeseriesChart({ const xFormatter = niceTimeFormatter([min, max]); const isEmpty = isTimeseriesEmpty(timeseries); - const annotationColor = theme.eui.euiColorSecondary; + const annotationColor = theme.eui.euiColorSuccess; const allSeries = [...timeseries, ...(anomalyTimeseries?.boundaries ?? [])]; const xDomain = isEmpty ? { min: 0, max: 1 } : { min, max }; diff --git a/x-pack/plugins/apm/public/components/shared/license_prompt/index.tsx b/x-pack/plugins/apm/public/components/shared/license_prompt/index.tsx index 0950cff5127fc..5d643614ba4d3 100644 --- a/x-pack/plugins/apm/public/components/shared/license_prompt/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/license_prompt/index.tsx @@ -27,21 +27,19 @@ export function LicensePrompt({ {i18n.translate( diff --git a/x-pack/plugins/apm/server/deprecations/index.ts b/x-pack/plugins/apm/server/deprecations/index.ts index 39e282e76d9a6..92955fa0c6d0b 100644 --- a/x-pack/plugins/apm/server/deprecations/index.ts +++ b/x-pack/plugins/apm/server/deprecations/index.ts @@ -9,7 +9,7 @@ import { GetDeprecationsContext, DeprecationsDetails } from 'src/core/server'; import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; import { CloudSetup } from '../../../cloud/server'; -import { getCloudAgentPolicy } from '../lib/fleet/get_cloud_apm_package_policy'; +import { getCloudAgentPolicy } from '../routes/fleet/get_cloud_apm_package_policy'; import { APMRouteHandlerResources } from '../'; export function getDeprecations({ diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts index 9b5820767690f..8aee60357ba73 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts @@ -12,7 +12,7 @@ import { ESSearchRequest, ESSearchResponse, } from '../../../../../../../src/core/types/elasticsearch'; -import { ApmIndicesConfig } from '../../settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../../../routes/settings/apm_indices/get_apm_indices'; import { tasks } from './tasks'; import { APMDataTelemetry } from '../types'; diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts index 1e697ebdcae06..b69aa1e6e0196 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { ApmIndicesConfig } from '../../settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../../../routes/settings/apm_indices/get_apm_indices'; import { tasks } from './tasks'; import { SERVICE_NAME, diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts index 88ef1203bae9f..bdbb1fe1dbcd3 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/index.ts @@ -24,7 +24,7 @@ import { APM_TELEMETRY_SAVED_OBJECT_TYPE, } from '../../../common/apm_saved_object_constants'; import { getInternalSavedObjectsClient } from '../helpers/get_internal_saved_objects_client'; -import { getApmIndices } from '../settings/apm_indices/get_apm_indices'; +import { getApmIndices } from '../../routes/settings/apm_indices/get_apm_indices'; import { collectDataTelemetry, CollectTelemetryParams, diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts index a45d314c33719..6c9a0cb45e273 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts @@ -26,7 +26,7 @@ import { APMError } from '../../../../../typings/es_schemas/ui/apm_error'; import { Metric } from '../../../../../typings/es_schemas/ui/metric'; import { Span } from '../../../../../typings/es_schemas/ui/span'; import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; -import { ApmIndicesConfig } from '../../../settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../../../../routes/settings/apm_indices/get_apm_indices'; import { callAsyncWithDebug, getDebugBody, diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.test.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.test.ts index 5ef3786e9bde4..d3f0fca0bb259 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.test.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.test.ts @@ -6,7 +6,7 @@ */ import { APMEventESSearchRequest } from '.'; -import { ApmIndicesConfig } from '../../../settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../../../../routes/settings/apm_indices/get_apm_indices'; import { unpackProcessorEvents } from './unpack_processor_events'; describe('unpackProcessorEvents', () => { diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.ts index 582fe0374c5ca..e62720e9fbd0c 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/unpack_processor_events.ts @@ -13,7 +13,7 @@ import { ESFilter, } from '../../../../../../../../src/core/types/elasticsearch'; import { APMEventESSearchRequest, APMEventESTermsEnumRequest } from '.'; -import { ApmIndicesConfig } from '../../../settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../../../../routes/settings/apm_indices/get_apm_indices'; const processorEventIndexMap = { [ProcessorEvent.transaction]: 'transaction', diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts index 7b3201095106e..ffcbe01b7f043 100644 --- a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts +++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts @@ -10,10 +10,10 @@ import { APMConfig } from '../..'; import { APMRouteHandlerResources } from '../../routes/typings'; import { ProcessorEvent } from '../../../common/processor_event'; import { PROCESSOR_EVENT } from '../../../common/elasticsearch_fieldnames'; -import { getApmIndices } from '../settings/apm_indices/get_apm_indices'; +import { getApmIndices } from '../../routes/settings/apm_indices/get_apm_indices'; import { PromiseReturnType } from '../../../../observability/typings/common'; -jest.mock('../settings/apm_indices/get_apm_indices', () => ({ +jest.mock('../../routes/settings/apm_indices/get_apm_indices', () => ({ getApmIndices: async () => ({ sourcemap: 'apm-*', @@ -26,7 +26,7 @@ jest.mock('../settings/apm_indices/get_apm_indices', () => ({ } as PromiseReturnType), })); -jest.mock('../data_view/get_dynamic_data_view', () => ({ +jest.mock('../../routes/data_view/get_dynamic_data_view', () => ({ getDynamicDataView: async () => { return; }, diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.ts index a0d908c68d84d..85fb94dd765b0 100644 --- a/x-pack/plugins/apm/server/lib/helpers/setup_request.ts +++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.ts @@ -13,7 +13,7 @@ import { APMRouteHandlerResources } from '../../routes/typings'; import { ApmIndicesConfig, getApmIndices, -} from '../settings/apm_indices/get_apm_indices'; +} from '../../routes/settings/apm_indices/get_apm_indices'; import { APMEventClient, createApmEventClient, diff --git a/x-pack/plugins/apm/server/plugin.ts b/x-pack/plugins/apm/server/plugin.ts index b273fc867e5a8..9ece2c507847e 100644 --- a/x-pack/plugins/apm/server/plugin.ts +++ b/x-pack/plugins/apm/server/plugin.ts @@ -20,14 +20,14 @@ import { Dataset } from '../../rule_registry/server'; import { APMConfig, APM_SERVER_FEATURE_ID } from '.'; import { UI_SETTINGS } from '../../../../src/plugins/data/common'; import { APM_FEATURE, registerFeaturesUsage } from './feature'; -import { registerApmAlerts } from './lib/alerts/register_apm_alerts'; -import { registerFleetPolicyCallbacks } from './lib/fleet/register_fleet_policy_callbacks'; +import { registerApmAlerts } from './routes/alerts/register_apm_alerts'; +import { registerFleetPolicyCallbacks } from './routes/fleet/register_fleet_policy_callbacks'; import { createApmTelemetry } from './lib/apm_telemetry'; import { createApmEventClient } from './lib/helpers/create_es_client/create_apm_event_client'; import { getInternalSavedObjectsClient } from './lib/helpers/get_internal_saved_objects_client'; -import { createApmAgentConfigurationIndex } from './lib/settings/agent_configuration/create_agent_config_index'; -import { getApmIndices } from './lib/settings/apm_indices/get_apm_indices'; -import { createApmCustomLinkIndex } from './lib/settings/custom_link/create_custom_link_index'; +import { createApmAgentConfigurationIndex } from './routes/settings/agent_configuration/create_agent_config_index'; +import { getApmIndices } from './routes/settings/apm_indices/get_apm_indices'; +import { createApmCustomLinkIndex } from './routes/settings/custom_link/create_custom_link_index'; import { apmIndices, apmTelemetry, apmServerSettings } from './saved_objects'; import type { ApmPluginRequestHandlerContext, diff --git a/x-pack/plugins/apm/server/projections/rum_page_load_transactions.ts b/x-pack/plugins/apm/server/projections/rum_page_load_transactions.ts index 6265ee71c27e1..e3e98cc3c1773 100644 --- a/x-pack/plugins/apm/server/projections/rum_page_load_transactions.ts +++ b/x-pack/plugins/apm/server/projections/rum_page_load_transactions.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SetupUX } from '../routes/rum_client'; +import { SetupUX } from '../routes/rum_client/route'; import { AGENT_NAME, TRANSACTION_TYPE, @@ -14,7 +14,7 @@ import { import { rangeQuery } from '../../../observability/server'; import { ProcessorEvent } from '../../common/processor_event'; import { TRANSACTION_PAGE_LOAD } from '../../common/transaction_types'; -import { getEsFilter } from '../lib/rum_client/ui_filters/get_es_filter'; +import { getEsFilter } from '../routes/rum_client/ui_filters/get_es_filter'; export function getRumPageLoadTransactionsProjection({ setup, diff --git a/x-pack/plugins/apm/server/lib/alerts/action_variables.ts b/x-pack/plugins/apm/server/routes/alerts/action_variables.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/action_variables.ts rename to x-pack/plugins/apm/server/routes/alerts/action_variables.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/alerting_es_client.ts b/x-pack/plugins/apm/server/routes/alerts/alerting_es_client.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/alerting_es_client.ts rename to x-pack/plugins/apm/server/routes/alerts/alerting_es_client.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts b/x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_duration.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts rename to x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_duration.ts index 693502d7629e8..0338f78a0a892 100644 --- a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts +++ b/x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_duration.ts @@ -12,14 +12,14 @@ import { TRANSACTION_TYPE, } from '../../../../common/elasticsearch_fieldnames'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { AlertParams } from '../../../routes/alerts/chart_preview'; +import { AlertParams } from '../route'; import { getSearchAggregatedTransactions, getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../../helpers/transactions'; -import { Setup } from '../../helpers/setup_request'; +} from '../../../lib/helpers/transactions'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getTransactionDurationChartPreview({ alertParams, diff --git a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_error_count.ts b/x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_error_count.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_error_count.ts rename to x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_error_count.ts index 0e1fa74199f60..708acd6d7f8ea 100644 --- a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_error_count.ts +++ b/x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_error_count.ts @@ -7,10 +7,10 @@ import { SERVICE_NAME } from '../../../../common/elasticsearch_fieldnames'; import { ProcessorEvent } from '../../../../common/processor_event'; -import { AlertParams } from '../../../routes/alerts/chart_preview'; +import { AlertParams } from '../route'; import { rangeQuery, termQuery } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getTransactionErrorCountChartPreview({ setup, diff --git a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_error_rate.ts b/x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_error_rate.ts similarity index 91% rename from x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_error_rate.ts rename to x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_error_rate.ts index e2bfaf29f83cb..cf3380c105ac8 100644 --- a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_error_rate.ts +++ b/x-pack/plugins/apm/server/routes/alerts/chart_preview/get_transaction_error_rate.ts @@ -11,17 +11,17 @@ import { TRANSACTION_TYPE, } from '../../../../common/elasticsearch_fieldnames'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { AlertParams } from '../../../routes/alerts/chart_preview'; +import { AlertParams } from '../route'; import { getSearchAggregatedTransactions, getDocumentTypeFilterForTransactions, getProcessorEventForTransactions, -} from '../../helpers/transactions'; -import { Setup } from '../../helpers/setup_request'; +} from '../../../lib/helpers/transactions'; +import { Setup } from '../../../lib/helpers/setup_request'; import { calculateFailedTransactionRate, getOutcomeAggregation, -} from '../../helpers/transaction_error_rate'; +} from '../../../lib/helpers/transaction_error_rate'; export async function getTransactionErrorRateChartPreview({ setup, diff --git a/x-pack/plugins/apm/server/lib/alerts/register_apm_alerts.ts b/x-pack/plugins/apm/server/routes/alerts/register_apm_alerts.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/register_apm_alerts.ts rename to x-pack/plugins/apm/server/routes/alerts/register_apm_alerts.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.test.ts rename to x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.test.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts b/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts rename to x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.ts index 723f52cb1eeda..2dacb5ca1e895 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_error_count_alert_type.ts +++ b/x-pack/plugins/apm/server/routes/alerts/register_error_count_alert_type.ts @@ -31,7 +31,7 @@ import { } from '../../../common/elasticsearch_fieldnames'; import { ProcessorEvent } from '../../../common/processor_event'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { getApmIndices } from '../settings/apm_indices/get_apm_indices'; +import { getApmIndices } from '../../routes/settings/apm_indices/get_apm_indices'; import { apmActionVariables } from './action_variables'; import { alertingEsClient } from './alerting_es_client'; import { RegisterRuleDependencies } from './register_apm_alerts'; diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.test.ts rename to x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.test.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts rename to x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.ts index 4e68ca6b52248..1e39b02655ada 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts +++ b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_alert_type.ts @@ -37,8 +37,8 @@ import { getDurationFormatter } from '../../../common/utils/formatters'; import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, -} from '../helpers/transactions'; -import { getApmIndices } from '../settings/apm_indices/get_apm_indices'; +} from '../../lib/helpers/transactions'; +import { getApmIndices } from '../../routes/settings/apm_indices/get_apm_indices'; import { apmActionVariables } from './action_variables'; import { alertingEsClient } from './alerting_es_client'; import { RegisterRuleDependencies } from './register_apm_alerts'; diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_anomaly_alert_type.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.test.ts rename to x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_anomaly_alert_type.test.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_anomaly_alert_type.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts rename to x-pack/plugins/apm/server/routes/alerts/register_transaction_duration_anomaly_alert_type.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.test.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.test.ts rename to x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.test.ts diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts b/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts rename to x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.ts index cf5b45d901228..f196b718968da 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_error_rate_alert_type.ts +++ b/x-pack/plugins/apm/server/routes/alerts/register_transaction_error_rate_alert_type.ts @@ -35,12 +35,12 @@ import { EventOutcome } from '../../../common/event_outcome'; import { ProcessorEvent } from '../../../common/processor_event'; import { asDecimalOrInteger } from '../../../common/utils/formatters'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { getApmIndices } from '../settings/apm_indices/get_apm_indices'; +import { getApmIndices } from '../../routes/settings/apm_indices/get_apm_indices'; import { apmActionVariables } from './action_variables'; import { alertingEsClient } from './alerting_es_client'; import { RegisterRuleDependencies } from './register_apm_alerts'; import { SearchAggregatedTransactionSetting } from '../../../common/aggregated_transactions'; -import { getDocumentTypeFilterForTransactions } from '../helpers/transactions'; +import { getDocumentTypeFilterForTransactions } from '../../lib/helpers/transactions'; import { asPercent } from '../../../../observability/common/utils/formatters'; import { termQuery } from '../../../../observability/server'; diff --git a/x-pack/plugins/apm/server/routes/alerts/chart_preview.ts b/x-pack/plugins/apm/server/routes/alerts/route.ts similarity index 89% rename from x-pack/plugins/apm/server/routes/alerts/chart_preview.ts rename to x-pack/plugins/apm/server/routes/alerts/route.ts index cae35c7f06a85..49baeda8d3a47 100644 --- a/x-pack/plugins/apm/server/routes/alerts/chart_preview.ts +++ b/x-pack/plugins/apm/server/routes/alerts/route.ts @@ -6,9 +6,9 @@ */ import * as t from 'io-ts'; -import { getTransactionDurationChartPreview } from '../../lib/alerts/chart_preview/get_transaction_duration'; -import { getTransactionErrorCountChartPreview } from '../../lib/alerts/chart_preview/get_transaction_error_count'; -import { getTransactionErrorRateChartPreview } from '../../lib/alerts/chart_preview/get_transaction_error_rate'; +import { getTransactionDurationChartPreview } from './chart_preview/get_transaction_duration'; +import { getTransactionErrorCountChartPreview } from './chart_preview/get_transaction_error_count'; +import { getTransactionErrorRateChartPreview } from './chart_preview/get_transaction_error_rate'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; diff --git a/x-pack/plugins/apm/server/lib/alerts/test_utils/index.ts b/x-pack/plugins/apm/server/routes/alerts/test_utils/index.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/alerts/test_utils/index.ts rename to x-pack/plugins/apm/server/routes/alerts/test_utils/index.ts diff --git a/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts b/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts index fa8bc1e54ebfb..ee4c9d1c8cfa5 100644 --- a/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts +++ b/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts @@ -10,33 +10,33 @@ import type { EndpointOf, } from '@kbn/server-route-repository'; import { PickByValue } from 'utility-types'; -import { correlationsRouteRepository } from '../correlations'; -import { alertsChartPreviewRouteRepository } from '../alerts/chart_preview'; +import { correlationsRouteRepository } from '../correlations/route'; +import { alertsChartPreviewRouteRepository } from '../alerts/route'; import { backendsRouteRepository } from '../backends/route'; import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; -import { environmentsRouteRepository } from '../environments'; -import { errorsRouteRepository } from '../errors'; -import { apmFleetRouteRepository } from '../fleet'; -import { dataViewRouteRepository } from '../data_view'; -import { latencyDistributionRouteRepository } from '../latency_distribution'; -import { metricsRouteRepository } from '../metrics'; -import { observabilityOverviewRouteRepository } from '../observability_overview'; -import { rumRouteRepository } from '../rum_client'; -import { fallbackToTransactionsRouteRepository } from '../fallback_to_transactions'; -import { serviceRouteRepository } from '../services'; -import { serviceMapRouteRepository } from '../service_map'; -import { serviceNodeRouteRepository } from '../service_nodes'; -import { agentConfigurationRouteRepository } from '../settings/agent_configuration'; -import { anomalyDetectionRouteRepository } from '../settings/anomaly_detection'; -import { apmIndicesRouteRepository } from '../settings/apm_indices'; -import { customLinkRouteRepository } from '../settings/custom_link'; -import { sourceMapsRouteRepository } from '../source_maps'; -import { traceRouteRepository } from '../traces'; -import { transactionRouteRepository } from '../transactions'; +import { environmentsRouteRepository } from '../environments/route'; +import { errorsRouteRepository } from '../errors/route'; +import { apmFleetRouteRepository } from '../fleet/route'; +import { dataViewRouteRepository } from '../data_view/route'; +import { latencyDistributionRouteRepository } from '../latency_distribution/route'; +import { metricsRouteRepository } from '../metrics/route'; +import { observabilityOverviewRouteRepository } from '../observability_overview/route'; +import { rumRouteRepository } from '../rum_client/route'; +import { fallbackToTransactionsRouteRepository } from '../fallback_to_transactions/route'; +import { serviceRouteRepository } from '../services/route'; +import { serviceMapRouteRepository } from '../service_map/route'; +import { serviceNodeRouteRepository } from '../service_nodes/route'; +import { agentConfigurationRouteRepository } from '../settings/agent_configuration/route'; +import { anomalyDetectionRouteRepository } from '../settings/anomaly_detection/route'; +import { apmIndicesRouteRepository } from '../settings/apm_indices/route'; +import { customLinkRouteRepository } from '../settings/custom_link/route'; +import { sourceMapsRouteRepository } from '../source_maps/route'; +import { traceRouteRepository } from '../traces/route'; +import { transactionRouteRepository } from '../transactions/route'; import { APMRouteHandlerResources } from '../typings'; import { historicalDataRouteRepository } from '../historical_data'; -import { eventMetadataRouteRepository } from '../event_metadata'; -import { suggestionsRouteRepository } from '../suggestions'; +import { eventMetadataRouteRepository } from '../event_metadata/route'; +import { suggestionsRouteRepository } from '../suggestions/route'; const getTypedGlobalApmServerRouteRepository = () => { const repository = createApmServerRouteRepository() diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_boolean_field_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_boolean_field_stats.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_boolean_field_stats.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_boolean_field_stats.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_field_stats.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_stats.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_field_stats.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_field_stats.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_fields_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_fields_stats.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_fields_stats.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_fields_stats.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_keyword_field_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_keyword_field_stats.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_keyword_field_stats.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_keyword_field_stats.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_numeric_field_stats.ts b/x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_numeric_field_stats.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/field_stats/get_numeric_field_stats.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/field_stats/get_numeric_field_stats.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/get_filters.ts b/x-pack/plugins/apm/server/routes/correlations/queries/get_filters.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/get_filters.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/get_filters.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/get_query_with_params.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/get_query_with_params.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/get_query_with_params.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/get_query_with_params.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/get_query_with_params.ts b/x-pack/plugins/apm/server/routes/correlations/queries/get_query_with_params.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/get_query_with_params.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/get_query_with_params.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/get_request_base.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/get_request_base.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/get_request_base.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/get_request_base.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/get_request_base.ts b/x-pack/plugins/apm/server/routes/correlations/queries/get_request_base.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/get_request_base.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/get_request_base.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/index.ts b/x-pack/plugins/apm/server/routes/correlations/queries/index.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/index.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/index.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_correlation.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_correlation.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_correlation.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_correlation.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_correlation.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_correlation_with_histogram.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_correlation_with_histogram.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_correlation_with_histogram.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_correlation_with_histogram.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_correlation_with_histogram.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_failure_correlation.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_failure_correlation.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_failure_correlation.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_failure_correlation.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_field_candidates.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_field_candidates.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_field_candidates.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_field_candidates.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_field_candidates.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_field_value_pairs.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_field_value_pairs.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_field_value_pairs.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_field_value_pairs.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_field_value_pairs.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_fractions.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_fractions.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_fractions.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_fractions.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_fractions.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_histogram.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_histogram.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_histogram.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_histogram.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_histogram.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_histogram_range_steps.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_histogram_range_steps.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_histogram_range_steps.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_histogram_range_steps.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_histogram_range_steps.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_p_values.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_p_values.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_p_values.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_p_values.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_percentiles.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_percentiles.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_percentiles.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_percentiles.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_percentiles.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_ranges.test.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_ranges.test.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_ranges.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_ranges.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_ranges.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/queries/query_significant_correlations.ts b/x-pack/plugins/apm/server/routes/correlations/queries/query_significant_correlations.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/queries/query_significant_correlations.ts rename to x-pack/plugins/apm/server/routes/correlations/queries/query_significant_correlations.ts diff --git a/x-pack/plugins/apm/server/routes/correlations.ts b/x-pack/plugins/apm/server/routes/correlations/route.ts similarity index 92% rename from x-pack/plugins/apm/server/routes/correlations.ts rename to x-pack/plugins/apm/server/routes/correlations/route.ts index f6ca064b4385f..b02a6fbc6b7a6 100644 --- a/x-pack/plugins/apm/server/routes/correlations.ts +++ b/x-pack/plugins/apm/server/routes/correlations/route.ts @@ -11,22 +11,22 @@ import Boom from '@hapi/boom'; import { i18n } from '@kbn/i18n'; import { toNumberRt } from '@kbn/io-ts-utils/to_number_rt'; -import { isActivePlatinumLicense } from '../../common/license_check'; +import { isActivePlatinumLicense } from '../../../common/license_check'; -import { setupRequest } from '../lib/helpers/setup_request'; +import { setupRequest } from '../../lib/helpers/setup_request'; import { fetchPValues, fetchSignificantCorrelations, fetchTransactionDurationFieldCandidates, fetchTransactionDurationFieldValuePairs, -} from '../lib/correlations/queries'; -import { fetchFieldsStats } from '../lib/correlations/queries/field_stats/get_fields_stats'; +} from './queries'; +import { fetchFieldsStats } from './queries/field_stats/get_fields_stats'; -import { withApmSpan } from '../utils/with_apm_span'; +import { withApmSpan } from '../../utils/with_apm_span'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { environmentRt, kueryRt, rangeRt } from './default_api_types'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; const INVALID_LICENSE = i18n.translate('xpack.apm.correlations.license.text', { defaultMessage: diff --git a/x-pack/plugins/apm/server/lib/correlations/utils/compute_expectations_and_ranges.test.ts b/x-pack/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/utils/compute_expectations_and_ranges.test.ts rename to x-pack/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.test.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/utils/compute_expectations_and_ranges.ts b/x-pack/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/utils/compute_expectations_and_ranges.ts rename to x-pack/plugins/apm/server/routes/correlations/utils/compute_expectations_and_ranges.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/utils/field_stats_utils.ts b/x-pack/plugins/apm/server/routes/correlations/utils/field_stats_utils.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/utils/field_stats_utils.ts rename to x-pack/plugins/apm/server/routes/correlations/utils/field_stats_utils.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/utils/index.ts b/x-pack/plugins/apm/server/routes/correlations/utils/index.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/utils/index.ts rename to x-pack/plugins/apm/server/routes/correlations/utils/index.ts diff --git a/x-pack/plugins/apm/server/lib/correlations/utils/split_all_settled_promises.ts b/x-pack/plugins/apm/server/routes/correlations/utils/split_all_settled_promises.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/correlations/utils/split_all_settled_promises.ts rename to x-pack/plugins/apm/server/routes/correlations/utils/split_all_settled_promises.ts diff --git a/x-pack/plugins/apm/server/lib/data_view/create_static_data_view.test.ts b/x-pack/plugins/apm/server/routes/data_view/create_static_data_view.test.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/data_view/create_static_data_view.test.ts rename to x-pack/plugins/apm/server/routes/data_view/create_static_data_view.test.ts index 77b9f0ffd4ad0..7d345b5e3bec1 100644 --- a/x-pack/plugins/apm/server/lib/data_view/create_static_data_view.test.ts +++ b/x-pack/plugins/apm/server/routes/data_view/create_static_data_view.test.ts @@ -6,9 +6,9 @@ */ import { createStaticDataView } from './create_static_data_view'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import * as HistoricalAgentData from '../../routes/historical_data/has_historical_agent_data'; -import { InternalSavedObjectsClient } from '../helpers/get_internal_saved_objects_client'; +import { InternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; import { APMConfig } from '../..'; function getMockSavedObjectsClient(existingDataViewTitle: string) { diff --git a/x-pack/plugins/apm/server/lib/data_view/create_static_data_view.ts b/x-pack/plugins/apm/server/routes/data_view/create_static_data_view.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/data_view/create_static_data_view.ts rename to x-pack/plugins/apm/server/routes/data_view/create_static_data_view.ts index 521d290b9ca22..13639d2efcbfe 100644 --- a/x-pack/plugins/apm/server/lib/data_view/create_static_data_view.ts +++ b/x-pack/plugins/apm/server/routes/data_view/create_static_data_view.ts @@ -9,9 +9,9 @@ import { SavedObjectsErrorHelpers } from '../../../../../../src/core/server'; import { APM_STATIC_INDEX_PATTERN_ID } from '../../../common/index_pattern_constants'; import apmDataView from '../../tutorial/index_pattern.json'; import { hasHistoricalAgentData } from '../../routes/historical_data/has_historical_agent_data'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { APMRouteHandlerResources } from '../../routes/typings'; -import { InternalSavedObjectsClient } from '../helpers/get_internal_saved_objects_client.js'; +import { InternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client.js'; import { withApmSpan } from '../../utils/with_apm_span'; import { getApmDataViewTitle } from './get_apm_data_view_title'; diff --git a/x-pack/plugins/apm/server/lib/data_view/get_apm_data_view_title.test.ts b/x-pack/plugins/apm/server/routes/data_view/get_apm_data_view_title.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/data_view/get_apm_data_view_title.test.ts rename to x-pack/plugins/apm/server/routes/data_view/get_apm_data_view_title.test.ts diff --git a/x-pack/plugins/apm/server/lib/data_view/get_apm_data_view_title.ts b/x-pack/plugins/apm/server/routes/data_view/get_apm_data_view_title.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/data_view/get_apm_data_view_title.ts rename to x-pack/plugins/apm/server/routes/data_view/get_apm_data_view_title.ts diff --git a/x-pack/plugins/apm/server/lib/data_view/get_dynamic_data_view.ts b/x-pack/plugins/apm/server/routes/data_view/get_dynamic_data_view.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/data_view/get_dynamic_data_view.ts rename to x-pack/plugins/apm/server/routes/data_view/get_dynamic_data_view.ts diff --git a/x-pack/plugins/apm/server/routes/data_view.ts b/x-pack/plugins/apm/server/routes/data_view/route.ts similarity index 78% rename from x-pack/plugins/apm/server/routes/data_view.ts rename to x-pack/plugins/apm/server/routes/data_view/route.ts index 3590ef9db9bd0..4e1c0ca050a09 100644 --- a/x-pack/plugins/apm/server/routes/data_view.ts +++ b/x-pack/plugins/apm/server/routes/data_view/route.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { createStaticDataView } from '../lib/data_view/create_static_data_view'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getDynamicDataView } from '../lib/data_view/get_dynamic_data_view'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; +import { createStaticDataView } from './create_static_data_view'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getDynamicDataView } from './get_dynamic_data_view'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; const staticDataViewRoute = createApmServerRoute({ endpoint: 'POST /internal/apm/data_view/static', diff --git a/x-pack/plugins/apm/server/lib/environments/__snapshots__/get_all_environments.test.ts.snap b/x-pack/plugins/apm/server/routes/environments/__snapshots__/get_all_environments.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/environments/__snapshots__/get_all_environments.test.ts.snap rename to x-pack/plugins/apm/server/routes/environments/__snapshots__/get_all_environments.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/environments/__snapshots__/get_environments.test.ts.snap b/x-pack/plugins/apm/server/routes/environments/__snapshots__/get_environments.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/environments/__snapshots__/get_environments.test.ts.snap rename to x-pack/plugins/apm/server/routes/environments/__snapshots__/get_environments.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/environments/get_all_environments.test.ts b/x-pack/plugins/apm/server/routes/environments/get_all_environments.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/environments/get_all_environments.test.ts rename to x-pack/plugins/apm/server/routes/environments/get_all_environments.test.ts diff --git a/x-pack/plugins/apm/server/lib/environments/get_all_environments.ts b/x-pack/plugins/apm/server/routes/environments/get_all_environments.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/environments/get_all_environments.ts rename to x-pack/plugins/apm/server/routes/environments/get_all_environments.ts index 7bdb21b9fda78..f479fd185b889 100644 --- a/x-pack/plugins/apm/server/lib/environments/get_all_environments.ts +++ b/x-pack/plugins/apm/server/routes/environments/get_all_environments.ts @@ -7,13 +7,13 @@ import { termQuery } from '../../../../observability/server'; import { ProcessorEvent } from '../../../common/processor_event'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { SERVICE_NAME, SERVICE_ENVIRONMENT, } from '../../../common/elasticsearch_fieldnames'; import { ENVIRONMENT_NOT_DEFINED } from '../../../common/environment_filter_values'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; /** * This is used for getting *all* environments, and does not filter by range. diff --git a/x-pack/plugins/apm/server/lib/environments/get_environments.test.ts b/x-pack/plugins/apm/server/routes/environments/get_environments.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/environments/get_environments.test.ts rename to x-pack/plugins/apm/server/routes/environments/get_environments.test.ts diff --git a/x-pack/plugins/apm/server/lib/environments/get_environments.ts b/x-pack/plugins/apm/server/routes/environments/get_environments.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/environments/get_environments.ts rename to x-pack/plugins/apm/server/routes/environments/get_environments.ts index cd5caab6d2587..34ac9cb18d796 100644 --- a/x-pack/plugins/apm/server/lib/environments/get_environments.ts +++ b/x-pack/plugins/apm/server/routes/environments/get_environments.ts @@ -12,8 +12,8 @@ import { import { ENVIRONMENT_NOT_DEFINED } from '../../../common/environment_filter_values'; import { ProcessorEvent } from '../../../common/processor_event'; import { rangeQuery, termQuery } from '../../../../observability/server'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; -import { Setup } from '../helpers/setup_request'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; /** * This is used for getting the list of environments for the environments selector, diff --git a/x-pack/plugins/apm/server/routes/environments.ts b/x-pack/plugins/apm/server/routes/environments/route.ts similarity index 72% rename from x-pack/plugins/apm/server/routes/environments.ts rename to x-pack/plugins/apm/server/routes/environments/route.ts index 38328a63a411e..6c980187cd331 100644 --- a/x-pack/plugins/apm/server/routes/environments.ts +++ b/x-pack/plugins/apm/server/routes/environments/route.ts @@ -6,13 +6,13 @@ */ import * as t from 'io-ts'; -import { maxSuggestions } from '../../../observability/common'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getEnvironments } from '../lib/environments/get_environments'; -import { rangeRt } from './default_api_types'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; +import { maxSuggestions } from '../../../../observability/common'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getEnvironments } from './get_environments'; +import { rangeRt } from '../default_api_types'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const environmentsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/environments', diff --git a/x-pack/plugins/apm/server/lib/errors/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/errors/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/errors/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/errors/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/errors/distribution/__snapshots__/get_buckets.test.ts.snap b/x-pack/plugins/apm/server/routes/errors/distribution/__snapshots__/get_buckets.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/errors/distribution/__snapshots__/get_buckets.test.ts.snap rename to x-pack/plugins/apm/server/routes/errors/distribution/__snapshots__/get_buckets.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/errors/distribution/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/errors/distribution/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/errors/distribution/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/errors/distribution/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/errors/distribution/get_buckets.test.ts b/x-pack/plugins/apm/server/routes/errors/distribution/get_buckets.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/errors/distribution/get_buckets.test.ts rename to x-pack/plugins/apm/server/routes/errors/distribution/get_buckets.test.ts diff --git a/x-pack/plugins/apm/server/lib/errors/distribution/get_buckets.ts b/x-pack/plugins/apm/server/routes/errors/distribution/get_buckets.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/errors/distribution/get_buckets.ts rename to x-pack/plugins/apm/server/routes/errors/distribution/get_buckets.ts index 625089e99d360..dd2dd3bc9ff3e 100644 --- a/x-pack/plugins/apm/server/lib/errors/distribution/get_buckets.ts +++ b/x-pack/plugins/apm/server/routes/errors/distribution/get_buckets.ts @@ -16,7 +16,7 @@ import { termQuery, } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getBuckets({ environment, diff --git a/x-pack/plugins/apm/server/lib/errors/distribution/get_distribution.ts b/x-pack/plugins/apm/server/routes/errors/distribution/get_distribution.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/errors/distribution/get_distribution.ts rename to x-pack/plugins/apm/server/routes/errors/distribution/get_distribution.ts index 7d5cbe9f95584..9e7221b7cd939 100644 --- a/x-pack/plugins/apm/server/lib/errors/distribution/get_distribution.ts +++ b/x-pack/plugins/apm/server/routes/errors/distribution/get_distribution.ts @@ -6,7 +6,7 @@ */ import { offsetPreviousPeriodCoordinates } from '../../../../common/utils/offset_previous_period_coordinate'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { BUCKET_TARGET_COUNT } from '../../transactions/constants'; import { getBuckets } from './get_buckets'; diff --git a/x-pack/plugins/apm/server/lib/errors/distribution/queries.test.ts b/x-pack/plugins/apm/server/routes/errors/distribution/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/errors/distribution/queries.test.ts rename to x-pack/plugins/apm/server/routes/errors/distribution/queries.test.ts diff --git a/x-pack/plugins/apm/server/lib/errors/get_error_group_sample.ts b/x-pack/plugins/apm/server/routes/errors/get_error_group_sample.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/errors/get_error_group_sample.ts rename to x-pack/plugins/apm/server/routes/errors/get_error_group_sample.ts index 35c3ce999a9ff..2c5073fb5dc66 100644 --- a/x-pack/plugins/apm/server/lib/errors/get_error_group_sample.ts +++ b/x-pack/plugins/apm/server/routes/errors/get_error_group_sample.ts @@ -14,7 +14,7 @@ import { import { ProcessorEvent } from '../../../common/processor_event'; import { rangeQuery, kqlQuery } from '../../../../observability/server'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { getTransaction } from '../transactions/get_transaction'; export async function getErrorGroupSample({ diff --git a/x-pack/plugins/apm/server/lib/errors/get_error_groups.ts b/x-pack/plugins/apm/server/routes/errors/get_error_groups.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/errors/get_error_groups.ts rename to x-pack/plugins/apm/server/routes/errors/get_error_groups.ts index 4d4c935d20e76..b26f3f4e7b4fe 100644 --- a/x-pack/plugins/apm/server/lib/errors/get_error_groups.ts +++ b/x-pack/plugins/apm/server/routes/errors/get_error_groups.ts @@ -18,8 +18,8 @@ import { ERROR_LOG_MESSAGE, SERVICE_NAME, } from '../../../common/elasticsearch_fieldnames'; -import { getErrorName } from '../helpers/get_error_name'; -import { Setup } from '../helpers/setup_request'; +import { getErrorName } from '../../lib/helpers/get_error_name'; +import { Setup } from '../../lib/helpers/setup_request'; export async function getErrorGroups({ environment, diff --git a/x-pack/plugins/apm/server/lib/errors/queries.test.ts b/x-pack/plugins/apm/server/routes/errors/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/errors/queries.test.ts rename to x-pack/plugins/apm/server/routes/errors/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/errors.ts b/x-pack/plugins/apm/server/routes/errors/route.ts similarity index 86% rename from x-pack/plugins/apm/server/routes/errors.ts rename to x-pack/plugins/apm/server/routes/errors/route.ts index 02df03f108083..602fed89be93c 100644 --- a/x-pack/plugins/apm/server/routes/errors.ts +++ b/x-pack/plugins/apm/server/routes/errors/route.ts @@ -6,18 +6,18 @@ */ import * as t from 'io-ts'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { getErrorDistribution } from '../lib/errors/distribution/get_distribution'; -import { getErrorGroupSample } from '../lib/errors/get_error_group_sample'; -import { getErrorGroups } from '../lib/errors/get_error_groups'; -import { setupRequest } from '../lib/helpers/setup_request'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { getErrorDistribution } from './distribution/get_distribution'; +import { getErrorGroupSample } from './get_error_group_sample'; +import { getErrorGroups } from './get_error_groups'; +import { setupRequest } from '../../lib/helpers/setup_request'; import { environmentRt, kueryRt, rangeRt, comparisonRangeRt, -} from './default_api_types'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; +} from '../default_api_types'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const errorsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/services/{serviceName}/errors', diff --git a/x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts b/x-pack/plugins/apm/server/routes/event_metadata/get_event_metadata.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts rename to x-pack/plugins/apm/server/routes/event_metadata/get_event_metadata.ts index b9e0dee52a42e..006c87a3dac20 100644 --- a/x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts +++ b/x-pack/plugins/apm/server/routes/event_metadata/get_event_metadata.ts @@ -12,7 +12,7 @@ import { TRANSACTION_ID, } from '../../../common/elasticsearch_fieldnames'; import { ProcessorEvent } from '../../../common/processor_event'; -import type { APMEventClient } from '../helpers/create_es_client/create_apm_event_client'; +import type { APMEventClient } from '../../lib/helpers/create_es_client/create_apm_event_client'; export async function getEventMetadata({ apmEventClient, diff --git a/x-pack/plugins/apm/server/routes/event_metadata.ts b/x-pack/plugins/apm/server/routes/event_metadata/route.ts similarity index 72% rename from x-pack/plugins/apm/server/routes/event_metadata.ts rename to x-pack/plugins/apm/server/routes/event_metadata/route.ts index 3a40e445007ee..3140372aa69de 100644 --- a/x-pack/plugins/apm/server/routes/event_metadata.ts +++ b/x-pack/plugins/apm/server/routes/event_metadata/route.ts @@ -6,11 +6,11 @@ */ import * as t from 'io-ts'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { getEventMetadata } from '../lib/event_metadata/get_event_metadata'; -import { processorEventRt } from '../../common/processor_event'; -import { setupRequest } from '../lib/helpers/setup_request'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { getEventMetadata } from './get_event_metadata'; +import { processorEventRt } from '../../../common/processor_event'; +import { setupRequest } from '../../lib/helpers/setup_request'; const eventMetadataRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/event_metadata/{processorEvent}/{id}', diff --git a/x-pack/plugins/apm/server/routes/fallback_to_transactions.ts b/x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts similarity index 70% rename from x-pack/plugins/apm/server/routes/fallback_to_transactions.ts rename to x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts index 53e3ebae0d4ff..77b5aeeac6ee8 100644 --- a/x-pack/plugins/apm/server/routes/fallback_to_transactions.ts +++ b/x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts @@ -6,11 +6,11 @@ */ import * as t from 'io-ts'; -import { getIsUsingTransactionEvents } from '../lib/helpers/transactions/get_is_using_transaction_events'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { kueryRt, rangeRt } from './default_api_types'; +import { getIsUsingTransactionEvents } from '../../lib/helpers/transactions/get_is_using_transaction_events'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { kueryRt, rangeRt } from '../default_api_types'; const fallbackToTransactionsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/fallback_to_transactions', diff --git a/x-pack/plugins/apm/server/lib/fleet/create_cloud_apm_package_policy.ts b/x-pack/plugins/apm/server/routes/fleet/create_cloud_apm_package_policy.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/fleet/create_cloud_apm_package_policy.ts rename to x-pack/plugins/apm/server/routes/fleet/create_cloud_apm_package_policy.ts index 6726865c6c3a5..a3c7bfd079a4c 100644 --- a/x-pack/plugins/apm/server/lib/fleet/create_cloud_apm_package_policy.ts +++ b/x-pack/plugins/apm/server/routes/fleet/create_cloud_apm_package_policy.ts @@ -20,7 +20,7 @@ import { APMPluginStartDependencies, } from '../../types'; import { getApmPackagePolicyDefinition } from './get_apm_package_policy_definition'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { mergePackagePolicyWithApm } from './merge_package_policy_with_apm'; export async function createCloudApmPackgePolicy({ diff --git a/x-pack/plugins/apm/server/lib/fleet/get_agents.ts b/x-pack/plugins/apm/server/routes/fleet/get_agents.ts similarity index 89% rename from x-pack/plugins/apm/server/lib/fleet/get_agents.ts rename to x-pack/plugins/apm/server/routes/fleet/get_agents.ts index 86a6294e96b09..bcfe42428dbe2 100644 --- a/x-pack/plugins/apm/server/lib/fleet/get_agents.ts +++ b/x-pack/plugins/apm/server/routes/fleet/get_agents.ts @@ -11,7 +11,7 @@ import { SavedObjectsClientContract, } from 'kibana/server'; import { APMPluginStartDependencies } from '../../types'; -import { getInternalSavedObjectsClient } from '../helpers/get_internal_saved_objects_client'; +import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; export async function getFleetAgents({ policyIds, diff --git a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts b/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policies.ts similarity index 89% rename from x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts rename to x-pack/plugins/apm/server/routes/fleet/get_apm_package_policies.ts index 5128339368f46..89ab9df051f70 100644 --- a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policies.ts +++ b/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policies.ts @@ -11,7 +11,7 @@ import { SavedObjectsClientContract, } from 'kibana/server'; import { APMPluginStartDependencies } from '../../types'; -import { getInternalSavedObjectsClient } from '../helpers/get_internal_saved_objects_client'; +import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; export async function getApmPackgePolicies({ core, diff --git a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.test.ts b/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.test.ts rename to x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.test.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.ts b/x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/get_apm_package_policy_definition.ts rename to x-pack/plugins/apm/server/routes/fleet/get_apm_package_policy_definition.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/get_cloud_apm_package_policy.ts b/x-pack/plugins/apm/server/routes/fleet/get_cloud_apm_package_policy.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/get_cloud_apm_package_policy.ts rename to x-pack/plugins/apm/server/routes/fleet/get_cloud_apm_package_policy.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/get_unsupported_apm_server_schema.test.ts b/x-pack/plugins/apm/server/routes/fleet/get_unsupported_apm_server_schema.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/get_unsupported_apm_server_schema.test.ts rename to x-pack/plugins/apm/server/routes/fleet/get_unsupported_apm_server_schema.test.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/get_unsupported_apm_server_schema.ts b/x-pack/plugins/apm/server/routes/fleet/get_unsupported_apm_server_schema.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/get_unsupported_apm_server_schema.ts rename to x-pack/plugins/apm/server/routes/fleet/get_unsupported_apm_server_schema.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/is_superuser.ts b/x-pack/plugins/apm/server/routes/fleet/is_superuser.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/is_superuser.ts rename to x-pack/plugins/apm/server/routes/fleet/is_superuser.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/merge_package_policy_with_apm.ts b/x-pack/plugins/apm/server/routes/fleet/merge_package_policy_with_apm.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/fleet/merge_package_policy_with_apm.ts rename to x-pack/plugins/apm/server/routes/fleet/merge_package_policy_with_apm.ts index fd3e3db700fd0..5442185decde3 100644 --- a/x-pack/plugins/apm/server/lib/fleet/merge_package_policy_with_apm.ts +++ b/x-pack/plugins/apm/server/routes/fleet/merge_package_policy_with_apm.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { APMPluginStartDependencies } from '../../types'; import { listConfigurations } from '../settings/agent_configuration/list_configurations'; import { diff --git a/x-pack/plugins/apm/server/lib/fleet/register_fleet_policy_callbacks.ts b/x-pack/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/fleet/register_fleet_policy_callbacks.ts rename to x-pack/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts index 6fcd0433e2e83..06e55c7fdcca8 100644 --- a/x-pack/plugins/apm/server/lib/fleet/register_fleet_policy_callbacks.ts +++ b/x-pack/plugins/apm/server/routes/fleet/register_fleet_policy_callbacks.ts @@ -17,7 +17,7 @@ import { import { AgentConfiguration } from '../../../common/agent_configuration/configuration_types'; import { AGENT_NAME } from '../../../common/elasticsearch_fieldnames'; import { APMPluginStartDependencies } from '../../types'; -import { setupRequest } from '../helpers/setup_request'; +import { setupRequest } from '../../lib/helpers/setup_request'; import { mergePackagePolicyWithApm } from './merge_package_policy_with_apm'; export async function registerFleetPolicyCallbacks({ diff --git a/x-pack/plugins/apm/server/routes/fleet.ts b/x-pack/plugins/apm/server/routes/fleet/route.ts similarity index 89% rename from x-pack/plugins/apm/server/routes/fleet.ts rename to x-pack/plugins/apm/server/routes/fleet/route.ts index a6e0cb09d894a..e9e7f2254bcfe 100644 --- a/x-pack/plugins/apm/server/routes/fleet.ts +++ b/x-pack/plugins/apm/server/routes/fleet/route.ts @@ -12,20 +12,20 @@ import { keyBy } from 'lodash'; import { APM_SERVER_SCHEMA_SAVED_OBJECT_ID, APM_SERVER_SCHEMA_SAVED_OBJECT_TYPE, -} from '../../common/apm_saved_object_constants'; -import { createCloudApmPackgePolicy } from '../lib/fleet/create_cloud_apm_package_policy'; -import { getFleetAgents } from '../lib/fleet/get_agents'; -import { getApmPackgePolicies } from '../lib/fleet/get_apm_package_policies'; +} from '../../../common/apm_saved_object_constants'; +import { createCloudApmPackgePolicy } from './create_cloud_apm_package_policy'; +import { getFleetAgents } from './get_agents'; +import { getApmPackgePolicies } from './get_apm_package_policies'; import { getApmPackagePolicy, getCloudAgentPolicy, -} from '../lib/fleet/get_cloud_apm_package_policy'; -import { getUnsupportedApmServerSchema } from '../lib/fleet/get_unsupported_apm_server_schema'; -import { isSuperuser } from '../lib/fleet/is_superuser'; -import { getInternalSavedObjectsClient } from '../lib/helpers/get_internal_saved_objects_client'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; +} from './get_cloud_apm_package_policy'; +import { getUnsupportedApmServerSchema } from './get_unsupported_apm_server_schema'; +import { isSuperuser } from './is_superuser'; +import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const hasFleetDataRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/fleet/has_data', diff --git a/x-pack/plugins/apm/server/lib/fleet/source_maps.test.ts b/x-pack/plugins/apm/server/routes/fleet/source_maps.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/fleet/source_maps.test.ts rename to x-pack/plugins/apm/server/routes/fleet/source_maps.test.ts diff --git a/x-pack/plugins/apm/server/lib/fleet/source_maps.ts b/x-pack/plugins/apm/server/routes/fleet/source_maps.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/fleet/source_maps.ts rename to x-pack/plugins/apm/server/routes/fleet/source_maps.ts index 8c11f80f21191..1d70076a828dd 100644 --- a/x-pack/plugins/apm/server/lib/fleet/source_maps.ts +++ b/x-pack/plugins/apm/server/routes/fleet/source_maps.ts @@ -13,7 +13,7 @@ import { import { promisify } from 'util'; import { unzip } from 'zlib'; import { Artifact } from '../../../../fleet/server'; -import { SourceMap } from '../../routes/source_maps'; +import { SourceMap } from '../source_maps/route'; import { APMPluginStartDependencies } from '../../types'; import { getApmPackgePolicies } from './get_apm_package_policies'; import { APM_SERVER, PackagePolicy } from './register_fleet_policy_callbacks'; diff --git a/x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts b/x-pack/plugins/apm/server/routes/fleet/sync_agent_configs_to_apm_package_policies.ts similarity index 90% rename from x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts rename to x-pack/plugins/apm/server/routes/fleet/sync_agent_configs_to_apm_package_policies.ts index 5f3a3f74598a1..c3660eee0afae 100644 --- a/x-pack/plugins/apm/server/lib/fleet/sync_agent_configs_to_apm_package_policies.ts +++ b/x-pack/plugins/apm/server/routes/fleet/sync_agent_configs_to_apm_package_policies.ts @@ -10,10 +10,10 @@ import { CoreStart, SavedObjectsClientContract, } from 'kibana/server'; -import { TelemetryUsageCounter } from '../../routes/typings'; +import { TelemetryUsageCounter } from '../typings'; import { APMPluginStartDependencies } from '../../types'; -import { getInternalSavedObjectsClient } from '../helpers/get_internal_saved_objects_client'; -import { Setup } from '../helpers/setup_request'; +import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; +import { Setup } from '../../lib/helpers/setup_request'; import { listConfigurations } from '../settings/agent_configuration/list_configurations'; import { getApmPackgePolicies } from './get_apm_package_policies'; import { getPackagePolicyWithAgentConfigurations } from './register_fleet_policy_callbacks'; diff --git a/x-pack/plugins/apm/server/lib/latency/get_overall_latency_distribution.ts b/x-pack/plugins/apm/server/routes/latency_distribution/get_overall_latency_distribution.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/latency/get_overall_latency_distribution.ts rename to x-pack/plugins/apm/server/routes/latency_distribution/get_overall_latency_distribution.ts diff --git a/x-pack/plugins/apm/server/lib/latency/get_percentile_threshold_value.ts b/x-pack/plugins/apm/server/routes/latency_distribution/get_percentile_threshold_value.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/latency/get_percentile_threshold_value.ts rename to x-pack/plugins/apm/server/routes/latency_distribution/get_percentile_threshold_value.ts diff --git a/x-pack/plugins/apm/server/routes/latency_distribution.ts b/x-pack/plugins/apm/server/routes/latency_distribution/route.ts similarity index 80% rename from x-pack/plugins/apm/server/routes/latency_distribution.ts rename to x-pack/plugins/apm/server/routes/latency_distribution/route.ts index 826898784835e..f30e98dd8c7b8 100644 --- a/x-pack/plugins/apm/server/routes/latency_distribution.ts +++ b/x-pack/plugins/apm/server/routes/latency_distribution/route.ts @@ -7,11 +7,11 @@ import * as t from 'io-ts'; import { toNumberRt } from '@kbn/io-ts-utils/to_number_rt'; -import { getOverallLatencyDistribution } from '../lib/latency/get_overall_latency_distribution'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { environmentRt, kueryRt, rangeRt } from './default_api_types'; +import { getOverallLatencyDistribution } from './get_overall_latency_distribution'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; const latencyOverallDistributionRoute = createApmServerRoute({ endpoint: 'POST /internal/apm/latency/overall_distribution', diff --git a/x-pack/plugins/apm/server/lib/latency/types.ts b/x-pack/plugins/apm/server/routes/latency_distribution/types.ts similarity index 92% rename from x-pack/plugins/apm/server/lib/latency/types.ts rename to x-pack/plugins/apm/server/routes/latency_distribution/types.ts index 17c036f44f088..d2eb9cde0bf3b 100644 --- a/x-pack/plugins/apm/server/lib/latency/types.ts +++ b/x-pack/plugins/apm/server/routes/latency_distribution/types.ts @@ -10,7 +10,7 @@ import type { CorrelationsClientParams, } from '../../../common/correlations/types'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; export interface OverallLatencyDistributionOptions extends CorrelationsClientParams { diff --git a/x-pack/plugins/apm/server/lib/metrics/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/metrics/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/metrics/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/metrics/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/default.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/default.ts similarity index 92% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/default.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/default.ts index 54e10bd8adde0..b4e95d5217daa 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/default.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/default.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getCPUChartData } from './shared/cpu'; import { getMemoryChartData } from './shared/memory'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.test.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.test.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.test.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.test.ts index c22c326473e2c..8b3fcbfe5ce88 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.test.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.test.ts @@ -9,7 +9,7 @@ import { METRIC_JAVA_GC_COUNT, METRIC_JAVA_GC_TIME, } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { ChartBase } from '../../../types'; import { fetchAndTransformGcMetrics } from './fetch_and_transform_gc_metrics'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts index 2d4cf2f70ab5f..790fcf5720745 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/fetch_and_transform_gc_metrics.ts @@ -8,8 +8,8 @@ import { sum, round } from 'lodash'; import { euiLightVars as theme } from '@kbn/ui-shared-deps-src/theme'; import { isFiniteNumber } from '../../../../../../common/utils/is_finite_number'; -import { Setup } from '../../../../helpers/setup_request'; -import { getMetricsDateHistogramParams } from '../../../../helpers/metrics'; +import { Setup } from '../../../../../lib/helpers/setup_request'; +import { getMetricsDateHistogramParams } from '../../../../../lib/helpers/metrics'; import { ChartBase } from '../../../types'; import { @@ -19,7 +19,7 @@ import { METRIC_JAVA_GC_TIME, SERVICE_NAME, } from '../../../../../../common/elasticsearch_fieldnames'; -import { getBucketSize } from '../../../../helpers/get_bucket_size'; +import { getBucketSize } from '../../../../../lib/helpers/get_bucket_size'; import { getVizColorForIndex } from '../../../../../../common/viz_colors'; import { JAVA_AGENT_NAMES } from '../../../../../../common/agent_name'; import { diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/get_gc_rate_chart.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/get_gc_rate_chart.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/get_gc_rate_chart.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/get_gc_rate_chart.ts index 22dcb3e0f08ff..a22f7df915617 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/get_gc_rate_chart.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/get_gc_rate_chart.ts @@ -8,7 +8,7 @@ import { euiLightVars as theme } from '@kbn/ui-shared-deps-src/theme'; import { i18n } from '@kbn/i18n'; import { METRIC_JAVA_GC_COUNT } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { fetchAndTransformGcMetrics } from './fetch_and_transform_gc_metrics'; import { ChartBase } from '../../../types'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/get_gc_time_chart.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/get_gc_time_chart.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/get_gc_time_chart.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/get_gc_time_chart.ts index 4b85ad94f6494..596d871b916f9 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/gc/get_gc_time_chart.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/gc/get_gc_time_chart.ts @@ -8,7 +8,7 @@ import { euiLightVars as theme } from '@kbn/ui-shared-deps-src/theme'; import { i18n } from '@kbn/i18n'; import { METRIC_JAVA_GC_TIME } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { fetchAndTransformGcMetrics } from './fetch_and_transform_gc_metrics'; import { ChartBase } from '../../../types'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/heap_memory/index.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/heap_memory/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/heap_memory/index.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/heap_memory/index.ts index a872a3af76d7e..cde28e77e38ca 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/heap_memory/index.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/heap_memory/index.ts @@ -13,7 +13,7 @@ import { METRIC_JAVA_HEAP_MEMORY_USED, AGENT_NAME, } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { fetchAndTransformMetrics } from '../../../fetch_and_transform_metrics'; import { ChartBase } from '../../../types'; import { JAVA_AGENT_NAMES } from '../../../../../../common/agent_name'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/index.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/index.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/index.ts index 9039bb19ebb78..5250884ed5e44 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/index.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/index.ts @@ -7,7 +7,7 @@ import { withApmSpan } from '../../../../utils/with_apm_span'; import { getHeapMemoryChart } from './heap_memory'; -import { Setup } from '../../../helpers/setup_request'; +import { Setup } from '../../../../lib/helpers/setup_request'; import { getNonHeapMemoryChart } from './non_heap_memory'; import { getThreadCountChart } from './thread_count'; import { getCPUChartData } from '../shared/cpu'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/non_heap_memory/index.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/non_heap_memory/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/non_heap_memory/index.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/non_heap_memory/index.ts index 9fa758cb4dbd8..ffcce74ee6766 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/non_heap_memory/index.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/non_heap_memory/index.ts @@ -13,7 +13,7 @@ import { METRIC_JAVA_NON_HEAP_MEMORY_USED, AGENT_NAME, } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { ChartBase } from '../../../types'; import { fetchAndTransformMetrics } from '../../../fetch_and_transform_metrics'; import { JAVA_AGENT_NAMES } from '../../../../../../common/agent_name'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/thread_count/index.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/thread_count/index.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/java/thread_count/index.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/java/thread_count/index.ts index 306666d27cd1c..699812ffc8463 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/java/thread_count/index.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/java/thread_count/index.ts @@ -11,7 +11,7 @@ import { METRIC_JAVA_THREAD_COUNT, AGENT_NAME, } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { ChartBase } from '../../../types'; import { fetchAndTransformMetrics } from '../../../fetch_and_transform_metrics'; import { JAVA_AGENT_NAMES } from '../../../../../../common/agent_name'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/cpu/index.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/shared/cpu/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/shared/cpu/index.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/shared/cpu/index.ts index 0911081b20324..95c39d4bd55cc 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/cpu/index.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/shared/cpu/index.ts @@ -11,7 +11,7 @@ import { METRIC_SYSTEM_CPU_PERCENT, METRIC_PROCESS_CPU_PERCENT, } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { ChartBase } from '../../../types'; import { fetchAndTransformMetrics } from '../../../fetch_and_transform_metrics'; diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts b/x-pack/plugins/apm/server/routes/metrics/by_agent/shared/memory/index.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts rename to x-pack/plugins/apm/server/routes/metrics/by_agent/shared/memory/index.ts index 828ee28260471..d0e84211ef455 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts +++ b/x-pack/plugins/apm/server/routes/metrics/by_agent/shared/memory/index.ts @@ -13,7 +13,7 @@ import { METRIC_SYSTEM_FREE_MEMORY, METRIC_SYSTEM_TOTAL_MEMORY, } from '../../../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../../../helpers/setup_request'; +import { Setup } from '../../../../../lib/helpers/setup_request'; import { fetchAndTransformMetrics } from '../../../fetch_and_transform_metrics'; import { ChartBase } from '../../../types'; diff --git a/x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts b/x-pack/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts rename to x-pack/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts index 0a24179ed9fc6..e607ae08e0b23 100644 --- a/x-pack/plugins/apm/server/lib/metrics/fetch_and_transform_metrics.ts +++ b/x-pack/plugins/apm/server/routes/metrics/fetch_and_transform_metrics.ts @@ -10,8 +10,9 @@ import { euiLightVars as theme } from '@kbn/ui-shared-deps-src/theme'; import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { getVizColorForIndex } from '../../../common/viz_colors'; import { AggregationOptionsByType } from '../../../../../../src/core/types/elasticsearch'; -import { getMetricsDateHistogramParams } from '../helpers/metrics'; -import { Setup } from '../helpers/setup_request'; +import { APMEventESSearchRequest } from '../../lib/helpers/create_es_client/create_apm_event_client'; +import { getMetricsDateHistogramParams } from '../../lib/helpers/metrics'; +import { Setup } from '../../lib/helpers/setup_request'; import { ChartBase } from './types'; import { environmentQuery, @@ -20,7 +21,6 @@ import { import { kqlQuery, rangeQuery } from '../../../../observability/server'; import { ProcessorEvent } from '../../../common/processor_event'; import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; -import { APMEventESSearchRequest } from '../helpers/create_es_client/create_apm_event_client'; import { PromiseReturnType } from '../../../../observability/typings/common'; type MetricsAggregationMap = Unionize<{ diff --git a/x-pack/plugins/apm/server/lib/metrics/get_metrics_chart_data_by_agent.ts b/x-pack/plugins/apm/server/routes/metrics/get_metrics_chart_data_by_agent.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/metrics/get_metrics_chart_data_by_agent.ts rename to x-pack/plugins/apm/server/routes/metrics/get_metrics_chart_data_by_agent.ts index 611bb8196032c..c6927417687da 100644 --- a/x-pack/plugins/apm/server/lib/metrics/get_metrics_chart_data_by_agent.ts +++ b/x-pack/plugins/apm/server/routes/metrics/get_metrics_chart_data_by_agent.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { getJavaMetricsCharts } from './by_agent/java'; import { getDefaultMetricsCharts } from './by_agent/default'; import { isJavaAgentName } from '../../../common/agent_name'; diff --git a/x-pack/plugins/apm/server/lib/metrics/queries.test.ts b/x-pack/plugins/apm/server/routes/metrics/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/metrics/queries.test.ts rename to x-pack/plugins/apm/server/routes/metrics/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/metrics.ts b/x-pack/plugins/apm/server/routes/metrics/route.ts similarity index 76% rename from x-pack/plugins/apm/server/routes/metrics.ts rename to x-pack/plugins/apm/server/routes/metrics/route.ts index 36a504859797a..4e15188827e9b 100644 --- a/x-pack/plugins/apm/server/routes/metrics.ts +++ b/x-pack/plugins/apm/server/routes/metrics/route.ts @@ -6,11 +6,11 @@ */ import * as t from 'io-ts'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getMetricsChartDataByAgent } from '../lib/metrics/get_metrics_chart_data_by_agent'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { environmentRt, kueryRt, rangeRt } from './default_api_types'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getMetricsChartDataByAgent } from './get_metrics_chart_data_by_agent'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; const metricsChartsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/services/{serviceName}/metrics/charts', diff --git a/x-pack/plugins/apm/server/lib/metrics/types.ts b/x-pack/plugins/apm/server/routes/metrics/types.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/metrics/types.ts rename to x-pack/plugins/apm/server/routes/metrics/types.ts diff --git a/x-pack/plugins/apm/server/lib/observability_overview/get_service_count.ts b/x-pack/plugins/apm/server/routes/observability_overview/get_service_count.ts similarity index 90% rename from x-pack/plugins/apm/server/lib/observability_overview/get_service_count.ts rename to x-pack/plugins/apm/server/routes/observability_overview/get_service_count.ts index 3eb11f668115d..74b70e5fa7d60 100644 --- a/x-pack/plugins/apm/server/lib/observability_overview/get_service_count.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview/get_service_count.ts @@ -8,8 +8,8 @@ import { ProcessorEvent } from '../../../common/processor_event'; import { rangeQuery } from '../../../../observability/server'; import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; -import { Setup } from '../helpers/setup_request'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; export async function getServiceCount({ setup, diff --git a/x-pack/plugins/apm/server/lib/observability_overview/get_transactions_per_minute.ts b/x-pack/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/observability_overview/get_transactions_per_minute.ts rename to x-pack/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts index de4d6dec4e1fe..83e51d7d638fe 100644 --- a/x-pack/plugins/apm/server/lib/observability_overview/get_transactions_per_minute.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview/get_transactions_per_minute.ts @@ -11,12 +11,12 @@ import { } from '../../../common/transaction_types'; import { TRANSACTION_TYPE } from '../../../common/elasticsearch_fieldnames'; import { rangeQuery } from '../../../../observability/server'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { getDocumentTypeFilterForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; -import { calculateThroughputWithRange } from '../helpers/calculate_throughput'; +} from '../../lib/helpers/transactions'; +import { calculateThroughputWithRange } from '../../lib/helpers/calculate_throughput'; export async function getTransactionsPerMinute({ setup, diff --git a/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts b/x-pack/plugins/apm/server/routes/observability_overview/has_data.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/observability_overview/has_data.ts rename to x-pack/plugins/apm/server/routes/observability_overview/has_data.ts index f09b67ec98dfb..9f98af055e696 100644 --- a/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview/has_data.ts @@ -6,7 +6,7 @@ */ import { ProcessorEvent } from '../../../common/processor_event'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; export async function getHasData({ setup }: { setup: Setup }) { const { apmEventClient } = setup; diff --git a/x-pack/plugins/apm/server/routes/observability_overview.ts b/x-pack/plugins/apm/server/routes/observability_overview/route.ts similarity index 74% rename from x-pack/plugins/apm/server/routes/observability_overview.ts rename to x-pack/plugins/apm/server/routes/observability_overview/route.ts index 2df3212d8da70..c99586638c3de 100644 --- a/x-pack/plugins/apm/server/routes/observability_overview.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview/route.ts @@ -7,15 +7,15 @@ import * as t from 'io-ts'; import { toNumberRt } from '@kbn/io-ts-utils/to_number_rt'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getServiceCount } from '../lib/observability_overview/get_service_count'; -import { getTransactionsPerMinute } from '../lib/observability_overview/get_transactions_per_minute'; -import { getHasData } from '../lib/observability_overview/has_data'; -import { rangeRt } from './default_api_types'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { withApmSpan } from '../utils/with_apm_span'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getServiceCount } from './get_service_count'; +import { getTransactionsPerMinute } from './get_transactions_per_minute'; +import { getHasData } from './has_data'; +import { rangeRt } from '../default_api_types'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { withApmSpan } from '../../utils/with_apm_span'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; const observabilityOverviewHasDataRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/observability_overview/has_data', diff --git a/x-pack/plugins/apm/server/lib/rum_client/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/rum_client/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/rum_client/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/rum_client/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_client_metrics.ts b/x-pack/plugins/apm/server/routes/rum_client/get_client_metrics.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/rum_client/get_client_metrics.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_client_metrics.ts index 206fc134a0c87..40352db9f18a6 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_client_metrics.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_client_metrics.ts @@ -7,7 +7,7 @@ import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { TRANSACTION_TIME_TO_FIRST_BYTE, TRANSACTION_DURATION, diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts b/x-pack/plugins/apm/server/routes/rum_client/get_js_errors.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_js_errors.ts index dca575b42cf0a..a0f7c0940b812 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_js_errors.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_js_errors.ts @@ -6,7 +6,7 @@ */ import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { getRumErrorsProjection } from '../../projections/rum_page_load_transactions'; import { ERROR_EXC_MESSAGE, diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_long_task_metrics.ts b/x-pack/plugins/apm/server/routes/rum_client/get_long_task_metrics.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/rum_client/get_long_task_metrics.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_long_task_metrics.ts index d5cc78e2f3062..29ef955e19aa4 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_long_task_metrics.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_long_task_metrics.ts @@ -7,7 +7,7 @@ import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; const LONG_TASK_SUM_FIELD = 'transaction.experience.longtask.sum'; const LONG_TASK_COUNT_FIELD = 'transaction.experience.longtask.count'; diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_page_load_distribution.ts b/x-pack/plugins/apm/server/routes/rum_client/get_page_load_distribution.ts similarity index 99% rename from x-pack/plugins/apm/server/lib/rum_client/get_page_load_distribution.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_page_load_distribution.ts index e551b4a34746c..27c8c4668ce9b 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_page_load_distribution.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_page_load_distribution.ts @@ -8,7 +8,7 @@ import { TRANSACTION_DURATION } from '../../../common/elasticsearch_fieldnames'; import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; export const MICRO_TO_SEC = 1000000; diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_page_view_trends.ts b/x-pack/plugins/apm/server/routes/rum_client/get_page_view_trends.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/rum_client/get_page_view_trends.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_page_view_trends.ts index 87766aae43272..6bcc7f66d1dfd 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_page_view_trends.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_page_view_trends.ts @@ -7,7 +7,7 @@ import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { BreakdownItem } from '../../../typings/ui_filters'; export async function getPageViewTrends({ diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_pl_dist_breakdown.ts b/x-pack/plugins/apm/server/routes/rum_client/get_pl_dist_breakdown.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/rum_client/get_pl_dist_breakdown.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_pl_dist_breakdown.ts index 298f2a3b7ddf0..d6a67b57fa98f 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_pl_dist_breakdown.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_pl_dist_breakdown.ts @@ -8,7 +8,7 @@ import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { ProcessorEvent } from '../../../common/processor_event'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { CLIENT_GEO_COUNTRY_ISO_CODE, USER_AGENT_DEVICE, diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts b/x-pack/plugins/apm/server/routes/rum_client/get_rum_services.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_rum_services.ts index 1929f7e3ed994..e62b54f00d212 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_rum_services.ts @@ -5,7 +5,7 @@ * 2.0. */ import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_url_search.ts b/x-pack/plugins/apm/server/routes/rum_client/get_url_search.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/rum_client/get_url_search.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_url_search.ts index 515df78f87bd8..0ffb836402f61 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_url_search.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_url_search.ts @@ -6,7 +6,7 @@ */ import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { TRANSACTION_DURATION, diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_visitor_breakdown.ts b/x-pack/plugins/apm/server/routes/rum_client/get_visitor_breakdown.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/rum_client/get_visitor_breakdown.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_visitor_breakdown.ts index ed0a4e90a4cb7..d7447889db849 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_visitor_breakdown.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_visitor_breakdown.ts @@ -7,7 +7,7 @@ import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { USER_AGENT_NAME, USER_AGENT_OS, diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_web_core_vitals.ts b/x-pack/plugins/apm/server/routes/rum_client/get_web_core_vitals.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/rum_client/get_web_core_vitals.ts rename to x-pack/plugins/apm/server/routes/rum_client/get_web_core_vitals.ts index 6dfa3abe117df..6a3b3a1c7b1c8 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/get_web_core_vitals.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/get_web_core_vitals.ts @@ -7,7 +7,7 @@ import { getRumPageLoadTransactionsProjection } from '../../projections/rum_page_load_transactions'; import { mergeProjection } from '../../projections/util/merge_projection'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { CLS_FIELD, FCP_FIELD, diff --git a/x-pack/plugins/apm/server/lib/rum_client/has_rum_data.ts b/x-pack/plugins/apm/server/routes/rum_client/has_rum_data.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/rum_client/has_rum_data.ts rename to x-pack/plugins/apm/server/routes/rum_client/has_rum_data.ts index ba35ac5c5c89c..6cb3bc069e072 100644 --- a/x-pack/plugins/apm/server/lib/rum_client/has_rum_data.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/has_rum_data.ts @@ -6,7 +6,7 @@ */ import moment from 'moment'; -import { SetupUX } from '../../routes/rum_client'; +import { SetupUX } from './route'; import { SERVICE_NAME, TRANSACTION_TYPE, diff --git a/x-pack/plugins/apm/server/lib/rum_client/queries.test.ts b/x-pack/plugins/apm/server/routes/rum_client/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/rum_client/queries.test.ts rename to x-pack/plugins/apm/server/routes/rum_client/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/rum_client.ts b/x-pack/plugins/apm/server/routes/rum_client/route.ts similarity index 87% rename from x-pack/plugins/apm/server/routes/rum_client.ts rename to x-pack/plugins/apm/server/routes/rum_client/route.ts index e84a281a7ce1b..482dcc0799ed0 100644 --- a/x-pack/plugins/apm/server/routes/rum_client.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/route.ts @@ -7,23 +7,23 @@ import * as t from 'io-ts'; import { Logger } from 'kibana/server'; import { isoToEpochRt } from '@kbn/io-ts-utils/iso_to_epoch_rt'; -import { setupRequest, Setup } from '../lib/helpers/setup_request'; -import { getClientMetrics } from '../lib/rum_client/get_client_metrics'; -import { getJSErrors } from '../lib/rum_client/get_js_errors'; -import { getLongTaskMetrics } from '../lib/rum_client/get_long_task_metrics'; -import { getPageLoadDistribution } from '../lib/rum_client/get_page_load_distribution'; -import { getPageViewTrends } from '../lib/rum_client/get_page_view_trends'; -import { getPageLoadDistBreakdown } from '../lib/rum_client/get_pl_dist_breakdown'; -import { getRumServices } from '../lib/rum_client/get_rum_services'; -import { getUrlSearch } from '../lib/rum_client/get_url_search'; -import { getVisitorBreakdown } from '../lib/rum_client/get_visitor_breakdown'; -import { getWebCoreVitals } from '../lib/rum_client/get_web_core_vitals'; -import { hasRumData } from '../lib/rum_client/has_rum_data'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { rangeRt } from './default_api_types'; -import { UxUIFilters } from '../../typings/ui_filters'; -import { APMRouteHandlerResources } from '../routes/typings'; +import { setupRequest, Setup } from '../../lib/helpers/setup_request'; +import { getClientMetrics } from './get_client_metrics'; +import { getJSErrors } from './get_js_errors'; +import { getLongTaskMetrics } from './get_long_task_metrics'; +import { getPageLoadDistribution } from './get_page_load_distribution'; +import { getPageViewTrends } from './get_page_view_trends'; +import { getPageLoadDistBreakdown } from './get_pl_dist_breakdown'; +import { getRumServices } from './get_rum_services'; +import { getUrlSearch } from './get_url_search'; +import { getVisitorBreakdown } from './get_visitor_breakdown'; +import { getWebCoreVitals } from './get_web_core_vitals'; +import { hasRumData } from './has_rum_data'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { rangeRt } from '../default_api_types'; +import { UxUIFilters } from '../../../typings/ui_filters'; +import { APMRouteHandlerResources } from '../typings'; export type SetupUX = Setup & { uiFilters: UxUIFilters; diff --git a/x-pack/plugins/apm/server/lib/rum_client/ui_filters/get_es_filter.test.ts b/x-pack/plugins/apm/server/routes/rum_client/ui_filters/get_es_filter.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/rum_client/ui_filters/get_es_filter.test.ts rename to x-pack/plugins/apm/server/routes/rum_client/ui_filters/get_es_filter.test.ts diff --git a/x-pack/plugins/apm/server/lib/rum_client/ui_filters/get_es_filter.ts b/x-pack/plugins/apm/server/routes/rum_client/ui_filters/get_es_filter.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/rum_client/ui_filters/get_es_filter.ts rename to x-pack/plugins/apm/server/routes/rum_client/ui_filters/get_es_filter.ts diff --git a/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts b/x-pack/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts similarity index 99% rename from x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts rename to x-pack/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts index 2f725b61942cd..b3bd4d1510180 100644 --- a/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts +++ b/x-pack/plugins/apm/server/routes/service_map/fetch_service_paths_from_trace_ids.ts @@ -13,7 +13,7 @@ import { ExternalConnectionNode, ServiceConnectionNode, } from '../../../common/service_map'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; export async function fetchServicePathsFromTraceIds( setup: Setup, diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_anomalies.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_anomalies.ts index 2aa2f5c6eead5..65c022b7175de 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_service_anomalies.ts @@ -20,8 +20,8 @@ import { } from '../../../common/transaction_types'; import { rangeQuery } from '../../../../observability/server'; import { withApmSpan } from '../../utils/with_apm_span'; -import { getMlJobsWithAPMGroup } from '../anomaly_detection/get_ml_jobs_with_apm_group'; -import { Setup } from '../helpers/setup_request'; +import { getMlJobsWithAPMGroup } from '../../lib/anomaly_detection/get_ml_jobs_with_apm_group'; +import { Setup } from '../../lib/helpers/setup_request'; import { apmMlAnomalyQuery } from '../../../common/anomaly_detection/apm_ml_anomaly_query'; import { ApmMlDetectorIndex } from '../../../common/anomaly_detection/apm_ml_detectors'; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_map.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/service_map/get_service_map.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_map.ts index 9f94bdd9275c0..d7eb101f77e38 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_service_map.ts @@ -17,7 +17,7 @@ import { } from '../../../common/elasticsearch_fieldnames'; import { environmentQuery } from '../../../common/utils/environment_query'; import { withApmSpan } from '../../utils/with_apm_span'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { DEFAULT_ANOMALIES, getServiceAnomalies, @@ -26,7 +26,7 @@ import { getServiceMapFromTraceIds } from './get_service_map_from_trace_ids'; import { getTraceSampleIds } from './get_trace_sample_ids'; import { transformServiceMapResponses } from './transform_service_map_responses'; import { ENVIRONMENT_ALL } from '../../../common/environment_filter_values'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; export interface IEnvOptions { setup: Setup; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_backend_node_info.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_map_backend_node_info.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/service_map/get_service_map_backend_node_info.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_map_backend_node_info.ts index c8242731e756c..3866bac88ef44 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_backend_node_info.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_service_map_backend_node_info.ts @@ -16,8 +16,8 @@ import { EventOutcome } from '../../../common/event_outcome'; import { ProcessorEvent } from '../../../common/processor_event'; import { environmentQuery } from '../../../common/utils/environment_query'; import { withApmSpan } from '../../utils/with_apm_span'; -import { calculateThroughput } from '../helpers/calculate_throughput'; -import { Setup } from '../helpers/setup_request'; +import { calculateThroughput } from '../../lib/helpers/calculate_throughput'; +import { Setup } from '../../lib/helpers/setup_request'; interface Options { setup: Setup; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.test.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_map_from_trace_ids.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.test.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_map_from_trace_ids.test.ts diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_map_from_trace_ids.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_map_from_trace_ids.ts index e77e127aebb42..6a61a514881b0 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_from_trace_ids.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_service_map_from_trace_ids.ts @@ -7,7 +7,7 @@ import { find, uniqBy } from 'lodash'; import { Connection, ConnectionNode } from '../../../common/service_map'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { fetchServicePathsFromTraceIds } from './fetch_service_paths_from_trace_ids'; export function getConnections({ diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_map_service_node_info.test.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_map_service_node_info.test.ts index e064d97bb7aee..9f65481d07489 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_service_map_service_node_info.test.ts @@ -6,8 +6,8 @@ */ import { getServiceMapServiceNodeInfo } from './get_service_map_service_node_info'; -import { Setup } from '../helpers/setup_request'; -import * as getErrorRateModule from '../transaction_groups/get_error_rate'; +import { Setup } from '../../lib/helpers/setup_request'; +import * as getErrorRateModule from '../../lib/transaction_groups/get_error_rate'; import { ENVIRONMENT_ALL } from '../../../common/environment_filter_values'; describe('getServiceMapServiceNodeInfo', () => { diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts b/x-pack/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts rename to x-pack/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts index 2f089adf70c1c..d6eb7729effaf 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_service_map_service_node_info.ts @@ -26,13 +26,13 @@ import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; -import { Setup } from '../helpers/setup_request'; +} from '../../lib/helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; import { percentCgroupMemoryUsedScript, percentSystemMemoryUsedScript, } from '../metrics/by_agent/shared/memory'; -import { getErrorRate } from '../transaction_groups/get_error_rate'; +import { getErrorRate } from '../../lib/transaction_groups/get_error_rate'; interface Options { setup: Setup; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_trace_sample_ids.ts b/x-pack/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/service_map/get_trace_sample_ids.ts rename to x-pack/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts index 7e16e69498e7c..af24953833a27 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_trace_sample_ids.ts +++ b/x-pack/plugins/apm/server/routes/service_map/get_trace_sample_ids.ts @@ -18,7 +18,7 @@ import { ProcessorEvent } from '../../../common/processor_event'; import { SERVICE_MAP_TIMEOUT_ERROR } from '../../../common/service_map'; import { rangeQuery } from '../../../../observability/server'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; const MAX_TRACES_TO_INSPECT = 1000; diff --git a/x-pack/plugins/apm/server/lib/service_map/group_resource_nodes.test.ts b/x-pack/plugins/apm/server/routes/service_map/group_resource_nodes.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/group_resource_nodes.test.ts rename to x-pack/plugins/apm/server/routes/service_map/group_resource_nodes.test.ts diff --git a/x-pack/plugins/apm/server/lib/service_map/group_resource_nodes.ts b/x-pack/plugins/apm/server/routes/service_map/group_resource_nodes.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/group_resource_nodes.ts rename to x-pack/plugins/apm/server/routes/service_map/group_resource_nodes.ts diff --git a/x-pack/plugins/apm/server/lib/service_map/mock_responses/group_resource_nodes_grouped.json b/x-pack/plugins/apm/server/routes/service_map/mock_responses/group_resource_nodes_grouped.json similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/mock_responses/group_resource_nodes_grouped.json rename to x-pack/plugins/apm/server/routes/service_map/mock_responses/group_resource_nodes_grouped.json diff --git a/x-pack/plugins/apm/server/lib/service_map/mock_responses/group_resource_nodes_pregrouped.json b/x-pack/plugins/apm/server/routes/service_map/mock_responses/group_resource_nodes_pregrouped.json similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/mock_responses/group_resource_nodes_pregrouped.json rename to x-pack/plugins/apm/server/routes/service_map/mock_responses/group_resource_nodes_pregrouped.json diff --git a/x-pack/plugins/apm/server/routes/service_map.ts b/x-pack/plugins/apm/server/routes/service_map/route.ts similarity index 81% rename from x-pack/plugins/apm/server/routes/service_map.ts rename to x-pack/plugins/apm/server/routes/service_map/route.ts index e75b4ec832d82..97d0c01ed6a44 100644 --- a/x-pack/plugins/apm/server/routes/service_map.ts +++ b/x-pack/plugins/apm/server/routes/service_map/route.ts @@ -7,17 +7,17 @@ import Boom from '@hapi/boom'; import * as t from 'io-ts'; -import { isActivePlatinumLicense } from '../../common/license_check'; -import { invalidLicenseMessage } from '../../common/service_map'; -import { notifyFeatureUsage } from '../feature'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getServiceMap } from '../lib/service_map/get_service_map'; -import { getServiceMapBackendNodeInfo } from '../lib/service_map/get_service_map_backend_node_info'; -import { getServiceMapServiceNodeInfo } from '../lib/service_map/get_service_map_service_node_info'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { environmentRt, rangeRt } from './default_api_types'; +import { isActivePlatinumLicense } from '../../../common/license_check'; +import { invalidLicenseMessage } from '../../../common/service_map'; +import { notifyFeatureUsage } from '../../feature'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getServiceMap } from './get_service_map'; +import { getServiceMapBackendNodeInfo } from './get_service_map_backend_node_info'; +import { getServiceMapServiceNodeInfo } from './get_service_map_service_node_info'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { environmentRt, rangeRt } from '../default_api_types'; const serviceMapRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/service-map', diff --git a/x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.test.ts b/x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.test.ts rename to x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.test.ts diff --git a/x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.ts b/x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/service_map/transform_service_map_responses.ts rename to x-pack/plugins/apm/server/routes/service_map/transform_service_map_responses.ts diff --git a/x-pack/plugins/apm/server/lib/service_nodes/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/service_nodes/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/service_nodes/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/service_nodes/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/service_nodes/index.ts b/x-pack/plugins/apm/server/routes/service_nodes/get_service_nodes.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/service_nodes/index.ts rename to x-pack/plugins/apm/server/routes/service_nodes/get_service_nodes.ts index 541fbb79c9e50..ebd56cb9768ce 100644 --- a/x-pack/plugins/apm/server/lib/service_nodes/index.ts +++ b/x-pack/plugins/apm/server/routes/service_nodes/get_service_nodes.ts @@ -21,7 +21,7 @@ import { import { ProcessorEvent } from '../../../common/processor_event'; import { kqlQuery, rangeQuery } from '../../../../observability/server'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; const getServiceNodes = async ({ kuery, diff --git a/x-pack/plugins/apm/server/lib/service_nodes/queries.test.ts b/x-pack/plugins/apm/server/routes/service_nodes/queries.test.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/service_nodes/queries.test.ts rename to x-pack/plugins/apm/server/routes/service_nodes/queries.test.ts index f8bc3879d5794..470be6142aaed 100644 --- a/x-pack/plugins/apm/server/lib/service_nodes/queries.test.ts +++ b/x-pack/plugins/apm/server/routes/service_nodes/queries.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { getServiceNodes } from './'; +import { getServiceNodes } from './get_service_nodes'; import { SearchParamsMock, inspectSearchParams, diff --git a/x-pack/plugins/apm/server/routes/service_nodes.ts b/x-pack/plugins/apm/server/routes/service_nodes/route.ts similarity index 72% rename from x-pack/plugins/apm/server/routes/service_nodes.ts rename to x-pack/plugins/apm/server/routes/service_nodes/route.ts index 61d58bfa3cf38..027a907dd2659 100644 --- a/x-pack/plugins/apm/server/routes/service_nodes.ts +++ b/x-pack/plugins/apm/server/routes/service_nodes/route.ts @@ -6,12 +6,12 @@ */ import * as t from 'io-ts'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getServiceNodes } from '../lib/service_nodes'; -import { rangeRt, kueryRt } from './default_api_types'; -import { environmentRt } from '../../common/environment_rt'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getServiceNodes } from './get_service_nodes'; +import { rangeRt, kueryRt } from '../default_api_types'; +import { environmentRt } from '../../../common/environment_rt'; const serviceNodesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/services/{serviceName}/serviceNodes', diff --git a/x-pack/plugins/apm/server/lib/services/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/services/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/services/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/services/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/multiple_versions.json b/x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/multiple_versions.json similarity index 100% rename from x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/multiple_versions.json rename to x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/multiple_versions.json diff --git a/x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/no_versions.json b/x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/no_versions.json similarity index 100% rename from x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/no_versions.json rename to x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/no_versions.json diff --git a/x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/one_version.json b/x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/one_version.json similarity index 100% rename from x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/one_version.json rename to x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/one_version.json diff --git a/x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/versions_first_seen.json b/x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/versions_first_seen.json similarity index 100% rename from x-pack/plugins/apm/server/lib/services/annotations/__fixtures__/versions_first_seen.json rename to x-pack/plugins/apm/server/routes/services/annotations/__fixtures__/versions_first_seen.json diff --git a/x-pack/plugins/apm/server/lib/services/annotations/get_derived_service_annotations.ts b/x-pack/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/annotations/get_derived_service_annotations.ts rename to x-pack/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts index 22b37e33a26e2..523775de170e7 100644 --- a/x-pack/plugins/apm/server/lib/services/annotations/get_derived_service_annotations.ts +++ b/x-pack/plugins/apm/server/routes/services/annotations/get_derived_service_annotations.ts @@ -17,8 +17,8 @@ import { environmentQuery } from '../../../../common/utils/environment_query'; import { getDocumentTypeFilterForTransactions, getProcessorEventForTransactions, -} from '../../helpers/transactions'; -import { Setup } from '../../helpers/setup_request'; +} from '../../../lib/helpers/transactions'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getDerivedServiceAnnotations({ setup, diff --git a/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts b/x-pack/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts rename to x-pack/plugins/apm/server/routes/services/annotations/get_stored_annotations.ts diff --git a/x-pack/plugins/apm/server/lib/services/annotations/index.test.ts b/x-pack/plugins/apm/server/routes/services/annotations/index.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/services/annotations/index.test.ts rename to x-pack/plugins/apm/server/routes/services/annotations/index.test.ts diff --git a/x-pack/plugins/apm/server/lib/services/annotations/index.ts b/x-pack/plugins/apm/server/routes/services/annotations/index.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/annotations/index.ts rename to x-pack/plugins/apm/server/routes/services/annotations/index.ts index 677530522f6ca..488a4ce6e4c20 100644 --- a/x-pack/plugins/apm/server/lib/services/annotations/index.ts +++ b/x-pack/plugins/apm/server/routes/services/annotations/index.ts @@ -8,7 +8,7 @@ import { ElasticsearchClient, Logger } from 'kibana/server'; import { ScopedAnnotationsClient } from '../../../../../observability/server'; import { getDerivedServiceAnnotations } from './get_derived_service_annotations'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getStoredAnnotations } from './get_stored_annotations'; export async function getServiceAnnotations({ diff --git a/x-pack/plugins/apm/server/lib/services/get_service_agent.ts b/x-pack/plugins/apm/server/routes/services/get_service_agent.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/get_service_agent.ts rename to x-pack/plugins/apm/server/routes/services/get_service_agent.ts index dc3fee20fdf68..8117729eb9b59 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_agent.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_agent.ts @@ -12,7 +12,7 @@ import { SERVICE_RUNTIME_NAME, } from '../../../common/elasticsearch_fieldnames'; import { rangeQuery } from '../../../../observability/server'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; interface ServiceAgent { agent?: { diff --git a/x-pack/plugins/apm/server/lib/services/get_service_alerts.ts b/x-pack/plugins/apm/server/routes/services/get_service_alerts.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/services/get_service_alerts.ts rename to x-pack/plugins/apm/server/routes/services/get_service_alerts.ts diff --git a/x-pack/plugins/apm/server/lib/services/get_service_dependencies.ts b/x-pack/plugins/apm/server/routes/services/get_service_dependencies.ts similarity index 77% rename from x-pack/plugins/apm/server/lib/services/get_service_dependencies.ts rename to x-pack/plugins/apm/server/routes/services/get_service_dependencies.ts index d4472d495230a..cf60502e9861b 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_dependencies.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_dependencies.ts @@ -7,9 +7,9 @@ import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { getConnectionStats } from '../connections/get_connection_stats'; -import { getConnectionStatsItemsWithRelativeImpact } from '../connections/get_connection_stats/get_connection_stats_items_with_relative_impact'; -import { Setup } from '../helpers/setup_request'; +import { getConnectionStats } from '../../lib/connections/get_connection_stats'; +import { getConnectionStatsItemsWithRelativeImpact } from '../../lib/connections/get_connection_stats/get_connection_stats_items_with_relative_impact'; +import { Setup } from '../../lib/helpers/setup_request'; export async function getServiceDependencies({ setup, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_dependencies_breakdown.ts b/x-pack/plugins/apm/server/routes/services/get_service_dependencies_breakdown.ts similarity index 90% rename from x-pack/plugins/apm/server/lib/services/get_service_dependencies_breakdown.ts rename to x-pack/plugins/apm/server/routes/services/get_service_dependencies_breakdown.ts index c0e1af40d98db..a0b8eb1768d6f 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_dependencies_breakdown.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_dependencies_breakdown.ts @@ -9,8 +9,8 @@ import { getNodeName } from '../../../common/connections'; import { kqlQuery } from '../../../../observability/server'; import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { Setup } from '../helpers/setup_request'; -import { getConnectionStats } from '../connections/get_connection_stats'; +import { Setup } from '../../lib/helpers/setup_request'; +import { getConnectionStats } from '../../lib/connections/get_connection_stats'; export async function getServiceDependenciesBreakdown({ setup, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/get_service_error_group_detailed_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_error_groups/get_service_error_group_detailed_statistics.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/get_service_error_groups/get_service_error_group_detailed_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_error_groups/get_service_error_group_detailed_statistics.ts index 9a0b6155fe84d..17c538d0fd7ea 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/get_service_error_group_detailed_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_error_groups/get_service_error_group_detailed_statistics.ts @@ -15,8 +15,8 @@ import { import { ProcessorEvent } from '../../../../common/processor_event'; import { rangeQuery, kqlQuery } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { getBucketSize } from '../../helpers/get_bucket_size'; -import { Setup } from '../../helpers/setup_request'; +import { getBucketSize } from '../../../lib/helpers/get_bucket_size'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getServiceErrorGroupDetailedStatistics({ kuery, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/get_service_error_group_main_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_error_groups/get_service_error_group_main_statistics.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/services/get_service_error_groups/get_service_error_group_main_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_error_groups/get_service_error_group_main_statistics.ts index 1a25b18f81aac..8d174abb1bed5 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/get_service_error_group_main_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_error_groups/get_service_error_group_main_statistics.ts @@ -15,8 +15,8 @@ import { } from '../../../../common/elasticsearch_fieldnames'; import { ProcessorEvent } from '../../../../common/processor_event'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { getErrorName } from '../../helpers/get_error_name'; -import { Setup } from '../../helpers/setup_request'; +import { getErrorName } from '../../../lib/helpers/get_error_name'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getServiceErrorGroupMainStatistics({ kuery, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts b/x-pack/plugins/apm/server/routes/services/get_service_error_groups/index.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts rename to x-pack/plugins/apm/server/routes/services/get_service_error_groups/index.ts index 83cb38da6e0a3..1a853231bb09a 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_error_groups/index.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_error_groups/index.ts @@ -19,9 +19,9 @@ import { import { ProcessorEvent } from '../../../../common/processor_event'; import { environmentQuery } from '../../../../common/utils/environment_query'; import { withApmSpan } from '../../../utils/with_apm_span'; -import { getBucketSize } from '../../helpers/get_bucket_size'; -import { getErrorName } from '../../helpers/get_error_name'; -import { Setup } from '../../helpers/setup_request'; +import { getBucketSize } from '../../../lib/helpers/get_bucket_size'; +import { getErrorName } from '../../../lib/helpers/get_error_name'; +import { Setup } from '../../../lib/helpers/setup_request'; export type ServiceErrorGroupItem = ValuesType< PromiseReturnType diff --git a/x-pack/plugins/apm/server/lib/services/get_service_infrastructure.ts b/x-pack/plugins/apm/server/routes/services/get_service_infrastructure.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/get_service_infrastructure.ts rename to x-pack/plugins/apm/server/routes/services/get_service_infrastructure.ts index 09946187b90a2..cda0beb6b2d70 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_infrastructure.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_infrastructure.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { rangeQuery, kqlQuery } from '../../../../observability/server'; import { environmentQuery } from '../../../common/utils/environment_query'; import { ProcessorEvent } from '../../../common/processor_event'; diff --git a/x-pack/plugins/apm/server/lib/services/get_service_instance_metadata_details.ts b/x-pack/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/get_service_instance_metadata_details.ts rename to x-pack/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts index d349ca3ce0399..957d655b98e5d 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_instance_metadata_details.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_instance_metadata_details.ts @@ -12,12 +12,12 @@ import { SERVICE_NODE_NAME, } from '../../../common/elasticsearch_fieldnames'; import { rangeQuery } from '../../../../observability/server'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { maybe } from '../../../common/utils/maybe'; import { getDocumentTypeFilterForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; +} from '../../lib/helpers/transactions'; export async function getServiceInstanceMetadataDetails({ serviceName, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_instances/detailed_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_instances/detailed_statistics.ts similarity index 98% rename from x-pack/plugins/apm/server/lib/services/get_service_instances/detailed_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_instances/detailed_statistics.ts index fd6f0f6d03c66..10393e3434779 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_instances/detailed_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_instances/detailed_statistics.ts @@ -11,7 +11,7 @@ import { Coordinate } from '../../../../typings/timeseries'; import { LatencyAggregationType } from '../../../../common/latency_aggregation_types'; import { joinByKey } from '../../../../common/utils/join_by_key'; import { withApmSpan } from '../../../utils/with_apm_span'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getServiceInstancesSystemMetricStatistics } from './get_service_instances_system_metric_statistics'; import { getServiceInstancesTransactionStatistics } from './get_service_instances_transaction_statistics'; diff --git a/x-pack/plugins/apm/server/lib/services/get_service_instances/get_service_instances_system_metric_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/get_service_instances/get_service_instances_system_metric_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts index 61e89ed8ca5e3..11fcbd8ce6561 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_instances/get_service_instances_system_metric_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_instances/get_service_instances_system_metric_statistics.ts @@ -19,8 +19,8 @@ import { SERVICE_NODE_NAME_MISSING } from '../../../../common/service_nodes'; import { Coordinate } from '../../../../typings/timeseries'; import { kqlQuery, rangeQuery } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { getBucketSize } from '../../helpers/get_bucket_size'; -import { Setup } from '../../helpers/setup_request'; +import { getBucketSize } from '../../../lib/helpers/get_bucket_size'; +import { Setup } from '../../../lib/helpers/setup_request'; import { percentCgroupMemoryUsedScript, percentSystemMemoryUsedScript, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_instances/get_service_instances_transaction_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_instances/get_service_instances_transaction_statistics.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/services/get_service_instances/get_service_instances_transaction_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_instances/get_service_instances_transaction_statistics.ts index b0f64036a1845..166e8d61142ea 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_instances/get_service_instances_transaction_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_instances/get_service_instances_transaction_statistics.ts @@ -20,14 +20,14 @@ import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../../helpers/transactions'; -import { calculateThroughput } from '../../helpers/calculate_throughput'; -import { getBucketSizeForAggregatedTransactions } from '../../helpers/get_bucket_size_for_aggregated_transactions'; +} from '../../../lib/helpers/transactions'; +import { calculateThroughput } from '../../../lib/helpers/calculate_throughput'; +import { getBucketSizeForAggregatedTransactions } from '../../../lib/helpers/get_bucket_size_for_aggregated_transactions'; import { getLatencyAggregation, getLatencyValue, -} from '../../helpers/latency_aggregation_type'; -import { Setup } from '../../helpers/setup_request'; +} from '../../../lib/helpers/latency_aggregation_type'; +import { Setup } from '../../../lib/helpers/setup_request'; interface ServiceInstanceTransactionPrimaryStatistics { serviceNodeName: string; diff --git a/x-pack/plugins/apm/server/lib/services/get_service_instances/main_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_instances/main_statistics.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/get_service_instances/main_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_instances/main_statistics.ts index ea34693bceb30..a064c71496de9 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_instances/main_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_instances/main_statistics.ts @@ -8,7 +8,7 @@ import { LatencyAggregationType } from '../../../../common/latency_aggregation_types'; import { joinByKey } from '../../../../common/utils/join_by_key'; import { withApmSpan } from '../../../utils/with_apm_span'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getServiceInstancesSystemMetricStatistics } from './get_service_instances_system_metric_statistics'; import { getServiceInstancesTransactionStatistics } from './get_service_instances_transaction_statistics'; diff --git a/x-pack/plugins/apm/server/lib/services/get_service_metadata_details.ts b/x-pack/plugins/apm/server/routes/services/get_service_metadata_details.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/get_service_metadata_details.ts rename to x-pack/plugins/apm/server/routes/services/get_service_metadata_details.ts index e2852a51b0c06..b7ce68a0de578 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_metadata_details.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_metadata_details.ts @@ -22,8 +22,8 @@ import { import { ContainerType } from '../../../common/service_metadata'; import { rangeQuery } from '../../../../observability/server'; import { TransactionRaw } from '../../../typings/es_schemas/raw/transaction_raw'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; -import { Setup } from '../helpers/setup_request'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; import { should } from './get_service_metadata_icons'; type ServiceMetadataDetailsRaw = Pick< diff --git a/x-pack/plugins/apm/server/lib/services/get_service_metadata_icons.ts b/x-pack/plugins/apm/server/routes/services/get_service_metadata_icons.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/services/get_service_metadata_icons.ts rename to x-pack/plugins/apm/server/routes/services/get_service_metadata_icons.ts index 2c93a298cb134..ca97e9d58f060 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_metadata_icons.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_metadata_icons.ts @@ -18,8 +18,8 @@ import { import { ContainerType } from '../../../common/service_metadata'; import { rangeQuery } from '../../../../observability/server'; import { TransactionRaw } from '../../../typings/es_schemas/raw/transaction_raw'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; -import { Setup } from '../helpers/setup_request'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; type ServiceMetadataIconsRaw = Pick< TransactionRaw, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_node_metadata.ts b/x-pack/plugins/apm/server/routes/services/get_service_node_metadata.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/get_service_node_metadata.ts rename to x-pack/plugins/apm/server/routes/services/get_service_node_metadata.ts index ab0fa91529917..89e0e42e95914 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_node_metadata.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_node_metadata.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { HOST_NAME, CONTAINER_ID, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_transaction_group_detailed_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_service_transaction_group_detailed_statistics.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/services/get_service_transaction_group_detailed_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_service_transaction_group_detailed_statistics.ts index 35256e6a7ecd6..70f77c26fdbf9 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_transaction_group_detailed_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_transaction_group_detailed_statistics.ts @@ -22,14 +22,14 @@ import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; -import { getBucketSizeForAggregatedTransactions } from '../helpers/get_bucket_size_for_aggregated_transactions'; +} from '../../lib/helpers/transactions'; +import { getBucketSizeForAggregatedTransactions } from '../../lib/helpers/get_bucket_size_for_aggregated_transactions'; import { getLatencyAggregation, getLatencyValue, -} from '../helpers/latency_aggregation_type'; -import { Setup } from '../helpers/setup_request'; -import { calculateFailedTransactionRate } from '../helpers/transaction_error_rate'; +} from '../../lib/helpers/latency_aggregation_type'; +import { Setup } from '../../lib/helpers/setup_request'; +import { calculateFailedTransactionRate } from '../../lib/helpers/transaction_error_rate'; export async function getServiceTransactionGroupDetailedStatistics({ environment, diff --git a/x-pack/plugins/apm/server/lib/services/get_service_transaction_groups.ts b/x-pack/plugins/apm/server/routes/services/get_service_transaction_groups.ts similarity index 92% rename from x-pack/plugins/apm/server/lib/services/get_service_transaction_groups.ts rename to x-pack/plugins/apm/server/routes/services/get_service_transaction_groups.ts index 7f624693a3b9c..711d6964221bd 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_transaction_groups.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_transaction_groups.ts @@ -19,14 +19,14 @@ import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; -import { calculateThroughput } from '../helpers/calculate_throughput'; +} from '../../lib/helpers/transactions'; +import { calculateThroughput } from '../../lib/helpers/calculate_throughput'; import { getLatencyAggregation, getLatencyValue, -} from '../helpers/latency_aggregation_type'; -import { Setup } from '../helpers/setup_request'; -import { calculateFailedTransactionRate } from '../helpers/transaction_error_rate'; +} from '../../lib/helpers/latency_aggregation_type'; +import { Setup } from '../../lib/helpers/setup_request'; +import { calculateFailedTransactionRate } from '../../lib/helpers/transaction_error_rate'; export type ServiceOverviewTransactionGroupSortField = | 'name' diff --git a/x-pack/plugins/apm/server/lib/services/get_service_transaction_types.ts b/x-pack/plugins/apm/server/routes/services/get_service_transaction_types.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/services/get_service_transaction_types.ts rename to x-pack/plugins/apm/server/routes/services/get_service_transaction_types.ts index 1c2d1c9207bc3..a3761df72156e 100644 --- a/x-pack/plugins/apm/server/lib/services/get_service_transaction_types.ts +++ b/x-pack/plugins/apm/server/routes/services/get_service_transaction_types.ts @@ -10,11 +10,11 @@ import { TRANSACTION_TYPE, } from '../../../common/elasticsearch_fieldnames'; import { rangeQuery } from '../../../../observability/server'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; import { getDocumentTypeFilterForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; +} from '../../lib/helpers/transactions'; export async function getServiceTransactionTypes({ setup, diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_health_statuses.ts b/x-pack/plugins/apm/server/routes/services/get_services/get_health_statuses.ts similarity index 92% rename from x-pack/plugins/apm/server/lib/services/get_services/get_health_statuses.ts rename to x-pack/plugins/apm/server/routes/services/get_services/get_health_statuses.ts index af6d0d9613b35..65fb04b821ffa 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_health_statuses.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services/get_health_statuses.ts @@ -7,7 +7,7 @@ import { getSeverity } from '../../../../common/anomaly_detection'; import { getServiceHealthStatus } from '../../../../common/service_health_status'; -import { getServiceAnomalies } from '../../service_map/get_service_anomalies'; +import { getServiceAnomalies } from '../../../routes/service_map/get_service_anomalies'; import { ServicesItemsSetup } from './get_services_items'; interface AggregationParams { diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts b/x-pack/plugins/apm/server/routes/services/get_services/get_legacy_data_status.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts rename to x-pack/plugins/apm/server/routes/services/get_services/get_legacy_data_status.ts index 5b94bb2314258..7275e34786e36 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services/get_legacy_data_status.ts @@ -8,7 +8,7 @@ import { rangeQuery } from '../../../../../observability/server'; import { ProcessorEvent } from '../../../../common/processor_event'; import { OBSERVER_VERSION_MAJOR } from '../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; // returns true if 6.x data is found export async function getLegacyDataStatus( diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_service_transaction_stats.ts b/x-pack/plugins/apm/server/routes/services/get_services/get_service_transaction_stats.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/services/get_services/get_service_transaction_stats.ts rename to x-pack/plugins/apm/server/routes/services/get_services/get_service_transaction_stats.ts index 36903f9ca229f..3eaa8053b6709 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_service_transaction_stats.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services/get_service_transaction_stats.ts @@ -22,12 +22,12 @@ import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../../helpers/transactions'; -import { calculateThroughput } from '../../helpers/calculate_throughput'; +} from '../../../lib/helpers/transactions'; +import { calculateThroughput } from '../../../lib/helpers/calculate_throughput'; import { calculateFailedTransactionRate, getOutcomeAggregation, -} from '../../helpers/transaction_error_rate'; +} from '../../../lib/helpers/transaction_error_rate'; import { ServicesItemsSetup } from './get_services_items'; interface AggregationParams { diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_services_from_metric_documents.ts b/x-pack/plugins/apm/server/routes/services/get_services/get_services_from_metric_documents.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/get_services/get_services_from_metric_documents.ts rename to x-pack/plugins/apm/server/routes/services/get_services/get_services_from_metric_documents.ts index cffd106d13348..055d82a807815 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_services_from_metric_documents.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services/get_services_from_metric_documents.ts @@ -14,7 +14,7 @@ import { import { kqlQuery, rangeQuery } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; import { ProcessorEvent } from '../../../../common/processor_event'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function getServicesFromMetricDocuments({ environment, diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts b/x-pack/plugins/apm/server/routes/services/get_services/get_services_items.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts rename to x-pack/plugins/apm/server/routes/services/get_services/get_services_items.ts index 47f1f6e7e6430..db3377b6710c5 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/get_services_items.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services/get_services_items.ts @@ -7,7 +7,7 @@ import { Logger } from '@kbn/logging'; import { withApmSpan } from '../../../utils/with_apm_span'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getHealthStatuses } from './get_health_statuses'; import { getServicesFromMetricDocuments } from './get_services_from_metric_documents'; import { getServiceTransactionStats } from './get_service_transaction_stats'; diff --git a/x-pack/plugins/apm/server/lib/services/get_services/index.ts b/x-pack/plugins/apm/server/routes/services/get_services/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/services/get_services/index.ts rename to x-pack/plugins/apm/server/routes/services/get_services/index.ts index d6a940bc14b5f..9d1670fe84582 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services/index.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services/index.ts @@ -7,7 +7,7 @@ import { Logger } from '@kbn/logging'; import { withApmSpan } from '../../../utils/with_apm_span'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getLegacyDataStatus } from './get_legacy_data_status'; import { getServicesItems } from './get_services_items'; diff --git a/x-pack/plugins/apm/server/lib/services/get_services/merge_service_stats.test.ts b/x-pack/plugins/apm/server/routes/services/get_services/merge_service_stats.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/services/get_services/merge_service_stats.test.ts rename to x-pack/plugins/apm/server/routes/services/get_services/merge_service_stats.test.ts diff --git a/x-pack/plugins/apm/server/lib/services/get_services/merge_service_stats.ts b/x-pack/plugins/apm/server/routes/services/get_services/merge_service_stats.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/services/get_services/merge_service_stats.ts rename to x-pack/plugins/apm/server/routes/services/get_services/merge_service_stats.ts diff --git a/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts b/x-pack/plugins/apm/server/routes/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts similarity index 92% rename from x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts rename to x-pack/plugins/apm/server/routes/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts index ea153a5ddcd4c..95f2c6f400de9 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts @@ -21,14 +21,14 @@ import { getDocumentTypeFilterForTransactions, getTransactionDurationFieldForTransactions, getProcessorEventForTransactions, -} from '../../helpers/transactions'; -import { calculateThroughput } from '../../helpers/calculate_throughput'; -import { getBucketSizeForAggregatedTransactions } from '../../helpers/get_bucket_size_for_aggregated_transactions'; -import { Setup } from '../../helpers/setup_request'; +} from '../../../lib/helpers/transactions'; +import { calculateThroughput } from '../../../lib/helpers/calculate_throughput'; +import { getBucketSizeForAggregatedTransactions } from '../../../lib/helpers/get_bucket_size_for_aggregated_transactions'; +import { Setup } from '../../../lib/helpers/setup_request'; import { calculateFailedTransactionRate, getOutcomeAggregation, -} from '../../helpers/transaction_error_rate'; +} from '../../../lib/helpers/transaction_error_rate'; export async function getServiceTransactionDetailedStatistics({ serviceNames, diff --git a/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/index.ts b/x-pack/plugins/apm/server/routes/services/get_services_detailed_statistics/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/index.ts rename to x-pack/plugins/apm/server/routes/services/get_services_detailed_statistics/index.ts index e2f2ee226ab1e..228add10184ba 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/index.ts +++ b/x-pack/plugins/apm/server/routes/services/get_services_detailed_statistics/index.ts @@ -6,7 +6,7 @@ */ import { withApmSpan } from '../../../utils/with_apm_span'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getServiceTransactionDetailedStatistics } from './get_service_transaction_detailed_statistics'; export async function getServicesDetailedStatistics({ diff --git a/x-pack/plugins/apm/server/lib/services/get_throughput.ts b/x-pack/plugins/apm/server/routes/services/get_throughput.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/get_throughput.ts rename to x-pack/plugins/apm/server/routes/services/get_throughput.ts index 3161066ebadf9..4a0366cc2f6ae 100644 --- a/x-pack/plugins/apm/server/lib/services/get_throughput.ts +++ b/x-pack/plugins/apm/server/routes/services/get_throughput.ts @@ -20,8 +20,8 @@ import { environmentQuery } from '../../../common/utils/environment_query'; import { getDocumentTypeFilterForTransactions, getProcessorEventForTransactions, -} from '../helpers/transactions'; -import { Setup } from '../helpers/setup_request'; +} from '../../lib/helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; interface Options { environment: string; diff --git a/x-pack/plugins/apm/server/lib/services/profiling/get_service_profiling_statistics.ts b/x-pack/plugins/apm/server/routes/services/profiling/get_service_profiling_statistics.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/services/profiling/get_service_profiling_statistics.ts rename to x-pack/plugins/apm/server/routes/services/profiling/get_service_profiling_statistics.ts index 0b96a6bd3d456..009d974e33721 100644 --- a/x-pack/plugins/apm/server/lib/services/profiling/get_service_profiling_statistics.ts +++ b/x-pack/plugins/apm/server/routes/services/profiling/get_service_profiling_statistics.ts @@ -23,8 +23,8 @@ import { } from '../../../../common/elasticsearch_fieldnames'; import { rangeQuery, kqlQuery } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { APMEventClient } from '../../helpers/create_es_client/create_apm_event_client'; -import { Setup } from '../../helpers/setup_request'; +import { APMEventClient } from '../../../lib/helpers/create_es_client/create_apm_event_client'; +import { Setup } from '../../../lib/helpers/setup_request'; import { withApmSpan } from '../../../utils/with_apm_span'; const MAX_STACK_IDS = 10000; diff --git a/x-pack/plugins/apm/server/lib/services/profiling/get_service_profiling_timeline.ts b/x-pack/plugins/apm/server/routes/services/profiling/get_service_profiling_timeline.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/services/profiling/get_service_profiling_timeline.ts rename to x-pack/plugins/apm/server/routes/services/profiling/get_service_profiling_timeline.ts index ce1580fc48290..47df939467d0e 100644 --- a/x-pack/plugins/apm/server/lib/services/profiling/get_service_profiling_timeline.ts +++ b/x-pack/plugins/apm/server/routes/services/profiling/get_service_profiling_timeline.ts @@ -14,8 +14,8 @@ import { getValueTypeConfig, ProfilingValueType, } from '../../../../common/profiling'; -import { Setup } from '../../helpers/setup_request'; -import { getBucketSize } from '../../helpers/get_bucket_size'; +import { Setup } from '../../../lib/helpers/setup_request'; +import { getBucketSize } from '../../../lib/helpers/get_bucket_size'; import { environmentQuery } from '../../../../common/utils/environment_query'; import { kqlQuery, rangeQuery } from '../../../../../observability/server'; diff --git a/x-pack/plugins/apm/server/lib/services/queries.test.ts b/x-pack/plugins/apm/server/routes/services/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/services/queries.test.ts rename to x-pack/plugins/apm/server/routes/services/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/services.ts b/x-pack/plugins/apm/server/routes/services/route.ts similarity index 89% rename from x-pack/plugins/apm/server/routes/services.ts rename to x-pack/plugins/apm/server/routes/services/route.ts index cb557f56d8165..d395be4c6adce 100644 --- a/x-pack/plugins/apm/server/routes/services.ts +++ b/x-pack/plugins/apm/server/routes/services/route.ts @@ -11,42 +11,42 @@ import { isoToEpochRt } from '@kbn/io-ts-utils/iso_to_epoch_rt'; import { toNumberRt } from '@kbn/io-ts-utils/to_number_rt'; import * as t from 'io-ts'; import { uniq } from 'lodash'; -import { latencyAggregationTypeRt } from '../../common/latency_aggregation_types'; -import { ProfilingValueType } from '../../common/profiling'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getServiceAnnotations } from '../lib/services/annotations'; -import { getServices } from '../lib/services/get_services'; -import { getServiceAgent } from '../lib/services/get_service_agent'; -import { getServiceAlerts } from '../lib/services/get_service_alerts'; -import { getServiceDependencies } from '../lib/services/get_service_dependencies'; -import { getServiceInstanceMetadataDetails } from '../lib/services/get_service_instance_metadata_details'; -import { getServiceErrorGroupPeriods } from '../lib/services/get_service_error_groups/get_service_error_group_detailed_statistics'; -import { getServiceErrorGroupMainStatistics } from '../lib/services/get_service_error_groups/get_service_error_group_main_statistics'; -import { getServiceInstancesDetailedStatisticsPeriods } from '../lib/services/get_service_instances/detailed_statistics'; -import { getServiceInstancesMainStatistics } from '../lib/services/get_service_instances/main_statistics'; -import { getServiceMetadataDetails } from '../lib/services/get_service_metadata_details'; -import { getServiceMetadataIcons } from '../lib/services/get_service_metadata_icons'; -import { getServiceNodeMetadata } from '../lib/services/get_service_node_metadata'; -import { getServiceTransactionTypes } from '../lib/services/get_service_transaction_types'; -import { getThroughput } from '../lib/services/get_throughput'; -import { getServiceProfilingStatistics } from '../lib/services/profiling/get_service_profiling_statistics'; -import { getServiceProfilingTimeline } from '../lib/services/profiling/get_service_profiling_timeline'; -import { getServiceInfrastructure } from '../lib/services/get_service_infrastructure'; -import { withApmSpan } from '../utils/with_apm_span'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; +import { latencyAggregationTypeRt } from '../../../common/latency_aggregation_types'; +import { ProfilingValueType } from '../../../common/profiling'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getServiceAnnotations } from './annotations'; +import { getServices } from './get_services'; +import { getServiceAgent } from './get_service_agent'; +import { getServiceAlerts } from './get_service_alerts'; +import { getServiceDependencies } from './get_service_dependencies'; +import { getServiceInstanceMetadataDetails } from './get_service_instance_metadata_details'; +import { getServiceErrorGroupPeriods } from './get_service_error_groups/get_service_error_group_detailed_statistics'; +import { getServiceErrorGroupMainStatistics } from './get_service_error_groups/get_service_error_group_main_statistics'; +import { getServiceInstancesDetailedStatisticsPeriods } from './get_service_instances/detailed_statistics'; +import { getServiceInstancesMainStatistics } from './get_service_instances/main_statistics'; +import { getServiceMetadataDetails } from './get_service_metadata_details'; +import { getServiceMetadataIcons } from './get_service_metadata_icons'; +import { getServiceNodeMetadata } from './get_service_node_metadata'; +import { getServiceTransactionTypes } from './get_service_transaction_types'; +import { getThroughput } from './get_throughput'; +import { getServiceProfilingStatistics } from './profiling/get_service_profiling_statistics'; +import { getServiceProfilingTimeline } from './profiling/get_service_profiling_timeline'; +import { getServiceInfrastructure } from './get_service_infrastructure'; +import { withApmSpan } from '../../utils/with_apm_span'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { comparisonRangeRt, environmentRt, kueryRt, offsetRt, rangeRt, -} from './default_api_types'; -import { offsetPreviousPeriodCoordinates } from '../../common/utils/offset_previous_period_coordinate'; -import { getServicesDetailedStatistics } from '../lib/services/get_services_detailed_statistics'; -import { getServiceDependenciesBreakdown } from '../lib/services/get_service_dependencies_breakdown'; -import { getBucketSizeForAggregatedTransactions } from '../lib/helpers/get_bucket_size_for_aggregated_transactions'; +} from '../default_api_types'; +import { offsetPreviousPeriodCoordinates } from '../../../common/utils/offset_previous_period_coordinate'; +import { getServicesDetailedStatistics } from './get_services_detailed_statistics'; +import { getServiceDependenciesBreakdown } from './get_service_dependencies_breakdown'; +import { getBucketSizeForAggregatedTransactions } from '../../lib/helpers/get_bucket_size_for_aggregated_transactions'; const servicesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/services', diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/settings/agent_configuration/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/convert_settings_to_string.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/convert_settings_to_string.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/convert_settings_to_string.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/convert_settings_to_string.ts diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/create_agent_config_index.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/create_agent_config_index.ts diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_or_update_configuration.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/create_or_update_configuration.ts similarity index 89% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/create_or_update_configuration.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/create_or_update_configuration.ts index c112c3be3362b..07a9f79829306 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_or_update_configuration.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/create_or_update_configuration.ts @@ -6,12 +6,12 @@ */ import hash from 'object-hash'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { AgentConfiguration, AgentConfigurationIntake, } from '../../../../common/agent_configuration/configuration_types'; -import { APMIndexDocumentParams } from '../../helpers/create_es_client/create_internal_es_client'; +import { APMIndexDocumentParams } from '../../../lib/helpers/create_es_client/create_internal_es_client'; export function createOrUpdateConfiguration({ configurationId, diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/delete_configuration.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/delete_configuration.ts similarity index 91% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/delete_configuration.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/delete_configuration.ts index 125c97730a6fa..5ac8437b15786 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/delete_configuration.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/delete_configuration.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; export async function deleteConfiguration({ configurationId, diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/find_exact_configuration.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/find_exact_configuration.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/find_exact_configuration.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/find_exact_configuration.ts index 90f82442f9bfa..ac95f36107994 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/find_exact_configuration.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/find_exact_configuration.ts @@ -11,7 +11,7 @@ import { SERVICE_ENVIRONMENT, SERVICE_NAME, } from '../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { convertConfigSettingsToString } from './convert_settings_to_string'; export async function findExactConfiguration({ diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_agent_name_by_service.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/get_agent_name_by_service.ts index 6ea3e2a578050..d16af2d95d22a 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_agent_name_by_service.ts @@ -6,7 +6,7 @@ */ import { ProcessorEvent } from '../../../../common/processor_event'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { SERVICE_NAME } from '../../../../common/elasticsearch_fieldnames'; import { AGENT_NAME } from '../../../../common/elasticsearch_fieldnames'; diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/get_existing_environments_for_service.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_environments/get_existing_environments_for_service.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/get_existing_environments_for_service.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/get_environments/get_existing_environments_for_service.ts index 4fd351f8708a2..a3925c060a1c5 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/get_existing_environments_for_service.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_environments/get_existing_environments_for_service.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../../helpers/setup_request'; +import { Setup } from '../../../../lib/helpers/setup_request'; import { SERVICE_NAME, SERVICE_ENVIRONMENT, diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_environments/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/get_environments/index.ts index a22c1d35dc663..46ab82152caad 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_environments/index.ts @@ -7,7 +7,7 @@ import { withApmSpan } from '../../../../utils/with_apm_span'; import { getAllEnvironments } from '../../../environments/get_all_environments'; -import { Setup } from '../../../helpers/setup_request'; +import { Setup } from '../../../../lib/helpers/setup_request'; import { getExistingEnvironmentsForService } from './get_existing_environments_for_service'; import { ALL_OPTION_VALUE } from '../../../../../common/agent_configuration/all_option'; diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_service_names.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_service_names.ts similarity index 90% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/get_service_names.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/get_service_names.ts index fc5167159b98d..18e359c5b9425 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_service_names.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/get_service_names.ts @@ -6,10 +6,10 @@ */ import { ProcessorEvent } from '../../../../common/processor_event'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { SERVICE_NAME } from '../../../../common/elasticsearch_fieldnames'; import { ALL_OPTION_VALUE } from '../../../../common/agent_configuration/all_option'; -import { getProcessorEventForTransactions } from '../../helpers/transactions'; +import { getProcessorEventForTransactions } from '../../../lib/helpers/transactions'; export async function getServiceNames({ setup, diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/list_configurations.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/list_configurations.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/list_configurations.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/list_configurations.ts index 098888c23ccbc..bc105106cb5e4 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/list_configurations.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/list_configurations.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { AgentConfiguration } from '../../../../common/agent_configuration/configuration_types'; import { convertConfigSettingsToString } from './convert_settings_to_string'; diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/mark_applied_by_agent.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/mark_applied_by_agent.ts similarity index 93% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/mark_applied_by_agent.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/mark_applied_by_agent.ts index 5fa4993921570..78e0ce68624a6 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/mark_applied_by_agent.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/mark_applied_by_agent.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { AgentConfiguration } from '../../../../common/agent_configuration/configuration_types'; // We're not wrapping this function with a span as it is not blocking the request diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/queries.test.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/queries.test.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts similarity index 86% rename from x-pack/plugins/apm/server/routes/settings/agent_configuration.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts index 563fa40c6c0d9..1122c2095ed3d 100644 --- a/x-pack/plugins/apm/server/routes/settings/agent_configuration.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts @@ -8,25 +8,25 @@ import * as t from 'io-ts'; import Boom from '@hapi/boom'; import { toBooleanRt } from '@kbn/io-ts-utils/to_boolean_rt'; -import { maxSuggestions } from '../../../../observability/common'; -import { setupRequest } from '../../lib/helpers/setup_request'; -import { getServiceNames } from '../../lib/settings/agent_configuration/get_service_names'; -import { createOrUpdateConfiguration } from '../../lib/settings/agent_configuration/create_or_update_configuration'; -import { searchConfigurations } from '../../lib/settings/agent_configuration/search_configurations'; -import { findExactConfiguration } from '../../lib/settings/agent_configuration/find_exact_configuration'; -import { listConfigurations } from '../../lib/settings/agent_configuration/list_configurations'; -import { getEnvironments } from '../../lib/settings/agent_configuration/get_environments'; -import { deleteConfiguration } from '../../lib/settings/agent_configuration/delete_configuration'; -import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { getAgentNameByService } from '../../lib/settings/agent_configuration/get_agent_name_by_service'; -import { markAppliedByAgent } from '../../lib/settings/agent_configuration/mark_applied_by_agent'; +import { maxSuggestions } from '../../../../../observability/common'; +import { setupRequest } from '../../../lib/helpers/setup_request'; +import { getServiceNames } from './get_service_names'; +import { createOrUpdateConfiguration } from './create_or_update_configuration'; +import { searchConfigurations } from './search_configurations'; +import { findExactConfiguration } from './find_exact_configuration'; +import { listConfigurations } from './list_configurations'; +import { getEnvironments } from './get_environments'; +import { deleteConfiguration } from './delete_configuration'; +import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; +import { getAgentNameByService } from './get_agent_name_by_service'; +import { markAppliedByAgent } from './mark_applied_by_agent'; import { serviceRt, agentConfigurationIntakeRt, -} from '../../../common/agent_configuration/runtime_types/agent_configuration_intake_rt'; -import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; -import { syncAgentConfigsToApmPackagePolicies } from '../../lib/fleet/sync_agent_configs_to_apm_package_policies'; +} from '../../../../common/agent_configuration/runtime_types/agent_configuration_intake_rt'; +import { getSearchAggregatedTransactions } from '../../../lib/helpers/transactions'; +import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; +import { syncAgentConfigsToApmPackagePolicies } from '../../fleet/sync_agent_configs_to_apm_package_policies'; // get list of configurations const agentConfigurationRoute = createApmServerRoute({ diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/search_configurations.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/search_configurations.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/search_configurations.ts rename to x-pack/plugins/apm/server/routes/settings/agent_configuration/search_configurations.ts index 1e37ae9108573..194e1eff4e657 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/search_configurations.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/search_configurations.ts @@ -10,7 +10,7 @@ import { SERVICE_NAME, SERVICE_ENVIRONMENT, } from '../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { AgentConfiguration } from '../../../../common/agent_configuration/configuration_types'; import { convertConfigSettingsToString } from './convert_settings_to_string'; diff --git a/x-pack/plugins/apm/server/routes/settings/anomaly_detection.ts b/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts similarity index 74% rename from x-pack/plugins/apm/server/routes/settings/anomaly_detection.ts rename to x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts index e8b2ef5e119cd..a924a9214977d 100644 --- a/x-pack/plugins/apm/server/routes/settings/anomaly_detection.ts +++ b/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts @@ -7,19 +7,19 @@ import * as t from 'io-ts'; import Boom from '@hapi/boom'; -import { maxSuggestions } from '../../../../observability/common'; -import { isActivePlatinumLicense } from '../../../common/license_check'; -import { ML_ERRORS } from '../../../common/anomaly_detection'; -import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { getAnomalyDetectionJobs } from '../../lib/anomaly_detection/get_anomaly_detection_jobs'; -import { createAnomalyDetectionJobs } from '../../lib/anomaly_detection/create_anomaly_detection_jobs'; -import { setupRequest } from '../../lib/helpers/setup_request'; -import { getAllEnvironments } from '../../lib/environments/get_all_environments'; -import { hasLegacyJobs } from '../../lib/anomaly_detection/has_legacy_jobs'; -import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; -import { notifyFeatureUsage } from '../../feature'; -import { withApmSpan } from '../../utils/with_apm_span'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { maxSuggestions } from '../../../../../observability/common'; +import { isActivePlatinumLicense } from '../../../../common/license_check'; +import { ML_ERRORS } from '../../../../common/anomaly_detection'; +import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; +import { getAnomalyDetectionJobs } from '../../../lib/anomaly_detection/get_anomaly_detection_jobs'; +import { createAnomalyDetectionJobs } from '../../../lib/anomaly_detection/create_anomaly_detection_jobs'; +import { setupRequest } from '../../../lib/helpers/setup_request'; +import { getAllEnvironments } from '../../environments/get_all_environments'; +import { hasLegacyJobs } from '../../../lib/anomaly_detection/has_legacy_jobs'; +import { getSearchAggregatedTransactions } from '../../../lib/helpers/transactions'; +import { notifyFeatureUsage } from '../../../feature'; +import { withApmSpan } from '../../../utils/with_apm_span'; +import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; // get ML anomaly detection jobs for each environment const anomalyDetectionJobsRoute = createApmServerRoute({ diff --git a/x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts rename to x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts index a37720cbc3790..6b917919bade5 100644 --- a/x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/get_apm_indices.ts @@ -12,7 +12,7 @@ import { APM_INDICES_SAVED_OBJECT_ID, } from '../../../../common/apm_saved_object_constants'; import { APMConfig } from '../../..'; -import { APMRouteHandlerResources } from '../../../routes/typings'; +import { APMRouteHandlerResources } from '../../typings'; import { withApmSpan } from '../../../utils/with_apm_span'; import { ApmIndicesConfig } from '../../../../../observability/common/typings'; diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts similarity index 82% rename from x-pack/plugins/apm/server/routes/settings/apm_indices.ts rename to x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts index ed99f0c8862f0..485ff8af88843 100644 --- a/x-pack/plugins/apm/server/routes/settings/apm_indices.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts @@ -6,14 +6,11 @@ */ import * as t from 'io-ts'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; -import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { - getApmIndices, - getApmIndexSettings, -} from '../../lib/settings/apm_indices/get_apm_indices'; -import { saveApmIndices } from '../../lib/settings/apm_indices/save_apm_indices'; -import { APMConfig } from '../..'; +import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; +import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; +import { getApmIndices, getApmIndexSettings } from './get_apm_indices'; +import { saveApmIndices } from './save_apm_indices'; +import { APMConfig } from '../../../'; // get list of apm indices and values const apmIndexSettingsRoute = createApmServerRoute({ diff --git a/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.test.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.test.ts rename to x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.test.ts diff --git a/x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/apm_indices/save_apm_indices.ts rename to x-pack/plugins/apm/server/routes/settings/apm_indices/save_apm_indices.ts diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/get_transaction.test.ts.snap b/x-pack/plugins/apm/server/routes/settings/custom_link/__snapshots__/get_transaction.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/get_transaction.test.ts.snap rename to x-pack/plugins/apm/server/routes/settings/custom_link/__snapshots__/get_transaction.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/list_custom_links.test.ts.snap b/x-pack/plugins/apm/server/routes/settings/custom_link/__snapshots__/list_custom_links.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/list_custom_links.test.ts.snap rename to x-pack/plugins/apm/server/routes/settings/custom_link/__snapshots__/list_custom_links.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/create_custom_link_index.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/create_custom_link_index.ts diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts index 1cec38ad4af69..7690210ac0123 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.test.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { mockNow } from '../../../utils/test_helpers'; import { CustomLink } from '../../../../common/custom_link/custom_link_types'; import { createOrUpdateCustomLink } from './create_or_update_custom_link'; diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts similarity index 86% rename from x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts index 8f14e87fe183b..6431390936763 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/create_or_update_custom_link.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/create_or_update_custom_link.ts @@ -9,9 +9,9 @@ import { CustomLink, CustomLinkES, } from '../../../../common/custom_link/custom_link_types'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { toESFormat } from './helper'; -import { APMIndexDocumentParams } from '../../helpers/create_es_client/create_internal_es_client'; +import { APMIndexDocumentParams } from '../../../lib/helpers/create_es_client/create_internal_es_client'; export function createOrUpdateCustomLink({ customLinkId, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/custom_link_types.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/custom_link_types.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/custom_link/custom_link_types.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/custom_link_types.ts diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/delete_custom_link.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/delete_custom_link.ts similarity index 90% rename from x-pack/plugins/apm/server/lib/settings/custom_link/delete_custom_link.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/delete_custom_link.ts index bf7cfb33d87ac..6366bbcfd9f07 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/delete_custom_link.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/delete_custom_link.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; export function deleteCustomLink({ customLinkId, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/get_transaction.test.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/get_transaction.test.ts index 03d0120b0043b..e6ba932ca58d6 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.test.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/get_transaction.test.ts @@ -10,7 +10,7 @@ import { SearchParamsMock, } from '../../../utils/test_helpers'; import { getTransaction } from './get_transaction'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { SERVICE_NAME, TRANSACTION_TYPE, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/get_transaction.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/get_transaction.ts index 1c3d1465527ba..88d2ae9f339ac 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/get_transaction.ts @@ -7,7 +7,7 @@ import * as t from 'io-ts'; import { compact } from 'lodash'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { ProcessorEvent } from '../../../../common/processor_event'; import { filterOptionsRt } from './custom_link_types'; import { splitFilterValueByComma } from './helper'; diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/helper.test.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/helper.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/custom_link/helper.test.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/helper.test.ts diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/helper.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/helper.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/settings/custom_link/helper.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/helper.ts diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/list_custom_links.test.ts similarity index 94% rename from x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/list_custom_links.test.ts index 844f886c21a46..8ea4061e46cf2 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.test.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/list_custom_links.test.ts @@ -10,7 +10,7 @@ import { inspectSearchParams, SearchParamsMock, } from '../../../utils/test_helpers'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { SERVICE_NAME, TRANSACTION_NAME, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts similarity index 96% rename from x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts index 633545e16acfd..a64d958dabd09 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/list_custom_links.ts @@ -11,7 +11,7 @@ import { CustomLink, CustomLinkES, } from '../../../../common/custom_link/custom_link_types'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { fromESFormat } from './helper'; import { filterOptionsRt } from './custom_link_types'; diff --git a/x-pack/plugins/apm/server/routes/settings/custom_link.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts similarity index 79% rename from x-pack/plugins/apm/server/routes/settings/custom_link.ts rename to x-pack/plugins/apm/server/routes/settings/custom_link/route.ts index 044b56c3c273d..42232581f1af3 100644 --- a/x-pack/plugins/apm/server/routes/settings/custom_link.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts @@ -8,21 +8,18 @@ import Boom from '@hapi/boom'; import * as t from 'io-ts'; import { pick } from 'lodash'; -import { isActiveGoldLicense } from '../../../common/license_check'; -import { INVALID_LICENSE } from '../../../common/custom_link'; -import { FILTER_OPTIONS } from '../../../common/custom_link/custom_link_filter_options'; -import { notifyFeatureUsage } from '../../feature'; -import { setupRequest } from '../../lib/helpers/setup_request'; -import { createOrUpdateCustomLink } from '../../lib/settings/custom_link/create_or_update_custom_link'; -import { - filterOptionsRt, - payloadRt, -} from '../../lib/settings/custom_link/custom_link_types'; -import { deleteCustomLink } from '../../lib/settings/custom_link/delete_custom_link'; -import { getTransaction } from '../../lib/settings/custom_link/get_transaction'; -import { listCustomLinks } from '../../lib/settings/custom_link/list_custom_links'; -import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { isActiveGoldLicense } from '../../../../common/license_check'; +import { INVALID_LICENSE } from '../../../../common/custom_link'; +import { FILTER_OPTIONS } from '../../../../common/custom_link/custom_link_filter_options'; +import { notifyFeatureUsage } from '../../../feature'; +import { setupRequest } from '../../../lib/helpers/setup_request'; +import { createOrUpdateCustomLink } from './create_or_update_custom_link'; +import { filterOptionsRt, payloadRt } from './custom_link_types'; +import { deleteCustomLink } from './delete_custom_link'; +import { getTransaction } from './get_transaction'; +import { listCustomLinks } from './list_custom_links'; +import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; const customLinkTransactionRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/settings/custom_links/transaction', diff --git a/x-pack/plugins/apm/server/routes/source_maps.ts b/x-pack/plugins/apm/server/routes/source_maps/route.ts similarity index 91% rename from x-pack/plugins/apm/server/routes/source_maps.ts rename to x-pack/plugins/apm/server/routes/source_maps/route.ts index 602a3a725eac4..b0b7eb5134fcf 100644 --- a/x-pack/plugins/apm/server/routes/source_maps.ts +++ b/x-pack/plugins/apm/server/routes/source_maps/route.ts @@ -14,11 +14,11 @@ import { listArtifacts, updateSourceMapsOnFleetPolicies, getCleanedBundleFilePath, -} from '../lib/fleet/source_maps'; -import { getInternalSavedObjectsClient } from '../lib/helpers/get_internal_saved_objects_client'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { stringFromBufferRt } from '../utils/string_from_buffer_rt'; +} from '../fleet/source_maps'; +import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { stringFromBufferRt } from '../../utils/string_from_buffer_rt'; export const sourceMapRt = t.intersection([ t.type({ diff --git a/x-pack/plugins/apm/server/lib/suggestions/get_suggestions.ts b/x-pack/plugins/apm/server/routes/suggestions/get_suggestions.ts similarity index 87% rename from x-pack/plugins/apm/server/lib/suggestions/get_suggestions.ts rename to x-pack/plugins/apm/server/routes/suggestions/get_suggestions.ts index 5ea28debc4437..624bf2bb4c018 100644 --- a/x-pack/plugins/apm/server/lib/suggestions/get_suggestions.ts +++ b/x-pack/plugins/apm/server/routes/suggestions/get_suggestions.ts @@ -6,8 +6,8 @@ */ import { ProcessorEvent } from '../../../common/processor_event'; -import { getProcessorEventForTransactions } from '../helpers/transactions'; -import { Setup } from '../helpers/setup_request'; +import { getProcessorEventForTransactions } from '../../lib/helpers/transactions'; +import { Setup } from '../../lib/helpers/setup_request'; export async function getSuggestions({ field, diff --git a/x-pack/plugins/apm/server/routes/suggestions.ts b/x-pack/plugins/apm/server/routes/suggestions/route.ts similarity index 72% rename from x-pack/plugins/apm/server/routes/suggestions.ts rename to x-pack/plugins/apm/server/routes/suggestions/route.ts index 9b8952d09d162..de3636c2c1502 100644 --- a/x-pack/plugins/apm/server/routes/suggestions.ts +++ b/x-pack/plugins/apm/server/routes/suggestions/route.ts @@ -6,12 +6,12 @@ */ import * as t from 'io-ts'; -import { maxSuggestions } from '../../../observability/common'; -import { getSuggestions } from '../lib/suggestions/get_suggestions'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; +import { maxSuggestions } from '../../../../observability/common'; +import { getSuggestions } from '../suggestions/get_suggestions'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const suggestionsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/suggestions', diff --git a/x-pack/plugins/apm/server/lib/traces/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/traces/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/traces/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/traces/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts b/x-pack/plugins/apm/server/routes/traces/get_trace_items.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/traces/get_trace_items.ts rename to x-pack/plugins/apm/server/routes/traces/get_trace_items.ts index 55204786b8e67..419c3e44d68a6 100644 --- a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts +++ b/x-pack/plugins/apm/server/routes/traces/get_trace_items.ts @@ -15,7 +15,7 @@ import { ERROR_LOG_LEVEL, } from '../../../common/elasticsearch_fieldnames'; import { rangeQuery } from '../../../../observability/server'; -import { Setup } from '../helpers/setup_request'; +import { Setup } from '../../lib/helpers/setup_request'; export async function getTraceItems( traceId: string, diff --git a/x-pack/plugins/apm/server/lib/traces/queries.test.ts b/x-pack/plugins/apm/server/routes/traces/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/traces/queries.test.ts rename to x-pack/plugins/apm/server/routes/traces/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/traces.ts b/x-pack/plugins/apm/server/routes/traces/route.ts similarity index 79% rename from x-pack/plugins/apm/server/routes/traces.ts rename to x-pack/plugins/apm/server/routes/traces/route.ts index 5fdac470a81ed..24b5faeedfc00 100644 --- a/x-pack/plugins/apm/server/routes/traces.ts +++ b/x-pack/plugins/apm/server/routes/traces/route.ts @@ -6,15 +6,15 @@ */ import * as t from 'io-ts'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getTraceItems } from '../lib/traces/get_trace_items'; -import { getTopTransactionGroupList } from '../lib/transaction_groups'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { environmentRt, kueryRt, rangeRt } from './default_api_types'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { getRootTransactionByTraceId } from '../lib/transactions/get_transaction_by_trace'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; -import { getTransaction } from '../lib/transactions/get_transaction'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getTraceItems } from './get_trace_items'; +import { getTopTransactionGroupList } from '../../lib/transaction_groups'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { getRootTransactionByTraceId } from '../transactions/get_transaction_by_trace'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; +import { getTransaction } from '../transactions/get_transaction'; const tracesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/traces', diff --git a/x-pack/plugins/apm/server/lib/transactions/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/routes/transactions/__snapshots__/queries.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/server/lib/transactions/__snapshots__/queries.test.ts.snap rename to x-pack/plugins/apm/server/routes/transactions/__snapshots__/queries.test.ts.snap diff --git a/x-pack/plugins/apm/server/lib/transactions/breakdown/constants.ts b/x-pack/plugins/apm/server/routes/transactions/breakdown/constants.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/transactions/breakdown/constants.ts rename to x-pack/plugins/apm/server/routes/transactions/breakdown/constants.ts diff --git a/x-pack/plugins/apm/server/lib/transactions/breakdown/index.test.ts b/x-pack/plugins/apm/server/routes/transactions/breakdown/index.test.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/transactions/breakdown/index.test.ts rename to x-pack/plugins/apm/server/routes/transactions/breakdown/index.test.ts index 41d4c60fd72b4..1d2602dcafc75 100644 --- a/x-pack/plugins/apm/server/lib/transactions/breakdown/index.test.ts +++ b/x-pack/plugins/apm/server/routes/transactions/breakdown/index.test.ts @@ -11,7 +11,7 @@ import noDataResponse from './mock_responses/no_data.json'; import dataResponse from './mock_responses/data.json'; import { APMConfig } from '../../..'; import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values'; -import { ApmIndicesConfig } from '../../settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../../../routes/settings/apm_indices/get_apm_indices'; const mockIndices: ApmIndicesConfig = { sourcemap: 'myIndex', diff --git a/x-pack/plugins/apm/server/lib/transactions/breakdown/index.ts b/x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/transactions/breakdown/index.ts rename to x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts index a5c11776c70b0..2c3bca8443db0 100644 --- a/x-pack/plugins/apm/server/lib/transactions/breakdown/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/breakdown/index.ts @@ -17,10 +17,10 @@ import { TRANSACTION_NAME, TRANSACTION_BREAKDOWN_COUNT, } from '../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { rangeQuery, kqlQuery } from '../../../../../observability/server'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { getMetricsDateHistogramParams } from '../../helpers/metrics'; +import { getMetricsDateHistogramParams } from '../../../lib/helpers/metrics'; import { MAX_KPIS } from './constants'; import { getVizColorForIndex } from '../../../../common/viz_colors'; diff --git a/x-pack/plugins/apm/server/lib/transactions/breakdown/mock_responses/data.json b/x-pack/plugins/apm/server/routes/transactions/breakdown/mock_responses/data.json similarity index 100% rename from x-pack/plugins/apm/server/lib/transactions/breakdown/mock_responses/data.json rename to x-pack/plugins/apm/server/routes/transactions/breakdown/mock_responses/data.json diff --git a/x-pack/plugins/apm/server/lib/transactions/breakdown/mock_responses/no_data.json b/x-pack/plugins/apm/server/routes/transactions/breakdown/mock_responses/no_data.json similarity index 100% rename from x-pack/plugins/apm/server/lib/transactions/breakdown/mock_responses/no_data.json rename to x-pack/plugins/apm/server/routes/transactions/breakdown/mock_responses/no_data.json diff --git a/x-pack/plugins/apm/server/lib/transactions/constants.ts b/x-pack/plugins/apm/server/routes/transactions/constants.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/transactions/constants.ts rename to x-pack/plugins/apm/server/routes/transactions/constants.ts diff --git a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts b/x-pack/plugins/apm/server/routes/transactions/get_anomaly_data/fetcher.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts rename to x-pack/plugins/apm/server/routes/transactions/get_anomaly_data/fetcher.ts index dd723f24abe1b..704bc751e5772 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts +++ b/x-pack/plugins/apm/server/routes/transactions/get_anomaly_data/fetcher.ts @@ -11,7 +11,7 @@ import { PromiseReturnType } from '../../../../../observability/typings/common'; import { rangeQuery } from '../../../../../observability/server'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; import { withApmSpan } from '../../../utils/with_apm_span'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { apmMlAnomalyQuery } from '../../../../common/anomaly_detection/apm_ml_anomaly_query'; import { ApmMlDetectorIndex } from '../../../../common/anomaly_detection/apm_ml_detectors'; diff --git a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts b/x-pack/plugins/apm/server/routes/transactions/get_anomaly_data/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts rename to x-pack/plugins/apm/server/routes/transactions/get_anomaly_data/index.ts index c1123182586b7..0cdbe1774504a 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/get_anomaly_data/index.ts @@ -10,8 +10,8 @@ import { Logger } from 'src/core/server'; import { isFiniteNumber } from '../../../../common/utils/is_finite_number'; import { maybe } from '../../../../common/utils/maybe'; import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values'; -import { getBucketSize } from '../../helpers/get_bucket_size'; -import { Setup } from '../../helpers/setup_request'; +import { getBucketSize } from '../../../lib/helpers/get_bucket_size'; +import { Setup } from '../../../lib/helpers/setup_request'; import { anomalySeriesFetcher } from './fetcher'; import { getMLJobIds } from '../../service_map/get_service_anomalies'; import { ANOMALY_THRESHOLD } from '../../../../common/ml_constants'; diff --git a/x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts b/x-pack/plugins/apm/server/routes/transactions/get_latency_charts/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts rename to x-pack/plugins/apm/server/routes/transactions/get_latency_charts/index.ts index 4612d399b54a1..5375da3606f18 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_latency_charts/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/get_latency_charts/index.ts @@ -25,11 +25,11 @@ import { getProcessorEventForTransactions, } from '../../../lib/helpers/transactions'; import { Setup } from '../../../lib/helpers/setup_request'; -import { getBucketSizeForAggregatedTransactions } from '../../helpers/get_bucket_size_for_aggregated_transactions'; +import { getBucketSizeForAggregatedTransactions } from '../../../lib/helpers/get_bucket_size_for_aggregated_transactions'; import { getLatencyAggregation, getLatencyValue, -} from '../../helpers/latency_aggregation_type'; +} from '../../../lib/helpers/latency_aggregation_type'; export type LatencyChartsSearchResponse = PromiseReturnType< typeof searchLatency >; diff --git a/x-pack/plugins/apm/server/lib/transactions/get_transaction/index.ts b/x-pack/plugins/apm/server/routes/transactions/get_transaction/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/transactions/get_transaction/index.ts rename to x-pack/plugins/apm/server/routes/transactions/get_transaction/index.ts index 6d0bbcdb55ca4..0522fb3a1899d 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_transaction/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/get_transaction/index.ts @@ -10,7 +10,7 @@ import { TRANSACTION_ID, } from '../../../../common/elasticsearch_fieldnames'; import { rangeQuery, termQuery } from '../../../../../observability/server'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { ProcessorEvent } from '../../../../common/processor_event'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; diff --git a/x-pack/plugins/apm/server/lib/transactions/get_transaction_by_trace/index.ts b/x-pack/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/transactions/get_transaction_by_trace/index.ts rename to x-pack/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts index 568ce16e7aedc..d9c6a64bdbcc6 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_transaction_by_trace/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/get_transaction_by_trace/index.ts @@ -9,7 +9,7 @@ import { TRACE_ID, PARENT_ID, } from '../../../../common/elasticsearch_fieldnames'; -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { ProcessorEvent } from '../../../../common/processor_event'; export async function getRootTransactionByTraceId( diff --git a/x-pack/plugins/apm/server/lib/transactions/queries.test.ts b/x-pack/plugins/apm/server/routes/transactions/queries.test.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/transactions/queries.test.ts rename to x-pack/plugins/apm/server/routes/transactions/queries.test.ts diff --git a/x-pack/plugins/apm/server/routes/transactions.ts b/x-pack/plugins/apm/server/routes/transactions/route.ts similarity index 90% rename from x-pack/plugins/apm/server/routes/transactions.ts rename to x-pack/plugins/apm/server/routes/transactions/route.ts index c0d83bac6e8e4..5b3f4e4f3bd4c 100644 --- a/x-pack/plugins/apm/server/routes/transactions.ts +++ b/x-pack/plugins/apm/server/routes/transactions/route.ts @@ -11,24 +11,24 @@ import * as t from 'io-ts'; import { LatencyAggregationType, latencyAggregationTypeRt, -} from '../../common/latency_aggregation_types'; -import { getSearchAggregatedTransactions } from '../lib/helpers/transactions'; -import { setupRequest } from '../lib/helpers/setup_request'; -import { getServiceTransactionGroups } from '../lib/services/get_service_transaction_groups'; -import { getServiceTransactionGroupDetailedStatisticsPeriods } from '../lib/services/get_service_transaction_group_detailed_statistics'; -import { getTransactionBreakdown } from '../lib/transactions/breakdown'; -import { getTransactionTraceSamples } from '../lib/transactions/trace_samples'; -import { getAnomalySeries } from '../lib/transactions/get_anomaly_data'; -import { getLatencyPeriods } from '../lib/transactions/get_latency_charts'; -import { getErrorRatePeriods } from '../lib/transaction_groups/get_error_rate'; -import { createApmServerRoute } from './apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from './apm_routes/create_apm_server_route_repository'; +} from '../../../common/latency_aggregation_types'; +import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getServiceTransactionGroups } from '../services/get_service_transaction_groups'; +import { getServiceTransactionGroupDetailedStatisticsPeriods } from '../services/get_service_transaction_group_detailed_statistics'; +import { getTransactionBreakdown } from './breakdown'; +import { getTransactionTraceSamples } from './trace_samples'; +import { getAnomalySeries } from './get_anomaly_data'; +import { getLatencyPeriods } from './get_latency_charts'; +import { getErrorRatePeriods } from '../../lib/transaction_groups/get_error_rate'; +import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; +import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { comparisonRangeRt, environmentRt, kueryRt, rangeRt, -} from './default_api_types'; +} from '../default_api_types'; const transactionGroupsMainStatisticsRoute = createApmServerRoute({ endpoint: diff --git a/x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts b/x-pack/plugins/apm/server/routes/transactions/trace_samples/get_trace_samples/index.ts similarity index 97% rename from x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts rename to x-pack/plugins/apm/server/routes/transactions/trace_samples/get_trace_samples/index.ts index 9b96cf19c516d..d4ceafd9f6306 100644 --- a/x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/trace_samples/get_trace_samples/index.ts @@ -17,7 +17,7 @@ import { import { ProcessorEvent } from '../../../../../common/processor_event'; import { rangeQuery, kqlQuery } from '../../../../../../observability/server'; import { environmentQuery } from '../../../../../common/utils/environment_query'; -import { Setup } from '../../../helpers/setup_request'; +import { Setup } from '../../../../lib/helpers/setup_request'; const TRACE_SAMPLES_SIZE = 500; diff --git a/x-pack/plugins/apm/server/lib/transactions/trace_samples/index.ts b/x-pack/plugins/apm/server/routes/transactions/trace_samples/index.ts similarity index 95% rename from x-pack/plugins/apm/server/lib/transactions/trace_samples/index.ts rename to x-pack/plugins/apm/server/routes/transactions/trace_samples/index.ts index e422be417438b..89bae10db5e87 100644 --- a/x-pack/plugins/apm/server/lib/transactions/trace_samples/index.ts +++ b/x-pack/plugins/apm/server/routes/transactions/trace_samples/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Setup } from '../../helpers/setup_request'; +import { Setup } from '../../../lib/helpers/setup_request'; import { getTraceSamples } from './get_trace_samples'; import { withApmSpan } from '../../../utils/with_apm_span'; diff --git a/x-pack/plugins/apm/server/tutorial/index.ts b/x-pack/plugins/apm/server/tutorial/index.ts index f04b794091ff2..5d3ff8636df4d 100644 --- a/x-pack/plugins/apm/server/tutorial/index.ts +++ b/x-pack/plugins/apm/server/tutorial/index.ts @@ -14,8 +14,8 @@ import { } from '../../../../../src/plugins/home/server'; import { CloudSetup } from '../../../cloud/server'; import { APM_STATIC_INDEX_PATTERN_ID } from '../../common/index_pattern_constants'; -import { getApmDataViewTitle } from '../lib/data_view/get_apm_data_view_title'; -import { ApmIndicesConfig } from '../lib/settings/apm_indices/get_apm_indices'; +import { getApmDataViewTitle } from '../routes/data_view/get_apm_data_view_title'; +import { ApmIndicesConfig } from '../routes/settings/apm_indices/get_apm_indices'; import { createElasticCloudInstructions } from './envs/elastic_cloud'; import { onPremInstructions } from './envs/on_prem'; import apmDataView from './index_pattern.json'; diff --git a/x-pack/plugins/apm/server/types.ts b/x-pack/plugins/apm/server/types.ts index c686c42beb6ef..02aae547407e5 100644 --- a/x-pack/plugins/apm/server/types.ts +++ b/x-pack/plugins/apm/server/types.ts @@ -47,7 +47,7 @@ import { FleetStartContract as FleetPluginStart, } from '../../fleet/server'; import { APMConfig } from '.'; -import { getApmIndices } from './lib/settings/apm_indices/get_apm_indices'; +import { getApmIndices } from './routes/settings/apm_indices/get_apm_indices'; import { createApmEventClient } from './lib/helpers/create_es_client/create_apm_event_client'; import { ApmPluginRequestHandlerContext } from './routes/typings'; diff --git a/x-pack/plugins/apm/server/utils/test_helpers.tsx b/x-pack/plugins/apm/server/utils/test_helpers.tsx index 0e1b9f2ba8051..19644b5bc87f8 100644 --- a/x-pack/plugins/apm/server/utils/test_helpers.tsx +++ b/x-pack/plugins/apm/server/utils/test_helpers.tsx @@ -12,7 +12,7 @@ import { ESSearchResponse, } from '../../../../../src/core/types/elasticsearch'; import { UxUIFilters } from '../../typings/ui_filters'; -import { ApmIndicesConfig } from '../lib/settings/apm_indices/get_apm_indices'; +import { ApmIndicesConfig } from '../routes/settings/apm_indices/get_apm_indices'; interface Options { mockResponse?: ( diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_simple_form.tsx b/x-pack/plugins/canvas/public/components/arg_form/arg_simple_form.tsx index 84b87373c1c5a..df73c149a9111 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_simple_form.tsx +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_simple_form.tsx @@ -52,7 +52,7 @@ export const ArgSimpleForm: React.FunctionComponent = ({ {!required && ( = (props) => { diff --git a/x-pack/plugins/canvas/public/components/datasource/__stories__/__snapshots__/datasource_component.stories.storyshot b/x-pack/plugins/canvas/public/components/datasource/__stories__/__snapshots__/datasource_component.stories.storyshot index 6e665f48b3e9a..7a34ee2b5aaad 100644 --- a/x-pack/plugins/canvas/public/components/datasource/__stories__/__snapshots__/datasource_component.stories.storyshot +++ b/x-pack/plugins/canvas/public/components/datasource/__stories__/__snapshots__/datasource_component.stories.storyshot @@ -118,7 +118,7 @@ exports[`Storyshots components/datasource/DatasourceComponent simple datasource className="euiFlexItem euiFlexItem--flexGrowZero" >
); diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx index aa6ed7ae910f8..cbfe133b2909d 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_table/data_stream_table.tsx @@ -183,7 +183,7 @@ export const DataStreamTable: React.FunctionComponent = ({ ) : undefined, toolsRight: [ { loadIndices(); }} diff --git a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_list.tsx b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_list.tsx index 57f18134be5d6..2df312771ca12 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/template_list/template_list.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/template_list/template_list.tsx @@ -162,7 +162,7 @@ export const TemplateList: React.FunctionComponent = (props) => { } )} iconSize="s" - color={'subdued'} + color="text" iconType={'crossInACircleFilled'} onClick={toggleWarningThreshold} /> diff --git a/x-pack/plugins/infra/public/alerting/inventory/components/metric.tsx b/x-pack/plugins/infra/public/alerting/inventory/components/metric.tsx index 7f8bcd6ae419b..3d9116905fb25 100644 --- a/x-pack/plugins/infra/public/alerting/inventory/components/metric.tsx +++ b/x-pack/plugins/infra/public/alerting/inventory/components/metric.tsx @@ -186,7 +186,7 @@ export const MetricExpression = ({ onClick={() => { setPopoverOpen(true); }} - color={errors.metric?.length ? 'danger' : 'secondary'} + color={errors.metric?.length ? 'danger' : 'success'} /> } isOpen={popoverOpen} diff --git a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/criterion.tsx b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/criterion.tsx index 47ba580c272bd..3dd092fa48b99 100644 --- a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/criterion.tsx +++ b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/criterion.tsx @@ -176,7 +176,7 @@ export const Criterion: React.FC = ({ uppercase={true} value={criterion.field ?? 'a chosen field'} isActive={isFieldPopoverOpen} - color={errors.field.length === 0 ? 'secondary' : 'danger'} + color={errors.field.length === 0 ? 'success' : 'danger'} onClick={(e) => { e.stopPropagation(); setIsFieldPopoverOpen(!isFieldPopoverOpen); @@ -227,7 +227,7 @@ export const Criterion: React.FC = ({ isActive={isComparatorPopoverOpen} color={ errors.comparator.length === 0 && errors.value.length === 0 - ? 'secondary' + ? 'success' : 'danger' } onClick={(e) => { diff --git a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx index 2664a0d6aa2b0..02b827d5915dd 100644 --- a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx +++ b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx @@ -339,7 +339,7 @@ export default ExpressionEditor; // components. export const ExpressionLike = ({ text }: { text: string }) => { return ( -
+
{text}
); diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx index 4dd191313261b..b4472b90efdb2 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx @@ -276,7 +276,7 @@ export const ExpressionRow: React.FC = (props) => { } )} iconSize="s" - color={'subdued'} + color="text" iconType={'crossInACircleFilled'} onClick={toggleWarningThreshold} /> diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx index 5931e1cbe49ee..4424410f552c6 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx @@ -65,7 +65,7 @@ export const LogAnalysisModuleListCard: React.FC<{ moduleStatus.type === 'required' ? ( ) : ( - + ); const moduleSetupButton = diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/single_metric_comparison.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/single_metric_comparison.tsx index 8eed47c1a833e..fe9297b9409c7 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/single_metric_comparison.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/single_metric_comparison.tsx @@ -29,14 +29,14 @@ export const SingleMetricComparison: React.FunctionComponent<{ return ( - {formatPercentage(changeFactor)} + {formatPercentage(changeFactor)} ); } else if (changeFactor > 0 && !Number.isFinite(changeFactor)) { return ( - {newCategoryTrendLabel} + {newCategoryTrendLabel} ); } diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx index 427f67ec7a211..8c51fbf9d805b 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx @@ -202,7 +202,7 @@ const ProcessesTableBody = ({ items, currentTime }: TableBodyProps) => ( const cells = columns.map((column) => ( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx index c354ddcd55d71..47049c7d9c893 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx @@ -12,7 +12,7 @@ import { STATE_NAMES } from './states'; export const StateBadge = ({ state }: { state: string }) => { switch (state) { case 'running': - return {STATE_NAMES.running}; + return {STATE_NAMES.running}; case 'sleeping': return {STATE_NAMES.sleeping}; case 'dead': diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/properties/table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/properties/table.tsx index 053e50ff87049..996e90c03f3db 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/properties/table.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/properties/table.tsx @@ -65,7 +65,7 @@ export const Table = (props: Props) => { )} > = memo( const disabled = isEditorNotInIdleMode && !isMovingThisProcessor; const moveButton = ( = ({ onAddDocuments }) => - + - + {i18nTexts.addDocumentSuccessMessage} diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx index 02fd7ec65957d..eeda40c96418c 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx @@ -138,7 +138,7 @@ export const PipelineForm: React.FunctionComponent = ({ = ({ diff --git a/x-pack/plugins/lens/public/shared_components/coloring/palette_panel_container.tsx b/x-pack/plugins/lens/public/shared_components/coloring/palette_panel_container.tsx index b546ffe5fb6fb..abcd714b3af97 100644 --- a/x-pack/plugins/lens/public/shared_components/coloring/palette_panel_container.tsx +++ b/x-pack/plugins/lens/public/shared_components/coloring/palette_panel_container.tsx @@ -56,6 +56,7 @@ export function PalettePanelContainer({
diff --git a/x-pack/plugins/logstash/kibana.json b/x-pack/plugins/logstash/kibana.json index 2ff4aac9ba55b..48391c9bc68c4 100644 --- a/x-pack/plugins/logstash/kibana.json +++ b/x-pack/plugins/logstash/kibana.json @@ -11,5 +11,5 @@ "optionalPlugins": ["home", "monitoring", "security"], "server": true, "ui": true, - "requiredBundles": ["home"] + "requiredBundles": ["esUiShared", "home"] } diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js b/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js index 334c7d0322a84..9d5f3b2d4af06 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js @@ -15,10 +15,10 @@ import 'brace/theme/github'; import { isEmpty } from 'lodash'; import { TOOLTIPS } from '../../../../common/constants/tooltips'; +import { EuiCodeEditor } from '../../../../../../../src/plugins/es_ui_shared/public'; import { EuiButton, EuiButtonEmpty, - EuiCodeEditor, EuiFlexGroup, EuiFieldNumber, EuiFlexItem, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.tsx.snap b/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.tsx.snap index 58af4d009e43a..dba9fa59dd424 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.tsx.snap +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.tsx.snap @@ -91,7 +91,7 @@ exports[`renderLegendDetailRow categorical Should render categorical legend with isPointsOnly={true} label={ Other diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_icon_property.test.tsx.snap b/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_icon_property.test.tsx.snap index 11a4fafda29e1..a3f23536326aa 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_icon_property.test.tsx.snap +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_icon_property.test.tsx.snap @@ -71,7 +71,7 @@ exports[`renderLegendDetailRow Should render categorical legend with breaks 1`] isPointsOnly={true} label={ Other diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.tsx b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.tsx index cfb5d54720ce7..03800fa03827e 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.tsx +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.tsx @@ -425,7 +425,7 @@ export class DynamicColorProperty extends DynamicStyleProperty{getOtherCategoryLabel()}, + label: {getOtherCategoryLabel()}, symbolId, }); } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.tsx b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.tsx index 15672bda941be..b5d5e90efa45f 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.tsx +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.tsx @@ -129,7 +129,7 @@ export class DynamicIconProperty extends DynamicStyleProperty{getOtherCategoryLabel()}, + label: {getOtherCategoryLabel()}, symbolId: fallbackSymbolId, }); } diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx index dc3ad26b48e84..1a4c8e36b3457 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx @@ -217,7 +217,7 @@ export class TooltipSelector extends Component { { { { try { const path = `/${encodeURIComponent(index)}/_mvt/${geometryFieldName}/${z}/${x}/${y}`; @@ -47,11 +49,16 @@ export async function getEsGridTile({ fields: requestBody.fields, runtime_mappings: requestBody.runtime_mappings, }; - const tile = await context.core.elasticsearch.client.asCurrentUser.transport.request({ - method: 'GET', - path, - body, - }); + const tile = await context.core.elasticsearch.client.asCurrentUser.transport.request( + { + method: 'GET', + path, + body, + }, + { + signal: abortController.signal, + } + ); return tile.body as unknown as Buffer; } catch (e) { if (!isAbortError(e)) { diff --git a/x-pack/plugins/maps/server/mvt/get_tile.ts b/x-pack/plugins/maps/server/mvt/get_tile.ts index 0864b373af3f8..478b4343038e3 100644 --- a/x-pack/plugins/maps/server/mvt/get_tile.ts +++ b/x-pack/plugins/maps/server/mvt/get_tile.ts @@ -22,6 +22,7 @@ export async function getEsTile({ y, z, requestBody = {}, + abortController, }: { x: number; y: number; @@ -31,6 +32,7 @@ export async function getEsTile({ context: DataRequestHandlerContext; logger: Logger; requestBody: any; + abortController: AbortController; }): Promise { try { const path = `/${encodeURIComponent(index)}/_mvt/${geometryFieldName}/${z}/${x}/${y}`; @@ -45,11 +47,16 @@ export async function getEsTile({ runtime_mappings: requestBody.runtime_mappings, track_total_hits: requestBody.size + 1, }; - const tile = await context.core.elasticsearch.client.asCurrentUser.transport.request({ - method: 'GET', - path, - body, - }); + const tile = await context.core.elasticsearch.client.asCurrentUser.transport.request( + { + method: 'GET', + path, + body, + }, + { + signal: abortController.signal, + } + ); return tile.body as unknown as Buffer; } catch (e) { if (!isAbortError(e)) { diff --git a/x-pack/plugins/maps/server/mvt/mvt_routes.ts b/x-pack/plugins/maps/server/mvt/mvt_routes.ts index 3c61a47a383d6..317f62e50825e 100644 --- a/x-pack/plugins/maps/server/mvt/mvt_routes.ts +++ b/x-pack/plugins/maps/server/mvt/mvt_routes.ts @@ -10,8 +10,6 @@ import { schema } from '@kbn/config-schema'; import { KibanaRequest, KibanaResponseFactory, Logger } from 'src/core/server'; import { IRouter } from 'src/core/server'; import type { DataRequestHandlerContext } from 'src/plugins/data/server'; -// @ts-ignore not typed -import { AbortController } from 'abortcontroller-polyfill/dist/cjs-ponyfill'; import { MVT_GETTILE_API_PATH, API_ROOT_PATH, @@ -54,11 +52,10 @@ export function initMVTRoutes({ ) => { const { query, params } = request; - // todo - replace with direct abortion of raw transport request - // const abortController = new AbortController(); - // request.events.aborted$.subscribe(() => { - // abortController.abort(); - // }); + const abortController = new AbortController(); + request.events.aborted$.subscribe(() => { + abortController.abort(); + }); const requestBodyDSL = rison.decode(query.requestBody as string); @@ -71,6 +68,7 @@ export function initMVTRoutes({ z: parseInt((params as any).z, 10) as number, index: query.index as string, requestBody: requestBodyDSL as any, + abortController, }); return sendResponse(response, tile); @@ -102,11 +100,10 @@ export function initMVTRoutes({ ) => { const { query, params } = request; - // todo - replace with direct abortion of raw transport request - // const abortController = new AbortController(); - // request.events.aborted$.subscribe(() => { - // abortController.abort(); - // }); + const abortController = new AbortController(); + request.events.aborted$.subscribe(() => { + abortController.abort(); + }); const requestBodyDSL = rison.decode(query.requestBody as string); @@ -120,6 +117,7 @@ export function initMVTRoutes({ index: query.index as string, requestBody: requestBodyDSL as any, requestType: query.requestType as RENDER_AS.POINT | RENDER_AS.GRID, + abortController, }); return sendResponse(response, tile); diff --git a/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx b/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx index b51c8ad987a35..64b2f63883254 100644 --- a/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx @@ -330,7 +330,7 @@ export const ImportJobsFlyout: FC = ({ isDisabled }) => { aria-label={i18n.translate('xpack.ml.importExport.importFlyout.deleteButtonAria', { defaultMessage: 'Delete', })} - color={deleteDisabled ? 'subdued' : 'danger'} + color={deleteDisabled ? 'text' : 'danger'} disabled={deleteDisabled} onClick={() => deleteJob(index)} /> diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx index 4cd76b4e410c7..b7dc4d617427d 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/components/cytoscape_options.tsx @@ -65,7 +65,7 @@ function borderColorForNode(el: cytoscape.NodeSingular, theme: EuiThemeType) { switch (type) { case JOB_MAP_NODE_TYPES.ANALYTICS: - return theme.euiColorSecondary; + return theme.euiColorSuccess; case JOB_MAP_NODE_TYPES.TRANSFORM: return theme.euiColorVis1; case JOB_MAP_NODE_TYPES.INDEX: diff --git a/x-pack/plugins/ml/public/application/explorer/anomaly_context_menu.tsx b/x-pack/plugins/ml/public/application/explorer/anomaly_context_menu.tsx index d40e9cae1a04f..c32745f8bce8c 100644 --- a/x-pack/plugins/ml/public/application/explorer/anomaly_context_menu.tsx +++ b/x-pack/plugins/ml/public/application/explorer/anomaly_context_menu.tsx @@ -75,7 +75,7 @@ export const AnomalyContextMenu: FC = ({ aria-label={i18n.translate('xpack.ml.explorer.anomalies.actionsAriaLabel', { defaultMessage: 'Actions', })} - color="subdued" + color="text" iconType="boxesHorizontal" onClick={setIsMenuOpen.bind(null, !isMenuOpen)} data-test-subj="mlExplorerAnomalyPanelMenu" diff --git a/x-pack/plugins/ml/public/application/explorer/anomaly_timeline.tsx b/x-pack/plugins/ml/public/application/explorer/anomaly_timeline.tsx index 6091ab22692af..c8006292f8e09 100644 --- a/x-pack/plugins/ml/public/application/explorer/anomaly_timeline.tsx +++ b/x-pack/plugins/ml/public/application/explorer/anomaly_timeline.tsx @@ -184,7 +184,7 @@ export const AnomalyTimeline: FC = React.memo( aria-label={i18n.translate('xpack.ml.explorer.swimlaneActions', { defaultMessage: 'Actions', })} - color="subdued" + color="text" iconType="boxesHorizontal" onClick={setIsMenuOpen.bind(null, !isMenuOpen)} data-test-subj="mlAnomalyTimelinePanelMenu" diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/ml_job_editor/ml_job_editor.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/ml_job_editor/ml_job_editor.tsx index 96708e83dd8be..9ee583ba2d3e7 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/ml_job_editor/ml_job_editor.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/ml_job_editor/ml_job_editor.tsx @@ -7,8 +7,12 @@ import React, { FC } from 'react'; -import { EuiCodeEditor, EuiCodeEditorProps } from '@elastic/eui'; -import { expandLiteralStrings, XJsonMode } from '../../../../../../shared_imports'; +import { + expandLiteralStrings, + XJsonMode, + EuiCodeEditor, + EuiCodeEditorProps, +} from '../../../../../../shared_imports'; export const ML_EDITOR_MODE = { TEXT: 'text', JSON: 'json', XJSON: new XJsonMode() }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx index 39d3eb634e9ce..53ffa593830e0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx @@ -53,7 +53,7 @@ export const JobItem: FC = memo( - + {jobPrefix} {id} @@ -118,7 +118,7 @@ export const JobItem: FC = memo( = memo( = memo( - + {title} {success === false && error !== undefined && ( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/_timeseriesexplorer.scss b/x-pack/plugins/ml/public/application/timeseriesexplorer/_timeseriesexplorer.scss index cfd521c882fb7..63cb8a57adba6 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/_timeseriesexplorer.scss +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/_timeseriesexplorer.scss @@ -10,7 +10,7 @@ } .entity-count-text { - color: $euiColorSecondary; + color: $euiColorSuccess; font-size: $euiFontSizeS; } } diff --git a/x-pack/plugins/ml/shared_imports.ts b/x-pack/plugins/ml/shared_imports.ts index 255a1e3c20d60..e70410c99a8f4 100644 --- a/x-pack/plugins/ml/shared_imports.ts +++ b/x-pack/plugins/ml/shared_imports.ts @@ -5,6 +5,9 @@ * 2.0. */ +export { EuiCodeEditor } from '../../../src/plugins/es_ui_shared/public'; +export type { EuiCodeEditorProps } from '../../../src/plugins/es_ui_shared/public'; + import { XJson } from '../../../src/plugins/es_ui_shared/public'; const { collapseLiteralStrings, expandLiteralStrings } = XJson; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/__snapshots__/shard.test.js.snap b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/__snapshots__/shard.test.js.snap index dcad0937066d5..5c0294ffdc8d8 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/__snapshots__/shard.test.js.snap +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/__snapshots__/shard.test.js.snap @@ -27,7 +27,7 @@ exports[`Shard should show for assigned replica shards 1`] = ` onMouseLeave={[Function]} > 0 diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js index a81e1f8db5ec8..6676b71b4bf13 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js @@ -39,7 +39,7 @@ function getColor(classes) { } if (classList.includes('replica')) { - return 'secondary'; + return 'success'; } } diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js index 7ca24853a9ccb..1c9021aeedf74 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js @@ -24,7 +24,7 @@ export const ShardAllocation = (props) => { label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.replicaLabel', { defaultMessage: 'Replica', }), - color: 'secondary', + color: 'success', }, { label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.relocatingLabel', { diff --git a/x-pack/plugins/monitoring/public/components/setup_mode/__snapshots__/tooltip.test.js.snap b/x-pack/plugins/monitoring/public/components/setup_mode/__snapshots__/tooltip.test.js.snap index 2a3a27cbc7c12..2edd5c1ab0cf2 100644 --- a/x-pack/plugins/monitoring/public/components/setup_mode/__snapshots__/tooltip.test.js.snap +++ b/x-pack/plugins/monitoring/public/components/setup_mode/__snapshots__/tooltip.test.js.snap @@ -127,7 +127,7 @@ exports[`setupMode SetupModeTooltip allMonitoredByMetricbeat should render for a position="top" > () => `generated-id`); describe('Summary Status Component', () => { it('should render metrics in a summary bar', () => { diff --git a/x-pack/plugins/observability/kibana.json b/x-pack/plugins/observability/kibana.json index 822e0cf9efe7c..343e16f4a4095 100644 --- a/x-pack/plugins/observability/kibana.json +++ b/x-pack/plugins/observability/kibana.json @@ -11,6 +11,7 @@ "observability" ], "optionalPlugins": [ + "discover", "embeddable", "home", "lens", diff --git a/x-pack/plugins/observability/public/components/app/cases/callout/callout.test.tsx b/x-pack/plugins/observability/public/components/app/cases/callout/callout.test.tsx index 25d32d0cae884..6f48d429071ca 100644 --- a/x-pack/plugins/observability/public/components/app/cases/callout/callout.test.tsx +++ b/x-pack/plugins/observability/public/components/app/cases/callout/callout.test.tsx @@ -60,7 +60,7 @@ describe('Callout', () => { const className = wrapper.find(`button[data-test-subj="calloutDismiss-md5-hex"]`).first().prop('className') ?? ''; - expect(className.includes('euiButton--secondary')).toBeTruthy(); + expect(className.includes('euiButton--success')).toBeTruthy(); }); it('transform the button color correctly - warning', () => { diff --git a/x-pack/plugins/observability/public/components/app/cases/callout/callout.tsx b/x-pack/plugins/observability/public/components/app/cases/callout/callout.tsx index 15bd250c6ceb6..25c9643a22af9 100644 --- a/x-pack/plugins/observability/public/components/app/cases/callout/callout.tsx +++ b/x-pack/plugins/observability/public/components/app/cases/callout/callout.tsx @@ -39,7 +39,7 @@ function CallOutComponent({ {i18n.DISMISS_CALLOUT} diff --git a/x-pack/plugins/observability/public/components/shared/exploratory_view/configurations/utils.ts b/x-pack/plugins/observability/public/components/shared/exploratory_view/configurations/utils.ts index 56e6cb5210356..7eab266ea35d1 100644 --- a/x-pack/plugins/observability/public/components/shared/exploratory_view/configurations/utils.ts +++ b/x-pack/plugins/observability/public/components/shared/exploratory_view/configurations/utils.ts @@ -5,10 +5,15 @@ * 2.0. */ import rison, { RisonValue } from 'rison-node'; +import { buildQueryFilter } from '@kbn/es-query'; import type { ReportViewType, SeriesUrl, UrlFilter } from '../types'; import type { AllSeries, AllShortSeries } from '../hooks/use_series_storage'; import { IndexPattern } from '../../../../../../../../src/plugins/data/common'; -import { esFilters, ExistsFilter } from '../../../../../../../../src/plugins/data/public'; +import { + esFilters, + ExistsFilter, + PhraseFilter, +} from '../../../../../../../../src/plugins/data/public'; import { URL_KEYS } from './constants/url_constants'; import { PersistableFilter } from '../../../../../../lens/common'; @@ -64,9 +69,32 @@ export function buildPhraseFilter(field: string, value: string, indexPattern: In return []; } +export function getQueryFilter(field: string, value: string[], indexPattern: IndexPattern) { + const fieldMeta = indexPattern?.fields.find((fieldT) => fieldT.name === field); + if (fieldMeta && indexPattern.id) { + return value.map((val) => + buildQueryFilter( + { + query_string: { + fields: [field], + query: `*${val}*`, + }, + }, + indexPattern.id!, + '' + ) + ); + } + + return []; +} + export function buildPhrasesFilter(field: string, value: string[], indexPattern: IndexPattern) { const fieldMeta = indexPattern?.fields.find((fieldT) => fieldT.name === field); if (fieldMeta) { + if (value.length === 1) { + return [esFilters.buildPhraseFilter(fieldMeta, value[0], indexPattern)]; + } return [esFilters.buildPhrasesFilter(fieldMeta, value, indexPattern)]; } return []; @@ -80,7 +108,7 @@ export function buildExistsFilter(field: string, indexPattern: IndexPattern) { return []; } -type FiltersType = PersistableFilter[] | ExistsFilter[]; +type FiltersType = Array; export function urlFilterToPersistedFilter({ urlFilters, @@ -88,23 +116,36 @@ export function urlFilterToPersistedFilter({ indexPattern, }: { urlFilters: UrlFilter[]; - initFilters: FiltersType; + initFilters?: FiltersType; indexPattern: IndexPattern; }) { const parsedFilters: FiltersType = initFilters ? [...initFilters] : []; - urlFilters.forEach(({ field, values = [], notValues = [] }) => { - if (values?.length > 0) { - const filter = buildPhrasesFilter(field, values, indexPattern); - parsedFilters.push(...filter); - } + urlFilters.forEach( + ({ field, values = [], notValues = [], wildcards = [], notWildcards = ([] = []) }) => { + if (values.length > 0) { + const filter = buildPhrasesFilter(field, values, indexPattern); + parsedFilters.push(...filter); + } + + if (notValues.length > 0) { + const filter = buildPhrasesFilter(field, notValues, indexPattern)[0]; + filter.meta.negate = true; + parsedFilters.push(filter); + } - if (notValues?.length > 0) { - const filter = buildPhrasesFilter(field, notValues, indexPattern)[0]; - filter.meta.negate = true; - parsedFilters.push(filter); + if (wildcards.length > 0) { + const filter = getQueryFilter(field, wildcards, indexPattern); + parsedFilters.push(...filter); + } + + if (notWildcards.length > 0) { + const filter = getQueryFilter(field, notWildcards, indexPattern)[0]; + filter.meta.negate = true; + parsedFilters.push(filter); + } } - }); + ); return parsedFilters; } diff --git a/x-pack/plugins/observability/public/components/shared/exploratory_view/hooks/use_discover_link.tsx b/x-pack/plugins/observability/public/components/shared/exploratory_view/hooks/use_discover_link.tsx index 4f19a8131f669..03396ffef9d8d 100644 --- a/x-pack/plugins/observability/public/components/shared/exploratory_view/hooks/use_discover_link.tsx +++ b/x-pack/plugins/observability/public/components/shared/exploratory_view/hooks/use_discover_link.tsx @@ -9,7 +9,7 @@ import { useCallback, useEffect, useState } from 'react'; import { useKibana } from '../../../../utils/kibana_react'; import { SeriesConfig, SeriesUrl } from '../types'; import { useAppIndexPatternContext } from './use_app_index_pattern'; -import { buildExistsFilter, buildPhraseFilter, buildPhrasesFilter } from '../configurations/utils'; +import { buildExistsFilter, urlFilterToPersistedFilter } from '../configurations/utils'; import { getFiltersFromDefs } from './use_lens_attributes'; import { RECORDS_FIELD, RECORDS_PERCENTAGE_FIELD } from '../configurations/constants'; @@ -32,42 +32,42 @@ export const useDiscoverLink = ({ series, seriesConfig }: UseDiscoverLink) => { useEffect(() => { const indexPattern = indexPatterns?.[series.dataType]; - const definitions = series.reportDefinitions ?? {}; - const filters = [...(seriesConfig?.baseFilters ?? [])]; + if (indexPattern) { + const definitions = series.reportDefinitions ?? {}; - const definitionFilters = getFiltersFromDefs(definitions); + const urlFilters = (series.filters ?? []).concat(getFiltersFromDefs(definitions)); - definitionFilters.forEach(({ field, values = [] }) => { - if (values.length > 1) { - filters.push(buildPhrasesFilter(field, values, indexPattern)[0]); - } else { - filters.push(buildPhraseFilter(field, values[0], indexPattern)[0]); - } - }); + const filters = urlFilterToPersistedFilter({ + indexPattern, + urlFilters, + initFilters: seriesConfig?.baseFilters, + }); - const selectedMetricField = series.selectedMetricField; + const selectedMetricField = series.selectedMetricField; - if ( - selectedMetricField && - selectedMetricField !== RECORDS_FIELD && - selectedMetricField !== RECORDS_PERCENTAGE_FIELD - ) { - filters.push(buildExistsFilter(selectedMetricField, indexPattern)[0]); - } + if ( + selectedMetricField && + selectedMetricField !== RECORDS_FIELD && + selectedMetricField !== RECORDS_PERCENTAGE_FIELD + ) { + filters.push(buildExistsFilter(selectedMetricField, indexPattern)[0]); + } - const getDiscoverUrl = async () => { - if (!urlGenerator?.createUrl) return; + const getDiscoverUrl = async () => { + if (!urlGenerator?.createUrl) return; - const newUrl = await urlGenerator.createUrl({ - filters, - indexPatternId: indexPattern?.id, - }); - setDiscoverUrl(newUrl); - }; - getDiscoverUrl(); + const newUrl = await urlGenerator.createUrl({ + filters, + indexPatternId: indexPattern?.id, + }); + setDiscoverUrl(newUrl); + }; + getDiscoverUrl(); + } }, [ indexPatterns, series.dataType, + series.filters, series.reportDefinitions, series.selectedMetricField, seriesConfig?.baseFilters, diff --git a/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx b/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx index f3e0eb767d336..2808dfae83527 100644 --- a/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx +++ b/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx @@ -66,7 +66,9 @@ export function ReportDefinitionField({ const values = selectedReportDefinitions?.[fieldT]; if (!values.includes(ALL_VALUES_SELECTED)) { const valueFilter = buildPhrasesFilter(fieldT, values, indexPattern)[0]; - filtersN.push(valueFilter.query); + if (valueFilter.query) { + filtersN.push(valueFilter.query); + } } } }); diff --git a/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/series_actions.tsx b/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/series_actions.tsx index c1462ce74b426..640e928b8ab98 100644 --- a/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/series_actions.tsx +++ b/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/columns/series_actions.tsx @@ -12,6 +12,7 @@ import { RemoveSeries } from './remove_series'; import { useSeriesStorage } from '../../hooks/use_series_storage'; import { SeriesConfig, SeriesUrl } from '../../types'; import { useDiscoverLink } from '../../hooks/use_discover_link'; +import { useAppIndexPatternContext } from '../../hooks/use_app_index_pattern'; interface Props { seriesId: number; @@ -25,6 +26,10 @@ export function SeriesActions({ seriesId, series, seriesConfig, onEditClick }: P const { href: discoverHref } = useDiscoverLink({ series, seriesConfig }); + const { indexPatterns } = useAppIndexPatternContext(); + + const indexPattern = indexPatterns?.[series.dataType]; + const copySeries = () => { let copySeriesId: string = `${series.name}-copy`; if (allSeries.find(({ name }) => name === copySeriesId)) { @@ -63,7 +68,7 @@ export function SeriesActions({ seriesId, series, seriesConfig, onEditClick }: P color="text" target="_blank" href={discoverHref} - isDisabled={!series.dataType || !series.selectedMetricField} + isDisabled={!series.dataType || !series.selectedMetricField || !indexPattern} /> diff --git a/x-pack/plugins/observability/public/components/shared/field_value_suggestions/field_value_selection.test.tsx b/x-pack/plugins/observability/public/components/shared/field_value_suggestions/field_value_selection.test.tsx index c142e50400e5f..3b9f6264c773a 100644 --- a/x-pack/plugins/observability/public/components/shared/field_value_suggestions/field_value_selection.test.tsx +++ b/x-pack/plugins/observability/public/components/shared/field_value_suggestions/field_value_selection.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { mount, render } from 'enzyme'; import { FieldValueSelection } from './field_value_selection'; import { EuiButton, EuiSelectableList } from '@elastic/eui'; +import { EuiThemeProvider } from '../../../../../../../src/plugins/kibana_react/common'; const values = [ { label: 'elastic co frontend', count: 1 }, @@ -32,16 +33,19 @@ describe('FieldValueSelection', () => { expect(btn.text()).toBe('Service name'); }); + it('renders a list on click', async () => { const wrapper = mount( - {}} - selectedValue={[]} - loading={false} - setQuery={() => {}} - /> + + {}} + selectedValue={[]} + loading={false} + setQuery={() => {}} + /> + ); const btn = wrapper.find(EuiButton); diff --git a/x-pack/plugins/osquery/public/action_results/services/agent_status.tsx b/x-pack/plugins/osquery/public/action_results/services/agent_status.tsx index 39a033f49ec90..1a2c9f370bc31 100644 --- a/x-pack/plugins/osquery/public/action_results/services/agent_status.tsx +++ b/x-pack/plugins/osquery/public/action_results/services/agent_status.tsx @@ -14,7 +14,7 @@ const visColors = euiPaletteColorBlindBehindText(); const colorToHexMap = { default: '#d3dae6', primary: visColors[1], - secondary: visColors[0], + success: visColors[0], accent: visColors[2], warning: visColors[5], danger: visColors[9], @@ -25,7 +25,7 @@ export const AGENT_STATUSES: ActionAgentStatus[] = ['success', 'pending', 'faile export function getColorForAgentStatus(agentStatus: ActionAgentStatus): string { switch (agentStatus) { case 'success': - return colorToHexMap.secondary; + return colorToHexMap.success; case 'pending': return colorToHexMap.default; case 'failed': diff --git a/x-pack/plugins/osquery/public/editor/index.tsx b/x-pack/plugins/osquery/public/editor/index.tsx index 7d6823acec2cd..df78d45d0cc93 100644 --- a/x-pack/plugins/osquery/public/editor/index.tsx +++ b/x-pack/plugins/osquery/public/editor/index.tsx @@ -6,10 +6,11 @@ */ import React, { useEffect, useState } from 'react'; -import { EuiCodeEditor } from '@elastic/eui'; import useDebounce from 'react-use/lib/useDebounce'; import 'brace/theme/tomorrow'; +import { EuiCodeEditor } from '../shared_imports'; + import './osquery_mode.ts'; const EDITOR_SET_OPTIONS = { diff --git a/x-pack/plugins/osquery/public/shared_imports.ts b/x-pack/plugins/osquery/public/shared_imports.ts index 227a276c41f18..c0f9d35ba51a8 100644 --- a/x-pack/plugins/osquery/public/shared_imports.ts +++ b/x-pack/plugins/osquery/public/shared_imports.ts @@ -40,3 +40,6 @@ export { } from '../../../../src/plugins/es_ui_shared/static/forms/components'; export { fieldValidators } from '../../../../src/plugins/es_ui_shared/static/forms/helpers'; export type { ERROR_CODE } from '../../../../src/plugins/es_ui_shared/static/forms/helpers/field_validators/types'; + +export { EuiCodeEditor } from '../../../../src/plugins/es_ui_shared/public'; +export type { EuiCodeEditorProps } from '../../../../src/plugins/es_ui_shared/public'; diff --git a/x-pack/plugins/painless_lab/public/application/components/output_pane/output_pane.tsx b/x-pack/plugins/painless_lab/public/application/components/output_pane/output_pane.tsx index 258c6bcdb1beb..8391ccbbe7ef4 100644 --- a/x-pack/plugins/painless_lab/public/application/components/output_pane/output_pane.tsx +++ b/x-pack/plugins/painless_lab/public/application/components/output_pane/output_pane.tsx @@ -34,7 +34,7 @@ export const OutputPane: FunctionComponent = ({ isLoading, response }) => ) : response && response.error ? ( ) : ( - + )} diff --git a/x-pack/plugins/painless_lab/public/plugin.tsx b/x-pack/plugins/painless_lab/public/plugin.tsx index 118adae22dc50..793947b9803c9 100644 --- a/x-pack/plugins/painless_lab/public/plugin.tsx +++ b/x-pack/plugins/painless_lab/public/plugin.tsx @@ -5,9 +5,7 @@ * 2.0. */ -import React from 'react'; import { first } from 'rxjs/operators'; -import { EuiBetaBadge, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { Plugin, CoreSetup } from 'src/core/public'; @@ -46,26 +44,10 @@ export class PainlessLabUIPlugin implements Plugin - - {i18n.translate('xpack.painlessLab.displayName', { - defaultMessage: 'Painless Lab', - })} - - - - - - - ) as any, + isBeta: true, + title: i18n.translate('xpack.painlessLab.displayName', { + defaultMessage: 'Painless Lab', + }), enableRouting: false, disabled: false, mount: async ({ element }) => { diff --git a/x-pack/plugins/painless_lab/public/styles/_index.scss b/x-pack/plugins/painless_lab/public/styles/_index.scss index 78182787a63b6..4844fe443e56f 100644 --- a/x-pack/plugins/painless_lab/public/styles/_index.scss +++ b/x-pack/plugins/painless_lab/public/styles/_index.scss @@ -34,10 +34,6 @@ $bottomBarHeight: $euiSize * 3; } } -.painlessLab__betaLabelContainer { - line-height: 0; -} - // adding dev tool top bar + bottom bar height to the body offset $bodyOffset: $euiHeaderHeightCompensation + $bottomBarHeight; diff --git a/x-pack/plugins/remote_clusters/public/application/sections/components/remote_cluster_form/remote_cluster_form.tsx b/x-pack/plugins/remote_clusters/public/application/sections/components/remote_cluster_form/remote_cluster_form.tsx index 766f12fedc81c..fdcbf220331d7 100644 --- a/x-pack/plugins/remote_clusters/public/application/sections/components/remote_cluster_form/remote_cluster_form.tsx +++ b/x-pack/plugins/remote_clusters/public/application/sections/components/remote_cluster_form/remote_cluster_form.tsx @@ -20,7 +20,7 @@ import { EuiForm, EuiFormRow, EuiLink, - EuiLoadingKibana, + EuiLoadingLogo, EuiLoadingSpinner, EuiOverlayMask, EuiSpacer, @@ -348,7 +348,7 @@ export class RemoteClusterForm extends Component { { if (this.props.isSaving) { return ( - + ); } diff --git a/x-pack/plugins/remote_clusters/public/application/sections/remote_cluster_list/remote_cluster_list.js b/x-pack/plugins/remote_clusters/public/application/sections/remote_cluster_list/remote_cluster_list.js index b94ae8f7edbc0..b6881aa02e0b9 100644 --- a/x-pack/plugins/remote_clusters/public/application/sections/remote_cluster_list/remote_cluster_list.js +++ b/x-pack/plugins/remote_clusters/public/application/sections/remote_cluster_list/remote_cluster_list.js @@ -13,7 +13,7 @@ import { EuiButton, EuiButtonEmpty, EuiEmptyPrompt, - EuiLoadingKibana, + EuiLoadingLogo, EuiOverlayMask, EuiPageContent, EuiSpacer, @@ -80,7 +80,7 @@ export class RemoteClusterList extends Component { if (isCopyingCluster || isRemovingCluster) { return ( - + ); } diff --git a/x-pack/plugins/rollup/public/crud_app/sections/job_create/job_create.js b/x-pack/plugins/rollup/public/crud_app/sections/job_create/job_create.js index 6f22345dc1cec..22d6f74c0aee5 100644 --- a/x-pack/plugins/rollup/public/crud_app/sections/job_create/job_create.js +++ b/x-pack/plugins/rollup/public/crud_app/sections/job_create/job_create.js @@ -16,7 +16,7 @@ import { withKibana } from '../../../../../../../src/plugins/kibana_react/public import { EuiCallOut, - EuiLoadingKibana, + EuiLoadingLogo, EuiOverlayMask, EuiPageContentBody, EuiPageHeader, @@ -494,7 +494,7 @@ export class JobCreateUi extends Component { if (isSaving) { savingFeedback = ( - + ); } diff --git a/x-pack/plugins/rollup/public/crud_app/sections/job_create/navigation/navigation.js b/x-pack/plugins/rollup/public/crud_app/sections/job_create/navigation/navigation.js index 6afb864fedbe4..e9c324cd5f87e 100644 --- a/x-pack/plugins/rollup/public/crud_app/sections/job_create/navigation/navigation.js +++ b/x-pack/plugins/rollup/public/crud_app/sections/job_create/navigation/navigation.js @@ -79,7 +79,7 @@ export const Navigation = ({ const saveButton = ( +

alert._id), + }, + }, + aggs: { + uuids: { + terms: { + field: ALERT_UUID, + size: CHUNK_SIZE, + }, + }, + }, + size: 0, + }, + }; + const response = await ruleDataClient + .getReader({ namespace: options.spaceId }) + .search(request); + const uuidsMap: Record = {}; + const aggs = response.aggregations as + | Record }> + | undefined; + if (aggs != null) { + aggs.uuids.buckets.forEach((bucket) => (uuidsMap[bucket.key] = true)); + const newAlerts = alertChunk.filter((alert) => !uuidsMap[alert._id]); + filteredAlerts.push(...newAlerts); + } else { + filteredAlerts.push(...alertChunk); + } + } + + if (filteredAlerts.length === 0) { + return { createdAlerts: [] }; + } + + const augmentedAlerts = filteredAlerts.map((alert) => { + return { + ...alert, + _source: { + [VERSION]: ruleDataClient.kibanaVersion, + ...commonRuleFields, + ...alert._source, + }, + }; + }); + const response = await ruleDataClient .getWriter({ namespace: options.spaceId }) .bulk({ - body: alerts.flatMap((alert) => [ - { index: { _id: alert.id } }, - { - [VERSION]: ruleDataClient.kibanaVersion, - ...commonRuleFields, - ...alert.fields, - }, + body: augmentedAlerts.flatMap((alert) => [ + { create: { _id: alert._id } }, + alert._source, ]), refresh, }); - return response; + + if (response == null) { + return { createdAlerts: [] }; + } + + return { + createdAlerts: augmentedAlerts.map((alert, idx) => { + const responseItem = response.body.items[idx].create; + return { + _id: responseItem?._id ?? '', + _index: responseItem?._index ?? '', + ...alert._source, + }; + }), + }; } else { logger.debug('Writing is disabled.'); + return { createdAlerts: [] }; } }, }, diff --git a/x-pack/plugins/rule_registry/server/utils/persistence_types.ts b/x-pack/plugins/rule_registry/server/utils/persistence_types.ts index 326a8bef49abd..5541bc6a6d00e 100644 --- a/x-pack/plugins/rule_registry/server/utils/persistence_types.ts +++ b/x-pack/plugins/rule_registry/server/utils/persistence_types.ts @@ -5,8 +5,6 @@ * 2.0. */ -import type { TransportResult } from '@elastic/elasticsearch'; -import { BulkResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { Logger } from '@kbn/logging'; import { AlertExecutorOptions, @@ -19,13 +17,17 @@ import { import { WithoutReservedActionGroups } from '../../../alerting/common'; import { IRuleDataClient } from '../rule_data_client'; -export type PersistenceAlertService = ( +export type PersistenceAlertService = ( alerts: Array<{ - id: string; - fields: Record; + _id: string; + _source: T; }>, refresh: boolean | 'wait_for' -) => Promise | undefined>; +) => Promise>; + +export interface PersistenceAlertServiceResult { + createdAlerts: Array; +} export interface PersistenceServices { alertWithPersistence: PersistenceAlertService; diff --git a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx index a4843e4637d8b..f950167d4b82e 100644 --- a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx +++ b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx @@ -528,7 +528,7 @@ export class APIKeysGridPage extends Component { render: (creation: string, item: ApiKey) => ( {item.id === createdApiKey?.id ? ( - + ({ import { act } from '@testing-library/react'; -import { coreMock, scopedHistoryMock } from 'src/core/public/mocks'; +import { coreMock, scopedHistoryMock, themeServiceMock } from 'src/core/public/mocks'; import type { Unmount } from 'src/plugins/management/public/types'; import { securityMock } from '../../mocks'; @@ -52,6 +52,7 @@ describe('apiKeysManagementApp', () => { element: container, setBreadcrumbs, history: scopedHistoryMock.create(), + theme$: themeServiceMock.createTheme$(), }); }); diff --git a/x-pack/plugins/security/public/management/badges/enabled_badge.tsx b/x-pack/plugins/security/public/management/badges/enabled_badge.tsx index f55914997c72e..a03a5ab3060e3 100644 --- a/x-pack/plugins/security/public/management/badges/enabled_badge.tsx +++ b/x-pack/plugins/security/public/management/badges/enabled_badge.tsx @@ -21,7 +21,7 @@ interface Props { export const EnabledBadge = (props: Props) => { return ( - + diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/json_rule_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/json_rule_editor.tsx index 86f7892e49d24..176d66049eade 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/json_rule_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/json_rule_editor.tsx @@ -5,6 +5,7 @@ * 2.0. */ +import 'react-ace'; import 'brace/mode/json'; import 'brace/theme/github'; diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx index 373f3366f36c8..c983f2c704f4a 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx @@ -255,7 +255,7 @@ export class RoleMappingsGridPage extends Component { ) : undefined, toolsRight: ( this.reloadRoleMappings()} data-test-subj="reloadButton" diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx b/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx index 892c7940675d3..3b7e96ffabd1e 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx @@ -8,7 +8,7 @@ import { act } from '@testing-library/react'; import { noop } from 'lodash'; -import { coreMock, scopedHistoryMock } from 'src/core/public/mocks'; +import { coreMock, scopedHistoryMock, themeServiceMock } from 'src/core/public/mocks'; import type { Unmount } from 'src/plugins/management/public/types'; import { roleMappingsManagementApp } from './role_mappings_management_app'; @@ -46,6 +46,7 @@ async function mountApp(basePath: string, pathname: string) { element: container, setBreadcrumbs, history: scopedHistoryMock.create({ pathname }), + theme$: themeServiceMock.createTheme$(), }); }); diff --git a/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx b/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx index faab47a858d67..007c3e306372e 100644 --- a/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx @@ -8,7 +8,7 @@ import { act } from '@testing-library/react'; import { noop } from 'lodash'; -import { coreMock, scopedHistoryMock } from 'src/core/public/mocks'; +import { coreMock, scopedHistoryMock, themeServiceMock } from 'src/core/public/mocks'; import type { Unmount } from 'src/plugins/management/public/types'; import { featuresPluginMock } from '../../../../features/public/mocks'; @@ -48,6 +48,7 @@ async function mountApp(basePath: string, pathname: string) { element: container, setBreadcrumbs, history: scopedHistoryMock.create({ pathname }), + theme$: themeServiceMock.createTheme$(), }); }); diff --git a/x-pack/plugins/security/public/management/users/users_management_app.test.tsx b/x-pack/plugins/security/public/management/users/users_management_app.test.tsx index f25fb211cb9de..84a6e82bf12ae 100644 --- a/x-pack/plugins/security/public/management/users/users_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/users/users_management_app.test.tsx @@ -8,7 +8,7 @@ import { act } from '@testing-library/react'; import { noop } from 'lodash'; -import { coreMock, scopedHistoryMock } from 'src/core/public/mocks'; +import { coreMock, scopedHistoryMock, themeServiceMock } from 'src/core/public/mocks'; import type { Unmount } from 'src/plugins/management/public/types'; import { securityMock } from '../../mocks'; @@ -33,6 +33,7 @@ describe('usersManagementApp', () => { element, setBreadcrumbs, history, + theme$: themeServiceMock.createTheme$(), }); }); diff --git a/x-pack/plugins/security_solution/common/endpoint/types/index.ts b/x-pack/plugins/security_solution/common/endpoint/types/index.ts index 2fee3e4c39d1d..2dc4f49919ef7 100644 --- a/x-pack/plugins/security_solution/common/endpoint/types/index.ts +++ b/x-pack/plugins/security_solution/common/endpoint/types/index.ts @@ -177,7 +177,7 @@ export interface ResolverPaginatedEvents { } /** - * Returned by the server via /api/endpoint/metadata + * Returned by the server via POST /api/endpoint/metadata */ export interface HostResultList { /* the hosts restricted by the page size */ @@ -1231,3 +1231,22 @@ export interface ListPageRouteState { /** The label for the button */ backButtonLabel?: string; } + +/** + * REST API standard base response for list types + */ +export interface BaseListResponse { + data: unknown[]; + page: number; + pageSize: number; + total: number; + sort?: string; + sortOrder?: 'asc' | 'desc'; +} + +/** + * Returned by the server via GET /api/endpoint/metadata + */ +export interface MetadataListResponse extends BaseListResponse { + data: HostInfo[]; +} diff --git a/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts b/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts index 378de8f0bc593..ef6db14dba896 100644 --- a/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts @@ -40,6 +40,7 @@ import { INDICATOR_INDEX_PATTERNS, INDICATOR_INDEX_QUERY, INDICATOR_MAPPING, + INDICATOR_PREFIX_OVERRIDE, INVESTIGATION_NOTES_MARKDOWN, INVESTIGATION_NOTES_TOGGLE, MITRE_ATTACK_DETAILS, @@ -448,6 +449,10 @@ describe('indicator match', () => { cy.get(ABOUT_DETAILS).within(() => { getDetails(SEVERITY_DETAILS).should('have.text', getNewThreatIndicatorRule().severity); getDetails(RISK_SCORE_DETAILS).should('have.text', getNewThreatIndicatorRule().riskScore); + getDetails(INDICATOR_PREFIX_OVERRIDE).should( + 'have.text', + getNewThreatIndicatorRule().threatIndicatorPath + ); getDetails(REFERENCE_URLS_DETAILS).should((details) => { expect(removeExternalLinkText(details.text())).equal(expectedUrls); }); diff --git a/x-pack/plugins/security_solution/cypress/objects/rule.ts b/x-pack/plugins/security_solution/cypress/objects/rule.ts index 0a9eecf83c7fc..1c81099d43dd5 100644 --- a/x-pack/plugins/security_solution/cypress/objects/rule.ts +++ b/x-pack/plugins/security_solution/cypress/objects/rule.ts @@ -77,6 +77,7 @@ export interface ThreatIndicatorRule extends CustomRule { indicatorIndexPattern: string[]; indicatorMappingField: string; indicatorIndexField: string; + threatIndicatorPath: string; type?: string; atomic?: string; } @@ -405,6 +406,7 @@ export const getNewThreatIndicatorRule = (): ThreatIndicatorRule => ({ atomic: 'a04ac6d98ad989312783d4fe3456c53730b212c79a426fb215708b6c6daa3de3', timeline: getIndicatorMatchTimelineTemplate(), maxSignals: 100, + threatIndicatorPath: 'threat.indicator', }); export const duplicatedRuleName = `${getNewThreatIndicatorRule().name} [Duplicate]`; diff --git a/x-pack/plugins/security_solution/cypress/screens/rule_details.ts b/x-pack/plugins/security_solution/cypress/screens/rule_details.ts index fb1fded1fe8a6..cdad6096ece1f 100644 --- a/x-pack/plugins/security_solution/cypress/screens/rule_details.ts +++ b/x-pack/plugins/security_solution/cypress/screens/rule_details.ts @@ -64,6 +64,8 @@ export const RULE_NAME_OVERRIDE_DETAILS = 'Rule name override'; export const RISK_SCORE_DETAILS = 'Risk score'; +export const INDICATOR_PREFIX_OVERRIDE = 'Indicator prefix override'; + export const RISK_SCORE_OVERRIDE_DETAILS = 'Risk score override'; export const REFERENCE_URLS_DETAILS = 'Reference URLs'; diff --git a/x-pack/plugins/security_solution/public/cases/components/callout/callout.test.tsx b/x-pack/plugins/security_solution/public/cases/components/callout/callout.test.tsx index 0a0caa40a8783..01c581f5401ba 100644 --- a/x-pack/plugins/security_solution/public/cases/components/callout/callout.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/callout/callout.test.tsx @@ -60,7 +60,7 @@ describe('Callout', () => { const className = wrapper.find(`button[data-test-subj="callout-dismiss-md5-hex"]`).first().prop('className') ?? ''; - expect(className.includes('euiButton--secondary')).toBeTruthy(); + expect(className.includes('euiButton--success')).toBeTruthy(); }); it('transform the button color correctly - warning', () => { diff --git a/x-pack/plugins/security_solution/public/cases/components/callout/callout.tsx b/x-pack/plugins/security_solution/public/cases/components/callout/callout.tsx index f00fa84c6ff0a..d0493ec7acb9c 100644 --- a/x-pack/plugins/security_solution/public/cases/components/callout/callout.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/callout/callout.tsx @@ -37,11 +37,7 @@ const CallOutComponent = ({ return showCallOut && !isEmpty(messages) ? ( - + {i18n.DISMISS_CALLOUT} diff --git a/x-pack/plugins/security_solution/public/common/components/callouts/callout_dismiss_button.tsx b/x-pack/plugins/security_solution/public/common/components/callouts/callout_dismiss_button.tsx index c657ee243b74b..b00072be6cc5f 100644 --- a/x-pack/plugins/security_solution/public/common/components/callouts/callout_dismiss_button.tsx +++ b/x-pack/plugins/security_solution/public/common/components/callouts/callout_dismiss_button.tsx @@ -23,7 +23,7 @@ export const CallOutDismissButton: FC = ({ onClick = noop, }) => { const { type } = message; - const buttonColor = type === 'success' ? 'secondary' : type; + const buttonColor = type; const buttonText = text ?? i18n.DISMISS_BUTTON; const handleClick = useCallback(() => onClick(message), [onClick, message]); diff --git a/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.tsx b/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.tsx index 487e0fe4981f1..3744297ded56a 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.tsx +++ b/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.tsx @@ -77,7 +77,7 @@ const EditableTitleComponent: React.FC = ({ - secondary + success { {'primary'} - - {'secondary'} + + {'success'} {'danger'} diff --git a/x-pack/plugins/security_solution/public/common/components/item_details_card/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/item_details_card/index.test.tsx index 12264e28d40c9..7fce50284d0d9 100644 --- a/x-pack/plugins/security_solution/public/common/components/item_details_card/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/item_details_card/index.test.tsx @@ -60,8 +60,8 @@ describe('item_details_card', () => { {'primary'} - - {'secondary'} + + {'success'} {'danger'} diff --git a/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap index 3440e5f4488c6..a2fffc32be46d 100644 --- a/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/paginated_table/__snapshots__/index.test.tsx.snap @@ -22,28 +22,36 @@ exports[`Paginated Table Component rendering it renders the default load more ta Array [ Object { "field": "node.host.name", - "hideForMobile": false, + "mobileOptions": Object { + "show": true, + }, "name": "Host", "render": [Function], "truncateText": false, }, Object { "field": "node.host.firstSeen", - "hideForMobile": false, + "mobileOptions": Object { + "show": true, + }, "name": "First seen", "render": [Function], "truncateText": false, }, Object { "field": "node.host.os", - "hideForMobile": false, + "mobileOptions": Object { + "show": true, + }, "name": "OS", "render": [Function], "truncateText": false, }, Object { "field": "node.host.version", - "hideForMobile": false, + "mobileOptions": Object { + "show": true, + }, "name": "Version", "render": [Function], "truncateText": false, diff --git a/x-pack/plugins/security_solution/public/common/components/paginated_table/index.mock.tsx b/x-pack/plugins/security_solution/public/common/components/paginated_table/index.mock.tsx index 070c8a8d53b43..2d728ffa915fc 100644 --- a/x-pack/plugins/security_solution/public/common/components/paginated_table/index.mock.tsx +++ b/x-pack/plugins/security_solution/public/common/components/paginated_table/index.mock.tsx @@ -57,28 +57,28 @@ export const getHostsColumns = (): [ field: 'node.host.name', name: 'Host', truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (name: string) => getOrEmptyTagFromValue(name), }, { field: 'node.host.firstSeen', name: 'First seen', truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (firstSeen: string) => getOrEmptyTagFromValue(firstSeen), }, { field: 'node.host.os', name: 'OS', truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (os: string) => getOrEmptyTagFromValue(os), }, { field: 'node.host.version', name: 'Version', truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (version: string) => getOrEmptyTagFromValue(version), }, ]; diff --git a/x-pack/plugins/security_solution/public/common/components/paginated_table/index.tsx b/x-pack/plugins/security_solution/public/common/components/paginated_table/index.tsx index f5828c9f65db9..ef49c8e2a5e8c 100644 --- a/x-pack/plugins/security_solution/public/common/components/paginated_table/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/paginated_table/index.tsx @@ -17,6 +17,7 @@ import { EuiLoadingContent, EuiPagination, EuiPopover, + EuiTableRowCellProps, } from '@elastic/eui'; import { noop } from 'lodash/fp'; import React, { FC, memo, useState, useMemo, useEffect, ComponentType } from 'react'; @@ -126,8 +127,7 @@ type Func = (arg: T) => string | number; export interface Columns { align?: string; field?: string; - hideForMobile?: boolean; - isMobileHeader?: boolean; + mobileOptions?: EuiTableRowCellProps['mobileOptions']; name: string | React.ReactNode; render?: (item: T, node: U) => React.ReactNode; sortable?: boolean | Func; diff --git a/x-pack/plugins/security_solution/public/common/components/progress_inline/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/progress_inline/__snapshots__/index.test.tsx.snap index e1fc1becd0188..bf36bf1afeef3 100644 --- a/x-pack/plugins/security_solution/public/common/components/progress_inline/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/progress_inline/__snapshots__/index.test.tsx.snap @@ -13,7 +13,7 @@ exports[`ProgressInline it renders 1`] = ` className="siemProgressInline__bar" > diff --git a/x-pack/plugins/security_solution/public/common/components/progress_inline/index.tsx b/x-pack/plugins/security_solution/public/common/components/progress_inline/index.tsx index bbea27f5a705a..7b7e24bf8707b 100644 --- a/x-pack/plugins/security_solution/public/common/components/progress_inline/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/progress_inline/index.tsx @@ -38,7 +38,7 @@ export const ProgressInline = React.memo(

{children}
- +
diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/ml_job_description.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/ml_job_description.tsx index 27afe847f7612..4b61504ec997a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/ml_job_description.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/ml_job_description.tsx @@ -51,7 +51,7 @@ export const AuditIcon = React.memo(AuditIconComponent); const JobStatusBadgeComponent: React.FC<{ job: MlSummaryJob }> = ({ job }) => { const isStarted = isJobStarted(job.jobState, job.datafeedState); - const color = isStarted ? 'secondary' : 'danger'; + const color = isStarted ? 'success' : 'danger'; const text = isStarted ? ML_JOB_STARTED : ML_JOB_STOPPED; return ( diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx index 9340ca2af1513..01ba47f728e43 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx @@ -20,6 +20,7 @@ import { AboutStepRule, RuleStepsFormHooks, RuleStep, + DefineStepRule, } from '../../../pages/detection_engine/rules/types'; import { fillEmptySeverityMappings } from '../../../pages/detection_engine/rules/helpers'; import { getMockTheme } from '../../../../common/lib/kibana/kibana_react.mock'; @@ -105,6 +106,63 @@ describe.skip('StepAboutRuleComponent', () => { }); }); + it('is invalid if threat match rule and threat_indicator_path is not present', async () => { + const wrapper = mount( + + + + ); + + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + wrapper + .find('[data-test-subj="detectionEngineStepAboutThreatIndicatorPath"] input') + .first() + .simulate('change', { target: { value: '' } }); + + const result = await formHook(); + expect(result?.isValid).toEqual(false); + }); + }); + + it('is valid if is not a threat match rule and threat_indicator_path is not present', async () => { + const wrapper = mount( + + + + ); + + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + wrapper + .find('[data-test-subj="detectionEngineStepAboutThreatIndicatorPath"] input') + .first() + .simulate('change', { target: { value: '' } }); + + const result = await formHook(); + expect(result?.isValid).toEqual(true); + }); + }); + it('is invalid if no "name" is present', async () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx index 91e428382dc30..5f5b636d6afe1 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx @@ -6,7 +6,7 @@ */ import { EuiAccordion, EuiFlexItem, EuiSpacer, EuiFormRow } from '@elastic/eui'; -import React, { FC, memo, useCallback, useEffect, useState } from 'react'; +import React, { FC, memo, useCallback, useEffect, useState, useMemo } from 'react'; import styled from 'styled-components'; import { @@ -31,7 +31,7 @@ import { import { defaultRiskScoreBySeverity, severityOptions } from './data'; import { stepAboutDefaultValue } from './default_value'; import { isUrlInvalid } from '../../../../common/utils/validators'; -import { schema } from './schema'; +import { schema as defaultSchema, threatIndicatorPathRequiredSchemaValue } from './schema'; import * as I18n from './translations'; import { StepContentWrapper } from '../step_content_wrapper'; import { NextStep } from '../next_step'; @@ -73,7 +73,28 @@ const StepAboutRuleComponent: FC = ({ onSubmit, setForm, }) => { - const initialState = defaultValues ?? stepAboutDefaultValue; + const isThreatMatchRuleValue = useMemo( + () => isThreatMatchRule(defineRuleData?.ruleType), + [defineRuleData?.ruleType] + ); + + const initialState: AboutStepRule = useMemo( + () => + defaultValues ?? + (isThreatMatchRuleValue + ? { ...stepAboutDefaultValue, threatIndicatorPath: DEFAULT_INDICATOR_SOURCE_PATH } + : stepAboutDefaultValue), + [defaultValues, isThreatMatchRuleValue] + ); + + const schema = useMemo( + () => + isThreatMatchRuleValue + ? { ...defaultSchema, threatIndicatorPath: threatIndicatorPathRequiredSchemaValue } + : defaultSchema, + [isThreatMatchRuleValue] + ); + const [severityValue, setSeverityValue] = useState(initialState.severity.value); const [indexPatternLoading, { indexPatterns }] = useFetchIndex(defineRuleData?.index ?? []); @@ -300,7 +321,7 @@ const StepAboutRuleComponent: FC = ({ /> - {isThreatMatchRule(defineRuleData?.ruleType) && ( + {isThreatMatchRuleValue && ( <> = { labelAppend: OptionalFieldLabel, }, }; + +export const threatIndicatorPathRequiredSchemaValue = { + type: FIELD_TYPES.TEXT, + label: i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldThreatIndicatorPathLabel', + { + defaultMessage: 'Indicator prefix override', + } + ), + helpText: i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldThreatIndicatorPathHelpText', + { + defaultMessage: + 'Specify the document prefix containing your indicator fields. Used for enrichment of indicator match alerts.', + } + ), + validations: [ + { + validator: emptyField( + i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.threatIndicatorPathFieldEmptyError', + { + defaultMessage: 'Indicator prefix override must not be empty', + } + ) + ), + type: VALIDATION_TYPES.FIELD, + }, + ], +}; diff --git a/x-pack/plugins/security_solution/public/hosts/components/authentications_table/index.tsx b/x-pack/plugins/security_solution/public/hosts/components/authentications_table/index.tsx index 23e5da28a3559..65357b15036ea 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/authentications_table/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/authentications_table/index.tsx @@ -140,7 +140,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.USER, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.user.name, @@ -151,7 +151,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.SUCCESSES, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => { const id = escapeDataProviderId( `authentications-table-${node._id}-node-successes-${node.successes}` @@ -189,7 +189,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.FAILURES, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => { const id = escapeDataProviderId( `authentications-table-${node._id}-failures-${node.failures}` @@ -227,7 +227,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.LAST_SUCCESSFUL_TIME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => has('lastSuccess.timestamp', node) && node.lastSuccess?.timestamp != null ? ( @@ -238,7 +238,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.LAST_SUCCESSFUL_SOURCE, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.lastSuccess?.source?.ip || null, @@ -250,7 +250,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.LAST_SUCCESSFUL_DESTINATION, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.lastSuccess?.host?.name ?? null, @@ -262,7 +262,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.LAST_FAILED_TIME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => has('lastFailure.timestamp', node) && node.lastFailure?.timestamp != null ? ( @@ -273,7 +273,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.LAST_FAILED_SOURCE, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.lastFailure?.source?.ip || null, @@ -285,7 +285,7 @@ const getAuthenticationColumns = (): AuthTableColumns => [ { name: i18n.LAST_FAILED_DESTINATION, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.lastFailure?.host?.name || null, diff --git a/x-pack/plugins/security_solution/public/hosts/components/hosts_table/columns.tsx b/x-pack/plugins/security_solution/public/hosts/components/hosts_table/columns.tsx index d6c51b2bfe05e..95f88da0a24ac 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/hosts_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/hosts_table/columns.tsx @@ -31,7 +31,7 @@ export const getHostsColumns = (): HostsTableColumns => [ field: 'node.host.name', name: i18n.NAME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (hostName) => { if (hostName != null && hostName.length > 0) { @@ -75,7 +75,7 @@ export const getHostsColumns = (): HostsTableColumns => [ ), truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (lastSeen: Maybe | undefined) => { if (lastSeen != null && lastSeen.length > 0) { @@ -92,7 +92,7 @@ export const getHostsColumns = (): HostsTableColumns => [ field: 'node.host.os.name', name: i18n.OS, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (hostOsName) => { if (hostOsName != null) { @@ -109,7 +109,7 @@ export const getHostsColumns = (): HostsTableColumns => [ field: 'node.host.os.version', name: i18n.VERSION, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (hostOsVersion) => { if (hostOsVersion != null) { diff --git a/x-pack/plugins/security_solution/public/hosts/components/uncommon_process_table/index.tsx b/x-pack/plugins/security_solution/public/hosts/components/uncommon_process_table/index.tsx index 0541f2f1d403d..0af27bdb0ba18 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/uncommon_process_table/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/uncommon_process_table/index.tsx @@ -144,7 +144,7 @@ const getUncommonColumns = (): UncommonProcessTableColumns => [ { name: i18n.NAME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.process.name, @@ -157,7 +157,7 @@ const getUncommonColumns = (): UncommonProcessTableColumns => [ align: 'right', name: i18n.NUMBER_OF_HOSTS, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => <>{node.hosts != null ? node.hosts.length : getEmptyValue()}, width: '8%', }, @@ -165,14 +165,14 @@ const getUncommonColumns = (): UncommonProcessTableColumns => [ align: 'right', name: i18n.NUMBER_OF_INSTANCES, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => defaultToEmptyTag(node.instances), width: '8%', }, { name: i18n.HOSTS, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: getHostNames(node), @@ -185,7 +185,7 @@ const getUncommonColumns = (): UncommonProcessTableColumns => [ { name: i18n.LAST_COMMAND, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.process != null ? node.process.args : null, @@ -198,7 +198,7 @@ const getUncommonColumns = (): UncommonProcessTableColumns => [ { name: i18n.LAST_USER, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: ({ node }) => getRowItemDraggables({ rowItems: node.user != null ? node.user.name : null, diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/effected_policy_select.test.tsx b/x-pack/plugins/security_solution/public/management/components/effected_policy_select/effected_policy_select.test.tsx similarity index 95% rename from x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/effected_policy_select.test.tsx rename to x-pack/plugins/security_solution/public/management/components/effected_policy_select/effected_policy_select.test.tsx index 3e48ccc6d9b6d..5eebc2721857f 100644 --- a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/effected_policy_select.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/effected_policy_select/effected_policy_select.test.tsx @@ -5,15 +5,12 @@ * 2.0. */ -import { EndpointDocGenerator } from '../../../../../../../common/endpoint/generate_data'; import { EffectedPolicySelect, EffectedPolicySelectProps } from './effected_policy_select'; -import { - AppContextTestRender, - createAppRootMockRenderer, -} from '../../../../../../common/mock/endpoint'; import React from 'react'; import { forceHTMLElementOffsetWidth } from './test_utils'; import { fireEvent, act } from '@testing-library/react'; +import { EndpointDocGenerator } from '../../../../common/endpoint/generate_data'; +import { AppContextTestRender, createAppRootMockRenderer } from '../../../common/mock/endpoint'; describe('when using EffectedPolicySelect component', () => { const generator = new EndpointDocGenerator('effected-policy-select'); diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/effected_policy_select.tsx b/x-pack/plugins/security_solution/public/management/components/effected_policy_select/effected_policy_select.tsx similarity index 76% rename from x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/effected_policy_select.tsx rename to x-pack/plugins/security_solution/public/management/components/effected_policy_select/effected_policy_select.tsx index 07de303c155aa..2249fc89430d2 100644 --- a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/effected_policy_select.tsx +++ b/x-pack/plugins/security_solution/public/management/components/effected_policy_select/effected_policy_select.tsx @@ -23,14 +23,27 @@ import { i18n } from '@kbn/i18n'; import { EuiSelectableOption } from '@elastic/eui/src/components/selectable/selectable_option'; import { FormattedMessage } from '@kbn/i18n/react'; import styled from 'styled-components'; -import { PolicyData } from '../../../../../../../common/endpoint/types'; -import { getPolicyDetailPath } from '../../../../../common/routing'; -import { useAppUrl } from '../../../../../../common/lib/kibana/hooks'; -import { LinkToApp } from '../../../../../../common/components/endpoint/link_to_app'; -import { useTestIdGenerator } from '../../../../../components/hooks/use_test_id_generator'; +import { PolicyData } from '../../../../common/endpoint/types'; +import { LinkToApp } from '../../../common/components/endpoint/link_to_app'; +import { getPolicyDetailPath } from '../../common/routing'; +import { useTestIdGenerator } from '../hooks/use_test_id_generator'; +import { useAppUrl } from '../../../common/lib/kibana/hooks'; const NOOP = () => {}; const DEFAULT_LIST_PROPS: EuiSelectableProps['listProps'] = { bordered: true, showIcons: false }; +const SEARCH_PROPS = { className: 'effected-policies-search' }; + +const StyledEuiSelectable = styled.div` + .effected-policies-search { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; + } + .euiSelectableList { + border-top-left-radius: 0; + border-top-right-radius: 0; + border-top-width: 0; + } +`; const EffectivePolicyFormContainer = styled.div` .policy-name .euiSelectableListItem__text { @@ -57,6 +70,7 @@ export type EffectedPolicySelectProps = Omit< options: PolicyData[]; isGlobal: boolean; isPlatinumPlus: boolean; + description?: string; onChange: (selection: EffectedPolicySelection) => void; selected?: PolicyData[]; }; @@ -64,6 +78,7 @@ export const EffectedPolicySelect = memo( ({ isGlobal, isPlatinumPlus, + description, onChange, listProps, options, @@ -79,7 +94,7 @@ export const EffectedPolicySelect = memo( () => [ { id: 'globalPolicy', - label: i18n.translate('xpack.securitySolution.endpoint.trustedAppsByPolicy.global', { + label: i18n.translate('xpack.securitySolution.endpoint.effectedPolicySelect.global', { defaultMessage: 'Global', }), iconType: isGlobal ? 'checkInCircleFilled' : '', @@ -87,7 +102,7 @@ export const EffectedPolicySelect = memo( }, { id: 'perPolicy', - label: i18n.translate('xpack.securitySolution.endpoint.trustedAppsByPolicy.perPolicy', { + label: i18n.translate('xpack.securitySolution.endpoint.effectedPolicySelect.perPolicy', { defaultMessage: 'Per Policy', }), iconType: !isGlobal ? 'checkInCircleFilled' : '', @@ -169,7 +184,7 @@ export const EffectedPolicySelect = memo(

@@ -179,10 +194,15 @@ export const EffectedPolicySelect = memo(

- {i18n.translate('xpack.securitySolution.trustedApps.assignmentSectionDescription', { - defaultMessage: - 'Assign this trusted application globally across all policies, or assign it to specific policies.', - })} + {description + ? description + : i18n.translate( + 'xpack.securitySolution.effectedPolicySelect.assignmentSectionDescription', + { + defaultMessage: + 'Assign globally across all policies, or assign it to specific policies.', + } + )}

@@ -202,16 +222,19 @@ export const EffectedPolicySelect = memo( {!isGlobal && ( - - {...otherSelectableProps} - options={selectableOptions} - listProps={listProps || DEFAULT_LIST_PROPS} - onChange={handleOnPolicySelectChange} - searchable={true} - data-test-subj={getTestId('policiesSelectable')} - > - {listBuilderCallback} - + + + {...otherSelectableProps} + options={selectableOptions} + listProps={listProps || DEFAULT_LIST_PROPS} + onChange={handleOnPolicySelectChange} + searchProps={SEARCH_PROPS} + searchable={true} + data-test-subj={getTestId('policiesSelectable')} + > + {listBuilderCallback} + + )} diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/index.ts b/x-pack/plugins/security_solution/public/management/components/effected_policy_select/index.ts similarity index 100% rename from x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/index.ts rename to x-pack/plugins/security_solution/public/management/components/effected_policy_select/index.ts diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/test_utils.ts b/x-pack/plugins/security_solution/public/management/components/effected_policy_select/test_utils.ts similarity index 100% rename from x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/effected_policy_select/test_utils.ts rename to x-pack/plugins/security_solution/public/management/components/effected_policy_select/test_utils.ts 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 287f66a48fce8..3f4afe8e4b108 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 @@ -54,7 +54,6 @@ import { TransformStatsResponse, } from '../types'; import { - sendGetEndpointSpecificPackagePolicies, sendGetEndpointSecurityPackage, sendGetAgentPolicyList, sendGetFleetAgentsWithEndpoint, @@ -81,6 +80,7 @@ import { EndpointPackageInfoStateChanged } from './action'; import { fetchPendingActionsByAgentId } from '../../../../common/lib/endpoint_pending_actions'; import { getIsInvalidDateRange } from '../utils'; import { METADATA_TRANSFORM_STATS_URL } from '../../../../../common/constants'; +import { sendGetEndpointSpecificPackagePolicies } from '../../../services/policies'; type EndpointPageStore = ImmutableMiddlewareAPI; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/host_constants.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/host_constants.ts index 8e0e4fd969c22..8fa4a9388e08e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/host_constants.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/host_constants.ts @@ -11,7 +11,7 @@ import { HostStatus, HostPolicyResponseActionStatus } from '../../../../../commo export const HOST_STATUS_TO_BADGE_COLOR = Object.freeze<{ [key in HostStatus]: string; }>({ - [HostStatus.HEALTHY]: 'secondary', + [HostStatus.HEALTHY]: 'success', [HostStatus.UNHEALTHY]: 'warning', [HostStatus.UPDATING]: 'primary', [HostStatus.OFFLINE]: 'default', @@ -22,7 +22,7 @@ export const HOST_STATUS_TO_BADGE_COLOR = Object.freeze<{ export const POLICY_STATUS_TO_HEALTH_COLOR = Object.freeze<{ [key in keyof typeof HostPolicyResponseActionStatus]: string; }>({ - success: 'secondary', + success: 'success', warning: 'warning', failure: 'danger', unsupported: 'default', @@ -31,7 +31,7 @@ export const POLICY_STATUS_TO_HEALTH_COLOR = Object.freeze<{ export const POLICY_STATUS_TO_BADGE_COLOR = Object.freeze<{ [key in keyof typeof HostPolicyResponseActionStatus]: string; }>({ - success: 'secondary', + success: 'success', warning: 'warning', failure: 'danger', unsupported: 'default', diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.test.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.test.ts index b5897d8fd3bc4..ef66c948e1127 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.test.ts @@ -9,15 +9,9 @@ import { INGEST_API_EPM_PACKAGES, sendGetPackagePolicy, sendGetEndpointSecurityPackage, - sendGetEndpointSpecificPackagePolicies, } from './ingest'; import { httpServiceMock } from '../../../../../../../../../src/core/public/mocks'; -import { - EPM_API_ROUTES, - PACKAGE_POLICY_SAVED_OBJECT_TYPE, - PACKAGE_POLICY_API_ROOT, - PACKAGE_POLICY_API_ROUTES, -} from '../../../../../../../fleet/common'; +import { EPM_API_ROUTES, PACKAGE_POLICY_API_ROOT } from '../../../../../../../fleet/common'; import { policyListApiPathHandlers } from '../test_mock_utils'; describe('ingest service', () => { @@ -27,29 +21,6 @@ describe('ingest service', () => { http = httpServiceMock.createStartContract(); }); - describe('sendGetEndpointSpecificPackagePolicies()', () => { - it('auto adds kuery to api request', async () => { - await sendGetEndpointSpecificPackagePolicies(http); - expect(http.get).toHaveBeenCalledWith(`${PACKAGE_POLICY_API_ROUTES.LIST_PATTERN}`, { - query: { - kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, - }, - }); - }); - it('supports additional KQL to be defined on input for query params', async () => { - await sendGetEndpointSpecificPackagePolicies(http, { - query: { kuery: 'someValueHere', page: 1, perPage: 10 }, - }); - expect(http.get).toHaveBeenCalledWith(`${PACKAGE_POLICY_API_ROUTES.LIST_PATTERN}`, { - query: { - kuery: `someValueHere and ${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, - perPage: 10, - page: 1, - }, - }); - }); - }); - describe('sendGetPackagePolicy()', () => { it('builds correct API path', async () => { await sendGetPackagePolicy(http, '123'); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.ts index 0375b0c434f18..27b567c3bb38c 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/services/ingest.ts @@ -7,17 +7,15 @@ import { HttpFetchOptions, HttpStart } from 'kibana/public'; import { - GetPackagePoliciesRequest, GetAgentStatusResponse, GetAgentsResponse, DeletePackagePoliciesResponse, DeletePackagePoliciesRequest, - PACKAGE_POLICY_SAVED_OBJECT_TYPE, GetPackagesResponse, GetAgentPoliciesRequest, GetAgentPoliciesResponse, } from '../../../../../../../fleet/common'; -import { GetPolicyListResponse, GetPolicyResponse, UpdatePolicyResponse } from '../../types'; +import { GetPolicyResponse, UpdatePolicyResponse } from '../../types'; import { NewPolicyData } from '../../../../../../common/endpoint/types'; const INGEST_API_ROOT = `/api/fleet`; @@ -28,27 +26,6 @@ export const INGEST_API_FLEET_AGENTS = `${INGEST_API_ROOT}/agents`; export const INGEST_API_EPM_PACKAGES = `${INGEST_API_ROOT}/epm/packages`; const INGEST_API_DELETE_PACKAGE_POLICY = `${INGEST_API_PACKAGE_POLICIES}/delete`; -/** - * Retrieves a list of endpoint specific package policies (those created with a `package.name` of - * `endpoint`) from Ingest - * @param http - * @param options - */ -export const sendGetEndpointSpecificPackagePolicies = ( - http: HttpStart, - options: HttpFetchOptions & Partial = {} -): Promise => { - return http.get(INGEST_API_PACKAGE_POLICIES, { - ...options, - query: { - ...options.query, - kuery: `${ - options?.query?.kuery ? `${options.query.kuery} and ` : '' - }${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, - }, - }); -}; - /** * Retrieves a single package policy based on ID from ingest * @param http diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.test.tsx index 30c95472e4d6d..0981c775e961b 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.test.tsx @@ -97,8 +97,8 @@ describe('Fleet event filters card', () => { }; }); const component = await renderComponent(); - expect(component.getByText('Event Filters')).not.toBeNull(); - expect(component.getByText('Manage event filters')).not.toBeNull(); + expect(component.getByText('Event filters')).not.toBeNull(); + expect(component.getByText('Manage')).not.toBeNull(); }); it('should render an error toast when api call fails', async () => { expect(addDanger).toBeCalledTimes(0); @@ -109,8 +109,8 @@ describe('Fleet event filters card', () => { }; }); const component = await renderComponent(); - expect(component.getByText('Event Filters')).not.toBeNull(); - expect(component.getByText('Manage event filters')).not.toBeNull(); + expect(component.getByText('Event filters')).not.toBeNull(); + expect(component.getByText('Manage')).not.toBeNull(); await reactTestingLibrary.waitFor(() => expect(addDanger).toBeCalledTimes(1)); }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.tsx index 41768f4be7d2e..7db76fee4efc5 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_event_filters_card.tsx @@ -95,7 +95,7 @@ export const FleetEventFiltersCard = memo(

@@ -115,7 +115,7 @@ export const FleetEventFiltersCard = memo( > diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_host_isolation_exceptions_card.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_host_isolation_exceptions_card.test.tsx new file mode 100644 index 0000000000000..ea1937c5a98d5 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_host_isolation_exceptions_card.test.tsx @@ -0,0 +1,110 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { I18nProvider } from '@kbn/i18n/react'; +import * as reactTestingLibrary from '@testing-library/react'; +import React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { GetExceptionSummaryResponse } from '../../../../../../../../common/endpoint/types'; +import { getMockTheme } from '../../../../../../../../public/common/lib/kibana/kibana_react.mock'; +import { useToasts } from '../../../../../../../common/lib/kibana'; +import { getHostIsolationExceptionSummary } from '../../../../../host_isolation_exceptions/service'; +import { FleetHostIsolationExceptionsCard } from './fleet_host_isolation_exceptions_card'; + +jest.mock('./exception_items_summary'); +jest.mock('../../../../../host_isolation_exceptions/service'); + +jest.mock('../../../../../../../../../../../src/plugins/kibana_react/public', () => { + const originalModule = jest.requireActual( + '../../../../../../../../../../../src/plugins/kibana_react/public' + ); + const useKibana = jest.fn().mockImplementation(() => ({ + services: { + http: {}, + data: {}, + notifications: {}, + application: { + getUrlForApp: jest.fn(), + }, + }, + })); + + return { + ...originalModule, + useKibana, + }; +}); + +jest.mock('../../../../../../../common/lib/kibana'); + +const mockTheme = getMockTheme({ + eui: { + paddingSizes: { m: '2' }, + }, +}); + +const getHostIsolationExceptionSummaryMock = getHostIsolationExceptionSummary as jest.Mock; +const useToastsMock = useToasts as jest.Mock; + +const summary: GetExceptionSummaryResponse = { + windows: 3, + linux: 2, + macos: 2, + total: 7, +}; + +describe('Fleet host isolation exceptions card filters card', () => { + let promise: Promise; + let addDanger: jest.Mock = jest.fn(); + const renderComponent: () => Promise = async () => { + const Wrapper: React.FC = ({ children }) => ( + + {children} + + ); + // @ts-expect-error TS2739 + const component = reactTestingLibrary.render(, { + wrapper: Wrapper, + }); + try { + // @ts-expect-error TS2769 + await reactTestingLibrary.act(() => promise); + } catch (err) { + return component; + } + return component; + }; + beforeAll(() => { + useToastsMock.mockImplementation(() => { + return { + addDanger, + }; + }); + }); + beforeEach(() => { + promise = Promise.resolve(summary); + addDanger = jest.fn(); + }); + afterEach(() => { + getHostIsolationExceptionSummaryMock.mockReset(); + }); + it('should render correctly', async () => { + getHostIsolationExceptionSummaryMock.mockReturnValueOnce(promise); + const component = await renderComponent(); + expect(component.getByText('Host isolation exceptions')).not.toBeNull(); + expect(component.getByText('Manage')).not.toBeNull(); + }); + it('should render an error toast when api call fails', async () => { + expect(addDanger).toBeCalledTimes(0); + promise = Promise.reject(new Error('error test')); + getHostIsolationExceptionSummaryMock.mockReturnValueOnce(promise); + const component = await renderComponent(); + expect(component.getByText('Host isolation exceptions')).not.toBeNull(); + expect(component.getByText('Manage')).not.toBeNull(); + await reactTestingLibrary.waitFor(() => expect(addDanger).toBeCalledTimes(1)); + }); +}); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_host_isolation_exceptions_card.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_host_isolation_exceptions_card.tsx new file mode 100644 index 0000000000000..535c0be4736cc --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_host_isolation_exceptions_card.tsx @@ -0,0 +1,130 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { EuiPanel, EuiText } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import React, { memo, useEffect, useMemo, useRef, useState } from 'react'; +import { INTEGRATIONS_PLUGIN_ID } from '../../../../../../../../../fleet/common'; +import { + PackageCustomExtensionComponentProps, + pagePathGetters, +} from '../../../../../../../../../fleet/public'; +import { + GetExceptionSummaryResponse, + ListPageRouteState, +} from '../../../../../../../../common/endpoint/types'; +import { useKibana, useToasts } from '../../../../../../../common/lib/kibana'; +import { useAppUrl } from '../../../../../../../common/lib/kibana/hooks'; +import { getHostIsolationExceptionsListPath } from '../../../../../../common/routing'; +import { getHostIsolationExceptionSummary } from '../../../../../host_isolation_exceptions/service'; +import { ExceptionItemsSummary } from './exception_items_summary'; +import { LinkWithIcon } from './link_with_icon'; +import { StyledEuiFlexGridGroup, StyledEuiFlexGridItem } from './styled_components'; + +export const FleetHostIsolationExceptionsCard = memo( + ({ pkgkey }) => { + const { getAppUrl } = useAppUrl(); + const { + services: { http }, + } = useKibana(); + const toasts = useToasts(); + const [stats, setStats] = useState(); + const hostIsolationExceptionsListUrlPath = getHostIsolationExceptionsListPath(); + const isMounted = useRef(); + + useEffect(() => { + isMounted.current = true; + const fetchStats = async () => { + try { + const summary = await getHostIsolationExceptionSummary(http); + if (isMounted.current) { + setStats(summary); + } + } catch (error) { + if (isMounted.current) { + toasts.addDanger( + i18n.translate( + 'xpack.securitySolution.endpoint.fleetCustomExtension.hostIsolationExceptionsSummary.error', + { + defaultMessage: + 'There was an error trying to fetch host isolation exceptions stats: "{error}"', + values: { error }, + } + ) + ); + } + } + }; + fetchStats(); + return () => { + isMounted.current = false; + }; + }, [http, toasts]); + + const hostIsolationExceptionsRouteState = useMemo(() => { + const fleetPackageCustomUrlPath = `#${ + pagePathGetters.integration_details_custom({ pkgkey })[1] + }`; + return { + backButtonLabel: i18n.translate( + 'xpack.securitySolution.endpoint.fleetCustomExtension.hostIsolationExceptionsSummary.backButtonLabel', + { defaultMessage: 'Back to Endpoint Integration' } + ), + onBackButtonNavigateTo: [ + INTEGRATIONS_PLUGIN_ID, + { + path: fleetPackageCustomUrlPath, + }, + ], + backButtonUrl: getAppUrl({ + appId: INTEGRATIONS_PLUGIN_ID, + path: fleetPackageCustomUrlPath, + }), + }; + }, [getAppUrl, pkgkey]); + + return ( + + + + +

+ +

+
+
+ + + + + <> + + + + + +
+
+ ); + } +); + +FleetHostIsolationExceptionsCard.displayName = 'FleetHostIsolationExceptionsCard'; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.test.tsx index c61f109c75a1e..1da2c41324f56 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.test.tsx @@ -100,8 +100,8 @@ describe('Fleet trusted apps card', () => { }; }); const component = await renderComponent(); - expect(component.getByText('Trusted Applications')).not.toBeNull(); - expect(component.getByText('Manage trusted applications')).not.toBeNull(); + expect(component.getByText('Trusted applications')).not.toBeNull(); + expect(component.getByText('Manage')).not.toBeNull(); }); it('should render an error toast when api call fails', async () => { expect(addDanger).toBeCalledTimes(0); @@ -112,8 +112,8 @@ describe('Fleet trusted apps card', () => { }; }); const component = await renderComponent(); - expect(component.getByText('Trusted Applications')).not.toBeNull(); - expect(component.getByText('Manage trusted applications')).not.toBeNull(); + expect(component.getByText('Trusted applications')).not.toBeNull(); + expect(component.getByText('Manage')).not.toBeNull(); await reactTestingLibrary.waitFor(() => expect(addDanger).toBeCalledTimes(1)); }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.tsx index 54b1c37c7093f..680023cc6fd07 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card.tsx @@ -72,7 +72,7 @@ export const FleetTrustedAppsCard = memo( const getTitleMessage = () => ( ); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card_wrapper.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card_wrapper.tsx index 5ac79a5dd5d5a..848a0916b1d2e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card_wrapper.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/fleet_trusted_apps_card_wrapper.tsx @@ -59,8 +59,8 @@ export const FleetTrustedAppsCardWrapper = memo ), diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/styled_components.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/styled_components.tsx index ad1d823677f22..ce28b4ac6c1cc 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/styled_components.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/components/styled_components.tsx @@ -9,7 +9,7 @@ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export const StyledEuiFlexGridGroup = styled(EuiFlexGroup)` display: grid; - grid-template-columns: 25% 45% 30%; + grid-template-columns: 33% 45% 22%; grid-template-areas: 'title summary link'; `; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/index.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/index.tsx index 0748a95f63c9f..d53fe308a90ec 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_package_custom_extension/index.tsx @@ -8,8 +8,9 @@ import { EuiSpacer } from '@elastic/eui'; import React, { memo } from 'react'; import { PackageCustomExtensionComponentProps } from '../../../../../../../../fleet/public'; -import { FleetTrustedAppsCardWrapper } from './components/fleet_trusted_apps_card_wrapper'; import { FleetEventFiltersCard } from './components/fleet_event_filters_card'; +import { FleetHostIsolationExceptionsCard } from './components/fleet_host_isolation_exceptions_card'; +import { FleetTrustedAppsCardWrapper } from './components/fleet_trusted_apps_card_wrapper'; export const EndpointPackageCustomExtension = memo( (props) => { @@ -18,6 +19,8 @@ export const EndpointPackageCustomExtension = memo + +
); } diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/locked_card.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/locked_card.tsx index 150ae5e82ef55..cd13e2f933526 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/locked_card.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/locked_card.tsx @@ -35,9 +35,11 @@ export const LockedPolicyCard = memo(({ title }: { title: string }) => { } title={ diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/service/index.ts b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/service/index.ts index b59fb6cfdd2f7..2549dd5a2a4dc 100644 --- a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/service/index.ts +++ b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/service/index.ts @@ -35,9 +35,9 @@ import { } from '../../../../../common/endpoint/types'; import { resolvePathVariables } from '../../../../common/utils/resolve_path_variables'; -import { sendGetEndpointSpecificPackagePolicies } from '../../policy/store/services/ingest'; import { toUpdateTrustedApp } from '../../../../../common/endpoint/service/trusted_apps/to_update_trusted_app'; import { isGlobalEffectScope } from '../state/type_guards'; +import { sendGetEndpointSpecificPackagePolicies } from '../../../services/policies'; export interface TrustedAppsService { getTrustedApp(params: GetOneTrustedAppRequestParams): Promise; diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.test.tsx b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.test.tsx index f05d018fe8e9a..23589843c28c3 100644 --- a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.test.tsx @@ -21,10 +21,10 @@ import { import { CreateTrustedAppForm, CreateTrustedAppFormProps } from './create_trusted_app_form'; import { defaultNewTrustedApp } from '../../store/builders'; -import { forceHTMLElementOffsetWidth } from './effected_policy_select/test_utils'; import { EndpointDocGenerator } from '../../../../../../common/endpoint/generate_data'; import { useIsExperimentalFeatureEnabled } from '../../../../../common/hooks/use_experimental_features'; import { licenseService } from '../../../../../common/hooks/use_license'; +import { forceHTMLElementOffsetWidth } from '../../../../components/effected_policy_select/test_utils'; jest.mock('../../../../../common/hooks/use_experimental_features'); const useIsExperimentalFeatureEnabledMock = useIsExperimentalFeatureEnabled as jest.Mock; diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.tsx b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.tsx index da925ddd8a6c1..147529b164ae1 100644 --- a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/components/create_trusted_app_form.tsx @@ -42,13 +42,13 @@ import { import { defaultConditionEntry } from '../../store/builders'; import { OS_TITLES } from '../translations'; import { LogicalConditionBuilder, LogicalConditionBuilderProps } from './logical_condition'; +import { useTestIdGenerator } from '../../../../components/hooks/use_test_id_generator'; +import { useLicense } from '../../../../../common/hooks/use_license'; import { EffectedPolicySelect, EffectedPolicySelection, EffectedPolicySelectProps, -} from './effected_policy_select'; -import { useTestIdGenerator } from '../../../../components/hooks/use_test_id_generator'; -import { useLicense } from '../../../../../common/hooks/use_license'; +} from '../../../../components/effected_policy_select'; const OPERATING_SYSTEMS: readonly OperatingSystem[] = [ OperatingSystem.MAC, @@ -564,6 +564,13 @@ export const CreateTrustedAppForm = memo( options={policies.options} onChange={handlePolicySelectChange} isLoading={policies?.isLoading} + description={i18n.translate( + 'xpack.securitySolution.trustedApps.assignmentSectionDescription', + { + defaultMessage: + 'Assign this trusted application globally across all policies, or assign it to specific policies.', + } + )} data-test-subj={getTestId('effectedPolicies')} /> diff --git a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/trusted_apps_page.test.tsx b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/trusted_apps_page.test.tsx index 39619379a1ee0..5d78de741e459 100644 --- a/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/trusted_apps_page.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/trusted_apps/view/trusted_apps_page.test.tsx @@ -30,11 +30,11 @@ import { } from '../../../../../../fleet/common'; import { EndpointDocGenerator } from '../../../../../common/endpoint/generate_data'; import { isFailedResourceState, isLoadedResourceState } from '../state'; -import { forceHTMLElementOffsetWidth } from './components/effected_policy_select/test_utils'; import { toUpdateTrustedApp } from '../../../../../common/endpoint/service/trusted_apps/to_update_trusted_app'; import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features'; import { resolvePathVariables } from '../../../../common/utils/resolve_path_variables'; import { licenseService } from '../../../../common/hooks/use_license'; +import { forceHTMLElementOffsetWidth } from '../../../components/effected_policy_select/test_utils'; // TODO: remove this mock when feature flag is removed jest.mock('../../../../common/hooks/use_experimental_features'); diff --git a/x-pack/plugins/security_solution/public/management/services/policies.test.ts b/x-pack/plugins/security_solution/public/management/services/policies.test.ts new file mode 100644 index 0000000000000..0b93dffb71d3c --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/services/policies.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { httpServiceMock } from '../../../../../../src/core/public/mocks'; +import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../../../../fleet/common'; +import { PACKAGE_POLICY_API_ROUTES } from '../../../../fleet/common/constants/routes'; +import { sendGetEndpointSpecificPackagePolicies } from './policies'; + +describe('ingest service', () => { + let http: ReturnType; + + beforeEach(() => { + http = httpServiceMock.createStartContract(); + }); + + describe('sendGetEndpointSpecificPackagePolicies()', () => { + it('auto adds kuery to api request', async () => { + await sendGetEndpointSpecificPackagePolicies(http); + expect(http.get).toHaveBeenCalledWith(`${PACKAGE_POLICY_API_ROUTES.LIST_PATTERN}`, { + query: { + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, + }, + }); + }); + it('supports additional KQL to be defined on input for query params', async () => { + await sendGetEndpointSpecificPackagePolicies(http, { + query: { kuery: 'someValueHere', page: 1, perPage: 10 }, + }); + expect(http.get).toHaveBeenCalledWith(`${PACKAGE_POLICY_API_ROUTES.LIST_PATTERN}`, { + query: { + kuery: `someValueHere and ${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, + perPage: 10, + page: 1, + }, + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/management/services/policies.ts b/x-pack/plugins/security_solution/public/management/services/policies.ts new file mode 100644 index 0000000000000..63810ad499c09 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/services/policies.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { HttpFetchOptions, HttpStart } from 'kibana/public'; +import { + GetPackagePoliciesRequest, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, +} from '../../../../fleet/common'; +import { INGEST_API_PACKAGE_POLICIES } from '../pages/policy/store/services/ingest'; +import { GetPolicyListResponse } from '../pages/policy/types'; + +/** + * Retrieves a list of endpoint specific package policies (those created with a `package.name` of + * `endpoint`) from Ingest + * @param http + * @param options + */ +export const sendGetEndpointSpecificPackagePolicies = ( + http: HttpStart, + options: HttpFetchOptions & Partial = {} +): Promise => { + return http.get(INGEST_API_PACKAGE_POLICIES, { + ...options, + query: { + ...options.query, + kuery: `${ + options?.query?.kuery ? `${options.query.kuery} and ` : '' + }${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, + }, + }); +}; diff --git a/x-pack/plugins/security_solution/public/network/components/network_dns_table/columns.tsx b/x-pack/plugins/security_solution/public/network/components/network_dns_table/columns.tsx index 03c2442982fc9..4dcdc92983168 100644 --- a/x-pack/plugins/security_solution/public/network/components/network_dns_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/network/components/network_dns_table/columns.tsx @@ -34,7 +34,7 @@ export const getNetworkDnsColumns = (): NetworkDnsColumns => [ field: `node.${NetworkDnsFields.dnsName}`, name: i18n.REGISTERED_DOMAIN, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (dnsName) => { if (dnsName != null) { @@ -77,7 +77,7 @@ export const getNetworkDnsColumns = (): NetworkDnsColumns => [ name: i18n.TOTAL_QUERIES, sortable: true, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (queryCount) => { if (queryCount != null) { return numeral(queryCount).format('0'); @@ -92,7 +92,7 @@ export const getNetworkDnsColumns = (): NetworkDnsColumns => [ name: i18n.UNIQUE_DOMAINS, sortable: true, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (uniqueDomains) => { if (uniqueDomains != null) { return numeral(uniqueDomains).format('0'); @@ -107,7 +107,7 @@ export const getNetworkDnsColumns = (): NetworkDnsColumns => [ name: i18n.DNS_BYTES_IN, sortable: true, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (dnsBytesIn) => { if (dnsBytesIn != null) { return ; @@ -122,7 +122,7 @@ export const getNetworkDnsColumns = (): NetworkDnsColumns => [ name: i18n.DNS_BYTES_OUT, sortable: true, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (dnsBytesOut) => { if (dnsBytesOut != null) { return ; diff --git a/x-pack/plugins/security_solution/public/network/components/tls_table/columns.tsx b/x-pack/plugins/security_solution/public/network/components/tls_table/columns.tsx index 7a45c418a4ff0..6641927082b6b 100644 --- a/x-pack/plugins/security_solution/public/network/components/tls_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/network/components/tls_table/columns.tsx @@ -32,7 +32,7 @@ export const getTlsColumns = (tableId: string): TlsColumns => [ field: 'node', name: i18n.ISSUER, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: ({ _id, issuers }) => getRowItemDraggables({ @@ -45,7 +45,7 @@ export const getTlsColumns = (tableId: string): TlsColumns => [ field: 'node', name: i18n.SUBJECT, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: ({ _id, subjects }) => getRowItemDraggables({ @@ -58,7 +58,7 @@ export const getTlsColumns = (tableId: string): TlsColumns => [ field: 'node._id', name: i18n.SHA1_FINGERPRINT, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (sha1) => getRowItemDraggable({ @@ -71,7 +71,7 @@ export const getTlsColumns = (tableId: string): TlsColumns => [ field: 'node', name: i18n.JA3_FINGERPRINT, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: ({ _id, ja3 }) => getRowItemDraggables({ @@ -84,7 +84,7 @@ export const getTlsColumns = (tableId: string): TlsColumns => [ field: 'node', name: i18n.VALID_UNTIL, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: ({ _id, notAfter }) => getRowItemDraggables({ diff --git a/x-pack/plugins/security_solution/public/network/components/users_table/columns.tsx b/x-pack/plugins/security_solution/public/network/components/users_table/columns.tsx index 473d014686795..4068c616228f2 100644 --- a/x-pack/plugins/security_solution/public/network/components/users_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/network/components/users_table/columns.tsx @@ -28,7 +28,7 @@ export const getUsersColumns = (flowTarget: FlowTarget, tableId: string): UsersC field: 'node.user.name', name: i18n.USER_NAME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (userName) => getRowItemDraggable({ @@ -41,7 +41,7 @@ export const getUsersColumns = (flowTarget: FlowTarget, tableId: string): UsersC field: 'node.user.id', name: i18n.USER_ID, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (userIds) => getRowItemDraggables({ @@ -54,7 +54,7 @@ export const getUsersColumns = (flowTarget: FlowTarget, tableId: string): UsersC field: 'node.user.groupName', name: i18n.GROUP_NAME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (groupNames) => getRowItemDraggables({ @@ -67,7 +67,7 @@ export const getUsersColumns = (flowTarget: FlowTarget, tableId: string): UsersC field: 'node.user.groupId', name: i18n.GROUP_ID, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (groupId) => getRowItemDraggables({ @@ -81,7 +81,7 @@ export const getUsersColumns = (flowTarget: FlowTarget, tableId: string): UsersC field: 'node.user.count', name: i18n.DOCUMENT_COUNT, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (docCount) => defaultToEmptyTag(docCount), }, diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.tsx index 1016a430807be..7693efad0730d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.tsx @@ -66,7 +66,7 @@ const ToggleEventDetailsButtonComponent: React.FC diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/footer/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/footer/index.tsx index 80a682293dbba..c11aaa3b17370 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/footer/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/footer/index.tsx @@ -387,7 +387,7 @@ export const FooterComponent = ({ {i18n.AUTO_REFRESH_ACTIVE}{' '} ({ useTimelineEvents: jest.fn(), })); +jest.mock('./tabs_content'); + jest.mock('../../../common/lib/kibana'); jest.mock('../../../common/components/url_state/normalize_time_range.ts'); jest.mock('@kbn/i18n/react', () => { @@ -54,21 +62,29 @@ jest.mock('react-router-dom', () => { useHistory: jest.fn(), }; }); -jest.mock('../../../common/containers/sourcerer', () => { - const originalModule = jest.requireActual('../../../common/containers/sourcerer'); +const mockDispatch = jest.fn(); + +jest.mock('react-redux', () => { + const actual = jest.requireActual('react-redux'); return { - ...originalModule, - useSourcererDataView: jest.fn().mockReturnValue({ - browserFields: mockBrowserFields, - docValueFields: mockDocValueFields, - loading: false, - indexPattern: mockIndexPattern, - pageInfo: { activePage: 0, querySize: 0 }, - selectedPatterns: mockIndexNames, - }), + ...actual, + useDispatch: () => mockDispatch, }; }); + +const mockUseSourcererDataView: jest.Mock = useSourcererDataView as jest.Mock; +jest.mock('../../../common/containers/sourcerer'); +const mockDataView = { + dataViewId: mockGlobalState.timeline.timelineById.test?.dataViewId, + browserFields: mockBrowserFields, + docValueFields: mockDocValueFields, + loading: false, + indexPattern: mockIndexPattern, + pageInfo: { activePage: 0, querySize: 0 }, + selectedPatterns: mockGlobalState.timeline.timelineById.test?.indexNames, +}; +mockUseSourcererDataView.mockReturnValue(mockDataView); describe('StatefulTimeline', () => { const props: StatefulTimelineOwnProps = { renderCellValue: DefaultCellRenderer, @@ -77,6 +93,7 @@ describe('StatefulTimeline', () => { }; beforeEach(() => { + jest.clearAllMocks(); (useTimelineEvents as jest.Mock).mockReturnValue([ false, { @@ -97,6 +114,25 @@ describe('StatefulTimeline', () => { ); expect(wrapper.find('[data-test-subj="timeline"]')).toBeTruthy(); + expect(mockDispatch).toBeCalledTimes(1); + }); + + test('data view updates, updates timeline', () => { + mockUseSourcererDataView.mockReturnValue({ ...mockDataView, selectedPatterns: mockIndexNames }); + mount( + + + + ); + expect(mockDispatch).toBeCalledTimes(2); + expect(mockDispatch).toHaveBeenNthCalledWith(2, { + payload: { + id: 'test', + dataViewId: mockDataView.dataViewId, + indexNames: mockIndexNames, + }, + type: 'x-pack/security_solution/local/timeline/UPDATE_DATA_VIEW', + }); }); test(`it add attribute data-timeline-id in ${SELECTOR_TIMELINE_GLOBAL_CONTAINER}`, () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx index 48f9274fa563f..12bd3113f3ea7 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx @@ -64,9 +64,16 @@ const StatefulTimelineComponent: React.FC = ({ const getTimeline = useMemo(() => timelineSelectors.getTimelineByIdSelector(), []); const { dataViewId, selectedPatterns } = useSourcererDataView(SourcererScopeName.timeline); - const { graphEventId, savedObjectId, timelineType, description } = useDeepEqualSelector((state) => + const { + dataViewId: dataViewIdCurrent, + indexNames: selectedPatternsCurrent, + graphEventId, + savedObjectId, + timelineType, + description, + } = useDeepEqualSelector((state) => pick( - ['graphEventId', 'savedObjectId', 'timelineType', 'description'], + ['indexNames', 'dataViewId', 'graphEventId', 'savedObjectId', 'timelineType', 'description'], getTimeline(state, timelineId) ?? timelineDefaults ) ); @@ -88,6 +95,38 @@ const StatefulTimelineComponent: React.FC = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const onDataViewChange = useCallback(() => { + if ( + // initial state will get set on create + (dataViewIdCurrent === '' && selectedPatternsCurrent.length === 0) || + // don't update if no change + (dataViewIdCurrent === dataViewId && + selectedPatternsCurrent.sort().join() === selectedPatterns.sort().join()) + ) { + return; + } + + dispatch( + timelineActions.updateDataView({ + id: timelineId, + dataViewId, + indexNames: selectedPatterns, + }) + ); + }, [ + dataViewId, + dataViewIdCurrent, + dispatch, + selectedPatterns, + selectedPatternsCurrent, + timelineId, + ]); + + useEffect(() => { + onDataViewChange(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [dataViewId, selectedPatterns]); + const onSkipFocusBeforeEventsTable = useCallback(() => { const exitFullScreenButton = containerElement.current?.querySelector( EXIT_FULL_SCREEN_CLASS_NAME diff --git a/x-pack/plugins/security_solution/public/ueba/components/host_rules_table/columns.tsx b/x-pack/plugins/security_solution/public/ueba/components/host_rules_table/columns.tsx index 2638635573aa6..456a0bbe898ea 100644 --- a/x-pack/plugins/security_solution/public/ueba/components/host_rules_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/ueba/components/host_rules_table/columns.tsx @@ -24,7 +24,7 @@ export const getHostRulesColumns = (): HostRulesColumns => [ field: `node.${HostRulesFields.ruleName}`, name: i18n.NAME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (ruleName) => { if (ruleName != null && ruleName.length > 0) { const id = escapeDataProviderId(`ueba-table-ruleName-${ruleName}`); @@ -63,7 +63,7 @@ export const getHostRulesColumns = (): HostRulesColumns => [ field: `node.${HostRulesFields.ruleType}`, name: i18n.RULE_TYPE, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (ruleType) => { if (ruleType != null && ruleType.length > 0) { const id = escapeDataProviderId(`ueba-table-ruleType-${ruleType}`); @@ -102,7 +102,7 @@ export const getHostRulesColumns = (): HostRulesColumns => [ field: `node.${HostRulesFields.riskScore}`, name: i18n.RISK_SCORE, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (riskScore) => { if (riskScore != null) { const id = escapeDataProviderId(`ueba-table-riskScore-${riskScore}`); @@ -141,7 +141,7 @@ export const getHostRulesColumns = (): HostRulesColumns => [ field: `node.${HostRulesFields.hits}`, name: i18n.HITS, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (hits) => { if (hits != null) { diff --git a/x-pack/plugins/security_solution/public/ueba/components/host_tactics_table/columns.tsx b/x-pack/plugins/security_solution/public/ueba/components/host_tactics_table/columns.tsx index 19516ad6fcafa..68e1195a9c7eb 100644 --- a/x-pack/plugins/security_solution/public/ueba/components/host_tactics_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/ueba/components/host_tactics_table/columns.tsx @@ -24,7 +24,7 @@ export const getHostTacticsColumns = (): HostTacticsColumns => [ field: `node.${HostTacticsFields.tactic}`, name: i18n.TACTIC, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (tactic) => { if (tactic != null && tactic.length > 0) { const id = escapeDataProviderId(`ueba-table-tactic-${tactic}`); @@ -63,7 +63,7 @@ export const getHostTacticsColumns = (): HostTacticsColumns => [ field: `node.${HostTacticsFields.technique}`, name: i18n.TECHNIQUE, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (technique) => { if (technique != null && technique.length > 0) { const id = escapeDataProviderId(`ueba-table-technique-${technique}`); @@ -102,7 +102,7 @@ export const getHostTacticsColumns = (): HostTacticsColumns => [ field: `node.${HostTacticsFields.riskScore}`, name: i18n.RISK_SCORE, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (riskScore) => { if (riskScore != null) { const id = escapeDataProviderId(`ueba-table-riskScore-${riskScore}`); @@ -141,7 +141,7 @@ export const getHostTacticsColumns = (): HostTacticsColumns => [ field: `node.${HostTacticsFields.hits}`, name: i18n.HITS, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (hits) => { if (hits != null) { diff --git a/x-pack/plugins/security_solution/public/ueba/components/risk_score_table/columns.tsx b/x-pack/plugins/security_solution/public/ueba/components/risk_score_table/columns.tsx index b751521001fe5..43512d6717363 100644 --- a/x-pack/plugins/security_solution/public/ueba/components/risk_score_table/columns.tsx +++ b/x-pack/plugins/security_solution/public/ueba/components/risk_score_table/columns.tsx @@ -27,7 +27,7 @@ export const getRiskScoreColumns = (): RiskScoreColumns => [ field: 'node.host_name', name: i18n.NAME, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: true, render: (hostName) => { if (hostName != null && hostName.length > 0) { @@ -63,7 +63,7 @@ export const getRiskScoreColumns = (): RiskScoreColumns => [ field: 'node.risk_keyword', name: i18n.CURRENT_RISK, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, sortable: false, render: (riskKeyword) => { if (riskKeyword != null) { diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts index 384fde6c7ceac..8b0e5abad228b 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/handlers.ts @@ -11,7 +11,6 @@ import { TypeOf } from '@kbn/config-schema'; import { IKibanaResponse, IScopedClusterClient, - KibanaRequest, KibanaResponseFactory, Logger, RequestHandler, @@ -22,6 +21,7 @@ import { HostMetadata, HostResultList, HostStatus, + MetadataListResponse, } from '../../../../common/endpoint/types'; import type { SecuritySolutionRequestHandlerContext } from '../../../types'; @@ -33,7 +33,11 @@ import { import { Agent, PackagePolicy } from '../../../../../fleet/common/types/models'; import { AgentNotFoundError } from '../../../../../fleet/server'; import { EndpointAppContext, HostListQueryResult } from '../../types'; -import { GetMetadataListRequestSchema, GetMetadataRequestSchema } from './index'; +import { + GetMetadataListRequestSchema, + GetMetadataListRequestSchemaV2, + GetMetadataRequestSchema, +} from './index'; import { findAllUnenrolledAgentIds } from './support/unenroll'; import { getAllEndpointPackagePolicies } from './support/endpoint_package_policies'; import { findAgentIdsByStatus } from './support/agent_status'; @@ -125,33 +129,35 @@ export const getMetadataListRequestHandler = function ( context.core.savedObjects.client ); - body = await legacyListMetadataQuery( - context, - request, - endpointAppContext, - logger, - endpointPolicies - ); + const pagingProperties = await getPagingProperties(request, endpointAppContext); + + body = await legacyListMetadataQuery(context, endpointAppContext, logger, endpointPolicies, { + page: pagingProperties.pageIndex, + pageSize: pagingProperties.pageSize, + kuery: request?.body?.filters?.kql || '', + hostStatuses: request?.body?.filters?.host_status || [], + }); return response.ok({ body }); } // Unified index is installed and being used - perform search using new approach try { const pagingProperties = await getPagingProperties(request, endpointAppContext); - const { data, page, total, pageSize } = await endpointMetadataService.getHostMetadataList( + const { data, total } = await endpointMetadataService.getHostMetadataList( context.core.elasticsearch.client.asCurrentUser, { - page: pagingProperties.pageIndex + 1, + page: pagingProperties.pageIndex, pageSize: pagingProperties.pageSize, - filters: request.body?.filters || {}, + hostStatuses: request.body?.filters.host_status || [], + kuery: request.body?.filters.kql || '', } ); body = { hosts: data, - request_page_index: page - 1, total, - request_page_size: pageSize, + request_page_index: pagingProperties.pageIndex * pagingProperties.pageSize, + request_page_size: pagingProperties.pageSize, }; } catch (error) { return errorHandler(logger, response, error); @@ -161,6 +167,83 @@ export const getMetadataListRequestHandler = function ( }; }; +export function getMetadataListRequestHandlerV2( + endpointAppContext: EndpointAppContext, + logger: Logger +): RequestHandler< + unknown, + TypeOf, + unknown, + SecuritySolutionRequestHandlerContext +> { + return async (context, request, response) => { + const endpointMetadataService = endpointAppContext.service.getEndpointMetadataService(); + if (!endpointMetadataService) { + throw new EndpointError('endpoint metadata service not available'); + } + + let doesUnitedIndexExist = false; + let didUnitedIndexError = false; + let body: MetadataListResponse = { + data: [], + total: 0, + page: 0, + pageSize: 0, + }; + + try { + doesUnitedIndexExist = await endpointMetadataService.doesUnitedIndexExist( + context.core.elasticsearch.client.asCurrentUser + ); + } catch (error) { + // for better UX, try legacy query instead of immediately failing on united index error + didUnitedIndexError = true; + } + + // If no unified Index present, then perform a search using the legacy approach + if (!doesUnitedIndexExist || didUnitedIndexError) { + const endpointPolicies = await getAllEndpointPackagePolicies( + endpointAppContext.service.getPackagePolicyService(), + context.core.savedObjects.client + ); + + const legacyResponse = await legacyListMetadataQuery( + context, + endpointAppContext, + logger, + endpointPolicies, + request.query + ); + body = { + data: legacyResponse.hosts, + total: legacyResponse.total, + page: request.query.page, + pageSize: request.query.pageSize, + }; + return response.ok({ body }); + } + + // Unified index is installed and being used - perform search using new approach + try { + const { data, total } = await endpointMetadataService.getHostMetadataList( + context.core.elasticsearch.client.asCurrentUser, + request.query + ); + + body = { + data, + total, + page: request.query.page, + pageSize: request.query.pageSize, + }; + } catch (error) { + return errorHandler(logger, response, error); + } + + return response.ok({ body }); + }; +} + export const getMetadataRequestHandler = function ( endpointAppContext: EndpointAppContext, logger: Logger @@ -420,11 +503,10 @@ export async function enrichHostMetadata( async function legacyListMetadataQuery( context: SecuritySolutionRequestHandlerContext, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - request: KibanaRequest, endpointAppContext: EndpointAppContext, logger: Logger, - endpointPolicies: PackagePolicy[] + endpointPolicies: PackagePolicy[], + queryOptions: TypeOf ): Promise { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const agentService = endpointAppContext.service.getAgentService()!; @@ -447,14 +529,16 @@ async function legacyListMetadataQuery( endpointPolicyIds ); - const statusesToFilter = request?.body?.filters?.host_status ?? []; const statusAgentIds = await findAgentIdsByStatus( agentService, context.core.elasticsearch.client.asCurrentUser, - statusesToFilter + queryOptions.hostStatuses ); - const queryParams = await kibanaRequestToMetadataListESQuery(request, endpointAppContext, { + const queryParams = await kibanaRequestToMetadataListESQuery({ + page: queryOptions.page, + pageSize: queryOptions.pageSize, + kuery: queryOptions.kuery, unenrolledAgentIds, statusAgentIds, }); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts index d9c3e6c195307..5ea465aa21799 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts @@ -9,7 +9,12 @@ import { schema } from '@kbn/config-schema'; import { HostStatus } from '../../../../common/endpoint/types'; import { EndpointAppContext } from '../../types'; -import { getLogger, getMetadataListRequestHandler, getMetadataRequestHandler } from './handlers'; +import { + getLogger, + getMetadataListRequestHandler, + getMetadataRequestHandler, + getMetadataListRequestHandlerV2, +} from './handlers'; import type { SecuritySolutionPluginRouter } from '../../../types'; import { HOST_METADATA_GET_ROUTE, @@ -60,27 +65,54 @@ export const GetMetadataListRequestSchema = { ), }; +export const GetMetadataListRequestSchemaV2 = { + query: schema.object({ + page: schema.number({ defaultValue: 0 }), + pageSize: schema.number({ defaultValue: 10, min: 1, max: 10000 }), + kuery: schema.maybe(schema.string()), + hostStatuses: schema.arrayOf( + schema.oneOf([ + schema.literal(HostStatus.HEALTHY.toString()), + schema.literal(HostStatus.OFFLINE.toString()), + schema.literal(HostStatus.UPDATING.toString()), + schema.literal(HostStatus.UNHEALTHY.toString()), + schema.literal(HostStatus.INACTIVE.toString()), + ]), + { defaultValue: [] } + ), + }), +}; + export function registerEndpointRoutes( router: SecuritySolutionPluginRouter, endpointAppContext: EndpointAppContext ) { const logger = getLogger(endpointAppContext); - router.post( + router.get( { - path: `${HOST_METADATA_LIST_ROUTE}`, - validate: GetMetadataListRequestSchema, + path: HOST_METADATA_LIST_ROUTE, + validate: GetMetadataListRequestSchemaV2, options: { authRequired: true, tags: ['access:securitySolution'] }, }, - getMetadataListRequestHandler(endpointAppContext, logger) + getMetadataListRequestHandlerV2(endpointAppContext, logger) ); router.get( { - path: `${HOST_METADATA_GET_ROUTE}`, + path: HOST_METADATA_GET_ROUTE, validate: GetMetadataRequestSchema, options: { authRequired: true, tags: ['access:securitySolution'] }, }, getMetadataRequestHandler(endpointAppContext, logger) ); + + router.post( + { + path: HOST_METADATA_LIST_ROUTE, + validate: GetMetadataListRequestSchema, + options: { authRequired: true, tags: ['access:securitySolution'] }, + }, + getMetadataListRequestHandler(endpointAppContext, logger) + ); } diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts index c0be1c7530cb4..c1dfee0252b38 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts @@ -18,7 +18,12 @@ import { loggingSystemMock, savedObjectsClientMock, } from '../../../../../../../src/core/server/mocks'; -import { HostInfo, HostResultList, HostStatus } from '../../../../common/endpoint/types'; +import { + HostInfo, + HostResultList, + HostStatus, + MetadataListResponse, +} from '../../../../common/endpoint/types'; import { parseExperimentalConfigValue } from '../../../../common/experimental_features'; import { registerEndpointRoutes } from './index'; import { @@ -40,6 +45,7 @@ import { } from './support/test_support'; import { PackageService } from '../../../../../fleet/server/services'; import { + HOST_METADATA_GET_ROUTE, HOST_METADATA_LIST_ROUTE, metadataCurrentIndexPattern, metadataTransformPrefix, @@ -64,7 +70,7 @@ class IndexNotFoundException extends Error { } } -describe('test endpoint route', () => { +describe('test endpoint routes', () => { let routerMock: jest.Mocked; let mockResponse: jest.Mocked; let mockClusterClient: ClusterClientMock; @@ -113,552 +119,616 @@ describe('test endpoint route', () => { }); }); - describe('with .metrics-endpoint.metadata_united_default index', () => { - beforeEach(() => { - endpointAppContextService = new EndpointAppContextService(); - mockPackageService = createMockPackageService(); - mockPackageService.getInstallation.mockReturnValue( - Promise.resolve({ - installed_kibana: [], - package_assets: [], - es_index_patterns: {}, - name: '', - version: '', - install_status: 'installed', - install_version: '', - install_started_at: '', - install_source: 'registry', - installed_es: [ - { - id: 'logs-endpoint.events.security', - type: ElasticsearchAssetType.indexTemplate, - }, - { - id: `${metadataTransformPrefix}-0.16.0-dev.0`, - type: ElasticsearchAssetType.transform, - }, - ], - keep_policies_up_to_date: false, - }) - ); - endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); - endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); - mockAgentService = startContract.agentService!; - mockAgentPolicyService = startContract.agentPolicyService!; + describe('POST list endpoints route', () => { + describe('with .metrics-endpoint.metadata_united_default index', () => { + beforeEach(() => { + endpointAppContextService = new EndpointAppContextService(); + mockPackageService = createMockPackageService(); + mockPackageService.getInstallation.mockReturnValue( + Promise.resolve({ + installed_kibana: [], + package_assets: [], + es_index_patterns: {}, + name: '', + version: '', + install_status: 'installed', + install_version: '', + install_started_at: '', + install_source: 'registry', + installed_es: [ + { + id: 'logs-endpoint.events.security', + type: ElasticsearchAssetType.indexTemplate, + }, + { + id: `${metadataTransformPrefix}-0.16.0-dev.0`, + type: ElasticsearchAssetType.transform, + }, + ], + keep_policies_up_to_date: false, + }) + ); + endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); + endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); + mockAgentService = startContract.agentService!; + mockAgentPolicyService = startContract.agentPolicyService!; - registerEndpointRoutes(routerMock, { - logFactory: loggingSystemMock.create(), - service: endpointAppContextService, - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + registerEndpointRoutes(routerMock, { + logFactory: loggingSystemMock.create(), + service: endpointAppContextService, + config: () => Promise.resolve(createMockConfig()), + experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + }); }); - }); - afterEach(() => endpointAppContextService.stop()); + afterEach(() => endpointAppContextService.stop()); - it('should fallback to legacy index if index not found', async () => { - const mockRequest = httpServerMock.createKibanaRequest({}); - const response = legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ); - (mockScopedClient.asCurrentUser.search as jest.Mock) - .mockImplementationOnce(() => { - throw new IndexNotFoundException(); - }) - .mockImplementationOnce(() => Promise.resolve({ body: response })); - [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) - )!; - mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); - mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); - await routeHandler( - createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), - mockRequest, - mockResponse - ); + it('should fallback to legacy index if index not found', async () => { + const mockRequest = httpServerMock.createKibanaRequest({}); + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); + }) + .mockImplementationOnce(() => Promise.resolve({ body: response })); + [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_LIST_ROUTE) + )!; + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); - const esSearchMock = mockScopedClient.asCurrentUser.search; - // should be called twice, united index first, then legacy index - expect(esSearchMock).toHaveBeenCalledTimes(2); - expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); - expect(esSearchMock.mock.calls[1][0]?.index).toEqual(metadataCurrentIndexPattern); - expect(routeConfig.options).toEqual({ - authRequired: true, - tags: ['access:securitySolution'], + const esSearchMock = mockScopedClient.asCurrentUser.search; + // should be called twice, united index first, then legacy index + expect(esSearchMock).toHaveBeenCalledTimes(2); + expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); + expect(esSearchMock.mock.calls[1][0]?.index).toEqual(metadataCurrentIndexPattern); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; + expect(endpointResultList.hosts.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.request_page_index).toEqual(0); + expect(endpointResultList.request_page_size).toEqual(10); }); - expect(mockResponse.ok).toBeCalled(); - const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; - expect(endpointResultList.hosts.length).toEqual(1); - expect(endpointResultList.total).toEqual(1); - expect(endpointResultList.request_page_index).toEqual(0); - expect(endpointResultList.request_page_size).toEqual(10); - }); - it('should return expected metadata', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ - body: { - paging_properties: [ - { - page_size: 10, - }, - { - page_index: 0, - }, - ], + it('should return expected metadata', async () => { + const mockRequest = httpServerMock.createKibanaRequest({ + body: { + paging_properties: [ + { + page_size: 10, + }, + { + page_index: 0, + }, + ], - filters: { - kql: 'not host.ip:10.140.73.246', - host_status: ['updating'], + filters: { + kql: 'not host.ip:10.140.73.246', + host_status: ['updating'], + }, }, - }, - }); + }); - mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); - mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); - mockAgentPolicyService.getByIds = jest.fn().mockResolvedValueOnce([]); - const metadata = new EndpointDocGenerator().generateHostMetadata(); - const esSearchMock = mockScopedClient.asCurrentUser.search as jest.Mock; - esSearchMock.mockResolvedValueOnce({}); - esSearchMock.mockResolvedValueOnce({ - body: unitedMetadataSearchResponseMock(metadata), - }); - [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) - )!; + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + mockAgentPolicyService.getByIds = jest.fn().mockResolvedValueOnce([]); + const metadata = new EndpointDocGenerator().generateHostMetadata(); + const esSearchMock = mockScopedClient.asCurrentUser.search as jest.Mock; + esSearchMock.mockResolvedValueOnce({}); + esSearchMock.mockResolvedValueOnce({ + body: unitedMetadataSearchResponseMock(metadata), + }); + [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_LIST_ROUTE) + )!; - await routeHandler( - createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), - mockRequest, - mockResponse - ); + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); - expect(esSearchMock).toHaveBeenCalledTimes(2); - expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); - expect(esSearchMock.mock.calls[0][0]?.size).toEqual(1); - expect(esSearchMock.mock.calls[1][0]?.index).toEqual(METADATA_UNITED_INDEX); - expect(esSearchMock.mock.calls[1][0]?.body?.query).toEqual({ - bool: { - must: [ - { - bool: { - filter: [ - { - terms: { - 'united.agent.policy_id': [], + expect(esSearchMock).toHaveBeenCalledTimes(2); + expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); + expect(esSearchMock.mock.calls[0][0]?.size).toEqual(1); + expect(esSearchMock.mock.calls[1][0]?.index).toEqual(METADATA_UNITED_INDEX); + expect(esSearchMock.mock.calls[1][0]?.body?.query).toEqual({ + bool: { + must: [ + { + bool: { + filter: [ + { + terms: { + 'united.agent.policy_id': [], + }, }, - }, - { - exists: { - field: 'united.endpoint.agent.id', + { + exists: { + field: 'united.endpoint.agent.id', + }, }, - }, - { - exists: { - field: 'united.agent.agent.id', + { + exists: { + field: 'united.agent.agent.id', + }, }, - }, - { - term: { - 'united.agent.active': { - value: true, + { + term: { + 'united.agent.active': { + value: true, + }, }, }, - }, - ], - must_not: { - terms: { - 'agent.id': [ - '00000000-0000-0000-0000-000000000000', - '11111111-1111-1111-1111-111111111111', - ], + ], + must_not: { + terms: { + 'agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, }, }, }, - }, - { - bool: { - should: [ - { - bool: { - filter: [ - { + { + bool: { + should: [ + { + bool: { + filter: [ + { + bool: { + should: [ + { + exists: { + field: 'united.agent.upgrade_started_at', + }, + }, + ], + minimum_should_match: 1, + }, + }, + { + bool: { + must_not: { + bool: { + should: [ + { + exists: { + field: 'united.agent.upgraded_at', + }, + }, + ], + minimum_should_match: 1, + }, + }, + }, + }, + ], + }, + }, + { + bool: { + must_not: { bool: { should: [ { exists: { - field: 'united.agent.upgrade_started_at', + field: 'united.agent.last_checkin', }, }, ], minimum_should_match: 1, }, }, - { - bool: { - must_not: { - bool: { - should: [ - { - exists: { - field: 'united.agent.upgraded_at', - }, - }, - ], - minimum_should_match: 1, - }, - }, - }, - }, - ], + }, }, - }, - { - bool: { - must_not: { - bool: { - should: [ - { - exists: { - field: 'united.agent.last_checkin', - }, + { + bool: { + should: [ + { + exists: { + field: 'united.agent.unenrollment_started_at', }, - ], - minimum_should_match: 1, - }, + }, + ], + minimum_should_match: 1, }, }, - }, - { + ], + minimum_should_match: 1, + }, + }, + { + bool: { + must_not: { bool: { should: [ { - exists: { - field: 'united.agent.unenrollment_started_at', + match: { + 'host.ip': '10.140.73.246', }, }, ], minimum_should_match: 1, }, }, - ], - minimum_should_match: 1, - }, - }, - { - bool: { - must_not: { - bool: { - should: [ - { - match: { - 'host.ip': '10.140.73.246', - }, - }, - ], - minimum_should_match: 1, - }, }, }, - }, - ], - }, - }); - expect(routeConfig.options).toEqual({ - authRequired: true, - tags: ['access:securitySolution'], + ], + }, + }); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; + expect(endpointResultList.hosts.length).toEqual(1); + expect(endpointResultList.hosts[0].metadata).toEqual(metadata); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.request_page_index).toEqual(0); + expect(endpointResultList.request_page_size).toEqual(10); }); - expect(mockResponse.ok).toBeCalled(); - const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; - expect(endpointResultList.hosts.length).toEqual(1); - expect(endpointResultList.hosts[0].metadata).toEqual(metadata); - expect(endpointResultList.total).toEqual(1); - expect(endpointResultList.request_page_index).toEqual(0); - expect(endpointResultList.request_page_size).toEqual(10); }); - }); - describe('with metrics-endpoint.metadata_current_default index', () => { - beforeEach(() => { - endpointAppContextService = new EndpointAppContextService(); - mockPackageService = createMockPackageService(); - mockPackageService.getInstallation.mockReturnValue( - Promise.resolve({ - installed_kibana: [], - package_assets: [], - es_index_patterns: {}, - name: '', - version: '', - install_status: 'installed', - install_version: '', - install_started_at: '', - install_source: 'registry', - installed_es: [ - { - id: 'logs-endpoint.events.security', - type: ElasticsearchAssetType.indexTemplate, - }, - { - id: `${metadataTransformPrefix}-0.16.0-dev.0`, - type: ElasticsearchAssetType.transform, - }, - ], - keep_policies_up_to_date: false, - }) - ); - endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); - endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); - mockAgentService = startContract.agentService!; + describe('with metrics-endpoint.metadata_current_default index', () => { + beforeEach(() => { + endpointAppContextService = new EndpointAppContextService(); + mockPackageService = createMockPackageService(); + mockPackageService.getInstallation.mockReturnValue( + Promise.resolve({ + installed_kibana: [], + package_assets: [], + es_index_patterns: {}, + name: '', + version: '', + install_status: 'installed', + install_version: '', + install_started_at: '', + install_source: 'registry', + installed_es: [ + { + id: 'logs-endpoint.events.security', + type: ElasticsearchAssetType.indexTemplate, + }, + { + id: `${metadataTransformPrefix}-0.16.0-dev.0`, + type: ElasticsearchAssetType.transform, + }, + ], + keep_policies_up_to_date: false, + }) + ); + endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); + endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); + mockAgentService = startContract.agentService!; - registerEndpointRoutes(routerMock, { - logFactory: loggingSystemMock.create(), - service: endpointAppContextService, - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + registerEndpointRoutes(routerMock, { + logFactory: loggingSystemMock.create(), + service: endpointAppContextService, + config: () => Promise.resolve(createMockConfig()), + experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + }); }); - }); - afterEach(() => endpointAppContextService.stop()); + afterEach(() => endpointAppContextService.stop()); - it('test find the latest of all endpoints', async () => { - const mockRequest = httpServerMock.createKibanaRequest({}); - const response = legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ); - (mockScopedClient.asCurrentUser.search as jest.Mock) - .mockImplementationOnce(() => { - throw new IndexNotFoundException(); - }) - .mockImplementationOnce(() => Promise.resolve({ body: response })); - [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) - )!; - mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); - mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); - await routeHandler( - createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), - mockRequest, - mockResponse - ); + it('test find the latest of all endpoints', async () => { + const mockRequest = httpServerMock.createKibanaRequest({}); + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); + }) + .mockImplementationOnce(() => Promise.resolve({ body: response })); + [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_LIST_ROUTE) + )!; + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(2); - expect(routeConfig.options).toEqual({ - authRequired: true, - tags: ['access:securitySolution'], - }); - expect(mockResponse.ok).toBeCalled(); - const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; - expect(endpointResultList.hosts.length).toEqual(1); - expect(endpointResultList.total).toEqual(1); - expect(endpointResultList.request_page_index).toEqual(0); - expect(endpointResultList.request_page_size).toEqual(10); - }); - - it('test find the latest of all endpoints with paging properties', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ - body: { - paging_properties: [ - { - page_size: 10, - }, - { - page_index: 1, - }, - ], - }, + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(2); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; + expect(endpointResultList.hosts.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.request_page_index).toEqual(0); + expect(endpointResultList.request_page_size).toEqual(10); }); - mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); - mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); - (mockScopedClient.asCurrentUser.search as jest.Mock) - .mockImplementationOnce(() => { - throw new IndexNotFoundException(); - }) - .mockImplementationOnce(() => - Promise.resolve({ - body: legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ), + it('test find the latest of all endpoints with paging properties', async () => { + const mockRequest = httpServerMock.createKibanaRequest({ + body: { + paging_properties: [ + { + page_size: 10, + }, + { + page_index: 1, + }, + ], + }, + }); + + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); }) - ); - [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) - )!; + .mockImplementationOnce(() => + Promise.resolve({ + body: legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ), + }) + ); + [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_LIST_ROUTE) + )!; - await routeHandler( - createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), - mockRequest, - mockResponse - ); - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(2); - expect( - (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool - .must_not - ).toContainEqual({ - terms: { - 'elastic.agent.id': [ - '00000000-0000-0000-0000-000000000000', - '11111111-1111-1111-1111-111111111111', - ], - }, - }); - expect(routeConfig.options).toEqual({ - authRequired: true, - tags: ['access:securitySolution'], + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(2); + expect( + (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool + .must_not + ).toContainEqual({ + terms: { + 'elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; + expect(endpointResultList.hosts.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.request_page_index).toEqual(10); + expect(endpointResultList.request_page_size).toEqual(10); }); - expect(mockResponse.ok).toBeCalled(); - const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; - expect(endpointResultList.hosts.length).toEqual(1); - expect(endpointResultList.total).toEqual(1); - expect(endpointResultList.request_page_index).toEqual(10); - expect(endpointResultList.request_page_size).toEqual(10); - }); - it('test find the latest of all endpoints with paging and filters properties', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ - body: { - paging_properties: [ - { - page_size: 10, - }, - { - page_index: 1, - }, - ], + it('test find the latest of all endpoints with paging and filters properties', async () => { + const mockRequest = httpServerMock.createKibanaRequest({ + body: { + paging_properties: [ + { + page_size: 10, + }, + { + page_index: 1, + }, + ], - filters: { kql: 'not host.ip:10.140.73.246' }, - }, - }); + filters: { kql: 'not host.ip:10.140.73.246' }, + }, + }); - mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); - mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); - (mockScopedClient.asCurrentUser.search as jest.Mock) - .mockImplementationOnce(() => { - throw new IndexNotFoundException(); - }) - .mockImplementationOnce(() => - Promise.resolve({ - body: legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ), + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); }) - ); - [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) - )!; + .mockImplementationOnce(() => + Promise.resolve({ + body: legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ), + }) + ); + [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_LIST_ROUTE) + )!; - await routeHandler( - createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), - mockRequest, - mockResponse - ); + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); - expect(mockScopedClient.asCurrentUser.search).toBeCalled(); - expect( - // KQL filter to be passed through - (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool.must - ).toContainEqual({ - bool: { - must_not: { - bool: { - should: [ - { - match: { - 'host.ip': '10.140.73.246', + expect(mockScopedClient.asCurrentUser.search).toBeCalled(); + expect( + // KQL filter to be passed through + (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool + .must + ).toContainEqual({ + bool: { + must_not: { + bool: { + should: [ + { + match: { + 'host.ip': '10.140.73.246', + }, }, - }, - ], - minimum_should_match: 1, - }, - }, - }, - }); - expect( - (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool.must - ).toContainEqual({ - bool: { - must_not: [ - { - terms: { - 'elastic.agent.id': [ - '00000000-0000-0000-0000-000000000000', - '11111111-1111-1111-1111-111111111111', ], + minimum_should_match: 1, }, }, - { - terms: { - // here we DO want to see both schemas are present - // to make this schema-compatible forward and back - 'HostDetails.elastic.agent.id': [ - '00000000-0000-0000-0000-000000000000', - '11111111-1111-1111-1111-111111111111', - ], + }, + }); + expect( + (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool + .must + ).toContainEqual({ + bool: { + must_not: [ + { + terms: { + 'elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, }, - }, - ], - }, - }); - expect(routeConfig.options).toEqual({ - authRequired: true, - tags: ['access:securitySolution'], + { + terms: { + // here we DO want to see both schemas are present + // to make this schema-compatible forward and back + 'HostDetails.elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }, + ], + }, + }); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; + expect(endpointResultList.hosts.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.request_page_index).toEqual(10); + expect(endpointResultList.request_page_size).toEqual(10); }); - expect(mockResponse.ok).toBeCalled(); - const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as HostResultList; - expect(endpointResultList.hosts.length).toEqual(1); - expect(endpointResultList.total).toEqual(1); - expect(endpointResultList.request_page_index).toEqual(10); - expect(endpointResultList.request_page_size).toEqual(10); }); + }); - describe('Endpoint Details route', () => { - it('should return 404 on no results', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ params: { id: 'BADID' } }); - - (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => - Promise.resolve({ body: legacyMetadataSearchResponseMock() }) + describe('GET list endpoints route', () => { + describe('with .metrics-endpoint.metadata_united_default index', () => { + beforeEach(() => { + endpointAppContextService = new EndpointAppContextService(); + mockPackageService = createMockPackageService(); + mockPackageService.getInstallation.mockReturnValue( + Promise.resolve({ + installed_kibana: [], + package_assets: [], + es_index_patterns: {}, + name: '', + version: '', + install_status: 'installed', + install_version: '', + install_started_at: '', + install_source: 'registry', + installed_es: [ + { + id: 'logs-endpoint.events.security', + type: ElasticsearchAssetType.indexTemplate, + }, + { + id: `${metadataTransformPrefix}-0.16.0-dev.0`, + type: ElasticsearchAssetType.transform, + }, + ], + keep_policies_up_to_date: false, + }) ); + endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); + endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); + mockAgentService = startContract.agentService!; + mockAgentPolicyService = startContract.agentPolicyService!; - mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); - mockAgentService.getAgent = jest.fn().mockReturnValue({ - active: true, - } as unknown as Agent); + registerEndpointRoutes(routerMock, { + logFactory: loggingSystemMock.create(), + service: endpointAppContextService, + config: () => Promise.resolve(createMockConfig()), + experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + }); + }); + + afterEach(() => endpointAppContextService.stop()); + it('should fallback to legacy index if index not found', async () => { + const mockRequest = httpServerMock.createKibanaRequest({ + query: { + page: 0, + pageSize: 10, + }, + }); + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); + }) + .mockImplementationOnce(() => Promise.resolve({ body: response })); [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) + path.startsWith(HOST_METADATA_LIST_ROUTE) )!; + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); await routeHandler( createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), mockRequest, mockResponse ); - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + const esSearchMock = mockScopedClient.asCurrentUser.search; + // should be called twice, united index first, then legacy index + expect(esSearchMock).toHaveBeenCalledTimes(2); + expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); + expect(esSearchMock.mock.calls[1][0]?.index).toEqual(metadataCurrentIndexPattern); expect(routeConfig.options).toEqual({ authRequired: true, tags: ['access:securitySolution'], }); - expect(mockResponse.notFound).toBeCalled(); - const message = mockResponse.notFound.mock.calls[0][0]?.body; - expect(message).toBeInstanceOf(EndpointHostNotFoundError); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as MetadataListResponse; + expect(endpointResultList.data.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.page).toEqual(0); + expect(endpointResultList.pageSize).toEqual(10); }); - it('should return a single endpoint with status healthy', async () => { - const response = legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ); + it('should return expected metadata', async () => { const mockRequest = httpServerMock.createKibanaRequest({ - params: { id: response.hits.hits[0]._id }, + query: { + page: 0, + pageSize: 10, + hostStatuses: ['updating'], + kuery: 'not host.ip:10.140.73.246', + }, }); - mockAgentService.getAgent = jest - .fn() - .mockReturnValue(agentGenerator.generate({ status: 'online' })); - (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => - Promise.resolve({ body: response }) - ); - + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + mockAgentPolicyService.getByIds = jest.fn().mockResolvedValueOnce([]); + const metadata = new EndpointDocGenerator().generateHostMetadata(); + const esSearchMock = mockScopedClient.asCurrentUser.search as jest.Mock; + esSearchMock.mockResolvedValueOnce({}); + esSearchMock.mockResolvedValueOnce({ + body: unitedMetadataSearchResponseMock(metadata), + }); [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) + path.startsWith(HOST_METADATA_LIST_ROUTE) )!; await routeHandler( @@ -667,74 +737,255 @@ describe('test endpoint route', () => { mockResponse ); - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(esSearchMock).toHaveBeenCalledTimes(2); + expect(esSearchMock.mock.calls[0][0]?.index).toEqual(METADATA_UNITED_INDEX); + expect(esSearchMock.mock.calls[0][0]?.size).toEqual(1); + expect(esSearchMock.mock.calls[1][0]?.index).toEqual(METADATA_UNITED_INDEX); + expect(esSearchMock.mock.calls[1][0]?.body?.query).toEqual({ + bool: { + must: [ + { + bool: { + filter: [ + { + terms: { + 'united.agent.policy_id': [], + }, + }, + { + exists: { + field: 'united.endpoint.agent.id', + }, + }, + { + exists: { + field: 'united.agent.agent.id', + }, + }, + { + term: { + 'united.agent.active': { + value: true, + }, + }, + }, + ], + must_not: { + terms: { + 'agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }, + }, + }, + { + bool: { + should: [ + { + bool: { + filter: [ + { + bool: { + should: [ + { + exists: { + field: 'united.agent.upgrade_started_at', + }, + }, + ], + minimum_should_match: 1, + }, + }, + { + bool: { + must_not: { + bool: { + should: [ + { + exists: { + field: 'united.agent.upgraded_at', + }, + }, + ], + minimum_should_match: 1, + }, + }, + }, + }, + ], + }, + }, + { + bool: { + must_not: { + bool: { + should: [ + { + exists: { + field: 'united.agent.last_checkin', + }, + }, + ], + minimum_should_match: 1, + }, + }, + }, + }, + { + bool: { + should: [ + { + exists: { + field: 'united.agent.unenrollment_started_at', + }, + }, + ], + minimum_should_match: 1, + }, + }, + ], + minimum_should_match: 1, + }, + }, + { + bool: { + must_not: { + bool: { + should: [ + { + match: { + 'host.ip': '10.140.73.246', + }, + }, + ], + minimum_should_match: 1, + }, + }, + }, + }, + ], + }, + }); expect(routeConfig.options).toEqual({ authRequired: true, tags: ['access:securitySolution'], }); expect(mockResponse.ok).toBeCalled(); - const result = mockResponse.ok.mock.calls[0][0]?.body as HostInfo; - expect(result).toHaveProperty('metadata.Endpoint'); - expect(result.host_status).toEqual(HostStatus.HEALTHY); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as MetadataListResponse; + expect(endpointResultList.data.length).toEqual(1); + expect(endpointResultList.data[0].metadata).toEqual(metadata); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.page).toEqual(0); + expect(endpointResultList.pageSize).toEqual(10); }); + }); - it('should return a single endpoint with status unhealthy when AgentService throw 404', async () => { - const response = legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() + describe('with metrics-endpoint.metadata_current_default index', () => { + beforeEach(() => { + endpointAppContextService = new EndpointAppContextService(); + mockPackageService = createMockPackageService(); + mockPackageService.getInstallation.mockReturnValue( + Promise.resolve({ + installed_kibana: [], + package_assets: [], + es_index_patterns: {}, + name: '', + version: '', + install_status: 'installed', + install_version: '', + install_started_at: '', + install_source: 'registry', + installed_es: [ + { + id: 'logs-endpoint.events.security', + type: ElasticsearchAssetType.indexTemplate, + }, + { + id: `${metadataTransformPrefix}-0.16.0-dev.0`, + type: ElasticsearchAssetType.transform, + }, + ], + keep_policies_up_to_date: false, + }) ); + endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); + endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); + mockAgentService = startContract.agentService!; - const mockRequest = httpServerMock.createKibanaRequest({ - params: { id: response.hits.hits[0]._id }, + registerEndpointRoutes(routerMock, { + logFactory: loggingSystemMock.create(), + service: endpointAppContextService, + config: () => Promise.resolve(createMockConfig()), + experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), }); + }); - mockAgentService.getAgent = jest - .fn() - .mockRejectedValue(new AgentNotFoundError('not found')); + afterEach(() => endpointAppContextService.stop()); - (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => - Promise.resolve({ body: response }) + it('test find the latest of all endpoints', async () => { + const mockRequest = httpServerMock.createKibanaRequest({ + query: { + page: 0, + pageSize: 10, + }, + }); + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() ); - + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); + }) + .mockImplementationOnce(() => Promise.resolve({ body: response })); [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) + path.startsWith(HOST_METADATA_LIST_ROUTE) )!; - + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); await routeHandler( createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), mockRequest, mockResponse ); - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(2); expect(routeConfig.options).toEqual({ authRequired: true, tags: ['access:securitySolution'], }); expect(mockResponse.ok).toBeCalled(); - const result = mockResponse.ok.mock.calls[0][0]?.body as HostInfo; - expect(result.host_status).toEqual(HostStatus.UNHEALTHY); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as MetadataListResponse; + expect(endpointResultList.data.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.page).toEqual(0); + expect(endpointResultList.pageSize).toEqual(10); }); - it('should return a single endpoint with status unhealthy when status is not offline, online or enrolling', async () => { - const response = legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ); - + it('test find the latest of all endpoints with paging properties', async () => { const mockRequest = httpServerMock.createKibanaRequest({ - params: { id: response.hits.hits[0]._id }, + query: { + page: 1, + pageSize: 10, + }, }); - mockAgentService.getAgent = jest.fn().mockReturnValue( - agentGenerator.generate({ - status: 'error', + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); }) - ); - (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => - Promise.resolve({ body: response }) - ); - + .mockImplementationOnce(() => + Promise.resolve({ + body: legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ), + }) + ); [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) + path.startsWith(HOST_METADATA_LIST_ROUTE) )!; await routeHandler( @@ -742,34 +993,54 @@ describe('test endpoint route', () => { mockRequest, mockResponse ); - - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(2); + expect( + (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool + .must_not + ).toContainEqual({ + terms: { + 'elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }); expect(routeConfig.options).toEqual({ authRequired: true, tags: ['access:securitySolution'], }); expect(mockResponse.ok).toBeCalled(); - const result = mockResponse.ok.mock.calls[0][0]?.body as HostInfo; - expect(result.host_status).toEqual(HostStatus.UNHEALTHY); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as MetadataListResponse; + expect(endpointResultList.data.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.page).toEqual(1); + expect(endpointResultList.pageSize).toEqual(10); }); - it('should throw error when endpoint agent is not active', async () => { - const response = legacyMetadataSearchResponseMock( - new EndpointDocGenerator().generateHostMetadata() - ); - + it('test find the latest of all endpoints with paging and filters properties', async () => { const mockRequest = httpServerMock.createKibanaRequest({ - params: { id: response.hits.hits[0]._id }, + query: { + page: 1, + pageSize: 10, + kuery: 'not host.ip:10.140.73.246', + }, }); - (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => - Promise.resolve({ body: response }) - ); - mockAgentService.getAgent = jest.fn().mockReturnValue({ - active: false, - } as unknown as Agent); + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.listAgents = jest.fn().mockReturnValue(noUnenrolledAgent); + (mockScopedClient.asCurrentUser.search as jest.Mock) + .mockImplementationOnce(() => { + throw new IndexNotFoundException(); + }) + .mockImplementationOnce(() => + Promise.resolve({ + body: legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ), + }) + ); [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => - path.startsWith(`${HOST_METADATA_LIST_ROUTE}`) + path.startsWith(HOST_METADATA_LIST_ROUTE) )!; await routeHandler( @@ -778,9 +1049,277 @@ describe('test endpoint route', () => { mockResponse ); - expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); - expect(mockResponse.badRequest).toBeCalled(); + expect(mockScopedClient.asCurrentUser.search).toBeCalled(); + expect( + // KQL filter to be passed through + (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool + .must + ).toContainEqual({ + bool: { + must_not: { + bool: { + should: [ + { + match: { + 'host.ip': '10.140.73.246', + }, + }, + ], + minimum_should_match: 1, + }, + }, + }, + }); + expect( + (mockScopedClient.asCurrentUser.search as jest.Mock).mock.calls[1][0]?.body?.query.bool + .must + ).toContainEqual({ + bool: { + must_not: [ + { + terms: { + 'elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }, + { + terms: { + // here we DO want to see both schemas are present + // to make this schema-compatible forward and back + 'HostDetails.elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }, + ], + }, + }); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const endpointResultList = mockResponse.ok.mock.calls[0][0]?.body as MetadataListResponse; + expect(endpointResultList.data.length).toEqual(1); + expect(endpointResultList.total).toEqual(1); + expect(endpointResultList.page).toEqual(1); + expect(endpointResultList.pageSize).toEqual(10); + }); + }); + }); + + describe('GET endpoint details route', () => { + beforeEach(() => { + endpointAppContextService = new EndpointAppContextService(); + mockPackageService = createMockPackageService(); + mockPackageService.getInstallation.mockReturnValue( + Promise.resolve({ + installed_kibana: [], + package_assets: [], + es_index_patterns: {}, + name: '', + version: '', + install_status: 'installed', + install_version: '', + install_started_at: '', + install_source: 'registry', + installed_es: [ + { + id: 'logs-endpoint.events.security', + type: ElasticsearchAssetType.indexTemplate, + }, + { + id: `${metadataTransformPrefix}-0.16.0-dev.0`, + type: ElasticsearchAssetType.transform, + }, + ], + keep_policies_up_to_date: false, + }) + ); + endpointAppContextService.setup(createMockEndpointAppContextServiceSetupContract()); + endpointAppContextService.start({ ...startContract, packageService: mockPackageService }); + mockAgentService = startContract.agentService!; + + registerEndpointRoutes(routerMock, { + logFactory: loggingSystemMock.create(), + service: endpointAppContextService, + config: () => Promise.resolve(createMockConfig()), + experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + }); + }); + + afterEach(() => endpointAppContextService.stop()); + + it('should return 404 on no results', async () => { + const mockRequest = httpServerMock.createKibanaRequest({ params: { id: 'BADID' } }); + + (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => + Promise.resolve({ body: legacyMetadataSearchResponseMock() }) + ); + + mockAgentService.getAgentStatusById = jest.fn().mockReturnValue('error'); + mockAgentService.getAgent = jest.fn().mockReturnValue({ + active: true, + } as unknown as Agent); + + [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_GET_ROUTE) + )!; + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); + + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.notFound).toBeCalled(); + const message = mockResponse.notFound.mock.calls[0][0]?.body; + expect(message).toBeInstanceOf(EndpointHostNotFoundError); + }); + + it('should return a single endpoint with status healthy', async () => { + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + const mockRequest = httpServerMock.createKibanaRequest({ + params: { id: response.hits.hits[0]._id }, }); + + mockAgentService.getAgent = jest + .fn() + .mockReturnValue(agentGenerator.generate({ status: 'online' })); + (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => + Promise.resolve({ body: response }) + ); + + [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_GET_ROUTE) + )!; + + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); + + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const result = mockResponse.ok.mock.calls[0][0]?.body as HostInfo; + expect(result).toHaveProperty('metadata.Endpoint'); + expect(result.host_status).toEqual(HostStatus.HEALTHY); + }); + + it('should return a single endpoint with status unhealthy when AgentService throw 404', async () => { + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + + const mockRequest = httpServerMock.createKibanaRequest({ + params: { id: response.hits.hits[0]._id }, + }); + + mockAgentService.getAgent = jest.fn().mockRejectedValue(new AgentNotFoundError('not found')); + + (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => + Promise.resolve({ body: response }) + ); + + [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_GET_ROUTE) + )!; + + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); + + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const result = mockResponse.ok.mock.calls[0][0]?.body as HostInfo; + expect(result.host_status).toEqual(HostStatus.UNHEALTHY); + }); + + it('should return a single endpoint with status unhealthy when status is not offline, online or enrolling', async () => { + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + + const mockRequest = httpServerMock.createKibanaRequest({ + params: { id: response.hits.hits[0]._id }, + }); + + mockAgentService.getAgent = jest.fn().mockReturnValue( + agentGenerator.generate({ + status: 'error', + }) + ); + (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => + Promise.resolve({ body: response }) + ); + + [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_GET_ROUTE) + )!; + + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); + + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(routeConfig.options).toEqual({ + authRequired: true, + tags: ['access:securitySolution'], + }); + expect(mockResponse.ok).toBeCalled(); + const result = mockResponse.ok.mock.calls[0][0]?.body as HostInfo; + expect(result.host_status).toEqual(HostStatus.UNHEALTHY); + }); + + it('should throw error when endpoint agent is not active', async () => { + const response = legacyMetadataSearchResponseMock( + new EndpointDocGenerator().generateHostMetadata() + ); + + const mockRequest = httpServerMock.createKibanaRequest({ + params: { id: response.hits.hits[0]._id }, + }); + (mockScopedClient.asCurrentUser.search as jest.Mock).mockImplementationOnce(() => + Promise.resolve({ body: response }) + ); + mockAgentService.getAgent = jest.fn().mockReturnValue({ + active: false, + } as unknown as Agent); + + [routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) => + path.startsWith(HOST_METADATA_GET_ROUTE) + )!; + + await routeHandler( + createRouteHandlerContext(mockScopedClient, mockSavedObjectClient), + mockRequest, + mockResponse + ); + + expect(mockScopedClient.asCurrentUser.search).toHaveBeenCalledTimes(1); + expect(mockResponse.badRequest).toBeCalled(); }); }); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts index a0cb5aad552d2..0a8f2616c516f 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.test.ts @@ -5,39 +5,35 @@ * 2.0. */ -import { httpServerMock, loggingSystemMock } from '../../../../../../../src/core/server/mocks'; import { kibanaRequestToMetadataListESQuery, getESQueryHostMetadataByID, buildUnitedIndexQuery, } from './query_builders'; -import { EndpointAppContextService } from '../../endpoint_app_context_services'; -import { createMockConfig } from '../../../lib/detection_engine/routes/__mocks__'; import { metadataCurrentIndexPattern } from '../../../../common/endpoint/constants'; -import { parseExperimentalConfigValue } from '../../../../common/experimental_features'; import { get } from 'lodash'; import { expectedCompleteUnitedIndexQuery } from './query_builders.fixtures'; describe('query builder', () => { describe('MetadataListESQuery', () => { it('queries the correct index', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ body: {} }); - const query = await kibanaRequestToMetadataListESQuery(mockRequest, { - logFactory: loggingSystemMock.create(), - service: new EndpointAppContextService(), - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + const query = await kibanaRequestToMetadataListESQuery({ + page: 0, + pageSize: 10, + kuery: '', + unenrolledAgentIds: [], + statusAgentIds: [], }); expect(query.index).toEqual(metadataCurrentIndexPattern); }); it('sorts using *event.created', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ body: {} }); - const query = await kibanaRequestToMetadataListESQuery(mockRequest, { - logFactory: loggingSystemMock.create(), - service: new EndpointAppContextService(), - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + const query = await kibanaRequestToMetadataListESQuery({ + page: 0, + pageSize: 10, + kuery: '', + unenrolledAgentIds: [], + statusAgentIds: [], }); expect(query.body.sort).toContainEqual({ 'event.created': { @@ -55,21 +51,13 @@ describe('query builder', () => { it('excludes unenrolled elastic agents when they exist, by default', async () => { const unenrolledElasticAgentId = '1fdca33f-799f-49f4-939c-ea4383c77672'; - const mockRequest = httpServerMock.createKibanaRequest({ - body: {}, + const query = await kibanaRequestToMetadataListESQuery({ + page: 0, + pageSize: 10, + kuery: '', + unenrolledAgentIds: [unenrolledElasticAgentId], + statusAgentIds: [], }); - const query = await kibanaRequestToMetadataListESQuery( - mockRequest, - { - logFactory: loggingSystemMock.create(), - service: new EndpointAppContextService(), - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), - }, - { - unenrolledAgentIds: [unenrolledElasticAgentId], - } - ); expect(query.body.query).toEqual({ bool: { @@ -100,16 +88,12 @@ describe('query builder', () => { describe('test query builder with kql filter', () => { it('test default query params for all endpoints metadata when body filter is provided', async () => { - const mockRequest = httpServerMock.createKibanaRequest({ - body: { - filters: { kql: 'not host.ip:10.140.73.246' }, - }, - }); - const query = await kibanaRequestToMetadataListESQuery(mockRequest, { - logFactory: loggingSystemMock.create(), - service: new EndpointAppContextService(), - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue(createMockConfig().enableExperimental), + const query = await kibanaRequestToMetadataListESQuery({ + page: 0, + pageSize: 10, + kuery: 'not host.ip:10.140.73.246', + unenrolledAgentIds: [], + statusAgentIds: [], }); expect(query.body.query.bool.must).toContainEqual({ @@ -135,25 +119,13 @@ describe('query builder', () => { 'and when body filter is provided', async () => { const unenrolledElasticAgentId = '1fdca33f-799f-49f4-939c-ea4383c77672'; - const mockRequest = httpServerMock.createKibanaRequest({ - body: { - filters: { kql: 'not host.ip:10.140.73.246' }, - }, + const query = await kibanaRequestToMetadataListESQuery({ + page: 0, + pageSize: 10, + kuery: 'not host.ip:10.140.73.246', + unenrolledAgentIds: [unenrolledElasticAgentId], + statusAgentIds: [], }); - const query = await kibanaRequestToMetadataListESQuery( - mockRequest, - { - logFactory: loggingSystemMock.create(), - service: new EndpointAppContextService(), - config: () => Promise.resolve(createMockConfig()), - experimentalFeatures: parseExperimentalConfigValue( - createMockConfig().enableExperimental - ), - }, - { - unenrolledAgentIds: [unenrolledElasticAgentId], - } - ); expect(query.body.query.bool.must).toEqual([ { @@ -222,7 +194,10 @@ describe('query builder', () => { describe('buildUnitedIndexQuery', () => { it('correctly builds empty query', async () => { - const query = await buildUnitedIndexQuery({ page: 1, pageSize: 10, filters: {} }, []); + const query = await buildUnitedIndexQuery( + { page: 1, pageSize: 10, hostStatuses: [], kuery: '' }, + [] + ); const expected = { bool: { must_not: { @@ -267,10 +242,8 @@ describe('query builder', () => { { page: 1, pageSize: 10, - filters: { - kql: 'united.endpoint.host.os.name : *', - host_status: ['healthy'], - }, + kuery: 'united.endpoint.host.os.name : *', + hostStatuses: ['healthy'], }, ['test-endpoint-policy-id'] ); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts index 73325a92a3324..2262028ec43bf 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/query_builders.ts @@ -6,14 +6,16 @@ */ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import { TypeOf } from '@kbn/config-schema'; import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { metadataCurrentIndexPattern, METADATA_UNITED_INDEX, } from '../../../../common/endpoint/constants'; import { KibanaRequest } from '../../../../../../../src/core/server'; -import { EndpointAppContext, GetHostMetadataListQuery } from '../../types'; +import { EndpointAppContext } from '../../types'; import { buildStatusesKuery } from './support/agent_status'; +import { GetMetadataListRequestSchemaV2 } from '.'; /** * 00000000-0000-0000-0000-000000000000 is initial Elastic Agent id sent by Endpoint before policy is configured @@ -25,6 +27,9 @@ const IGNORED_ELASTIC_AGENT_IDS = [ ]; export interface QueryBuilderOptions { + page: number; + pageSize: number; + kuery?: string; unenrolledAgentIds?: string[]; statusAgentIds?: string[]; } @@ -50,26 +55,21 @@ export const MetadataSortMethod: estypes.SearchSortContainer[] = [ ]; export async function kibanaRequestToMetadataListESQuery( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - request: KibanaRequest, - endpointAppContext: EndpointAppContext, - queryBuilderOptions?: QueryBuilderOptions + queryBuilderOptions: QueryBuilderOptions // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Promise> { - const pagingProperties = await getPagingProperties(request, endpointAppContext); - return { body: { query: buildQueryBody( - request, + queryBuilderOptions?.kuery, IGNORED_ELASTIC_AGENT_IDS.concat(queryBuilderOptions?.unenrolledAgentIds ?? []), queryBuilderOptions?.statusAgentIds ), track_total_hits: true, sort: MetadataSortMethod, }, - from: pagingProperties.pageIndex * pagingProperties.pageSize, - size: pagingProperties.pageSize, + from: queryBuilderOptions.page * queryBuilderOptions.pageSize, + size: queryBuilderOptions.pageSize, index: metadataCurrentIndexPattern, }; } @@ -96,8 +96,7 @@ export async function getPagingProperties( } function buildQueryBody( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - request: KibanaRequest, + kuery: string = '', unerolledAgentIds: string[] | undefined, statusAgentIds: string[] | undefined // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -136,8 +135,8 @@ function buildQueryBody( }, }; - if (request?.body?.filters?.kql) { - const kqlQuery = toElasticsearchQuery(fromKueryExpression(request.body.filters.kql)); + if (kuery) { + const kqlQuery = toElasticsearchQuery(fromKueryExpression(kuery)); const q = []; if (filterUnenrolledAgents || filterStatusAgents) { q.push(idFilter); @@ -233,12 +232,17 @@ interface BuildUnitedIndexQueryResponse { size: number; index: string; } + export async function buildUnitedIndexQuery( - { page = 1, pageSize = 10, filters = {} }: GetHostMetadataListQuery, + { + page = 0, + pageSize = 10, + hostStatuses = [], + kuery = '', + }: TypeOf, endpointPolicyIds: string[] = [] ): Promise { - const statusesToFilter = filters?.host_status ?? []; - const statusesKuery = buildStatusesKuery(statusesToFilter); + const statusesKuery = buildStatusesKuery(hostStatuses); const filterIgnoredAgents = { must_not: { terms: { 'agent.id': IGNORED_ELASTIC_AGENT_IDS } }, @@ -272,8 +276,8 @@ export async function buildUnitedIndexQuery( let query: BuildUnitedIndexQueryResponse['body']['query'] = idFilter; - if (statusesKuery || filters?.kql) { - const kqlQuery = toElasticsearchQuery(fromKueryExpression(filters.kql ?? '')); + if (statusesKuery || kuery) { + const kqlQuery = toElasticsearchQuery(fromKueryExpression(kuery ?? '')); const q = []; if (filterIgnoredAgents || filterEndpointPolicyAgents) { @@ -295,7 +299,7 @@ export async function buildUnitedIndexQuery( track_total_hits: true, sort: MetadataSortMethod, }, - from: (page - 1) * pageSize, + from: page * pageSize, size: pageSize, index: METADATA_UNITED_INDEX, }; diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.ts index f9e04f4edebee..a7781cb77e8c0 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/agent_status.ts @@ -36,7 +36,7 @@ export function buildStatusesKuery(statusesToFilter: string[]): string | undefin export async function findAgentIdsByStatus( agentService: AgentService, esClient: ElasticsearchClient, - statuses: string[], + statuses: string[] = [], pageSize: number = 1000 ): Promise { if (!statuses.length) { diff --git a/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts b/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts index d3cc7b32bbc1c..5af108304ff9d 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.test.ts @@ -117,7 +117,12 @@ describe('EndpointMetadataService', () => { it('should throw wrapped error if es error', async () => { const esMockResponse = elasticsearchServiceMock.createErrorTransportRequestPromise({}); esClient.search.mockResolvedValue(esMockResponse); - const metadataListResponse = metadataService.getHostMetadataList(esClient); + const metadataListResponse = metadataService.getHostMetadataList(esClient, { + page: 0, + pageSize: 10, + kuery: '', + hostStatuses: [], + }); await expect(metadataListResponse).rejects.toThrow(EndpointError); }); @@ -168,18 +173,16 @@ describe('EndpointMetadataService', () => { } ); - const metadataListResponse = await metadataService.getHostMetadataList(esClient); - const unitedIndexQuery = await buildUnitedIndexQuery( - { page: 1, pageSize: 10, filters: {} }, - packagePolicyIds + const queryOptions = { page: 1, pageSize: 10, kuery: '', hostStatuses: [] }; + const metadataListResponse = await metadataService.getHostMetadataList( + esClient, + queryOptions ); + const unitedIndexQuery = await buildUnitedIndexQuery(queryOptions, packagePolicyIds); expect(esClient.search).toBeCalledWith(unitedIndexQuery); expect(agentPolicyServiceMock.getByIds).toBeCalledWith(expect.anything(), agentPolicyIds); expect(metadataListResponse).toEqual({ - pageSize: 10, - page: 1, - total: 1, data: [ { metadata: endpointMetadataDoc, @@ -202,6 +205,7 @@ describe('EndpointMetadataService', () => { }, }, ], + total: 1, }); }); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts b/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts index be8a6625c111e..832b8b507e5d4 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/metadata/endpoint_metadata_service.ts @@ -12,12 +12,14 @@ import { SavedObjectsServiceStart, } from 'kibana/server'; +import { TypeOf } from '@kbn/config-schema'; import { TransportResult } from '@elastic/elasticsearch'; import { SearchTotalHits, SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { HostInfo, HostMetadata, MaybeImmutable, + MetadataListResponse, PolicyData, UnitedAgentMetadata, } from '../../../../common/endpoint/types'; @@ -52,10 +54,10 @@ import { } from '../../utils'; import { EndpointError } from '../../errors'; import { createInternalReadonlySoClient } from '../../utils/create_internal_readonly_so_client'; -import { GetHostMetadataListQuery } from '../../types'; import { METADATA_UNITED_INDEX } from '../../../../common/endpoint/constants'; import { getAllEndpointPackagePolicies } from '../../routes/metadata/support/endpoint_package_policies'; import { getAgentStatus } from '../../../../../fleet/common/services/agent_status'; +import { GetMetadataListRequestSchemaV2 } from '../../routes/metadata'; type AgentPolicyWithPackagePolicies = Omit & { package_policies: PackagePolicy[]; @@ -401,8 +403,8 @@ export class EndpointMetadataService { */ async getHostMetadataList( esClient: ElasticsearchClient, - queryOptions: GetHostMetadataListQuery = {} - ): Promise<{ data: HostInfo[]; total: number; page: number; pageSize: number }> { + queryOptions: TypeOf + ): Promise> { const endpointPolicies = await getAllEndpointPackagePolicies( this.packagePolicyService, this.DANGEROUS_INTERNAL_SO_CLIENT @@ -474,8 +476,6 @@ export class EndpointMetadataService { return { data: hosts, - pageSize: unitedIndexQuery.size, - page: unitedIndexQuery.from + 1, total: (docsCount as unknown as SearchTotalHits).value, }; } diff --git a/x-pack/plugins/security_solution/server/endpoint/types.ts b/x-pack/plugins/security_solution/server/endpoint/types.ts index 919e62785f698..bc52b759b9f0a 100644 --- a/x-pack/plugins/security_solution/server/endpoint/types.ts +++ b/x-pack/plugins/security_solution/server/endpoint/types.ts @@ -7,12 +7,10 @@ import { LoggerFactory } from 'kibana/server'; -import { TypeOf } from '@kbn/config-schema'; import { ConfigType } from '../config'; import { EndpointAppContextService } from './endpoint_app_context_services'; import { HostMetadata } from '../../common/endpoint/types'; import { ExperimentalFeatures } from '../../common/experimental_features'; -import { endpointFilters } from './routes/metadata'; /** * The context for Endpoint apps. @@ -37,11 +35,3 @@ export interface HostQueryResult { resultLength: number; result: HostMetadata | undefined; } - -// FIXME: when new Host Metadata list API is created (and existing one deprecated - 8.0?), move this type out of here and created it from Schema -export interface GetHostMetadataListQuery { - /* page number 1 based - not an index */ - page?: number; - pageSize?: number; - filters?: Partial>; -} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts index 0ad88c61bab36..07b93f04e965f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/factories/bulk_create_factory.ts @@ -6,12 +6,11 @@ */ import { performance } from 'perf_hooks'; -import { countBy, isEmpty } from 'lodash'; import { Logger } from 'kibana/server'; import { BaseHit } from '../../../../../common/detection_engine/types'; import { BuildRuleMessage } from '../../signals/rule_messages'; -import { errorAggregator, makeFloatString } from '../../signals/utils'; +import { makeFloatString } from '../../signals/utils'; import { RefreshTypes } from '../../types'; import { PersistenceAlertService } from '../../../../../../rule_registry/server'; @@ -45,11 +44,11 @@ export const bulkCreateFactory = const start = performance.now(); - const response = await alertWithPersistence( + const { createdAlerts } = await alertWithPersistence( wrappedDocs.map((doc) => ({ - id: doc._id, + _id: doc._id, // `fields` should have already been merged into `doc._source` - fields: doc._source, + _source: doc._source, })), refreshForBulkCreate ); @@ -62,64 +61,11 @@ export const bulkCreateFactory = ) ); - if (response == null) { - return { - errors: [ - 'alertWithPersistence returned undefined response. Alerts as Data write flag may be disabled.', - ], - success: false, - bulkCreateDuration: makeFloatString(end - start), - createdItemsCount: 0, - createdItems: [], - }; - } - - logger.debug( - buildRuleMessage(`took property says bulk took: ${response.body.took} milliseconds`) - ); - - const createdItems = wrappedDocs - .map((doc, index) => { - const responseIndex = response.body.items[index].index; - return { - _id: responseIndex?._id ?? '', - _index: responseIndex?._index ?? '', - ...doc._source, - }; - }) - .filter((_, index) => response.body.items[index].index?.status === 201); - const createdItemsCount = createdItems.length; - - const duplicateSignalsCount = countBy(response.body.items, 'create.status')['409']; - const errorCountByMessage = errorAggregator(response.body, [409]); - - logger.debug(buildRuleMessage(`bulk created ${createdItemsCount} signals`)); - - if (duplicateSignalsCount > 0) { - logger.debug(buildRuleMessage(`ignored ${duplicateSignalsCount} duplicate signals`)); - } - - if (!isEmpty(errorCountByMessage)) { - logger.error( - buildRuleMessage( - `[-] bulkResponse had errors with responses of: ${JSON.stringify(errorCountByMessage)}` - ) - ); - - return { - errors: Object.keys(errorCountByMessage), - success: false, - bulkCreateDuration: makeFloatString(end - start), - createdItemsCount: createdItems.length, - createdItems, - }; - } else { - return { - errors: [], - success: true, - bulkCreateDuration: makeFloatString(end - start), - createdItemsCount: createdItems.length, - createdItems, - }; - } + return { + errors: [], + success: true, + bulkCreateDuration: makeFloatString(end - start), + createdItemsCount: createdAlerts.length, + createdItems: createdAlerts, + }; }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/create_indicator_match_alert_type.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/create_indicator_match_alert_type.test.ts index 89e8e7f70e4aa..29054a4022715 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/create_indicator_match_alert_type.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/indicator_match/create_indicator_match_alert_type.test.ts @@ -14,7 +14,6 @@ import { allowedExperimentalValues } from '../../../../../common/experimental_fe import { createRuleTypeMocks } from '../__mocks__/rule_type'; import { createIndicatorMatchAlertType } from './create_indicator_match_alert_type'; import { sampleDocNoSortId } from '../../signals/__mocks__/es_results'; -import { CountResponse } from 'kibana/server'; import { RuleParams } from '../../schemas/rule_schemas'; import { createSecurityRuleTypeWrapper } from '../create_security_rule_type_wrapper'; import { createMockConfig } from '../../routes/__mocks__'; @@ -133,121 +132,4 @@ describe('Indicator Match Alerts', () => { await executor({ params }); expect(dependencies.ruleDataClient.getWriter).not.toBeCalled(); }); - - it('sends an alert when enrichments are found', async () => { - const indicatorMatchAlertType = securityRuleTypeWrapper( - createIndicatorMatchAlertType({ - experimentalFeatures: allowedExperimentalValues, - logger: dependencies.logger, - version: '1.0.0', - }) - ); - - dependencies.alerting.registerType(indicatorMatchAlertType); - - // threat list count - services.scopedClusterClient.asCurrentUser.count.mockReturnValue( - elasticsearchClientMock.createSuccessTransportRequestPromise({ count: 1 } as CountResponse) - ); - - services.scopedClusterClient.asCurrentUser.search.mockReturnValueOnce( - elasticsearchClientMock.createSuccessTransportRequestPromise({ - hits: { - hits: [ - { - ...sampleDocNoSortId(v4()), - _source: { - ...sampleDocNoSortId(v4())._source, - 'threat.indicator.file.hash.md5': 'a1b2c3', - }, - fields: { - ...sampleDocNoSortId(v4()).fields, - 'threat.indicator.file.hash.md5': ['a1b2c3'], - }, - }, - ], - total: { - relation: 'eq', - value: 1, - }, - }, - took: 0, - timed_out: false, - _shards: { - failed: 0, - skipped: 0, - successful: 1, - total: 1, - }, - }) - ); - - services.scopedClusterClient.asCurrentUser.search.mockReturnValueOnce( - elasticsearchClientMock.createSuccessTransportRequestPromise({ - hits: { - hits: [ - { - ...sampleDocNoSortId(v4()), - _source: { - ...sampleDocNoSortId(v4())._source, - 'file.hash.md5': 'a1b2c3', - }, - fields: { - ...sampleDocNoSortId(v4()).fields, - 'file.hash.md5': ['a1b2c3'], - }, - }, - ], - total: { - relation: 'eq', - value: 1, - }, - }, - took: 0, - timed_out: false, - _shards: { - failed: 0, - skipped: 0, - successful: 1, - total: 1, - }, - }) - ); - - services.scopedClusterClient.asCurrentUser.search.mockReturnValueOnce( - elasticsearchClientMock.createSuccessTransportRequestPromise({ - hits: { - hits: [ - { - ...sampleDocNoSortId(v4()), - _source: { - ...sampleDocNoSortId(v4())._source, - 'file.hash.md5': 'a1b2c3', - }, - fields: { - ...sampleDocNoSortId(v4()).fields, - 'file.hash.md5': ['a1b2c3'], - }, - }, - ], - total: { - relation: 'eq', - value: 1, - }, - }, - took: 0, - timed_out: false, - _shards: { - failed: 0, - skipped: 0, - successful: 1, - total: 1, - }, - }) - ); - - await executor({ params }); - - expect(dependencies.ruleDataClient.getWriter).toBeCalled(); - }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/query/create_query_alert_type.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/query/create_query_alert_type.test.ts index 40ef2b46ed8d9..07eb096d0dd83 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/query/create_query_alert_type.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/query/create_query_alert_type.test.ts @@ -5,13 +5,10 @@ * 2.0. */ -import { v4 } from 'uuid'; - // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks'; import { allowedExperimentalValues } from '../../../../../common/experimental_features'; -import { sampleDocNoSortId } from '../../signals/__mocks__/es_results'; import { createQueryAlertType } from './create_query_alert_type'; import { createRuleTypeMocks } from '../__mocks__/rule_type'; import { createSecurityRuleTypeWrapper } from '../create_security_rule_type_wrapper'; @@ -79,48 +76,4 @@ describe('Custom Query Alerts', () => { await executor({ params }); expect(dependencies.ruleDataClient.getWriter).not.toBeCalled(); }); - - it('sends a properly formatted alert when events are found', async () => { - const queryAlertType = securityRuleTypeWrapper( - createQueryAlertType({ - experimentalFeatures: allowedExperimentalValues, - logger: dependencies.logger, - version: '1.0.0', - }) - ); - - dependencies.alerting.registerType(queryAlertType); - - const params = { - query: '*:*', - index: ['*'], - from: 'now-1m', - to: 'now', - language: 'kuery', - type: 'query', - }; - - services.scopedClusterClient.asCurrentUser.search.mockReturnValue( - elasticsearchClientMock.createSuccessTransportRequestPromise({ - hits: { - hits: [sampleDocNoSortId(v4()), sampleDocNoSortId(v4()), sampleDocNoSortId(v4())], - total: { - relation: 'eq', - value: 3, - }, - }, - took: 0, - timed_out: false, - _shards: { - failed: 0, - skipped: 0, - successful: 1, - total: 1, - }, - }) - ); - - await executor({ params }); - expect(dependencies.ruleDataClient.getWriter).toBeCalled(); - }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts index 2c25134cc3760..c3e15b061842e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.mock.ts @@ -117,3 +117,69 @@ export const getCreateMlRulesOptionsMock = ( exceptionsList: [], actions: [], }); + +export const getCreateThreatMatchRulesOptionsMock = ( + isRuleRegistryEnabled: boolean +): CreateRulesOptions => ({ + actions: [], + anomalyThreshold: undefined, + author: ['Elastic'], + buildingBlockType: undefined, + concurrentSearches: undefined, + description: 'some description', + enabled: true, + eventCategoryOverride: undefined, + exceptionsList: [], + falsePositives: ['false positive 1', 'false positive 2'], + filters: [], + from: 'now-1m', + immutable: false, + index: ['*'], + interval: '5m', + isRuleRegistryEnabled, + itemsPerSearch: undefined, + language: 'kuery', + license: 'Elastic License', + machineLearningJobId: undefined, + maxSignals: 100, + meta: {}, + name: 'Query with a rule id', + note: '# sample markdown', + outputIndex: 'output-1', + query: 'user.name: root or user.name: admin', + references: ['http://www.example.com'], + riskScore: 80, + riskScoreMapping: [], + ruleId: 'rule-1', + ruleNameOverride: undefined, + rulesClient: rulesClientMock.create(), + savedId: 'savedId-123', + severity: 'high', + severityMapping: [], + tags: [], + threat: [], + threatFilters: undefined, + threatIndex: ['filebeat-*'], + threatIndicatorPath: 'threat.indicator', + threatLanguage: 'kuery', + threatMapping: [ + { + entries: [ + { + field: 'file.hash.md5', + type: 'mapping', + value: 'threat.indicator.file.hash.md5', + }, + ], + }, + ], + threatQuery: '*:*', + threshold: undefined, + throttle: null, + timelineId: 'timelineid-123', + timelineTitle: 'timeline-title-123', + timestampOverride: undefined, + to: 'now', + type: 'threat_match', + version: 1, +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts index 0fd708791712a..3d5619ab1306b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.test.ts @@ -6,7 +6,11 @@ */ import { createRules } from './create_rules'; -import { getCreateMlRulesOptionsMock } from './create_rules.mock'; +import { + getCreateMlRulesOptionsMock, + getCreateThreatMatchRulesOptionsMock, +} from './create_rules.mock'; +import { DEFAULT_INDICATOR_SOURCE_PATH } from '../../../../common/constants'; describe.each([ ['Legacy', false], @@ -44,4 +48,34 @@ describe.each([ }) ); }); + + it('populates a threatIndicatorPath value for threat_match rule if empty', async () => { + const ruleOptions = getCreateThreatMatchRulesOptionsMock(isRuleRegistryEnabled); + delete ruleOptions.threatIndicatorPath; + await createRules(ruleOptions); + expect(ruleOptions.rulesClient.create).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + params: expect.objectContaining({ + threatIndicatorPath: DEFAULT_INDICATOR_SOURCE_PATH, + }), + }), + }) + ); + }); + + it('does not populate a threatIndicatorPath value for other rules if empty', async () => { + const ruleOptions = getCreateMlRulesOptionsMock(isRuleRegistryEnabled); + delete ruleOptions.threatIndicatorPath; + await createRules(ruleOptions); + expect(ruleOptions.rulesClient.create).not.toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + params: expect.objectContaining({ + threatIndicatorPath: DEFAULT_INDICATOR_SOURCE_PATH, + }), + }), + }) + ); + }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts index 1d0010b38578d..5ff5358fbc4cd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/create_rules.ts @@ -13,7 +13,11 @@ import { } from '../../../../common/detection_engine/utils'; import { transformRuleToAlertAction } from '../../../../common/detection_engine/transform_actions'; import { SanitizedAlert } from '../../../../../alerting/common'; -import { NOTIFICATION_THROTTLE_NO_ACTIONS, SERVER_APP_ID } from '../../../../common/constants'; +import { + DEFAULT_INDICATOR_SOURCE_PATH, + NOTIFICATION_THROTTLE_NO_ACTIONS, + SERVER_APP_ID, +} from '../../../../common/constants'; import { CreateRulesOptions } from './types'; import { addTags } from './add_tags'; import { PartialFilter, RuleTypeParams } from '../types'; @@ -115,7 +119,9 @@ export const createRules = async ({ */ threatFilters: threatFilters as PartialFilter[] | undefined, threatIndex, - threatIndicatorPath, + threatIndicatorPath: + threatIndicatorPath ?? + (type === 'threat_match' ? DEFAULT_INDICATOR_SOURCE_PATH : undefined), threatQuery, concurrentSearches, itemsPerSearch, diff --git a/x-pack/plugins/snapshot_restore/public/application/components/policy_form/policy_form.tsx b/x-pack/plugins/snapshot_restore/public/application/components/policy_form/policy_form.tsx index f3ce07cd732ca..185d3bb90bae5 100644 --- a/x-pack/plugins/snapshot_restore/public/application/components/policy_form/policy_form.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/components/policy_form/policy_form.tsx @@ -193,7 +193,7 @@ export const PolicyForm: React.FunctionComponent = ({ savePolicy()} isLoading={isSaving} diff --git a/x-pack/plugins/snapshot_restore/public/application/components/repository_form/step_two.tsx b/x-pack/plugins/snapshot_restore/public/application/components/repository_form/step_two.tsx index 011b8e883316c..a985a6dee0bae 100644 --- a/x-pack/plugins/snapshot_restore/public/application/components/repository_form/step_two.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/components/repository_form/step_two.tsx @@ -143,7 +143,7 @@ export const RepositoryFormStepTwo: React.FunctionComponent = ({ )} = ({ executeRestore()} isLoading={isSaving} diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/policy_list/policy_details/policy_details.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/policy_list/policy_details/policy_details.tsx index 0a283d406e5aa..33f83ca30c04e 100644 --- a/x-pack/plugins/snapshot_restore/public/application/sections/home/policy_list/policy_details/policy_details.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/policy_list/policy_details/policy_details.tsx @@ -307,7 +307,7 @@ export const PolicyDetails: React.FunctionComponent = ({ {policyName}{' '} = ({ toolsRight: [ = ({ toolsRight: [ { data-test-subj={`cts-summary-success-count`} title={summarizedResults.successCount} titleSize="s" - titleColor={initialCopyFinished ? 'secondary' : 'subdued'} + titleColor={initialCopyFinished ? 'success' : 'subdued'} isLoading={!initialCopyFinished} textAlign="center" description={ diff --git a/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx b/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx index aefff7fb3c76a..2c64f559602cc 100644 --- a/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx +++ b/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx @@ -18,7 +18,7 @@ jest.mock('./edit_space', () => ({ }, })); -import { coreMock, scopedHistoryMock } from 'src/core/public/mocks'; +import { coreMock, scopedHistoryMock, themeServiceMock } from 'src/core/public/mocks'; import { featuresPluginMock } from '../../../features/public/mocks'; import type { PluginsStart } from '../plugin'; @@ -51,6 +51,7 @@ async function mountApp(basePath: string, pathname: string, spaceId?: string) { element: container, setBreadcrumbs, history: scopedHistoryMock.create({ pathname }), + theme$: themeServiceMock.createTheme$(), }); return { unmount, container, setBreadcrumbs, docTitle: coreStart.chrome.docTitle }; diff --git a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_mode_control.tsx b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_mode_control.tsx index 2740533e52715..45a2d3f4964b1 100644 --- a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_mode_control.tsx +++ b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_mode_control.tsx @@ -139,7 +139,7 @@ export const ShareModeControl = (props: Props) => { onChange(updatedSpaceIds); }} legend={buttonGroupLegend} - color="secondary" + color="success" isFullWidth={true} isDisabled={!canShareToAllSpaces} /> diff --git a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.test.tsx b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.test.tsx index 51c2f0471d486..ad624c345272d 100644 --- a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.test.tsx +++ b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.test.tsx @@ -22,7 +22,6 @@ import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; import { EsQueryAlertParams } from './types'; jest.mock('../../../../../../src/plugins/kibana_react/public'); -jest.mock('../../../../../../src/plugins/es_ui_shared/public'); jest.mock('../../../../../../src/plugins/es_ui_shared/public', () => ({ XJson: { useXJsonMode: jest.fn().mockReturnValue({ @@ -31,26 +30,18 @@ jest.mock('../../../../../../src/plugins/es_ui_shared/public', () => ({ xJson: jest.fn(), }), }, + // Mocking EuiCodeEditor, which uses React Ace under the hood + // eslint-disable-next-line @typescript-eslint/no-explicit-any + EuiCodeEditor: (props: any) => ( + { + props.onChange(syntheticEvent.jsonString); + }} + /> + ), })); -jest.mock(''); -jest.mock('@elastic/eui', () => { - const original = jest.requireActual('@elastic/eui'); - - return { - ...original, - // Mocking EuiCodeEditor, which uses React Ace under the hood - // eslint-disable-next-line @typescript-eslint/no-explicit-any - EuiCodeEditor: (props: any) => ( - { - props.onChange(syntheticEvent.jsonString); - }} - /> - ), - }; -}); jest.mock('../../../../triggers_actions_ui/public', () => { const original = jest.requireActual('../../../../triggers_actions_ui/public'); return { diff --git a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx index 4cba80a9a541a..b98df85e0b8a0 100644 --- a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx +++ b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx @@ -9,12 +9,11 @@ import React, { useState, Fragment, useEffect } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import 'brace/theme/github'; import { XJsonMode } from '@kbn/ace'; +import 'brace/theme/github'; import { EuiButtonEmpty, - EuiCodeEditor, EuiSpacer, EuiFormRow, EuiCallOut, @@ -25,7 +24,7 @@ import { import { DocLinksStart, HttpSetup } from 'kibana/public'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import { XJson } from '../../../../../../src/plugins/es_ui_shared/public'; +import { XJson, EuiCodeEditor } from '../../../../../../src/plugins/es_ui_shared/public'; import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; import { getFields, diff --git a/x-pack/plugins/timelines/public/components/t_grid/event_rendered_view/index.tsx b/x-pack/plugins/timelines/public/components/t_grid/event_rendered_view/index.tsx index 6267c9d3a4953..3caa53988c005 100644 --- a/x-pack/plugins/timelines/public/components/t_grid/event_rendered_view/index.tsx +++ b/x-pack/plugins/timelines/public/components/t_grid/event_rendered_view/index.tsx @@ -115,7 +115,7 @@ const EventRenderedViewComponent = ({ field: 'actions', name: ActionTitle, truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (name: unknown, item: unknown) => { const alertId = get(item, '_id'); const rowIndex = events.findIndex((evt) => evt._id === alertId); @@ -147,7 +147,7 @@ const EventRenderedViewComponent = ({ defaultMessage: 'Timestamp', }), truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (name: unknown, item: TimelineItem) => { const timestamp = get(item, `ecs.timestamp`); return ; @@ -159,7 +159,7 @@ const EventRenderedViewComponent = ({ defaultMessage: 'Rule', }), truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (name: unknown, item: TimelineItem) => { const ruleName = get(item, `ecs.signal.rule.name`); /* `ecs.${ALERT_RULE_NAME}`*/ const ruleId = get(item, `ecs.signal.rule.id`); /* `ecs.${ALERT_RULE_ID}`*/ @@ -172,7 +172,7 @@ const EventRenderedViewComponent = ({ defaultMessage: 'Event Summary', }), truncateText: false, - hideForMobile: false, + mobileOptions: { show: true }, render: (name: unknown, item: TimelineItem) => { const ecsData = get(item, 'ecs'); const reason = get(item, `ecs.signal.reason`); /* `ecs.${ALERT_REASON}`*/ diff --git a/x-pack/plugins/timelines/public/container/index.tsx b/x-pack/plugins/timelines/public/container/index.tsx index e43d9571f8001..28e4a5ffda4af 100644 --- a/x-pack/plugins/timelines/public/container/index.tsx +++ b/x-pack/plugins/timelines/public/container/index.tsx @@ -275,6 +275,7 @@ export const useTimelineEvents = ({ filterQuery: createFilter(filterQuery), querySize: limit, sort, + runtimeMappings, timerange: { interval: '12h', from: startDate, diff --git a/x-pack/plugins/transform/public/app/sections/transform_management/components/refresh_transform_list_button/refresh_transform_list_button.tsx b/x-pack/plugins/transform/public/app/sections/transform_management/components/refresh_transform_list_button/refresh_transform_list_button.tsx index f9f5f79bf4620..183847362851b 100644 --- a/x-pack/plugins/transform/public/app/sections/transform_management/components/refresh_transform_list_button/refresh_transform_list_button.tsx +++ b/x-pack/plugins/transform/public/app/sections/transform_management/components/refresh_transform_list_button/refresh_transform_list_button.tsx @@ -19,7 +19,7 @@ export const RefreshTransformListButton: FC = ({ isLoading, }) => ( = ({ {onTestConnector && ( = ({ { @@ -408,7 +408,7 @@ const ConnectorEditFlyout = ({ = ({
= ({ {filteredDeprecations.length === 0 ? ( - + {i18nTexts.noDeprecationsMessage} diff --git a/x-pack/plugins/uptime/common/constants/settings_defaults.ts b/x-pack/plugins/uptime/common/constants/settings_defaults.ts index b57bc8a85d7cd..8fbc4c19df6b0 100644 --- a/x-pack/plugins/uptime/common/constants/settings_defaults.ts +++ b/x-pack/plugins/uptime/common/constants/settings_defaults.ts @@ -8,7 +8,7 @@ import { DynamicSettings } from '../runtime_types'; export const DYNAMIC_SETTINGS_DEFAULTS: DynamicSettings = { - heartbeatIndices: 'heartbeat-8*,synthetics-*', + heartbeatIndices: 'heartbeat-8*,heartbeat-7*,synthetics-*', certAgeThreshold: 730, certExpirationThreshold: 30, defaultConnectors: [], diff --git a/x-pack/plugins/uptime/public/components/common/charts/monitor_bar_series.tsx b/x-pack/plugins/uptime/public/components/common/charts/monitor_bar_series.tsx index 08cac07250fea..145ec5f199db4 100644 --- a/x-pack/plugins/uptime/public/components/common/charts/monitor_bar_series.tsx +++ b/x-pack/plugins/uptime/public/components/common/charts/monitor_bar_series.tsx @@ -114,7 +114,7 @@ export const MonitorBarSeries = ({ histogramSeries, minInterval }: MonitorBarSer /> } > - -- + -- ); }; diff --git a/x-pack/plugins/uptime/public/components/monitor/ping_list/columns/ping_status.tsx b/x-pack/plugins/uptime/public/components/monitor/ping_list/columns/ping_status.tsx index 3a4ee53f63223..dcf3fdb9163db 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ping_list/columns/ping_status.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ping_list/columns/ping_status.tsx @@ -50,7 +50,7 @@ export const PingStatusColumn = ({ pingStatus, item }: Props) => {
{getPingStatusLabel(pingStatus, item)} diff --git a/x-pack/plugins/uptime/public/components/monitor/ping_list/ping_redirects.tsx b/x-pack/plugins/uptime/public/components/monitor/ping_list/ping_redirects.tsx index b1a36b1c0d61b..01e0cb5be2b0f 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ping_list/ping_redirects.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ping_list/ping_redirects.tsx @@ -37,7 +37,7 @@ export const PingRedirects: React.FC = ({ monitorStatus, showTitle }) => size: 's', target: '_blank', extraAction: { - color: 'subdued', + color: 'text', iconType: 'popout', iconSize: 's', alwaysShow: true, @@ -56,7 +56,7 @@ export const PingRedirects: React.FC = ({ monitorStatus, showTitle }) => size: 's', target: '_blank', extraAction: { - color: 'subdued', + color: 'text', iconType: 'popout', iconSize: 's', 'aria-label': i18n.translate('xpack.uptime.monitorList.redirects.openWindow', { diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/__snapshots__/tag_label.test.tsx.snap b/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/__snapshots__/tag_label.test.tsx.snap index 2e55e7024f444..345a8f2786d41 100644 --- a/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/__snapshots__/tag_label.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/__snapshots__/tag_label.test.tsx.snap @@ -36,7 +36,7 @@ exports[`TagLabel component renders correctly against snapshot 1`] = ` exports[`TagLabel component shallow render correctly against snapshot 1`] = ` US-East diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/tag_label.tsx b/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/tag_label.tsx index a53beb60ab410..6bf73b9609e58 100644 --- a/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/tag_label.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/availability_reporting/tag_label.tsx @@ -23,7 +23,7 @@ const BadgeItem = styled.div` export const TagLabel: React.FC = ({ color, label, status }) => { return ( - {label} + {label} ); }; diff --git a/x-pack/plugins/uptime/public/components/monitor/synthetics/waterfall/components/middle_truncated_text.tsx b/x-pack/plugins/uptime/public/components/monitor/synthetics/waterfall/components/middle_truncated_text.tsx index 311a496bd58a3..3e3b08f49d705 100644 --- a/x-pack/plugins/uptime/public/components/monitor/synthetics/waterfall/components/middle_truncated_text.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/synthetics/waterfall/components/middle_truncated_text.tsx @@ -145,7 +145,7 @@ export const MiddleTruncatedText = ({ { +): 'primary' | 'success' | 'subdued' | 'danger' => { if (isInvalid === true) return 'danger'; if (isEnabled === false) return 'subdued'; - return isOpen ? 'primary' : 'secondary'; + return isOpen ? 'primary' : 'success'; }; export const AlertExpressionPopover: React.FC = ({ diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/alert_tls.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/alert_tls.tsx index e2de834a379b5..f7cd341e04dae 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/alert_tls.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/alert_tls.tsx @@ -23,7 +23,7 @@ export const AlertTlsComponent: React.FC = (props) => ( diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__snapshots__/down_number_select.test.tsx.snap b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__snapshots__/down_number_select.test.tsx.snap index bf56ebd0de236..f9e169b976d1d 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__snapshots__/down_number_select.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__snapshots__/down_number_select.test.tsx.snap @@ -10,7 +10,7 @@ exports[`DownNoExpressionSelect component should renders against props 1`] = ` > = button={ setIsOpen(!isOpen)} diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/monitor_status_column.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/monitor_status_column.tsx index f5581f75b3759..6960bb5632852 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/monitor_status_column.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/monitor_status_column.tsx @@ -162,7 +162,7 @@ export const MonitorListStatusColumn = ({ {getHealthMessage(status)} diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_row.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_row.tsx index 03655d11c983d..15e40773ae6df 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_row.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list_drawer/monitor_status_row.tsx @@ -23,7 +23,7 @@ interface MonitorStatusRowProps { } export const MonitorStatusRow = ({ locationNames, status }: MonitorStatusRowProps) => { - const color = status === STATUS.UP ? 'secondary' : 'danger'; + const color = status === STATUS.UP ? 'success' : 'danger'; let checkListArray = [...locationNames]; // If un-named location exists, move it to end diff --git a/x-pack/plugins/uptime/public/pages/settings.test.tsx b/x-pack/plugins/uptime/public/pages/settings.test.tsx index 84bd4270951cf..f02e35506135b 100644 --- a/x-pack/plugins/uptime/public/pages/settings.test.tsx +++ b/x-pack/plugins/uptime/public/pages/settings.test.tsx @@ -29,7 +29,7 @@ describe('settings', () => { it('handles no spaces error', async () => { const { getByText, getByTestId } = render(); - expect(getByText('heartbeat-8*,synthetics-*')); + expect(getByText('heartbeat-8*,heartbeat-7*,synthetics-*')); fireEvent.input(getByTestId('heartbeat-indices-input-loaded'), { target: { value: 'heartbeat-8*, synthetics-*' }, @@ -41,7 +41,7 @@ describe('settings', () => { it('it show select a connector flyout', async () => { const { getByText, getByTestId } = render(); - expect(getByText('heartbeat-8*,synthetics-*')); + expect(getByText('heartbeat-8*,heartbeat-7*,synthetics-*')); fireEvent.click(getByTestId('createConnectorButton')); await waitFor(() => expect(getByText('Select a connector'))); diff --git a/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_charts.test.ts.snap b/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_charts.test.ts.snap index 2d1bdf791e39a..14e4261c28283 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_charts.test.ts.snap +++ b/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_charts.test.ts.snap @@ -55,7 +55,7 @@ Array [ }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `; diff --git a/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_details.test.ts.snap b/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_details.test.ts.snap index 56b7ed25a74ad..9464f9960b8d2 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_details.test.ts.snap +++ b/x-pack/plugins/uptime/server/lib/requests/__snapshots__/get_monitor_details.test.ts.snap @@ -55,7 +55,7 @@ Array [ }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `; @@ -103,7 +103,7 @@ Array [ }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `; diff --git a/x-pack/plugins/uptime/server/lib/requests/get_certs.test.ts b/x-pack/plugins/uptime/server/lib/requests/get_certs.test.ts index a6b37215c141a..dbbbf5d82c970 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_certs.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_certs.test.ts @@ -212,7 +212,7 @@ describe('getCerts', () => { }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ], ] diff --git a/x-pack/plugins/uptime/server/lib/requests/get_monitor_availability.test.ts b/x-pack/plugins/uptime/server/lib/requests/get_monitor_availability.test.ts index 0f1bd606307e5..ee8386dfce5d7 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_monitor_availability.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_monitor_availability.test.ts @@ -241,7 +241,7 @@ describe('monitor availability', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); }); @@ -387,7 +387,7 @@ describe('monitor availability', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); @@ -701,7 +701,7 @@ describe('monitor availability', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); @@ -799,7 +799,7 @@ describe('monitor availability', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `); @@ -929,7 +929,7 @@ describe('monitor availability', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); }); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_monitor_status.test.ts b/x-pack/plugins/uptime/server/lib/requests/get_monitor_status.test.ts index 08b675576a5d2..4a790ad2a1e99 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_monitor_status.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_monitor_status.test.ts @@ -197,7 +197,7 @@ describe('getMonitorStatus', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); }); @@ -311,7 +311,7 @@ describe('getMonitorStatus', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); }); @@ -510,7 +510,7 @@ describe('getMonitorStatus', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); }); @@ -629,7 +629,7 @@ describe('getMonitorStatus', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); }); @@ -754,7 +754,7 @@ describe('getMonitorStatus', () => { }, "size": 0, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", } `); expect(result.length).toBe(3); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_network_events.test.ts b/x-pack/plugins/uptime/server/lib/requests/get_network_events.test.ts index e0cd17327a9b6..68fd53729f58d 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_network_events.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_network_events.test.ts @@ -215,7 +215,7 @@ describe('getNetworkEvents', () => { "size": 1000, "track_total_hits": true, }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ], ] diff --git a/x-pack/plugins/uptime/server/lib/requests/get_pings.test.ts b/x-pack/plugins/uptime/server/lib/requests/get_pings.test.ts index 96b95fafa921e..7b9a97a4f5cb9 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_pings.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_pings.test.ts @@ -175,7 +175,7 @@ describe('getAll', () => { }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `); @@ -244,7 +244,7 @@ describe('getAll', () => { }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `); @@ -313,7 +313,7 @@ describe('getAll', () => { }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `); @@ -387,7 +387,7 @@ describe('getAll', () => { }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `); @@ -506,7 +506,7 @@ describe('getAll', () => { }, ], }, - "index": "heartbeat-8*,synthetics-*", + "index": "heartbeat-8*,heartbeat-7*,synthetics-*", }, ] `); diff --git a/x-pack/plugins/watcher/public/application/components/watch_status.tsx b/x-pack/plugins/watcher/public/application/components/watch_status.tsx index 5c1fd39b5b486..8c6ea0e01b357 100644 --- a/x-pack/plugins/watcher/public/application/components/watch_status.tsx +++ b/x-pack/plugins/watcher/public/application/components/watch_status.tsx @@ -17,7 +17,7 @@ function StatusIcon({ status }: { status: string }) { case WATCH_STATES.OK: case ACTION_STATES.OK: case ACTION_STATES.ACKNOWLEDGED: - return ; + return ; case ACTION_STATES.THROTTLED: return ; case WATCH_STATES.DISABLED: diff --git a/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx index b19d97f67d2e0..c59147d7e7ce6 100644 --- a/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx @@ -197,7 +197,7 @@ export const JsonWatchEditForm = () => { { onClick={() => { setAggFieldPopoverOpen(true); }} - color={watch.aggField ? 'secondary' : 'danger'} + color={watch.aggField ? 'success' : 'danger'} /> } isOpen={aggFieldPopoverOpen} @@ -617,7 +617,7 @@ export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { }} color={ watch.groupBy === 'all' || (watch.termSize && watch.termField) - ? 'secondary' + ? 'success' : 'danger' } /> @@ -730,7 +730,7 @@ export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { color={ errors.threshold0.length || (errors.threshold1 && errors.threshold1.length) ? 'danger' - : 'secondary' + : 'success' } /> } @@ -816,7 +816,7 @@ export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { onClick={() => { setWatchDurationPopoverOpen(true); }} - color={watch.timeWindowSize ? 'secondary' : 'danger'} + color={watch.timeWindowSize ? 'success' : 'danger'} /> } isOpen={watchDurationPopoverOpen} @@ -890,7 +890,7 @@ export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { { const objectRemover = new ObjectRemover(supertestWithoutAuth); - const alertUtils = new AlertUtils({ space: Spaces.space1, supertestWithoutAuth }); + const ruleUtils = new RuleUtils({ space: Spaces.space1, supertestWithoutAuth }); after(() => objectRemover.removeAll()); @@ -38,18 +38,18 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte }); } - it('should handle disable alert request appropriately', async () => { - const { body: createdAlert } = await supertestWithoutAuth + it('should handle disable rule request appropriately', async () => { + const { body: createdRule } = await supertestWithoutAuth .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: true })) + .send(getTestRuleData({ enabled: true })) .expect(200); - objectRemover.add(Spaces.space1.id, createdAlert.id, 'rule', 'alerting'); + objectRemover.add(Spaces.space1.id, createdRule.id, 'rule', 'alerting'); - await alertUtils.disable(createdAlert.id); + await ruleUtils.disable(createdRule.id); try { - await getScheduledTask(createdAlert.scheduledTaskId); + await getScheduledTask(createdRule.scheduled_task_id); throw new Error('Should have removed scheduled task'); } catch (e) { expect(e.meta.statusCode).to.eql(404); @@ -60,27 +60,27 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, type: 'alert', - id: createdAlert.id, + id: createdRule.id, }); }); - it(`shouldn't disable alert from another space`, async () => { - const { body: createdAlert } = await supertestWithoutAuth + it(`shouldn't disable rule from another space`, async () => { + const { body: createdRule } = await supertestWithoutAuth .post(`${getUrlPrefix(Spaces.other.id)}/api/alerting/rule`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: true })) + .send(getTestRuleData({ enabled: true })) .expect(200); - objectRemover.add(Spaces.other.id, createdAlert.id, 'rule', 'alerting'); + objectRemover.add(Spaces.other.id, createdRule.id, 'rule', 'alerting'); - await alertUtils.getDisableRequest(createdAlert.id).expect(404, { + await ruleUtils.getDisableRequest(createdRule.id).expect(404, { statusCode: 404, error: 'Not Found', - message: `Saved object [alert/${createdAlert.id}] not found`, + message: `Saved object [alert/${createdRule.id}] not found`, }); }); - it('should create recovered-instance events for all alert instances', async () => { - const { body: createdAlert } = await supertest + it('should create recovered-instance events for all alerts', async () => { + const { body: createdRule } = await supertest .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) .set('kbn-xsrf', 'foo') .send({ @@ -96,12 +96,12 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte notify_when: 'onThrottleInterval', }) .expect(200); - objectRemover.add(Spaces.space1.id, createdAlert.id, 'rule', 'alerting'); + objectRemover.add(Spaces.space1.id, createdRule.id, 'rule', 'alerting'); - // wait for alert to actually execute + // wait for rule to actually execute await retry.try(async () => { const response = await supertest.get( - `${getUrlPrefix(Spaces.space1.id)}/internal/alerting/rule/${createdAlert.id}/state` + `${getUrlPrefix(Spaces.space1.id)}/internal/alerting/rule/${createdRule.id}/state` ); expect(response.status).to.eql(200); @@ -109,8 +109,8 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte expect(response.body.rule_type_state.runCount).to.greaterThan(1); }); - await alertUtils.getDisableRequest(createdAlert.id); - const ruleId = createdAlert.id; + await ruleUtils.getDisableRequest(createdRule.id); + const ruleId = createdRule.id; // wait for the events we're expecting const events = await retry.try(async () => { @@ -140,7 +140,7 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte shouldHaveTask: false, rule: { id: ruleId, - category: createdAlert.rule_type_id, + category: createdRule.rule_type_id, license: 'basic', ruleset: 'alertsFixture', name: 'abc', @@ -148,22 +148,46 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte }); }); + it('should disable rule even if associated task manager document is missing', async () => { + const { body: createdRule } = await supertestWithoutAuth + .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) + .set('kbn-xsrf', 'foo') + .send(getTestRuleData({ enabled: true })) + .expect(200); + objectRemover.add(Spaces.space1.id, createdRule.id, 'rule', 'alerting'); + + // manually remove scheduled task + await es.delete({ + id: `task:${createdRule.scheduled_task_id}`, + index: '.kibana_task_manager', + }); + await ruleUtils.disable(createdRule.id); + + // Ensure AAD isn't broken + await checkAAD({ + supertest: supertestWithoutAuth, + spaceId: Spaces.space1.id, + type: 'alert', + id: createdRule.id, + }); + }); + describe('legacy', () => { - it('should handle disable alert request appropriately', async () => { - const { body: createdAlert } = await supertestWithoutAuth + it('should handle disable rule request appropriately', async () => { + const { body: createdRule } = await supertestWithoutAuth .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerting/rule`) .set('kbn-xsrf', 'foo') - .send(getTestAlertData({ enabled: true })) + .send(getTestRuleData({ enabled: true })) .expect(200); - objectRemover.add(Spaces.space1.id, createdAlert.id, 'rule', 'alerting'); + objectRemover.add(Spaces.space1.id, createdRule.id, 'rule', 'alerting'); await supertestWithoutAuth - .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerts/alert/${createdAlert.id}/_disable`) + .post(`${getUrlPrefix(Spaces.space1.id)}/api/alerts/alert/${createdRule.id}/_disable`) .set('kbn-xsrf', 'foo') .expect(204); try { - await getScheduledTask(createdAlert.scheduledTaskId); + await getScheduledTask(createdRule.scheduled_task_id); throw new Error('Should have removed scheduled task'); } catch (e) { expect(e.meta.statusCode).to.eql(404); @@ -174,7 +198,7 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte supertest: supertestWithoutAuth, spaceId: Spaces.space1.id, type: 'alert', - id: createdAlert.id, + id: createdRule.id, }); }); }); diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/doc_count.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/doc_count.json index 5151f0adb0011..5edaafd30ad21 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/doc_count.json +++ b/x-pack/test/api_integration/apis/uptime/rest/fixtures/doc_count.json @@ -1,5 +1,5 @@ { "indexExists": true, "docCount": 1, - "indices": "heartbeat-8*,synthetics-*" + "indices": "heartbeat-8*,heartbeat-7*,synthetics-*" } diff --git a/x-pack/test/apm_api_integration/tests/metrics_charts/metrics_charts.spec.ts b/x-pack/test/apm_api_integration/tests/metrics_charts/metrics_charts.spec.ts index d70ee347d4c2d..beaaae24fb220 100644 --- a/x-pack/test/apm_api_integration/tests/metrics_charts/metrics_charts.spec.ts +++ b/x-pack/test/apm_api_integration/tests/metrics_charts/metrics_charts.spec.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { first } from 'lodash'; -import { GenericMetricsChart } from '../../../../plugins/apm/server/lib/metrics/fetch_and_transform_metrics'; +import { GenericMetricsChart } from '../../../../plugins/apm/server/routes/metrics/fetch_and_transform_metrics'; import { SupertestReturnType } from '../../common/apm_api_supertest'; import { FtrProviderContext } from '../../common/ftr_provider_context'; diff --git a/x-pack/test/apm_api_integration/tests/settings/agent_configuration.spec.ts b/x-pack/test/apm_api_integration/tests/settings/agent_configuration.spec.ts index df504ec7444d7..cea718c2c69d5 100644 --- a/x-pack/test/apm_api_integration/tests/settings/agent_configuration.spec.ts +++ b/x-pack/test/apm_api_integration/tests/settings/agent_configuration.spec.ts @@ -10,7 +10,7 @@ import { inspect } from 'util'; import expect from '@kbn/expect'; import { omit, orderBy } from 'lodash'; import { AgentConfigurationIntake } from '../../../../plugins/apm/common/agent_configuration/configuration_types'; -import { AgentConfigSearchParams } from '../../../../plugins/apm/server/routes/settings/agent_configuration'; +import { AgentConfigSearchParams } from '../../../../plugins/apm/server/routes/settings/agent_configuration/route'; import { FtrProviderContext } from '../../common/ftr_provider_context'; diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/generating_signals.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/generating_signals.ts index b28ff3fdc714d..073c5a9971f4b 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/generating_signals.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/generating_signals.ts @@ -56,6 +56,7 @@ import { ALERT_GROUP_ID, ALERT_THRESHOLD_RESULT, } from '../../../../plugins/security_solution/common/field_maps/field_names'; +import { DETECTION_ENGINE_RULES_URL } from '../../../../plugins/security_solution/common/constants'; /** * Specific _id to use for some of the tests. If the archiver changes and you see errors @@ -1157,5 +1158,71 @@ export default ({ getService }: FtrProviderContext) => { }); }); }); + + describe.skip('Signal deduplication', async () => { + before(async () => { + await esArchiver.load('x-pack/test/functional/es_archives/auditbeat/hosts'); + }); + + after(async () => { + await esArchiver.unload('x-pack/test/functional/es_archives/auditbeat/hosts'); + }); + + beforeEach(async () => { + await deleteSignalsIndex(supertest, log); + }); + + afterEach(async () => { + await deleteSignalsIndex(supertest, log); + await deleteAllAlerts(supertest, log); + }); + + it('should not generate duplicate signals', async () => { + const rule: QueryCreateSchema = { + ...getRuleForSignalTesting(['auditbeat-*']), + query: `_id:${ID}`, + }; + + const ruleResponse = await createRule(supertest, log, rule); + + const signals = await getOpenSignals(supertest, log, es, ruleResponse); + expect(signals.hits.hits.length).to.eql(1); + + const statusResponse = await supertest + .post(`${DETECTION_ENGINE_RULES_URL}/_find_statuses`) + .set('kbn-xsrf', 'true') + .send({ ids: [ruleResponse.id] }); + const initialStatusDate = new Date( + statusResponse.body[ruleResponse.id].current_status.status_date + ); + + const initialSignal = signals.hits.hits[0]; + + // Disable the rule then re-enable to trigger another run + await supertest + .patch(DETECTION_ENGINE_RULES_URL) + .set('kbn-xsrf', 'true') + .send({ rule_id: ruleResponse.rule_id, enabled: false }) + .expect(200); + + await supertest + .patch(DETECTION_ENGINE_RULES_URL) + .set('kbn-xsrf', 'true') + .send({ rule_id: ruleResponse.rule_id, enabled: true }) + .expect(200); + + await waitForRuleSuccessOrStatus( + supertest, + log, + ruleResponse.id, + 'succeeded', + initialStatusDate + ); + + const newSignals = await getOpenSignals(supertest, log, es, ruleResponse); + expect(newSignals.hits.hits.length).to.eql(1); + expect(newSignals.hits.hits[0]).to.eql(initialSignal); + }); + }); }); }; diff --git a/x-pack/test/detection_engine_api_integration/utils.ts b/x-pack/test/detection_engine_api_integration/utils.ts index cc915324a4a35..bb4f564edaf1e 100644 --- a/x-pack/test/detection_engine_api_integration/utils.ts +++ b/x-pack/test/detection_engine_api_integration/utils.ts @@ -1308,7 +1308,8 @@ export const waitForRuleSuccessOrStatus = async ( supertest: SuperTest.SuperTest, log: ToolingLog, id: string, - status: 'succeeded' | 'failed' | 'partial failure' | 'warning' = 'succeeded' + status: 'succeeded' | 'failed' | 'partial failure' | 'warning' = 'succeeded', + afterDate?: Date ): Promise => { await waitFor( async () => { @@ -1324,15 +1325,20 @@ export const waitForRuleSuccessOrStatus = async ( )}, status: ${JSON.stringify(response.status)}` ); } - if (response.body[id]?.current_status?.status !== status) { + const currentStatus = response.body[id]?.current_status; + + if (currentStatus?.status !== status) { log.debug( `Did not get an expected status of ${status} while waiting for a rule success or status for rule id ${id} (waitForRuleSuccessOrStatus). Will continue retrying until status is found. body: ${JSON.stringify( response.body )}, status: ${JSON.stringify(response.status)}` ); } - - return response.body[id]?.current_status?.status === status; + return ( + currentStatus != null && + currentStatus.status === status && + (afterDate ? new Date(currentStatus.status_date) > afterDate : true) + ); } catch (e) { if ((e as Error).message.includes('got 503 "Service Unavailable"')) { return false; diff --git a/x-pack/test/examples/search_examples/search_session_example.ts b/x-pack/test/examples/search_examples/search_session_example.ts index ab96a7767baff..e6261f69e14f6 100644 --- a/x-pack/test/examples/search_examples/search_session_example.ts +++ b/x-pack/test/examples/search_examples/search_session_example.ts @@ -15,7 +15,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const es = getService('es'); const searchSessions = getService('searchSessions'); - describe('Search session example', () => { + // FLAKY: https://github.com/elastic/kibana/issues/118921 + describe.skip('Search session example', () => { const appId = 'searchExamples'; before(async function () { diff --git a/x-pack/test/functional/apps/dev_tools/breadcrumbs.ts b/x-pack/test/functional/apps/dev_tools/breadcrumbs.ts new file mode 100644 index 0000000000000..c41e75c45fd43 --- /dev/null +++ b/x-pack/test/functional/apps/dev_tools/breadcrumbs.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const PageObjects = getPageObjects(['common']); + const testSubjects = getService('testSubjects'); + const security = getService('security'); + + describe('Breadcrumbs', () => { + before(async () => { + await security.testUser.setRoles(['global_devtools_read']); + await PageObjects.common.navigateToApp('searchProfiler'); + }); + + after(async () => { + await security.testUser.restoreDefaults(); + }); + + it('Sets the right breadcrumbs when navigating to console app', async () => { + await PageObjects.common.navigateToApp('dev_tools'); + + const lastBreadcrumbdcrumb = await testSubjects.getVisibleText('breadcrumb last'); + expect(lastBreadcrumbdcrumb).to.be('Console'); + }); + + it('Sets the right breadcrumbs when navigating to grok debugger app', async () => { + await PageObjects.common.navigateToApp('grokDebugger'); + + const lastBreadcrumb = await testSubjects.getVisibleText('breadcrumb last'); + expect(lastBreadcrumb).to.be('Grok Debugger'); + }); + + it('Sets the right breadcrumbs when navigating to search profiler app', async () => { + await PageObjects.common.navigateToApp('searchProfiler'); + + const lastBreadcrumb = await testSubjects.getVisibleText('breadcrumb last'); + expect(lastBreadcrumb).to.be('Search Profiler'); + }); + + it('Sets the right breadcrumbs when navigating to painless lab app', async () => { + await PageObjects.common.navigateToApp('painlessLab'); + + const lastBreadcrumb = await testSubjects.getVisibleText('breadcrumb last'); + expect(lastBreadcrumb).to.be('Painless Lab'); + }); + }); +} diff --git a/x-pack/test/functional/apps/dev_tools/index.ts b/x-pack/test/functional/apps/dev_tools/index.ts index 87904a5ab8cb8..4f0e9290cc25e 100644 --- a/x-pack/test/functional/apps/dev_tools/index.ts +++ b/x-pack/test/functional/apps/dev_tools/index.ts @@ -8,9 +8,10 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ loadTestFile }: FtrProviderContext) { - describe('console', function () { + describe('Dev Tools', function () { this.tags('ciGroup13'); + loadTestFile(require.resolve('./breadcrumbs')); loadTestFile(require.resolve('./feature_controls')); loadTestFile(require.resolve('./searchprofiler_editor')); }); diff --git a/x-pack/test/functional/apps/lens/index.ts b/x-pack/test/functional/apps/lens/index.ts index e63aadf3451d7..72442be7645fa 100644 --- a/x-pack/test/functional/apps/lens/index.ts +++ b/x-pack/test/functional/apps/lens/index.ts @@ -17,7 +17,7 @@ export default function ({ getService, loadTestFile, getPageObjects }: FtrProvid describe('lens app', () => { before(async () => { log.debug('Starting lens before method'); - await browser.setWindowSize(1280, 800); + await browser.setWindowSize(1280, 1200); await esArchiver.load('x-pack/test/functional/es_archives/logstash_functional'); // changing the timepicker default here saves us from having to set it in Discover (~8s) await PageObjects.timePicker.setDefaultAbsoluteRangeViaUiSettings(); diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index 5b7136a8d677b..78b9762e3889a 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -20,8 +20,6 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont const browser = getService('browser'); const dashboardAddPanel = getService('dashboardAddPanel'); - const FORMULA_TAB_HEIGHT = 40; - const PageObjects = getPageObjects([ 'common', 'header', @@ -133,7 +131,7 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont : `lns-indexPatternDimension-${opts.operation}`; async function getAriaPressed() { const operationSelectorContainer = await testSubjects.find(operationSelector); - await testSubjects.click(operationSelector, undefined, FORMULA_TAB_HEIGHT); + await testSubjects.click(operationSelector); const ariaPressed = await operationSelectorContainer.getAttribute('aria-pressed'); return ariaPressed; } @@ -872,7 +870,12 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont }, async openPalettePanel(chartType: string) { - await testSubjects.click(`${chartType}_dynamicColoring_trigger`); + await retry.try(async () => { + await testSubjects.click(`${chartType}_dynamicColoring_trigger`); + // wait for the UI to settle + await PageObjects.common.sleep(100); + await testSubjects.existOrFail('lns-indexPattern-PalettePanelContainer', { timeout: 2500 }); + }); }, async closePalettePanel() { diff --git a/x-pack/test/performance/tests/home.ts b/x-pack/test/performance/tests/home.ts new file mode 100644 index 0000000000000..eda690b9b0a19 --- /dev/null +++ b/x-pack/test/performance/tests/home.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrProviderContext } from '../ftr_provider_context'; + +export default function ({ getService, getPageObjects }: FtrProviderContext) { + const PageObjects = getPageObjects(['common', 'security']); + const testSubjects = getService('testSubjects'); + + describe('Login', () => { + it('login and navigate to homepage', async () => { + await PageObjects.common.navigateToApp('login'); + + await testSubjects.existOrFail('loginSubmit', { timeout: 2000 }); + + await PageObjects.security.login(); + + await testSubjects.existOrFail('homeApp', { timeout: 2000 }); + }); + }); +} diff --git a/x-pack/test/performance/tests/index.ts b/x-pack/test/performance/tests/index.ts index b1023bde688e2..d784fa3031739 100644 --- a/x-pack/test/performance/tests/index.ts +++ b/x-pack/test/performance/tests/index.ts @@ -11,6 +11,6 @@ export default function ({ loadTestFile }: FtrProviderContext) { describe('performance', function () { this.tags('ciGroup8'); - loadTestFile(require.resolve('./reporting_dashboard')); + loadTestFile(require.resolve('./home')); }); } diff --git a/x-pack/test/performance/tests/reporting_dashboard.ts b/x-pack/test/performance/tests/reporting_dashboard.ts index f363f8449df96..93b4010ab27a8 100644 --- a/x-pack/test/performance/tests/reporting_dashboard.ts +++ b/x-pack/test/performance/tests/reporting_dashboard.ts @@ -16,7 +16,7 @@ export default function ({ getService, getPageObject }: FtrProviderContext) { const dashboard = getPageObject('dashboard'); const reporting = getPageObject('reporting'); - describe('reporting dashbaord', () => { + describe('Reporting Dashboard', () => { before(async () => { await kibanaServer.importExport.load( 'x-pack/test/performance/kbn_archives/reporting_dashboard' diff --git a/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts index 35e316f309d7f..471d00728bac3 100644 --- a/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts +++ b/x-pack/test/security_solution_endpoint_api_int/apis/metadata.ts @@ -5,6 +5,7 @@ * 2.0. */ +import uuid from 'uuid'; import expect from '@kbn/expect'; import { FtrProviderContext } from '../ftr_provider_context'; import { @@ -31,317 +32,56 @@ import { indexFleetEndpointPolicy } from '../../../plugins/security_solution/com export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); - describe('test metadata api', () => { - describe('with .metrics-endpoint.metadata_united_default index', () => { - const numberOfHostsInFixture = 2; - - before(async () => { - await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); - await deleteAllDocsFromFleetAgents(getService); - await deleteAllDocsFromMetadataDatastream(getService); - await deleteAllDocsFromMetadataCurrentIndex(getService); - await deleteAllDocsFromIndex(getService, METADATA_UNITED_INDEX); - - // generate an endpoint policy and attach id to agents since - // metadata list api filters down to endpoint policies only - const policy = await indexFleetEndpointPolicy( - getService('kibanaServer'), - 'Default', - '1.1.1' - ); - const policyId = policy.integrationPolicies[0].policy_id; - const currentTime = new Date().getTime(); - - await Promise.all([ - bulkIndex(getService, AGENTS_INDEX, generateAgentDocs(currentTime, policyId)), - bulkIndex(getService, METADATA_DATASTREAM, generateMetadataDocs(currentTime)), - ]); - - // wait for latest metadata transform to run - await new Promise((r) => setTimeout(r, 30000)); - await startTransform(getService, METADATA_UNITED_TRANSFORM); - - // wait for united metadata transform to run - await new Promise((r) => setTimeout(r, 15000)); - }); - - after(async () => { - await deleteAllDocsFromFleetAgents(getService); - await deleteAllDocsFromMetadataDatastream(getService); - await deleteAllDocsFromMetadataCurrentIndex(getService); - await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); - await deleteAllDocsFromIndex(getService, METADATA_UNITED_INDEX); - }); - - it('should return one entry for each host with default paging', async () => { - const res = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send() - .expect(200); - const { body } = res; - expect(body.total).to.eql(numberOfHostsInFixture); - expect(body.hosts.length).to.eql(numberOfHostsInFixture); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); + describe('test metadata apis', () => { + describe('list endpoints POST route', () => { + describe('with .metrics-endpoint.metadata_united_default index', () => { + const numberOfHostsInFixture = 2; - it('metadata api should return page based on paging properties passed.', async () => { - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - paging_properties: [ - { - page_size: 1, - }, - { - page_index: 1, - }, - ], - }) - .expect(200); - expect(body.total).to.eql(numberOfHostsInFixture); - expect(body.hosts.length).to.eql(1); - expect(body.request_page_size).to.eql(1); - expect(body.request_page_index).to.eql(1); - }); - - it('metadata api should return accurate total metadata if page index produces no result', async () => { - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - paging_properties: [ - { - page_size: 10, - }, - { - page_index: 3, - }, - ], - }) - .expect(200); - expect(body.total).to.eql(numberOfHostsInFixture); - expect(body.hosts.length).to.eql(0); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(30); - }); - - it('metadata api should return 400 when pagingProperties is below boundaries.', async () => { - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - paging_properties: [ - { - page_size: 0, - }, - { - page_index: 1, - }, - ], - }) - .expect(400); - expect(body.message).to.contain('Value must be equal to or greater than [1]'); - }); - - it('metadata api should return page based on filters passed.', async () => { - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - filters: { - kql: 'not (united.endpoint.host.ip:10.101.149.26)', - }, - }) - .expect(200); - expect(body.total).to.eql(1); - expect(body.hosts.length).to.eql(1); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); - - it('metadata api should return page based on filters and paging passed.', async () => { - const notIncludedIp = '10.101.149.26'; - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - paging_properties: [ - { - page_size: 10, - }, - { - page_index: 0, - }, - ], - filters: { - kql: `not (united.endpoint.host.ip:${notIncludedIp})`, - }, - }) - .expect(200); - expect(body.total).to.eql(1); - const resultIps: string[] = [].concat( - ...body.hosts.map((hostInfo: Record) => hostInfo.metadata.host.ip) - ); - expect(resultIps.sort()).to.eql(['10.192.213.130', '10.70.28.129'].sort()); - expect(resultIps).not.include.eql(notIncludedIp); - expect(body.hosts.length).to.eql(1); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); - - it('metadata api should return page based on host.os.Ext.variant filter.', async () => { - const variantValue = 'Windows Pro'; - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - filters: { - kql: `united.endpoint.host.os.Ext.variant:${variantValue}`, - }, - }) - .expect(200); - expect(body.total).to.eql(2); - const resultOsVariantValue: Set = new Set( - body.hosts.map((hostInfo: Record) => hostInfo.metadata.host.os.Ext.variant) - ); - expect(Array.from(resultOsVariantValue)).to.eql([variantValue]); - expect(body.hosts.length).to.eql(2); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); - - it('metadata api should return the latest event for all the events for an endpoint', async () => { - const targetEndpointIp = '10.101.149.26'; - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - filters: { - kql: `united.endpoint.host.ip:${targetEndpointIp}`, - }, - }) - .expect(200); - expect(body.total).to.eql(1); - const resultIp: string = body.hosts[0].metadata.host.ip.filter( - (ip: string) => ip === targetEndpointIp - ); - expect(resultIp).to.eql([targetEndpointIp]); - expect(body.hosts.length).to.eql(1); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); - - it('metadata api should return the latest event for all the events where policy status is not success', async () => { - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - filters: { - kql: `not (united.endpoint.Endpoint.policy.applied.status:success)`, - }, - }) - .expect(200); - const statuses: Set = new Set( - body.hosts.map( - (hostInfo: Record) => hostInfo.metadata.Endpoint.policy.applied.status - ) - ); - expect(statuses.size).to.eql(1); - expect(Array.from(statuses)).to.eql(['failure']); - }); + before(async () => { + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteAllDocsFromFleetAgents(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + await deleteAllDocsFromIndex(getService, METADATA_UNITED_INDEX); - it('metadata api should return the endpoint based on the elastic agent id, and status should be healthy', async () => { - const targetEndpointId = 'fc0ff548-feba-41b6-8367-65e8790d0eaf'; - const targetElasticAgentId = '023fa40c-411d-4188-a941-4147bfadd095'; - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - filters: { - kql: `united.endpoint.elastic.agent.id:${targetElasticAgentId}`, - }, - }) - .expect(200); - expect(body.total).to.eql(1); - const resultHostId: string = body.hosts[0].metadata.host.id; - const resultElasticAgentId: string = body.hosts[0].metadata.elastic.agent.id; - expect(resultHostId).to.eql(targetEndpointId); - expect(resultElasticAgentId).to.eql(targetElasticAgentId); - expect(body.hosts[0].host_status).to.eql('healthy'); - expect(body.hosts.length).to.eql(1); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); + // generate an endpoint policy and attach id to agents since + // metadata list api filters down to endpoint policies only + const policy = await indexFleetEndpointPolicy( + getService('kibanaServer'), + `Default ${uuid.v4()}`, + '1.1.1' + ); + const policyId = policy.integrationPolicies[0].policy_id; + const currentTime = new Date().getTime(); - it('metadata api should return all hosts when filter is empty string', async () => { - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send({ - filters: { - kql: '', - }, - }) - .expect(200); - expect(body.total).to.eql(numberOfHostsInFixture); - expect(body.hosts.length).to.eql(numberOfHostsInFixture); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); - }); - }); + await Promise.all([ + bulkIndex(getService, AGENTS_INDEX, generateAgentDocs(currentTime, policyId)), + bulkIndex(getService, METADATA_DATASTREAM, generateMetadataDocs(currentTime)), + ]); - describe('with metrics-endpoint.metadata_current_default index', () => { - /** - * The number of host documents in the es archive. - */ - const numberOfHostsInFixture = 3; + // wait for latest metadata transform to run + await new Promise((r) => setTimeout(r, 30000)); + await startTransform(getService, METADATA_UNITED_TRANSFORM); - describe(`POST ${HOST_METADATA_LIST_ROUTE} when index is empty`, () => { - it('metadata api should return empty result when index is empty', async () => { - await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); - await deleteIndex(getService, METADATA_UNITED_INDEX); - await deleteMetadataStream(getService); - await deleteAllDocsFromMetadataDatastream(getService); - await deleteAllDocsFromMetadataCurrentIndex(getService); - const { body } = await supertest - .post(HOST_METADATA_LIST_ROUTE) - .set('kbn-xsrf', 'xxx') - .send() - .expect(200); - expect(body.total).to.eql(0); - expect(body.hosts.length).to.eql(0); - expect(body.request_page_size).to.eql(10); - expect(body.request_page_index).to.eql(0); + // wait for united metadata transform to run + await new Promise((r) => setTimeout(r, 15000)); }); - }); - describe(`POST ${HOST_METADATA_LIST_ROUTE} when index is not empty`, () => { - const timestamp = new Date().getTime(); - before(async () => { - // stop the united transform and delete the index - // otherwise it won't hit metrics-endpoint.metadata_current_default index - await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); - await deleteIndex(getService, METADATA_UNITED_INDEX); - await bulkIndex(getService, METADATA_DATASTREAM, generateMetadataDocs(timestamp)); - // wait for transform - await new Promise((r) => setTimeout(r, 60000)); - }); - // the endpoint uses data streams and es archiver does not support deleting them at the moment so we need - // to do it manually after(async () => { - await deleteMetadataStream(getService); + await deleteAllDocsFromFleetAgents(getService); await deleteAllDocsFromMetadataDatastream(getService); await deleteAllDocsFromMetadataCurrentIndex(getService); + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteAllDocsFromIndex(getService, METADATA_UNITED_INDEX); }); - it('metadata api should return one entry for each host with default paging', async () => { - const { body } = await supertest + + it('should return one entry for each host with default paging', async () => { + const res = await supertest .post(HOST_METADATA_LIST_ROUTE) .set('kbn-xsrf', 'xxx') .send() .expect(200); + const { body } = res; expect(body.total).to.eql(numberOfHostsInFixture); expect(body.hosts.length).to.eql(numberOfHostsInFixture); expect(body.request_page_size).to.eql(10); @@ -369,9 +109,6 @@ export default function ({ getService }: FtrProviderContext) { expect(body.request_page_index).to.eql(1); }); - /* test that when paging properties produces no result, the total should reflect the actual number of metadata - in the index. - */ it('metadata api should return accurate total metadata if page index produces no result', async () => { const { body } = await supertest .post(HOST_METADATA_LIST_ROUTE) @@ -417,18 +154,18 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .send({ filters: { - kql: 'not (HostDetails.host.ip:10.46.229.234 or host.ip:10.46.229.234)', + kql: 'not (united.endpoint.host.ip:10.101.149.26)', }, }) .expect(200); - expect(body.total).to.eql(2); - expect(body.hosts.length).to.eql(2); + expect(body.total).to.eql(1); + expect(body.hosts.length).to.eql(1); expect(body.request_page_size).to.eql(10); expect(body.request_page_index).to.eql(0); }); it('metadata api should return page based on filters and paging passed.', async () => { - const notIncludedIp = '10.46.229.234'; + const notIncludedIp = '10.101.149.26'; const { body } = await supertest .post(HOST_METADATA_LIST_ROUTE) .set('kbn-xsrf', 'xxx') @@ -442,24 +179,17 @@ export default function ({ getService }: FtrProviderContext) { }, ], filters: { - kql: `not (HostDetails.host.ip:${notIncludedIp} or host.ip:${notIncludedIp})`, + kql: `not (united.endpoint.host.ip:${notIncludedIp})`, }, }) .expect(200); - expect(body.total).to.eql(2); + expect(body.total).to.eql(1); const resultIps: string[] = [].concat( ...body.hosts.map((hostInfo: Record) => hostInfo.metadata.host.ip) ); - expect(resultIps.sort()).to.eql( - [ - '10.192.213.130', - '10.70.28.129', - '10.101.149.26', - '2606:a000:ffc0:39:11ef:37b9:3371:578c', - ].sort() - ); + expect(resultIps.sort()).to.eql(['10.192.213.130', '10.70.28.129'].sort()); expect(resultIps).not.include.eql(notIncludedIp); - expect(body.hosts.length).to.eql(2); + expect(body.hosts.length).to.eql(1); expect(body.request_page_size).to.eql(10); expect(body.request_page_index).to.eql(0); }); @@ -471,7 +201,7 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .send({ filters: { - kql: `HostDetails.host.os.Ext.variant:${variantValue} or host.os.Ext.variant:${variantValue}`, + kql: `united.endpoint.host.os.Ext.variant:${variantValue}`, }, }) .expect(200); @@ -486,13 +216,13 @@ export default function ({ getService }: FtrProviderContext) { }); it('metadata api should return the latest event for all the events for an endpoint', async () => { - const targetEndpointIp = '10.46.229.234'; + const targetEndpointIp = '10.101.149.26'; const { body } = await supertest .post(HOST_METADATA_LIST_ROUTE) .set('kbn-xsrf', 'xxx') .send({ filters: { - kql: `HostDetails.host.ip:${targetEndpointIp} or host.ip:${targetEndpointIp}`, + kql: `united.endpoint.host.ip:${targetEndpointIp}`, }, }) .expect(200); @@ -501,7 +231,6 @@ export default function ({ getService }: FtrProviderContext) { (ip: string) => ip === targetEndpointIp ); expect(resultIp).to.eql([targetEndpointIp]); - expect(body.hosts[0].metadata.event.created).to.eql(timestamp); expect(body.hosts.length).to.eql(1); expect(body.request_page_size).to.eql(10); expect(body.request_page_index).to.eql(0); @@ -513,7 +242,7 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .send({ filters: { - kql: `not (HostDetails.Endpoint.policy.applied.status:success or Endpoint.policy.applied.status:success)`, + kql: `not (united.endpoint.Endpoint.policy.applied.status:success)`, }, }) .expect(200); @@ -526,7 +255,7 @@ export default function ({ getService }: FtrProviderContext) { expect(Array.from(statuses)).to.eql(['failure']); }); - it('metadata api should return the endpoint based on the elastic agent id, and status should be unhealthy', async () => { + it('metadata api should return the endpoint based on the elastic agent id, and status should be healthy', async () => { const targetEndpointId = 'fc0ff548-feba-41b6-8367-65e8790d0eaf'; const targetElasticAgentId = '023fa40c-411d-4188-a941-4147bfadd095'; const { body } = await supertest @@ -534,7 +263,7 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .send({ filters: { - kql: `HostDetails.elastic.agent.id:${targetElasticAgentId} or elastic.agent.id:${targetElasticAgentId}`, + kql: `united.endpoint.elastic.agent.id:${targetElasticAgentId}`, }, }) .expect(200); @@ -543,8 +272,7 @@ export default function ({ getService }: FtrProviderContext) { const resultElasticAgentId: string = body.hosts[0].metadata.elastic.agent.id; expect(resultHostId).to.eql(targetEndpointId); expect(resultElasticAgentId).to.eql(targetElasticAgentId); - expect(body.hosts[0].metadata.event.created).to.eql(timestamp); - expect(body.hosts[0].host_status).to.eql('unhealthy'); + expect(body.hosts[0].host_status).to.eql('healthy'); expect(body.hosts.length).to.eql(1); expect(body.request_page_size).to.eql(10); expect(body.request_page_index).to.eql(0); @@ -566,6 +294,755 @@ export default function ({ getService }: FtrProviderContext) { expect(body.request_page_index).to.eql(0); }); }); + + describe('with metrics-endpoint.metadata_current_default index', () => { + /** + * The number of host documents in the es archive. + */ + const numberOfHostsInFixture = 3; + + describe(`POST ${HOST_METADATA_LIST_ROUTE} when index is empty`, () => { + it('metadata api should return empty result when index is empty', async () => { + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteIndex(getService, METADATA_UNITED_INDEX); + await deleteMetadataStream(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send() + .expect(200); + expect(body.total).to.eql(0); + expect(body.hosts.length).to.eql(0); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + }); + + describe(`POST ${HOST_METADATA_LIST_ROUTE} when index is not empty`, () => { + const timestamp = new Date().getTime(); + before(async () => { + // stop the united transform and delete the index + // otherwise it won't hit metrics-endpoint.metadata_current_default index + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteIndex(getService, METADATA_UNITED_INDEX); + await bulkIndex(getService, METADATA_DATASTREAM, generateMetadataDocs(timestamp)); + // wait for transform + await new Promise((r) => setTimeout(r, 60000)); + }); + // the endpoint uses data streams and es archiver does not support deleting them at the moment so we need + // to do it manually + after(async () => { + await deleteMetadataStream(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + }); + it('metadata api should return one entry for each host with default paging', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send() + .expect(200); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.hosts.length).to.eql(numberOfHostsInFixture); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + + it('metadata api should return page based on paging properties passed.', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + paging_properties: [ + { + page_size: 1, + }, + { + page_index: 1, + }, + ], + }) + .expect(200); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.hosts.length).to.eql(1); + expect(body.request_page_size).to.eql(1); + expect(body.request_page_index).to.eql(1); + }); + + /* test that when paging properties produces no result, the total should reflect the actual number of metadata + in the index. + */ + it('metadata api should return accurate total metadata if page index produces no result', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + paging_properties: [ + { + page_size: 10, + }, + { + page_index: 3, + }, + ], + }) + .expect(200); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.hosts.length).to.eql(0); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(30); + }); + + it('metadata api should return 400 when pagingProperties is below boundaries.', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + paging_properties: [ + { + page_size: 0, + }, + { + page_index: 1, + }, + ], + }) + .expect(400); + expect(body.message).to.contain('Value must be equal to or greater than [1]'); + }); + + it('metadata api should return page based on filters passed.', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + filters: { + kql: 'not (HostDetails.host.ip:10.46.229.234 or host.ip:10.46.229.234)', + }, + }) + .expect(200); + expect(body.total).to.eql(2); + expect(body.hosts.length).to.eql(2); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + + it('metadata api should return page based on filters and paging passed.', async () => { + const notIncludedIp = '10.46.229.234'; + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + paging_properties: [ + { + page_size: 10, + }, + { + page_index: 0, + }, + ], + filters: { + kql: `not (HostDetails.host.ip:${notIncludedIp} or host.ip:${notIncludedIp})`, + }, + }) + .expect(200); + expect(body.total).to.eql(2); + const resultIps: string[] = [].concat( + ...body.hosts.map((hostInfo: Record) => hostInfo.metadata.host.ip) + ); + expect(resultIps.sort()).to.eql( + [ + '10.192.213.130', + '10.70.28.129', + '10.101.149.26', + '2606:a000:ffc0:39:11ef:37b9:3371:578c', + ].sort() + ); + expect(resultIps).not.include.eql(notIncludedIp); + expect(body.hosts.length).to.eql(2); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + + it('metadata api should return page based on host.os.Ext.variant filter.', async () => { + const variantValue = 'Windows Pro'; + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + filters: { + kql: `HostDetails.host.os.Ext.variant:${variantValue} or host.os.Ext.variant:${variantValue}`, + }, + }) + .expect(200); + expect(body.total).to.eql(2); + const resultOsVariantValue: Set = new Set( + body.hosts.map( + (hostInfo: Record) => hostInfo.metadata.host.os.Ext.variant + ) + ); + expect(Array.from(resultOsVariantValue)).to.eql([variantValue]); + expect(body.hosts.length).to.eql(2); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + + it('metadata api should return the latest event for all the events for an endpoint', async () => { + const targetEndpointIp = '10.46.229.234'; + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + filters: { + kql: `HostDetails.host.ip:${targetEndpointIp} or host.ip:${targetEndpointIp}`, + }, + }) + .expect(200); + expect(body.total).to.eql(1); + const resultIp: string = body.hosts[0].metadata.host.ip.filter( + (ip: string) => ip === targetEndpointIp + ); + expect(resultIp).to.eql([targetEndpointIp]); + expect(body.hosts[0].metadata.event.created).to.eql(timestamp); + expect(body.hosts.length).to.eql(1); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + + it('metadata api should return the latest event for all the events where policy status is not success', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + filters: { + kql: `not (HostDetails.Endpoint.policy.applied.status:success or Endpoint.policy.applied.status:success)`, + }, + }) + .expect(200); + const statuses: Set = new Set( + body.hosts.map( + (hostInfo: Record) => hostInfo.metadata.Endpoint.policy.applied.status + ) + ); + expect(statuses.size).to.eql(1); + expect(Array.from(statuses)).to.eql(['failure']); + }); + + it('metadata api should return the endpoint based on the elastic agent id, and status should be unhealthy', async () => { + const targetEndpointId = 'fc0ff548-feba-41b6-8367-65e8790d0eaf'; + const targetElasticAgentId = '023fa40c-411d-4188-a941-4147bfadd095'; + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + filters: { + kql: `HostDetails.elastic.agent.id:${targetElasticAgentId} or elastic.agent.id:${targetElasticAgentId}`, + }, + }) + .expect(200); + expect(body.total).to.eql(1); + const resultHostId: string = body.hosts[0].metadata.host.id; + const resultElasticAgentId: string = body.hosts[0].metadata.elastic.agent.id; + expect(resultHostId).to.eql(targetEndpointId); + expect(resultElasticAgentId).to.eql(targetElasticAgentId); + expect(body.hosts[0].metadata.event.created).to.eql(timestamp); + expect(body.hosts[0].host_status).to.eql('unhealthy'); + expect(body.hosts.length).to.eql(1); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + + it('metadata api should return all hosts when filter is empty string', async () => { + const { body } = await supertest + .post(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .send({ + filters: { + kql: '', + }, + }) + .expect(200); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.hosts.length).to.eql(numberOfHostsInFixture); + expect(body.request_page_size).to.eql(10); + expect(body.request_page_index).to.eql(0); + }); + }); + }); + }); + + describe('list endpoints GET route', () => { + describe('with .metrics-endpoint.metadata_united_default index', () => { + const numberOfHostsInFixture = 2; + + before(async () => { + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteAllDocsFromFleetAgents(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + await deleteAllDocsFromIndex(getService, METADATA_UNITED_INDEX); + + // generate an endpoint policy and attach id to agents since + // metadata list api filters down to endpoint policies only + const policy = await indexFleetEndpointPolicy( + getService('kibanaServer'), + `Default ${uuid.v4()}`, + '1.1.1' + ); + const policyId = policy.integrationPolicies[0].policy_id; + const currentTime = new Date().getTime(); + + await Promise.all([ + bulkIndex(getService, AGENTS_INDEX, generateAgentDocs(currentTime, policyId)), + bulkIndex(getService, METADATA_DATASTREAM, generateMetadataDocs(currentTime)), + ]); + + // wait for latest metadata transform to run + await new Promise((r) => setTimeout(r, 30000)); + await startTransform(getService, METADATA_UNITED_TRANSFORM); + + // wait for united metadata transform to run + await new Promise((r) => setTimeout(r, 15000)); + }); + + after(async () => { + await deleteAllDocsFromFleetAgents(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteAllDocsFromIndex(getService, METADATA_UNITED_INDEX); + }); + + it('should return one entry for each host with default paging', async () => { + const res = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 0, + pageSize: 10, + }) + .expect(200); + const { body } = res; + expect(body.data.length).to.eql(numberOfHostsInFixture); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return page based on paging properties passed', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 1, + pageSize: 1, + }) + .expect(200); + expect(body.data.length).to.eql(1); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(1); + expect(body.pageSize).to.eql(1); + }); + + it('metadata api should return accurate total metadata if page index produces no result', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 3, + pageSize: 10, + }) + .expect(200); + expect(body.data.length).to.eql(0); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(3); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return 400 when pagingProperties is below boundaries.', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 1, + pageSize: 0, + }) + .expect(400); + expect(body.message).to.contain('Value must be equal to or greater than [1]'); + }); + + it('metadata api should return page based on filters passed.', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: 'not (united.endpoint.host.ip:10.101.149.26)', + }) + .expect(200); + expect(body.data.length).to.eql(1); + expect(body.total).to.eql(1); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return page based on filters and paging passed.', async () => { + const notIncludedIp = '10.101.149.26'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 0, + pageSize: 10, + kuery: `not (united.endpoint.host.ip:${notIncludedIp})`, + }) + .expect(200); + expect(body.total).to.eql(1); + const resultIps: string[] = [].concat( + ...body.data.map((hostInfo: Record) => hostInfo.metadata.host.ip) + ); + expect(resultIps.sort()).to.eql(['10.192.213.130', '10.70.28.129'].sort()); + expect(resultIps).not.include.eql(notIncludedIp); + expect(body.data.length).to.eql(1); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return page based on host.os.Ext.variant filter.', async () => { + const variantValue = 'Windows Pro'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `united.endpoint.host.os.Ext.variant:${variantValue}`, + }) + .expect(200); + expect(body.total).to.eql(2); + const resultOsVariantValue: Set = new Set( + body.data.map((hostInfo: Record) => hostInfo.metadata.host.os.Ext.variant) + ); + expect(Array.from(resultOsVariantValue)).to.eql([variantValue]); + expect(body.data.length).to.eql(2); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return the latest event for all the events for an endpoint', async () => { + const targetEndpointIp = '10.101.149.26'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `united.endpoint.host.ip:${targetEndpointIp}`, + }) + .expect(200); + expect(body.total).to.eql(1); + const resultIp: string = body.data[0].metadata.host.ip.filter( + (ip: string) => ip === targetEndpointIp + ); + expect(resultIp).to.eql([targetEndpointIp]); + expect(body.data.length).to.eql(1); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return the latest event for all the events where policy status is not success', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: 'not (united.endpoint.Endpoint.policy.applied.status:success)', + }) + .expect(200); + const statuses: Set = new Set( + body.data.map( + (hostInfo: Record) => hostInfo.metadata.Endpoint.policy.applied.status + ) + ); + expect(statuses.size).to.eql(1); + expect(Array.from(statuses)).to.eql(['failure']); + }); + + it('metadata api should return the endpoint based on the elastic agent id, and status should be healthy', async () => { + const targetEndpointId = 'fc0ff548-feba-41b6-8367-65e8790d0eaf'; + const targetElasticAgentId = '023fa40c-411d-4188-a941-4147bfadd095'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `united.endpoint.elastic.agent.id:${targetElasticAgentId}`, + }) + .expect(200); + expect(body.total).to.eql(1); + const resultHostId: string = body.data[0].metadata.host.id; + const resultElasticAgentId: string = body.data[0].metadata.elastic.agent.id; + expect(resultHostId).to.eql(targetEndpointId); + expect(resultElasticAgentId).to.eql(targetElasticAgentId); + expect(body.data.length).to.eql(1); + expect(body.data[0].host_status).to.eql('healthy'); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return all hosts when filter is empty string', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .expect(200); + expect(body.data.length).to.eql(numberOfHostsInFixture); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + }); + + describe('with metrics-endpoint.metadata_current_default index', () => { + /** + * The number of host documents in the es archive. + */ + const numberOfHostsInFixture = 3; + + describe('when index is empty', () => { + it('metadata api should return empty result when index is empty', async () => { + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteIndex(getService, METADATA_UNITED_INDEX); + await deleteMetadataStream(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 0, + pageSize: 10, + }) + .expect(200); + expect(body.data.length).to.eql(0); + expect(body.total).to.eql(0); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + }); + + describe('when index is not empty', () => { + const timestamp = new Date().getTime(); + before(async () => { + // stop the united transform and delete the index + // otherwise it won't hit metrics-endpoint.metadata_current_default index + await stopTransform(getService, `${METADATA_UNITED_TRANSFORM}*`); + await deleteIndex(getService, METADATA_UNITED_INDEX); + await bulkIndex(getService, METADATA_DATASTREAM, generateMetadataDocs(timestamp)); + // wait for transform + await new Promise((r) => setTimeout(r, 60000)); + }); + // the endpoint uses data streams and es archiver does not support deleting them at the moment so we need + // to do it manually + after(async () => { + await deleteMetadataStream(getService); + await deleteAllDocsFromMetadataDatastream(getService); + await deleteAllDocsFromMetadataCurrentIndex(getService); + }); + + it('metadata api should return one entry for each host with default paging', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 0, + pageSize: 10, + }) + .expect(200); + expect(body.data.length).to.eql(numberOfHostsInFixture); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return page based on paging properties passed.', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 1, + pageSize: 1, + }) + .expect(200); + expect(body.data.length).to.eql(1); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(1); + expect(body.pageSize).to.eql(1); + }); + + /* test that when paging properties produces no result, the total should reflect the actual number of metadata + in the index. + */ + it('metadata api should return accurate total metadata if page index produces no result', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 3, + pageSize: 10, + }) + .expect(200); + expect(body.data.length).to.eql(0); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(3); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return 400 when pagingProperties is below boundaries.', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 1, + pageSize: 0, + }) + .expect(400); + expect(body.message).to.contain('Value must be equal to or greater than [1]'); + }); + + it('metadata api should return page based on filters passed.', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: 'not (HostDetails.host.ip:10.46.229.234 or host.ip:10.46.229.234)', + }) + .expect(200); + expect(body.data.length).to.eql(2); + expect(body.total).to.eql(2); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return page based on filters and paging passed.', async () => { + const notIncludedIp = '10.46.229.234'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + page: 0, + pageSize: 10, + kuery: `not (HostDetails.host.ip:${notIncludedIp} or host.ip:${notIncludedIp})`, + }) + .expect(200); + expect(body.data.length).to.eql(2); + expect(body.total).to.eql(2); + const resultIps: string[] = [].concat( + ...body.data.map((hostInfo: Record) => hostInfo.metadata.host.ip) + ); + expect(resultIps.sort()).to.eql( + [ + '10.192.213.130', + '10.70.28.129', + '10.101.149.26', + '2606:a000:ffc0:39:11ef:37b9:3371:578c', + ].sort() + ); + expect(resultIps).not.include.eql(notIncludedIp); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return page based on host.os.Ext.variant filter.', async () => { + const variantValue = 'Windows Pro'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `HostDetails.host.os.Ext.variant:${variantValue} or host.os.Ext.variant:${variantValue}`, + }) + .expect(200); + expect(body.data.length).to.eql(2); + expect(body.total).to.eql(2); + const resultOsVariantValue: Set = new Set( + body.data.map( + (hostInfo: Record) => hostInfo.metadata.host.os.Ext.variant + ) + ); + expect(Array.from(resultOsVariantValue)).to.eql([variantValue]); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return the latest event for all the events for an endpoint', async () => { + const targetEndpointIp = '10.46.229.234'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `HostDetails.host.ip:${targetEndpointIp} or host.ip:${targetEndpointIp}`, + }) + .expect(200); + expect(body.data.length).to.eql(1); + expect(body.total).to.eql(1); + const resultIp: string = body.data[0].metadata.host.ip.filter( + (ip: string) => ip === targetEndpointIp + ); + expect(resultIp).to.eql([targetEndpointIp]); + expect(body.data[0].metadata.event.created).to.eql(timestamp); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return the latest event for all the events where policy status is not success', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: + 'not (HostDetails.Endpoint.policy.applied.status:success or Endpoint.policy.applied.status:success)', + }) + .expect(200); + const statuses: Set = new Set( + body.data.map( + (hostInfo: Record) => hostInfo.metadata.Endpoint.policy.applied.status + ) + ); + expect(statuses.size).to.eql(1); + expect(Array.from(statuses)).to.eql(['failure']); + }); + + it('metadata api should return the endpoint based on the elastic agent id, and status should be unhealthy', async () => { + const targetEndpointId = 'fc0ff548-feba-41b6-8367-65e8790d0eaf'; + const targetElasticAgentId = '023fa40c-411d-4188-a941-4147bfadd095'; + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: `HostDetails.elastic.agent.id:${targetElasticAgentId} or elastic.agent.id:${targetElasticAgentId}`, + }) + .expect(200); + expect(body.data.length).to.eql(1); + expect(body.total).to.eql(1); + const resultHostId: string = body.data[0].metadata.host.id; + const resultElasticAgentId: string = body.data[0].metadata.elastic.agent.id; + expect(resultHostId).to.eql(targetEndpointId); + expect(resultElasticAgentId).to.eql(targetElasticAgentId); + expect(body.data[0].metadata.event.created).to.eql(timestamp); + expect(body.data[0].host_status).to.eql('unhealthy'); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + + it('metadata api should return all hosts when filter is empty string', async () => { + const { body } = await supertest + .get(HOST_METADATA_LIST_ROUTE) + .set('kbn-xsrf', 'xxx') + .query({ + kuery: '', + }) + .expect(200); + expect(body.data.length).to.eql(numberOfHostsInFixture); + expect(body.total).to.eql(numberOfHostsInFixture); + expect(body.page).to.eql(0); + expect(body.pageSize).to.eql(10); + }); + }); + }); }); }); } diff --git a/x-pack/test/upgrade/apps/dashboard/dashboard_smoke_tests.ts b/x-pack/test/upgrade/apps/dashboard/dashboard_smoke_tests.ts index 2c79191f6269d..c983361071170 100644 --- a/x-pack/test/upgrade/apps/dashboard/dashboard_smoke_tests.ts +++ b/x-pack/test/upgrade/apps/dashboard/dashboard_smoke_tests.ts @@ -12,7 +12,6 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getPageObjects, getService }: FtrProviderContext) { const find = getService('find'); const log = getService('log'); - const pieChart = getService('pieChart'); const renderable = getService('renderable'); const dashboardExpect = getService('dashboardExpect'); const PageObjects = getPageObjects(['common', 'header', 'home', 'dashboard', 'timePicker']); @@ -63,10 +62,6 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await PageObjects.home.launchSampleDashboard('flights'); await PageObjects.header.waitUntilLoadingHasFinished(); await renderable.waitForRender(); - log.debug('Checking pie charts rendered'); - await pieChart.expectPieSliceCount(4); - log.debug('Checking area, bar and heatmap charts rendered'); - await dashboardExpect.seriesElementCount(15); log.debug('Checking saved searches rendered'); await dashboardExpect.savedSearchRowCount(49); log.debug('Checking input controls rendered'); diff --git a/x-pack/test/upgrade/apps/maps/maps_smoke_tests.ts b/x-pack/test/upgrade/apps/maps/maps_smoke_tests.ts index fb8d8c6c59a9d..53acb8b016313 100644 --- a/x-pack/test/upgrade/apps/maps/maps_smoke_tests.ts +++ b/x-pack/test/upgrade/apps/maps/maps_smoke_tests.ts @@ -168,7 +168,7 @@ export default function ({ await PageObjects.header.waitUntilLoadingHasFinished(); await PageObjects.maps.waitForLayersToLoad(); await PageObjects.maps.toggleLayerVisibility('Road map - desaturated'); - await PageObjects.maps.toggleLayerVisibility('Total Requests by Destination'); + await PageObjects.maps.toggleLayerVisibility('Total Requests by Country'); await PageObjects.timePicker.setCommonlyUsedTime('sample_data range'); await PageObjects.maps.enterFullScreen(); await PageObjects.maps.closeLegend(); diff --git a/yarn.lock b/yarn.lock index 9f661aca62673..2f3d3865b54ee 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1623,10 +1623,10 @@ dependencies: object-hash "^1.3.0" -"@elastic/charts@39.0.1": - version "39.0.1" - resolved "https://registry.yarnpkg.com/@elastic/charts/-/charts-39.0.1.tgz#7891d6efb3a12eb73fcb57d9a1f71565c22f4501" - integrity sha512-k64+vrfRkP7Gn8+T0Vtdev/DKpy6G+M9H6OFQcf1fgXAd7qOnTXVaN4Ru+BRTPylTFwxf9pqHraz8Ayi+3VpjA== +"@elastic/charts@39.0.2": + version "39.0.2" + resolved "https://registry.yarnpkg.com/@elastic/charts/-/charts-39.0.2.tgz#5533fc57c4ceed4c5ae826cd9a13c55cc03c55e5" + integrity sha512-jjdZSV6PGKsjA2qDAwEw+SjHWq5/Rm9FQk9lrmxrX+0rc7TlsPyr840RT1BAfkDDoo8+o3WWbfg+r61Y0FQ1Pg== dependencies: "@popperjs/core" "^2.4.0" chroma-js "^2.1.0" @@ -1697,10 +1697,10 @@ resolved "https://registry.yarnpkg.com/@elastic/eslint-plugin-eui/-/eslint-plugin-eui-0.0.2.tgz#56b9ef03984a05cc213772ae3713ea8ef47b0314" integrity sha512-IoxURM5zraoQ7C8f+mJb9HYSENiZGgRVcG4tLQxE61yHNNRDXtGDWTZh8N1KIHcsqN1CEPETjuzBXkJYF/fDiQ== -"@elastic/eui@40.1.0": - version "40.1.0" - resolved "https://registry.yarnpkg.com/@elastic/eui/-/eui-40.1.0.tgz#d5ad63e9ed4ae482037a637e9b3f2598712c9e94" - integrity sha512-xlmbu4ZjdKtpgkQZ6GNMWCyyjSJaNFPMj97pLs11UEag2L1W0IwISlGF9+K45Qp4KLatR6iphwiyLFGmqGOOTA== +"@elastic/eui@41.0.0": + version "41.0.0" + resolved "https://registry.yarnpkg.com/@elastic/eui/-/eui-41.0.0.tgz#64d7efef5a15d5495f2db1eebd5384e412296e06" + integrity sha512-+cExohPqWzahLW6Z6X6dc0voaDkYQ4ruHMSFe0H78YhTECrbu+f9mWDx841C7WDtvKKJVPbCZ/dyTeB2Ogwabw== dependencies: "@types/chroma-js" "^2.0.0" "@types/lodash" "^4.14.160" @@ -1718,7 +1718,6 @@ mdast-util-to-hast "^10.0.0" numeral "^2.0.6" prop-types "^15.6.0" - react-ace "^7.0.5" react-beautiful-dnd "^13.0.0" react-dropzone "^11.2.0" react-focus-on "^3.5.0" @@ -5387,6 +5386,10 @@ resolved "https://registry.yarnpkg.com/@types/ejs/-/ejs-3.0.6.tgz#aca442289df623bfa8e47c23961f0357847b83fe" integrity sha512-fj1hi+ZSW0xPLrJJD+YNwIh9GZbyaIepG26E/gXvp8nCa2pYokxUYO1sK9qjGxp2g8ryZYuon7wmjpwE2cyASQ== +"@types/elastic__apm-synthtrace@link:bazel-bin/packages/elastic-apm-synthtrace/npm_module_types": + version "0.0.0" + uid "" + "@types/elastic__datemath@link:bazel-bin/packages/elastic-datemath/npm_module_types": version "0.0.0" uid ""