From 653c28a8895e08665f35e8c88c8fc1413f67bff4 Mon Sep 17 00:00:00 2001 From: Andrew Cholakian Date: Mon, 3 Feb 2020 20:09:56 -0600 Subject: [PATCH 01/11] [Uptime] Add unit tests for QueryContext time calculation (#56671) Add Unit tests for the QueryContext class that was missing testing. This would have caught #56612 --- .../search/__tests__/query_context.test.ts | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 x-pack/legacy/plugins/uptime/server/lib/adapters/monitor_states/search/__tests__/query_context.test.ts diff --git a/x-pack/legacy/plugins/uptime/server/lib/adapters/monitor_states/search/__tests__/query_context.test.ts b/x-pack/legacy/plugins/uptime/server/lib/adapters/monitor_states/search/__tests__/query_context.test.ts new file mode 100644 index 00000000000000..8924d07ac0c4dc --- /dev/null +++ b/x-pack/legacy/plugins/uptime/server/lib/adapters/monitor_states/search/__tests__/query_context.test.ts @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { QueryContext } from '../query_context'; +import { CursorPagination } from '../..'; +import { CursorDirection, SortOrder } from '../../../../../../common/graphql/types'; + +describe(QueryContext, () => { + // 10 minute range + const rangeStart = '2019-02-03T19:06:54.939Z'; + const rangeEnd = '2019-02-03T19:16:54.939Z'; + + const pagination: CursorPagination = { + cursorDirection: CursorDirection.AFTER, + sortOrder: SortOrder.DESC, + }; + + let qc: QueryContext; + beforeEach(() => (qc = new QueryContext({}, rangeStart, rangeEnd, pagination, null, 10))); + + describe('dateRangeFilter()', () => { + const expectedRange = { + range: { + '@timestamp': { + gte: rangeStart, + lte: rangeEnd, + }, + }, + }; + describe('when hasTimespan() is true', () => { + it('should create a date range filter including the timespan', async () => { + const mockHasTimespan = jest.fn(); + mockHasTimespan.mockReturnValue(true); + qc.hasTimespan = mockHasTimespan; + + expect(await qc.dateRangeFilter()).toEqual({ + bool: { + filter: [ + expectedRange, + { + bool: { + should: [ + qc.timespanClause(), + { bool: { must_not: { exists: { field: 'monitor.timespan' } } } }, + ], + }, + }, + ], + }, + }); + }); + }); + + describe('when hasTimespan() is false', () => { + it('should only use the timestamp fields in the returned filter', async () => { + const mockHasTimespan = jest.fn(); + mockHasTimespan.mockReturnValue(false); + qc.hasTimespan = mockHasTimespan; + + expect(await qc.dateRangeFilter()).toEqual(expectedRange); + }); + }); + }); + + describe('timespanClause()', () => { + it('should always cover the last 5m', () => { + // 5m expected range between GTE and LTE in the response + // since timespan is hardcoded to 5m + expect(qc.timespanClause()).toEqual({ + range: { + 'monitor.timespan': { + // end date minus 5m + gte: new Date(Date.parse(rangeEnd) - 5 * 60 * 1000).toISOString(), + lte: rangeEnd, + }, + }, + }); + }); + }); +}); From 0f117c9c3276c40f40a4812c128a266db6174346 Mon Sep 17 00:00:00 2001 From: Nick Partridge Date: Mon, 3 Feb 2020 22:05:32 -0600 Subject: [PATCH 02/11] Vislib replacement toggle (#56439) * Add new vislib replacement plugin shell * Add config to toggle new vislib replacement --- .github/CODEOWNERS | 1 + .i18nrc.json | 6 +- .sass-lint.yml | 1 + .../vis_type_vislib/public/plugin.ts | 32 ++++++-- src/legacy/core_plugins/vis_type_xy/index.ts | 56 +++++++++++++ .../core_plugins/vis_type_xy/package.json | 4 + .../core_plugins/vis_type_xy/public/index.ts | 25 ++++++ .../core_plugins/vis_type_xy/public/legacy.ts | 44 ++++++++++ .../core_plugins/vis_type_xy/public/plugin.ts | 82 +++++++++++++++++++ 9 files changed, 244 insertions(+), 7 deletions(-) create mode 100644 src/legacy/core_plugins/vis_type_xy/index.ts create mode 100644 src/legacy/core_plugins/vis_type_xy/package.json create mode 100644 src/legacy/core_plugins/vis_type_xy/public/index.ts create mode 100644 src/legacy/core_plugins/vis_type_xy/public/legacy.ts create mode 100644 src/legacy/core_plugins/vis_type_xy/public/plugin.ts diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0b0addf117f6fc..de7159489689e9 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -15,6 +15,7 @@ /src/legacy/core_plugins/kibana/public/dev_tools/ @elastic/kibana-app /src/legacy/core_plugins/metrics/ @elastic/kibana-app /src/legacy/core_plugins/vis_type_vislib/ @elastic/kibana-app +/src/legacy/core_plugins/vis_type_xy/ @elastic/kibana-app # Exclude tutorials folder for now because they are not owned by Kibana app and most will move out soon /src/plugins/home/public @elastic/kibana-app /src/plugins/home/server/*.ts @elastic/kibana-app diff --git a/.i18nrc.json b/.i18nrc.json index 1230151212f573..7d7685b5c1ef1b 100644 --- a/.i18nrc.json +++ b/.i18nrc.json @@ -22,7 +22,10 @@ "interpreter": "src/legacy/core_plugins/interpreter", "kbn": "src/legacy/core_plugins/kibana", "kbnDocViews": "src/legacy/core_plugins/kbn_doc_views", - "management": ["src/legacy/core_plugins/management", "src/plugins/management"], + "management": [ + "src/legacy/core_plugins/management", + "src/plugins/management" + ], "kibana_react": "src/legacy/core_plugins/kibana_react", "kibana-react": "src/plugins/kibana_react", "kibana_utils": "src/plugins/kibana_utils", @@ -43,6 +46,7 @@ "visTypeTimeseries": ["src/legacy/core_plugins/vis_type_timeseries", "src/plugins/vis_type_timeseries"], "visTypeVega": "src/legacy/core_plugins/vis_type_vega", "visTypeVislib": "src/legacy/core_plugins/vis_type_vislib", + "visTypeXy": "src/legacy/core_plugins/vis_type_xy", "visualizations": [ "src/plugins/visualizations", "src/legacy/core_plugins/visualizations" diff --git a/.sass-lint.yml b/.sass-lint.yml index fba2c003484f6a..9c64c1e5eea569 100644 --- a/.sass-lint.yml +++ b/.sass-lint.yml @@ -3,6 +3,7 @@ files: - 'src/legacy/core_plugins/metrics/**/*.s+(a|c)ss' - 'src/legacy/core_plugins/timelion/**/*.s+(a|c)ss' - 'src/legacy/core_plugins/vis_type_vislib/**/*.s+(a|c)ss' + - 'src/legacy/core_plugins/vis_type_xy/**/*.s+(a|c)ss' - 'x-pack/legacy/plugins/rollup/**/*.s+(a|c)ss' - 'x-pack/legacy/plugins/security/**/*.s+(a|c)ss' - 'x-pack/legacy/plugins/canvas/**/*.s+(a|c)ss' diff --git a/src/legacy/core_plugins/vis_type_vislib/public/plugin.ts b/src/legacy/core_plugins/vis_type_vislib/public/plugin.ts index 9bf7ee3d594013..056849a2926570 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/plugin.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/plugin.ts @@ -39,6 +39,7 @@ import { createGoalVisTypeDefinition, } from './vis_type_vislib_vis_types'; import { ChartsPluginSetup } from '../../../../plugins/charts/public'; +import { ConfigSchema as VisTypeXyConfigSchema } from '../../vis_type_xy'; export interface VisTypeVislibDependencies { uiSettings: IUiSettingsClient; @@ -72,11 +73,7 @@ export class VisTypeVislibPlugin implements Plugin, void> { uiSettings: core.uiSettings, charts, }; - - expressions.registerFunction(createVisTypeVislibVisFn); - expressions.registerFunction(createPieVisFn); - - [ + const vislibTypes = [ createHistogramVisTypeDefinition, createLineVisTypeDefinition, createPieVisTypeDefinition, @@ -85,7 +82,30 @@ export class VisTypeVislibPlugin implements Plugin, void> { createHorizontalBarVisTypeDefinition, createGaugeVisTypeDefinition, createGoalVisTypeDefinition, - ].forEach(vis => visualizations.types.createBaseVisualization(vis(visualizationDependencies))); + ]; + const vislibFns = [createVisTypeVislibVisFn, createPieVisFn]; + + const visTypeXy = core.injectedMetadata.getInjectedVar('visTypeXy') as + | VisTypeXyConfigSchema['visTypeXy'] + | undefined; + + // if visTypeXy plugin is disabled it's config will be undefined + if (!visTypeXy || !visTypeXy.enabled) { + const convertedTypes: any[] = []; + const convertedFns: any[] = []; + + // Register legacy vislib types that have been converted + convertedFns.forEach(expressions.registerFunction); + convertedTypes.forEach(vis => + visualizations.types.createBaseVisualization(vis(visualizationDependencies)) + ); + } + + // Register non-converted types + vislibFns.forEach(expressions.registerFunction); + vislibTypes.forEach(vis => + visualizations.types.createBaseVisualization(vis(visualizationDependencies)) + ); } public start(core: CoreStart, deps: VisTypeVislibPluginStartDependencies) { diff --git a/src/legacy/core_plugins/vis_type_xy/index.ts b/src/legacy/core_plugins/vis_type_xy/index.ts new file mode 100644 index 00000000000000..975399f891503d --- /dev/null +++ b/src/legacy/core_plugins/vis_type_xy/index.ts @@ -0,0 +1,56 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { resolve } from 'path'; +import { Legacy } from 'kibana'; + +import { LegacyPluginApi, LegacyPluginInitializer } from '../../types'; + +export interface ConfigSchema { + visTypeXy: { + enabled: boolean; + }; +} + +const visTypeXyPluginInitializer: LegacyPluginInitializer = ({ Plugin }: LegacyPluginApi) => + new Plugin({ + id: 'visTypeXy', + require: ['kibana', 'elasticsearch', 'visualizations', 'interpreter', 'data'], + publicDir: resolve(__dirname, 'public'), + uiExports: { + hacks: [resolve(__dirname, 'public/legacy')], + injectDefaultVars(server): ConfigSchema { + const config = server.config(); + + return { + visTypeXy: { + enabled: config.get('visTypeXy.enabled') as boolean, + }, + }; + }, + }, + config(Joi: any) { + return Joi.object({ + enabled: Joi.boolean().default(false), + }).default(); + }, + } as Legacy.PluginSpecOptions); + +// eslint-disable-next-line import/no-default-export +export default visTypeXyPluginInitializer; diff --git a/src/legacy/core_plugins/vis_type_xy/package.json b/src/legacy/core_plugins/vis_type_xy/package.json new file mode 100644 index 00000000000000..920f7dcb44e87c --- /dev/null +++ b/src/legacy/core_plugins/vis_type_xy/package.json @@ -0,0 +1,4 @@ +{ + "name": "visTypeXy", + "version": "kibana" +} diff --git a/src/legacy/core_plugins/vis_type_xy/public/index.ts b/src/legacy/core_plugins/vis_type_xy/public/index.ts new file mode 100644 index 00000000000000..218dc8aa8a6831 --- /dev/null +++ b/src/legacy/core_plugins/vis_type_xy/public/index.ts @@ -0,0 +1,25 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { PluginInitializerContext } from '../../../../core/public'; +import { VisTypeXyPlugin as Plugin } from './plugin'; + +export function plugin(initializerContext: PluginInitializerContext) { + return new Plugin(initializerContext); +} diff --git a/src/legacy/core_plugins/vis_type_xy/public/legacy.ts b/src/legacy/core_plugins/vis_type_xy/public/legacy.ts new file mode 100644 index 00000000000000..e1cee9c30804a2 --- /dev/null +++ b/src/legacy/core_plugins/vis_type_xy/public/legacy.ts @@ -0,0 +1,44 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { npSetup, npStart } from 'ui/new_platform'; +import { PluginInitializerContext } from 'kibana/public'; + +import { plugin } from '.'; +import { VisTypeXyPluginSetupDependencies, VisTypeXyPluginStartDependencies } from './plugin'; +import { + setup as visualizationsSetup, + start as visualizationsStart, +} from '../../visualizations/public/np_ready/public/legacy'; + +const setupPlugins: Readonly = { + expressions: npSetup.plugins.expressions, + visualizations: visualizationsSetup, + charts: npSetup.plugins.charts, +}; + +const startPlugins: Readonly = { + expressions: npStart.plugins.expressions, + visualizations: visualizationsStart, +}; + +const pluginInstance = plugin({} as PluginInitializerContext); + +export const setup = pluginInstance.setup(npSetup.core, setupPlugins); +export const start = pluginInstance.start(npStart.core, startPlugins); diff --git a/src/legacy/core_plugins/vis_type_xy/public/plugin.ts b/src/legacy/core_plugins/vis_type_xy/public/plugin.ts new file mode 100644 index 00000000000000..59bb64b337256c --- /dev/null +++ b/src/legacy/core_plugins/vis_type_xy/public/plugin.ts @@ -0,0 +1,82 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + CoreSetup, + CoreStart, + Plugin, + IUiSettingsClient, + PluginInitializerContext, +} from 'kibana/public'; + +import { Plugin as ExpressionsPublicPlugin } from '../../../../plugins/expressions/public'; +import { VisualizationsSetup, VisualizationsStart } from '../../visualizations/public'; +import { ChartsPluginSetup } from '../../../../plugins/charts/public'; + +export interface VisTypeXyDependencies { + uiSettings: IUiSettingsClient; + charts: ChartsPluginSetup; +} + +/** @internal */ +export interface VisTypeXyPluginSetupDependencies { + expressions: ReturnType; + visualizations: VisualizationsSetup; + charts: ChartsPluginSetup; +} + +/** @internal */ +export interface VisTypeXyPluginStartDependencies { + expressions: ReturnType; + visualizations: VisualizationsStart; +} + +type VisTypeXyCoreSetup = CoreSetup; + +/** @internal */ +export class VisTypeXyPlugin implements Plugin, void> { + constructor(public initializerContext: PluginInitializerContext) {} + + public async setup( + core: VisTypeXyCoreSetup, + { expressions, visualizations, charts }: VisTypeXyPluginSetupDependencies + ) { + // eslint-disable-next-line no-console + console.warn( + 'The visTypeXy plugin is enabled\n\n', + 'This may negatively alter existing vislib visualization configurations if saved.' + ); + const visualizationDependencies: Readonly = { + uiSettings: core.uiSettings, + charts, + }; + + const visTypeDefinitions: any[] = []; + const visFunctions: any = []; + + visFunctions.forEach((fn: any) => expressions.registerFunction(fn)); + visTypeDefinitions.forEach((vis: any) => + visualizations.types.createBaseVisualization(vis(visualizationDependencies)) + ); + } + + public start(core: CoreStart, deps: VisTypeXyPluginStartDependencies) { + // nothing to do here + } +} From 186a82669f9c2f48080ccfac4efa515c3065bdb5 Mon Sep 17 00:00:00 2001 From: Nick Partridge Date: Mon, 3 Feb 2020 22:17:27 -0600 Subject: [PATCH 03/11] Kibana property config migrations (#55937) * Move defaultAppId config param into kibanaLegacy * Move disableWelcomeScreen config param into Home plugin * Update api and docs with silent option for renameFromRoot --- ...-plugin-server.configdeprecationfactory.md | 2 +- ...configdeprecationfactory.renamefromroot.md | 3 +- .../config/deprecation/deprecation_factory.ts | 20 ++++++--- src/core/server/config/deprecation/types.ts | 2 +- src/core/server/kibana_config.ts | 2 - src/core/server/mocks.ts | 2 +- .../server/plugins/plugin_context.test.ts | 2 +- src/core/server/plugins/types.ts | 2 +- src/core/server/server.api.md | 2 +- src/legacy/core_plugins/kibana/index.js | 2 - src/legacy/core_plugins/kibana/inject_vars.js | 2 - .../public/dashboard/np_ready/application.ts | 2 + .../dashboard/np_ready/dashboard_app.tsx | 2 - .../np_ready/dashboard_app_controller.tsx | 6 +-- .../public/dashboard/np_ready/legacy_app.js | 4 +- .../kibana/public/dashboard/plugin.ts | 1 + .../kibana/public/home/kibana_services.ts | 9 +++- .../public/home/np_ready/components/home.js | 2 +- .../home/np_ready/components/home.test.js | 1 + .../home/np_ready/components/home_app.js | 4 +- .../core_plugins/kibana/public/home/plugin.ts | 5 +++ .../core_plugins/kibana/public/kibana.js | 4 +- .../public/visualize/kibana_services.ts | 2 + .../public/visualize/np_ready/legacy_app.js | 2 +- .../kibana/public/visualize/plugin.ts | 1 + .../public/new_platform/__mocks__/helpers.ts | 3 ++ .../new_platform/new_platform.karma_mock.js | 12 +++++ src/plugins/home/config.ts | 26 +++++++++++ src/plugins/home/public/index.ts | 5 ++- src/plugins/home/public/plugin.test.ts | 11 +++-- src/plugins/home/public/plugin.ts | 12 +++-- src/plugins/home/server/index.ts | 13 +++++- src/plugins/home/server/plugin.ts | 2 +- src/plugins/kibana_legacy/config.ts | 26 +++++++++++ src/plugins/kibana_legacy/kibana.json | 2 +- src/plugins/kibana_legacy/public/index.ts | 5 +-- src/plugins/kibana_legacy/public/mocks.ts | 44 +++++++++++++++++++ src/plugins/kibana_legacy/public/plugin.ts | 9 +++- src/plugins/kibana_legacy/server/index.ts | 41 +++++++++++++++++ .../public/management_service.test.ts | 7 +-- test/common/config.js | 2 +- .../dashboard_mode/public/dashboard_viewer.js | 8 ++-- 42 files changed, 257 insertions(+), 57 deletions(-) create mode 100644 src/plugins/home/config.ts create mode 100644 src/plugins/kibana_legacy/config.ts create mode 100644 src/plugins/kibana_legacy/public/mocks.ts create mode 100644 src/plugins/kibana_legacy/server/index.ts diff --git a/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.md b/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.md index c61907f3663012..2ebee16874c801 100644 --- a/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.md +++ b/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.md @@ -30,7 +30,7 @@ const provider: ConfigDeprecationProvider = ({ rename, unused }) => [ | Method | Description | | --- | --- | | [rename(oldKey, newKey)](./kibana-plugin-server.configdeprecationfactory.rename.md) | Rename a configuration property from inside a plugin's configuration path. Will log a deprecation warning if the oldKey was found and deprecation applied. | -| [renameFromRoot(oldKey, newKey)](./kibana-plugin-server.configdeprecationfactory.renamefromroot.md) | Rename a configuration property from the root configuration. Will log a deprecation warning if the oldKey was found and deprecation applied.This should be only used when renaming properties from different configuration's path. To rename properties from inside a plugin's configuration, use 'rename' instead. | +| [renameFromRoot(oldKey, newKey, silent)](./kibana-plugin-server.configdeprecationfactory.renamefromroot.md) | Rename a configuration property from the root configuration. Will log a deprecation warning if the oldKey was found and deprecation applied.This should be only used when renaming properties from different configuration's path. To rename properties from inside a plugin's configuration, use 'rename' instead. | | [unused(unusedKey)](./kibana-plugin-server.configdeprecationfactory.unused.md) | Remove a configuration property from inside a plugin's configuration path. Will log a deprecation warning if the unused key was found and deprecation applied. | | [unusedFromRoot(unusedKey)](./kibana-plugin-server.configdeprecationfactory.unusedfromroot.md) | Remove a configuration property from the root configuration. Will log a deprecation warning if the unused key was found and deprecation applied.This should be only used when removing properties from outside of a plugin's configuration. To remove properties from inside a plugin's configuration, use 'unused' instead. | diff --git a/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.renamefromroot.md b/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.renamefromroot.md index 269f242ec35da6..40ea891b17c957 100644 --- a/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.renamefromroot.md +++ b/docs/development/core/server/kibana-plugin-server.configdeprecationfactory.renamefromroot.md @@ -11,7 +11,7 @@ This should be only used when renaming properties from different configuration's Signature: ```typescript -renameFromRoot(oldKey: string, newKey: string): ConfigDeprecation; +renameFromRoot(oldKey: string, newKey: string, silent?: boolean): ConfigDeprecation; ``` ## Parameters @@ -20,6 +20,7 @@ renameFromRoot(oldKey: string, newKey: string): ConfigDeprecation; | --- | --- | --- | | oldKey | string | | | newKey | string | | +| silent | boolean | | Returns: diff --git a/src/core/server/config/deprecation/deprecation_factory.ts b/src/core/server/config/deprecation/deprecation_factory.ts index 6f7ed4c4e84cc6..0b19a996243119 100644 --- a/src/core/server/config/deprecation/deprecation_factory.ts +++ b/src/core/server/config/deprecation/deprecation_factory.ts @@ -26,7 +26,8 @@ const _rename = ( rootPath: string, log: ConfigDeprecationLogger, oldKey: string, - newKey: string + newKey: string, + silent?: boolean ) => { const fullOldPath = getPath(rootPath, oldKey); const oldValue = get(config, fullOldPath); @@ -40,11 +41,16 @@ const _rename = ( const newValue = get(config, fullNewPath); if (newValue === undefined) { set(config, fullNewPath, oldValue); - log(`"${fullOldPath}" is deprecated and has been replaced by "${fullNewPath}"`); + + if (!silent) { + log(`"${fullOldPath}" is deprecated and has been replaced by "${fullNewPath}"`); + } } else { - log( - `"${fullOldPath}" is deprecated and has been replaced by "${fullNewPath}". However both key are present, ignoring "${fullOldPath}"` - ); + if (!silent) { + log( + `"${fullOldPath}" is deprecated and has been replaced by "${fullNewPath}". However both key are present, ignoring "${fullOldPath}"` + ); + } } return config; }; @@ -67,11 +73,11 @@ const _unused = ( const rename = (oldKey: string, newKey: string): ConfigDeprecation => (config, rootPath, log) => _rename(config, rootPath, log, oldKey, newKey); -const renameFromRoot = (oldKey: string, newKey: string): ConfigDeprecation => ( +const renameFromRoot = (oldKey: string, newKey: string, silent?: boolean): ConfigDeprecation => ( config, rootPath, log -) => _rename(config, '', log, oldKey, newKey); +) => _rename(config, '', log, oldKey, newKey, silent); const unused = (unusedKey: string): ConfigDeprecation => (config, rootPath, log) => _unused(config, rootPath, log, unusedKey); diff --git a/src/core/server/config/deprecation/types.ts b/src/core/server/config/deprecation/types.ts index 19fba7800c919d..dbfbad771f0749 100644 --- a/src/core/server/config/deprecation/types.ts +++ b/src/core/server/config/deprecation/types.ts @@ -102,7 +102,7 @@ export interface ConfigDeprecationFactory { * ] * ``` */ - renameFromRoot(oldKey: string, newKey: string): ConfigDeprecation; + renameFromRoot(oldKey: string, newKey: string, silent?: boolean): ConfigDeprecation; /** * Remove a configuration property from inside a plugin's configuration path. * Will log a deprecation warning if the unused key was found and deprecation applied. diff --git a/src/core/server/kibana_config.ts b/src/core/server/kibana_config.ts index d46960289a8d01..17f77a6e9328f3 100644 --- a/src/core/server/kibana_config.ts +++ b/src/core/server/kibana_config.ts @@ -25,9 +25,7 @@ export const config = { path: 'kibana', schema: schema.object({ enabled: schema.boolean({ defaultValue: true }), - defaultAppId: schema.string({ defaultValue: 'home' }), index: schema.string({ defaultValue: '.kibana' }), - disableWelcomeScreen: schema.boolean({ defaultValue: false }), autocompleteTerminateAfter: schema.duration({ defaultValue: 100000 }), autocompleteTimeout: schema.duration({ defaultValue: 1000 }), }), diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts index 50ce507520d048..7d6f09b5232c0c 100644 --- a/src/core/server/mocks.ts +++ b/src/core/server/mocks.ts @@ -43,7 +43,7 @@ import { uuidServiceMock } from './uuid/uuid_service.mock'; export function pluginInitializerContextConfigMock(config: T) { const globalConfig: SharedGlobalConfig = { - kibana: { defaultAppId: 'home-mocks', index: '.kibana-tests' }, + kibana: { index: '.kibana-tests' }, elasticsearch: { shardTimeout: duration('30s'), requestTimeout: duration('30s'), diff --git a/src/core/server/plugins/plugin_context.test.ts b/src/core/server/plugins/plugin_context.test.ts index 3fcd7fbbbe1ff9..823299771544cd 100644 --- a/src/core/server/plugins/plugin_context.test.ts +++ b/src/core/server/plugins/plugin_context.test.ts @@ -75,7 +75,7 @@ describe('Plugin Context', () => { .pipe(first()) .toPromise(); expect(configObject).toStrictEqual({ - kibana: { defaultAppId: 'home', index: '.kibana' }, + kibana: { index: '.kibana' }, elasticsearch: { shardTimeout: duration(30, 's'), requestTimeout: duration(30, 's'), diff --git a/src/core/server/plugins/types.ts b/src/core/server/plugins/types.ts index a89e2f8c684e40..9ae04787767bb6 100644 --- a/src/core/server/plugins/types.ts +++ b/src/core/server/plugins/types.ts @@ -214,7 +214,7 @@ export interface Plugin< export const SharedGlobalConfigKeys = { // We can add more if really needed - kibana: ['defaultAppId', 'index'] as const, + kibana: ['index'] as const, elasticsearch: ['shardTimeout', 'requestTimeout', 'pingTimeout', 'startupTimeout'] as const, path: ['data'] as const, }; diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index e4ea06769007a1..20d9692391a691 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -509,7 +509,7 @@ export type ConfigDeprecation = (config: Record, fromPath: string, // @public export interface ConfigDeprecationFactory { rename(oldKey: string, newKey: string): ConfigDeprecation; - renameFromRoot(oldKey: string, newKey: string): ConfigDeprecation; + renameFromRoot(oldKey: string, newKey: string, silent?: boolean): ConfigDeprecation; unused(unusedKey: string): ConfigDeprecation; unusedFromRoot(unusedKey: string): ConfigDeprecation; } diff --git a/src/legacy/core_plugins/kibana/index.js b/src/legacy/core_plugins/kibana/index.js index 8e0497732e2305..8c35044b52c9e1 100644 --- a/src/legacy/core_plugins/kibana/index.js +++ b/src/legacy/core_plugins/kibana/index.js @@ -42,9 +42,7 @@ export default function(kibana) { config: function(Joi) { return Joi.object({ enabled: Joi.boolean().default(true), - defaultAppId: Joi.string().default('home'), index: Joi.string().default('.kibana'), - disableWelcomeScreen: Joi.boolean().default(false), autocompleteTerminateAfter: Joi.number() .integer() .min(1) diff --git a/src/legacy/core_plugins/kibana/inject_vars.js b/src/legacy/core_plugins/kibana/inject_vars.js index 4bf11f28732ee1..01623341e4d38b 100644 --- a/src/legacy/core_plugins/kibana/inject_vars.js +++ b/src/legacy/core_plugins/kibana/inject_vars.js @@ -28,8 +28,6 @@ export function injectVars(server) { ); return { - kbnDefaultAppId: serverConfig.get('kibana.defaultAppId'), - disableWelcomeScreen: serverConfig.get('kibana.disableWelcomeScreen'), importAndExportableTypes, autocompleteTerminateAfter: serverConfig.get('kibana.autocompleteTerminateAfter'), autocompleteTimeout: serverConfig.get('kibana.autocompleteTimeout'), diff --git a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/application.ts b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/application.ts index 0d461028d994a3..f1fd93fd09b3dd 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/application.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/application.ts @@ -46,6 +46,7 @@ import { IEmbeddableStart } from '../../../../../../plugins/embeddable/public'; import { NavigationPublicPluginStart as NavigationStart } from '../../../../../../plugins/navigation/public'; import { DataPublicPluginStart as NpDataStart } from '../../../../../../plugins/data/public'; import { SharePluginStart } from '../../../../../../plugins/share/public'; +import { KibanaLegacyStart } from '../../../../../../plugins/kibana_legacy/public'; export interface RenderDeps { core: LegacyCoreStart; @@ -62,6 +63,7 @@ export interface RenderDeps { embeddables: IEmbeddableStart; localStorage: Storage; share: SharePluginStart; + config: KibanaLegacyStart['config']; } let angularModuleInstance: IModule | null = null; diff --git a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app.tsx b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app.tsx index a48c165116304f..0537e3f8fc456d 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app.tsx +++ b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app.tsx @@ -88,7 +88,6 @@ export interface DashboardAppScope extends ng.IScope { export function initDashboardAppDirective(app: any, deps: RenderDeps) { app.directive('dashboardApp', function($injector: IInjector) { const confirmModal = $injector.get('confirmModal'); - const config = deps.uiSettings; return { restrict: 'E', @@ -106,7 +105,6 @@ export function initDashboardAppDirective(app: any, deps: RenderDeps) { $route, $scope, $routeParams, - config, confirmModal, indexPatterns: deps.npDataStart.indexPatterns, kbnUrlStateStorage, diff --git a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app_controller.tsx b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app_controller.tsx index a8eec9c2504a7c..624be02ac3b9da 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app_controller.tsx +++ b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_app_controller.tsx @@ -90,7 +90,6 @@ export interface DashboardAppControllerDependencies extends RenderDeps { $routeParams: any; indexPatterns: IndexPatternsContract; dashboardConfig: any; - config: any; confirmModal: ConfirmModalFn; history: History; kbnUrlStateStorage: IKbnUrlStateStorage; @@ -109,7 +108,6 @@ export class DashboardAppController { dashboardConfig, localStorage, indexPatterns, - config, confirmModal, savedQueryService, embeddables, @@ -376,7 +374,7 @@ export class DashboardAppController { dashboardStateManager.getQuery() || { query: '', language: - localStorage.get('kibana.userQueryLanguage') || config.get('search:queryLanguage'), + localStorage.get('kibana.userQueryLanguage') || uiSettings.get('search:queryLanguage'), }, queryFilter.getFilters() ); @@ -493,7 +491,7 @@ export class DashboardAppController { { query: '', language: - localStorage.get('kibana.userQueryLanguage') || config.get('search:queryLanguage'), + localStorage.get('kibana.userQueryLanguage') || uiSettings.get('search:queryLanguage'), }, queryFilter.getGlobalFilters() ); diff --git a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/legacy_app.js b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/legacy_app.js index abc0c789326f8a..b0f70b7a0c68f3 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/legacy_app.js +++ b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/legacy_app.js @@ -246,10 +246,10 @@ export function initDashboardApp(app, deps) { }, }) .when(`dashboard/:tail*?`, { - redirectTo: `/${deps.core.injectedMetadata.getInjectedVar('kbnDefaultAppId')}`, + redirectTo: `/${deps.config.defaultAppId}`, }) .when(`dashboards/:tail*?`, { - redirectTo: `/${deps.core.injectedMetadata.getInjectedVar('kbnDefaultAppId')}`, + redirectTo: `/${deps.config.defaultAppId}`, }); }); } diff --git a/src/legacy/core_plugins/kibana/public/dashboard/plugin.ts b/src/legacy/core_plugins/kibana/public/dashboard/plugin.ts index ca4b18a37504c6..227bcb53ca0df7 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/plugin.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/plugin.ts @@ -107,6 +107,7 @@ export class DashboardPlugin implements Plugin { chrome: contextCore.chrome, addBasePath: contextCore.http.basePath.prepend, uiSettings: contextCore.uiSettings, + config: kibana_legacy.config, savedQueryService: npDataStart.query.savedQueries, embeddables, dashboardCapabilities: contextCore.application.capabilities.dashboard, diff --git a/src/legacy/core_plugins/kibana/public/home/kibana_services.ts b/src/legacy/core_plugins/kibana/public/home/kibana_services.ts index 4d9177735556df..90fb32a88d43cb 100644 --- a/src/legacy/core_plugins/kibana/public/home/kibana_services.ts +++ b/src/legacy/core_plugins/kibana/public/home/kibana_services.ts @@ -29,7 +29,12 @@ import { UiSettingsState, } from 'kibana/public'; import { UiStatsMetricType } from '@kbn/analytics'; -import { Environment, FeatureCatalogueEntry } from '../../../../../plugins/home/public'; +import { + Environment, + FeatureCatalogueEntry, + HomePublicPluginSetup, +} from '../../../../../plugins/home/public'; +import { KibanaLegacySetup } from '../../../../../plugins/kibana_legacy/public'; export interface HomeKibanaServices { indexPatternService: any; @@ -51,6 +56,8 @@ export interface HomeKibanaServices { chrome: ChromeStart; telemetryOptInProvider: any; uiSettings: IUiSettingsClient; + config: KibanaLegacySetup['config']; + homeConfig: HomePublicPluginSetup['config']; http: HttpStart; savedObjectsClient: SavedObjectsClientContract; toastNotifications: NotificationsSetup['toasts']; diff --git a/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.js b/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.js index 5c32a463da1153..0c09c6c3c74fcb 100644 --- a/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.js +++ b/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.js @@ -48,7 +48,7 @@ export class Home extends Component { super(props); const isWelcomeEnabled = !( - getServices().getInjected('disableWelcomeScreen') || + getServices().homeConfig.disableWelcomeScreen || props.localStorage.getItem(KEY_ENABLE_WELCOME) === 'false' ); const currentOptInStatus = this.props.getOptInStatus(); diff --git a/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.test.js b/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.test.js index 27d4f1a8b1c1fa..d25a1f81dae5a5 100644 --- a/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.test.js +++ b/src/legacy/core_plugins/kibana/public/home/np_ready/components/home.test.js @@ -30,6 +30,7 @@ jest.mock('../../kibana_services', () => ({ getServices: () => ({ getBasePath: () => 'path', getInjected: () => '', + homeConfig: { disableWelcomeScreen: false }, }), })); diff --git a/src/legacy/core_plugins/kibana/public/home/np_ready/components/home_app.js b/src/legacy/core_plugins/kibana/public/home/np_ready/components/home_app.js index e49f00b949da5b..f6c91b412381cd 100644 --- a/src/legacy/core_plugins/kibana/public/home/np_ready/components/home_app.js +++ b/src/legacy/core_plugins/kibana/public/home/np_ready/components/home_app.js @@ -30,7 +30,7 @@ import { replaceTemplateStrings } from './tutorial/replace_template_strings'; import { getServices } from '../../kibana_services'; export function HomeApp({ directories }) { const { - getInjected, + config, savedObjectsClient, getBasePath, addBasePath, @@ -41,7 +41,7 @@ export function HomeApp({ directories }) { const mlEnabled = environment.ml; const apmUiEnabled = environment.apmUi; - const defaultAppId = getInjected('kbnDefaultAppId', 'discover'); + const defaultAppId = config.defaultAppId || 'discover'; const renderTutorialDirectory = props => { return ( diff --git a/src/legacy/core_plugins/kibana/public/home/plugin.ts b/src/legacy/core_plugins/kibana/public/home/plugin.ts index 502c8f45646cf0..aec3835dc075d9 100644 --- a/src/legacy/core_plugins/kibana/public/home/plugin.ts +++ b/src/legacy/core_plugins/kibana/public/home/plugin.ts @@ -27,6 +27,7 @@ import { Environment, FeatureCatalogueEntry, HomePublicPluginStart, + HomePublicPluginSetup, } from '../../../../../plugins/home/public'; export interface LegacyAngularInjectedDependencies { @@ -59,6 +60,7 @@ export interface HomePluginSetupDependencies { }; usageCollection: UsageCollectionSetup; kibana_legacy: KibanaLegacySetup; + home: HomePublicPluginSetup; } export class HomePlugin implements Plugin { @@ -69,6 +71,7 @@ export class HomePlugin implements Plugin { setup( core: CoreSetup, { + home, kibana_legacy, usageCollection, __LEGACY: { getAngularDependencies, ...legacyServices }, @@ -95,6 +98,8 @@ export class HomePlugin implements Plugin { getBasePath: core.http.basePath.get, indexPatternService: this.dataStart!.indexPatterns, environment: this.environment!, + config: kibana_legacy.config, + homeConfig: home.config, ...angularDependencies, }); const { renderApp } = await import('./np_ready/application'); diff --git a/src/legacy/core_plugins/kibana/public/kibana.js b/src/legacy/core_plugins/kibana/public/kibana.js index 50f1702a2a6d0e..f2868da947a75d 100644 --- a/src/legacy/core_plugins/kibana/public/kibana.js +++ b/src/legacy/core_plugins/kibana/public/kibana.js @@ -20,7 +20,6 @@ // autoloading // preloading (for faster webpack builds) -import chrome from 'ui/chrome'; import routes from 'ui/routes'; import { uiModules } from 'ui/modules'; import { npSetup } from 'ui/new_platform'; @@ -64,8 +63,9 @@ localApplicationService.attachToAngular(routes); routes.enable(); +const { config } = npSetup.plugins.kibana_legacy; routes.otherwise({ - redirectTo: `/${chrome.getInjected('kbnDefaultAppId', 'discover')}`, + redirectTo: `/${config.defaultAppId || 'discover'}`, }); uiModules.get('kibana').run(showAppRedirectNotification); diff --git a/src/legacy/core_plugins/kibana/public/visualize/kibana_services.ts b/src/legacy/core_plugins/kibana/public/visualize/kibana_services.ts index f7fd19e8288e73..15e9c73a39effe 100644 --- a/src/legacy/core_plugins/kibana/public/visualize/kibana_services.ts +++ b/src/legacy/core_plugins/kibana/public/visualize/kibana_services.ts @@ -34,6 +34,7 @@ import { VisualizationsStart } from '../../../visualizations/public'; import { SavedVisualizations } from './np_ready/types'; import { UsageCollectionSetup } from '../../../../../plugins/usage_collection/public'; import { Chrome } from './legacy_imports'; +import { KibanaLegacyStart } from '../../../../../plugins/kibana_legacy/public'; export interface VisualizeKibanaServices { addBasePath: (url: string) => string; @@ -52,6 +53,7 @@ export interface VisualizeKibanaServices { savedVisualizations: SavedVisualizations; share: SharePluginStart; uiSettings: IUiSettingsClient; + config: KibanaLegacyStart['config']; visualizeCapabilities: any; visualizations: VisualizationsStart; usageCollection?: UsageCollectionSetup; diff --git a/src/legacy/core_plugins/kibana/public/visualize/np_ready/legacy_app.js b/src/legacy/core_plugins/kibana/public/visualize/np_ready/legacy_app.js index d99771ccc912dd..24055b9a2d9ed9 100644 --- a/src/legacy/core_plugins/kibana/public/visualize/np_ready/legacy_app.js +++ b/src/legacy/core_plugins/kibana/public/visualize/np_ready/legacy_app.js @@ -173,7 +173,7 @@ export function initVisualizeApp(app, deps) { }, }) .when(`visualize/:tail*?`, { - redirectTo: `/${deps.core.injectedMetadata.getInjectedVar('kbnDefaultAppId')}`, + redirectTo: `/${deps.config.defaultAppId}`, }); }); } diff --git a/src/legacy/core_plugins/kibana/public/visualize/plugin.ts b/src/legacy/core_plugins/kibana/public/visualize/plugin.ts index 26c6691a3613f1..8e7487fee55f69 100644 --- a/src/legacy/core_plugins/kibana/public/visualize/plugin.ts +++ b/src/legacy/core_plugins/kibana/public/visualize/plugin.ts @@ -108,6 +108,7 @@ export class VisualizePlugin implements Plugin { share, toastNotifications: contextCore.notifications.toasts, uiSettings: contextCore.uiSettings, + config: kibana_legacy.config, visualizeCapabilities: contextCore.application.capabilities.visualize, visualizations, usageCollection, diff --git a/src/legacy/ui/public/new_platform/__mocks__/helpers.ts b/src/legacy/ui/public/new_platform/__mocks__/helpers.ts index c89ae9f8b3c9b1..439ac9b5713dfa 100644 --- a/src/legacy/ui/public/new_platform/__mocks__/helpers.ts +++ b/src/legacy/ui/public/new_platform/__mocks__/helpers.ts @@ -27,6 +27,7 @@ import { inspectorPluginMock } from '../../../../../plugins/inspector/public/moc import { uiActionsPluginMock } from '../../../../../plugins/ui_actions/public/mocks'; import { managementPluginMock } from '../../../../../plugins/management/public/mocks'; import { usageCollectionPluginMock } from '../../../../../plugins/usage_collection/public/mocks'; +import { kibanaLegacyPluginMock } from '../../../../../plugins/kibana_legacy/public/mocks'; import { chartPluginMock } from '../../../../../plugins/charts/public/mocks'; /* eslint-enable @kbn/eslint/no-restricted-paths */ @@ -40,6 +41,7 @@ export const pluginsMock = { expressions: expressionsPluginMock.createSetupContract(), uiActions: uiActionsPluginMock.createSetupContract(), usageCollection: usageCollectionPluginMock.createSetupContract(), + kibana_legacy: kibanaLegacyPluginMock.createSetupContract(), }), createStart: () => ({ data: dataPluginMock.createStartContract(), @@ -50,6 +52,7 @@ export const pluginsMock = { expressions: expressionsPluginMock.createStartContract(), uiActions: uiActionsPluginMock.createStartContract(), management: managementPluginMock.createStartContract(), + kibana_legacy: kibanaLegacyPluginMock.createStartContract(), }), }; diff --git a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js index f98b8801d52663..c2c8b5a0fae7a7 100644 --- a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js +++ b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js @@ -119,6 +119,9 @@ export const npSetup = { kibana_legacy: { registerLegacyApp: () => {}, forwardApp: () => {}, + config: { + defaultAppId: 'home', + }, }, inspector: { registerView: () => undefined, @@ -140,6 +143,9 @@ export const npSetup = { environment: { update: sinon.fake(), }, + config: { + disableWelcomeScreen: false, + }, }, charts: { theme: { @@ -196,6 +202,9 @@ export const npStart = { kibana_legacy: { getApps: () => [], getForwards: () => [], + config: { + defaultAppId: 'home', + }, }, data: { autocomplete: { @@ -297,6 +306,9 @@ export const npStart = { environment: { get: sinon.fake(), }, + config: { + disableWelcomeScreen: false, + }, }, navigation: { ui: { diff --git a/src/plugins/home/config.ts b/src/plugins/home/config.ts new file mode 100644 index 00000000000000..149723a7ee5ae2 --- /dev/null +++ b/src/plugins/home/config.ts @@ -0,0 +1,26 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { schema, TypeOf } from '@kbn/config-schema'; + +export const configSchema = schema.object({ + disableWelcomeScreen: schema.boolean({ defaultValue: false }), +}); + +export type ConfigSchema = TypeOf; diff --git a/src/plugins/home/public/index.ts b/src/plugins/home/public/index.ts index ca05c8b5f760e7..114d442b40943b 100644 --- a/src/plugins/home/public/index.ts +++ b/src/plugins/home/public/index.ts @@ -17,6 +17,8 @@ * under the License. */ +import { PluginInitializerContext } from 'kibana/public'; + export { FeatureCatalogueSetup, FeatureCatalogueStart, @@ -26,4 +28,5 @@ export { export { FeatureCatalogueEntry, FeatureCatalogueCategory, Environment } from './services'; import { HomePublicPlugin } from './plugin'; -export const plugin = () => new HomePublicPlugin(); +export const plugin = (initializerContext: PluginInitializerContext) => + new HomePublicPlugin(initializerContext); diff --git a/src/plugins/home/public/plugin.test.ts b/src/plugins/home/public/plugin.test.ts index 34502d7d2c6cd8..fa44a110c63b70 100644 --- a/src/plugins/home/public/plugin.test.ts +++ b/src/plugins/home/public/plugin.test.ts @@ -19,6 +19,9 @@ import { registryMock, environmentMock } from './plugin.test.mocks'; import { HomePublicPlugin } from './plugin'; +import { coreMock } from '../../../core/public/mocks'; + +const mockInitializerContext = coreMock.createPluginInitializerContext(); describe('HomePublicPlugin', () => { beforeEach(() => { @@ -30,13 +33,13 @@ describe('HomePublicPlugin', () => { describe('setup', () => { test('wires up and returns registry', async () => { - const setup = await new HomePublicPlugin().setup(); + const setup = await new HomePublicPlugin(mockInitializerContext).setup(); expect(setup).toHaveProperty('featureCatalogue'); expect(setup.featureCatalogue).toHaveProperty('register'); }); test('wires up and returns environment service', async () => { - const setup = await new HomePublicPlugin().setup(); + const setup = await new HomePublicPlugin(mockInitializerContext).setup(); expect(setup).toHaveProperty('environment'); expect(setup.environment).toHaveProperty('update'); }); @@ -44,7 +47,7 @@ describe('HomePublicPlugin', () => { describe('start', () => { test('wires up and returns registry', async () => { - const service = new HomePublicPlugin(); + const service = new HomePublicPlugin(mockInitializerContext); await service.setup(); const core = { application: { capabilities: { catalogue: {} } } } as any; const start = await service.start(core); @@ -55,7 +58,7 @@ describe('HomePublicPlugin', () => { }); test('wires up and returns environment service', async () => { - const service = new HomePublicPlugin(); + const service = new HomePublicPlugin(mockInitializerContext); await service.setup(); const start = await service.start({ application: { capabilities: { catalogue: {} } }, diff --git a/src/plugins/home/public/plugin.ts b/src/plugins/home/public/plugin.ts index 39a7f23826900b..fe68dbc3e7e490 100644 --- a/src/plugins/home/public/plugin.ts +++ b/src/plugins/home/public/plugin.ts @@ -17,7 +17,8 @@ * under the License. */ -import { CoreStart, Plugin } from 'src/core/public'; +import { CoreStart, Plugin, PluginInitializerContext } from 'kibana/public'; + import { EnvironmentService, EnvironmentServiceSetup, @@ -26,19 +27,23 @@ import { FeatureCatalogueRegistrySetup, FeatureCatalogueRegistryStart, } from './services'; +import { ConfigSchema } from '../config'; export class HomePublicPlugin implements Plugin { private readonly featuresCatalogueRegistry = new FeatureCatalogueRegistry(); private readonly environmentService = new EnvironmentService(); - public async setup() { + constructor(private readonly initializerContext: PluginInitializerContext) {} + + public setup(): HomePublicPluginSetup { return { featureCatalogue: { ...this.featuresCatalogueRegistry.setup() }, environment: { ...this.environmentService.setup() }, + config: this.initializerContext.config.get(), }; } - public async start(core: CoreStart) { + public start(core: CoreStart): HomePublicPluginStart { return { featureCatalogue: { ...this.featuresCatalogueRegistry.start({ @@ -71,6 +76,7 @@ export interface HomePublicPluginSetup { * @deprecated */ environment: EnvironmentSetup; + config: ConfigSchema; } /** @public */ diff --git a/src/plugins/home/server/index.ts b/src/plugins/home/server/index.ts index 0961c729698b9d..02f4c91a414cc9 100644 --- a/src/plugins/home/server/index.ts +++ b/src/plugins/home/server/index.ts @@ -20,8 +20,19 @@ export { HomeServerPluginSetup, HomeServerPluginStart } from './plugin'; export { TutorialProvider } from './services'; export { SampleDatasetProvider, SampleDataRegistrySetup } from './services'; -import { PluginInitializerContext } from 'src/core/server'; +import { PluginInitializerContext, PluginConfigDescriptor } from 'kibana/server'; import { HomeServerPlugin } from './plugin'; +import { configSchema, ConfigSchema } from '../config'; + +export const config: PluginConfigDescriptor = { + exposeToBrowser: { + disableWelcomeScreen: true, + }, + schema: configSchema, + deprecations: ({ renameFromRoot }) => [ + renameFromRoot('kibana.disableWelcomeScreen', 'home.disableWelcomeScreen'), + ], +}; export const plugin = (initContext: PluginInitializerContext) => new HomeServerPlugin(initContext); diff --git a/src/plugins/home/server/plugin.ts b/src/plugins/home/server/plugin.ts index 23c236764cddcf..d2f2d7041024e3 100644 --- a/src/plugins/home/server/plugin.ts +++ b/src/plugins/home/server/plugin.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { CoreSetup, Plugin, PluginInitializerContext } from 'src/core/server'; +import { CoreSetup, Plugin, PluginInitializerContext } from 'kibana/server'; import { TutorialsRegistry, TutorialsRegistrySetup, diff --git a/src/plugins/kibana_legacy/config.ts b/src/plugins/kibana_legacy/config.ts new file mode 100644 index 00000000000000..291f8813ecfb91 --- /dev/null +++ b/src/plugins/kibana_legacy/config.ts @@ -0,0 +1,26 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { schema, TypeOf } from '@kbn/config-schema'; + +export const configSchema = schema.object({ + defaultAppId: schema.string({ defaultValue: 'home' }), +}); + +export type ConfigSchema = TypeOf; diff --git a/src/plugins/kibana_legacy/kibana.json b/src/plugins/kibana_legacy/kibana.json index 26ee6db3ba06ae..b6d11309a4f964 100644 --- a/src/plugins/kibana_legacy/kibana.json +++ b/src/plugins/kibana_legacy/kibana.json @@ -1,6 +1,6 @@ { "id": "kibana_legacy", "version": "kibana", - "server": false, + "server": true, "ui": true } diff --git a/src/plugins/kibana_legacy/public/index.ts b/src/plugins/kibana_legacy/public/index.ts index 4cb30be8917acd..de8788808e74c6 100644 --- a/src/plugins/kibana_legacy/public/index.ts +++ b/src/plugins/kibana_legacy/public/index.ts @@ -20,8 +20,7 @@ import { PluginInitializerContext } from 'kibana/public'; import { KibanaLegacyPlugin } from './plugin'; -export function plugin(initializerContext: PluginInitializerContext) { - return new KibanaLegacyPlugin(); -} +export const plugin = (initializerContext: PluginInitializerContext) => + new KibanaLegacyPlugin(initializerContext); export * from './plugin'; diff --git a/src/plugins/kibana_legacy/public/mocks.ts b/src/plugins/kibana_legacy/public/mocks.ts new file mode 100644 index 00000000000000..b6287dd9d9a556 --- /dev/null +++ b/src/plugins/kibana_legacy/public/mocks.ts @@ -0,0 +1,44 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { KibanaLegacyPlugin } from './plugin'; + +export type Setup = jest.Mocked>; +export type Start = jest.Mocked>; + +const createSetupContract = (): Setup => ({ + forwardApp: jest.fn(), + registerLegacyApp: jest.fn(), + config: { + defaultAppId: 'home', + }, +}); + +const createStartContract = (): Start => ({ + getApps: jest.fn(), + getForwards: jest.fn(), + config: { + defaultAppId: 'home', + }, +}); + +export const kibanaLegacyPluginMock = { + createSetupContract, + createStartContract, +}; diff --git a/src/plugins/kibana_legacy/public/plugin.ts b/src/plugins/kibana_legacy/public/plugin.ts index cb95088320d7b3..b9a61a1c9b2000 100644 --- a/src/plugins/kibana_legacy/public/plugin.ts +++ b/src/plugins/kibana_legacy/public/plugin.ts @@ -17,7 +17,9 @@ * under the License. */ -import { App } from 'kibana/public'; +import { App, PluginInitializerContext } from 'kibana/public'; + +import { ConfigSchema } from '../config'; interface ForwardDefinition { legacyAppId: string; @@ -29,6 +31,8 @@ export class KibanaLegacyPlugin { private apps: App[] = []; private forwards: ForwardDefinition[] = []; + constructor(private readonly initializerContext: PluginInitializerContext) {} + public setup() { return { /** @@ -77,6 +81,8 @@ export class KibanaLegacyPlugin { ) => { this.forwards.push({ legacyAppId, newAppId, ...options }); }, + + config: this.initializerContext.config.get(), }; } @@ -92,6 +98,7 @@ export class KibanaLegacyPlugin { * Just exported for wiring up with legacy platform, should not be used. */ getForwards: () => this.forwards, + config: this.initializerContext.config.get(), }; } } diff --git a/src/plugins/kibana_legacy/server/index.ts b/src/plugins/kibana_legacy/server/index.ts new file mode 100644 index 00000000000000..4d0fe8364a66c5 --- /dev/null +++ b/src/plugins/kibana_legacy/server/index.ts @@ -0,0 +1,41 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { CoreSetup, CoreStart, PluginConfigDescriptor } from 'kibana/server'; + +import { configSchema, ConfigSchema } from '../config'; + +export const config: PluginConfigDescriptor = { + exposeToBrowser: { + defaultAppId: true, + }, + schema: configSchema, + deprecations: ({ renameFromRoot }) => [ + // TODO: Remove deprecation once defaultAppId is deleted + renameFromRoot('kibana.defaultAppId', 'kibana_legacy.defaultAppId', true), + ], +}; + +class Plugin { + public setup(core: CoreSetup) {} + + public start(core: CoreStart) {} +} + +export const plugin = () => new Plugin(); diff --git a/src/plugins/management/public/management_service.test.ts b/src/plugins/management/public/management_service.test.ts index 854406a10335be..b34e76474cec23 100644 --- a/src/plugins/management/public/management_service.test.ts +++ b/src/plugins/management/public/management_service.test.ts @@ -19,12 +19,13 @@ import { ManagementService } from './management_service'; import { coreMock } from '../../../core/public/mocks'; +import { npSetup } from '../../../legacy/ui/public/new_platform/__mocks__'; -const mockKibanaLegacy = { registerLegacyApp: () => {}, forwardApp: () => {} }; +jest.mock('ui/new_platform'); test('Provides default sections', () => { const service = new ManagementService().setup( - mockKibanaLegacy, + npSetup.plugins.kibana_legacy, () => {}, coreMock.createSetup().getStartServices ); @@ -36,7 +37,7 @@ test('Provides default sections', () => { test('Register section, enable and disable', () => { const service = new ManagementService().setup( - mockKibanaLegacy, + npSetup.plugins.kibana_legacy, () => {}, coreMock.createSetup().getStartServices ); diff --git a/test/common/config.js b/test/common/config.js index 29d4bbf10a6cee..faf8cef0271709 100644 --- a/test/common/config.js +++ b/test/common/config.js @@ -54,7 +54,7 @@ export default function() { `--elasticsearch.hosts=${formatUrl(servers.elasticsearch)}`, `--elasticsearch.username=${kibanaServerTestUser.username}`, `--elasticsearch.password=${kibanaServerTestUser.password}`, - `--kibana.disableWelcomeScreen=true`, + `--home.disableWelcomeScreen=true`, '--telemetry.banner=false', `--server.maxPayloadBytes=1679958`, // newsfeed mock service diff --git a/x-pack/legacy/plugins/dashboard_mode/public/dashboard_viewer.js b/x-pack/legacy/plugins/dashboard_mode/public/dashboard_viewer.js index ebae49f9947239..4215f96c8de4a4 100644 --- a/x-pack/legacy/plugins/dashboard_mode/public/dashboard_viewer.js +++ b/x-pack/legacy/plugins/dashboard_mode/public/dashboard_viewer.js @@ -55,10 +55,12 @@ chrome.setRootController('kibana', function() { uiModules.get('kibana').run(showAppRedirectNotification); -// If there is a configured kbnDefaultAppId, and it is a dashboard ID, we'll -// show that dashboard, otherwise, we'll show the default dasbhoard landing page. +/** + * If there is a configured `kibana.defaultAppId`, and it is a dashboard ID, we'll + * show that dashboard, otherwise, we'll show the default dasbhoard landing page. + */ function defaultUrl() { - const defaultAppId = chrome.getInjected('kbnDefaultAppId', ''); + const defaultAppId = npStart.plugins.kibana_legacy.config.defaultAppId || ''; const isDashboardId = defaultAppId.startsWith(dashboardAppIdPrefix()); return isDashboardId ? `/${defaultAppId}` : DashboardConstants.LANDING_PAGE_PATH; } From 0440ae50f7ad0aec051710efde2d26d158a75ecc Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Mon, 3 Feb 2020 20:54:59 -0800 Subject: [PATCH 04/11] Updates Monitoring alert Jest snapshots A UI bump caused changes the EuiSuperSelect component which were not reflected in kibana#54306. The EUI change went in after the PR went green, but then failed once it hit master. Signed-off-by: Tyler Smalley --- .../configuration/__snapshots__/configuration.test.tsx.snap | 1 + .../alerts/configuration/__snapshots__/step1.test.tsx.snap | 3 +++ 2 files changed, 4 insertions(+) diff --git a/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap b/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap index f044e001700c50..429d19fbb887ec 100644 --- a/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap +++ b/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap @@ -7,6 +7,7 @@ exports[`Configuration shallow view should render step 1 1`] = ` fullWidth={false} hasDividers={true} isInvalid={false} + isLoading={false} onChange={[Function]} options={ Array [ diff --git a/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap b/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap index fa03769ea3d090..94d951a94fe29a 100644 --- a/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap +++ b/x-pack/legacy/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap @@ -42,6 +42,7 @@ exports[`Step1 should render normally 1`] = ` fullWidth={false} hasDividers={true} isInvalid={false} + isLoading={false} onChange={[Function]} options={ Array [ @@ -135,6 +136,7 @@ exports[`Step1 testing should show a failed test error 1`] = ` fullWidth={false} hasDividers={true} isInvalid={false} + isLoading={false} onChange={[Function]} options={ Array [ @@ -220,6 +222,7 @@ exports[`Step1 testing should show a successful test 1`] = ` fullWidth={false} hasDividers={true} isInvalid={false} + isLoading={false} onChange={[Function]} options={ Array [ From 4bb56c80b7175a40eed275ddbe2245a95eebb393 Mon Sep 17 00:00:00 2001 From: Pierre Gayvallet Date: Tue, 4 Feb 2020 08:03:36 +0100 Subject: [PATCH 05/11] Add `getServerInfo` API to http setup contract (#56636) * add getServerInfo http setup api * update generated doc --- ...ibana-plugin-server.httpserverinfo.host.md | 13 +++++++ .../kibana-plugin-server.httpserverinfo.md | 22 ++++++++++++ ...ibana-plugin-server.httpserverinfo.name.md | 13 +++++++ ...ibana-plugin-server.httpserverinfo.port.md | 13 +++++++ ...a-plugin-server.httpserverinfo.protocol.md | 13 +++++++ ...n-server.httpservicesetup.getserverinfo.md | 13 +++++++ .../kibana-plugin-server.httpservicesetup.md | 1 + .../core/server/kibana-plugin-server.md | 1 + src/core/server/http/http_server.test.ts | 34 +++++++++++++++++++ src/core/server/http/http_server.ts | 9 ++++- src/core/server/http/http_service.mock.ts | 7 ++++ src/core/server/http/types.ts | 17 ++++++++++ src/core/server/index.ts | 1 + src/core/server/legacy/legacy_service.ts | 1 + src/core/server/mocks.ts | 1 + src/core/server/plugins/plugin_context.ts | 1 + src/core/server/server.api.md | 9 +++++ 17 files changed, 168 insertions(+), 1 deletion(-) create mode 100644 docs/development/core/server/kibana-plugin-server.httpserverinfo.host.md create mode 100644 docs/development/core/server/kibana-plugin-server.httpserverinfo.md create mode 100644 docs/development/core/server/kibana-plugin-server.httpserverinfo.name.md create mode 100644 docs/development/core/server/kibana-plugin-server.httpserverinfo.port.md create mode 100644 docs/development/core/server/kibana-plugin-server.httpserverinfo.protocol.md create mode 100644 docs/development/core/server/kibana-plugin-server.httpservicesetup.getserverinfo.md diff --git a/docs/development/core/server/kibana-plugin-server.httpserverinfo.host.md b/docs/development/core/server/kibana-plugin-server.httpserverinfo.host.md new file mode 100644 index 00000000000000..ee7e1e5b7c9c94 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.httpserverinfo.host.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HttpServerInfo](./kibana-plugin-server.httpserverinfo.md) > [host](./kibana-plugin-server.httpserverinfo.host.md) + +## HttpServerInfo.host property + +The hostname of the server + +Signature: + +```typescript +host: string; +``` diff --git a/docs/development/core/server/kibana-plugin-server.httpserverinfo.md b/docs/development/core/server/kibana-plugin-server.httpserverinfo.md new file mode 100644 index 00000000000000..6dbdb11ddb66ef --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.httpserverinfo.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HttpServerInfo](./kibana-plugin-server.httpserverinfo.md) + +## HttpServerInfo interface + + +Signature: + +```typescript +export interface HttpServerInfo +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [host](./kibana-plugin-server.httpserverinfo.host.md) | string | The hostname of the server | +| [name](./kibana-plugin-server.httpserverinfo.name.md) | string | The name of the Kibana server | +| [port](./kibana-plugin-server.httpserverinfo.port.md) | number | The port the server is listening on | +| [protocol](./kibana-plugin-server.httpserverinfo.protocol.md) | 'http' | 'https' | 'socket' | The protocol used by the server | + diff --git a/docs/development/core/server/kibana-plugin-server.httpserverinfo.name.md b/docs/development/core/server/kibana-plugin-server.httpserverinfo.name.md new file mode 100644 index 00000000000000..8d3a45c90a3427 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.httpserverinfo.name.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HttpServerInfo](./kibana-plugin-server.httpserverinfo.md) > [name](./kibana-plugin-server.httpserverinfo.name.md) + +## HttpServerInfo.name property + +The name of the Kibana server + +Signature: + +```typescript +name: string; +``` diff --git a/docs/development/core/server/kibana-plugin-server.httpserverinfo.port.md b/docs/development/core/server/kibana-plugin-server.httpserverinfo.port.md new file mode 100644 index 00000000000000..5dd5a53830c441 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.httpserverinfo.port.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HttpServerInfo](./kibana-plugin-server.httpserverinfo.md) > [port](./kibana-plugin-server.httpserverinfo.port.md) + +## HttpServerInfo.port property + +The port the server is listening on + +Signature: + +```typescript +port: number; +``` diff --git a/docs/development/core/server/kibana-plugin-server.httpserverinfo.protocol.md b/docs/development/core/server/kibana-plugin-server.httpserverinfo.protocol.md new file mode 100644 index 00000000000000..08afb5c3f72133 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.httpserverinfo.protocol.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HttpServerInfo](./kibana-plugin-server.httpserverinfo.md) > [protocol](./kibana-plugin-server.httpserverinfo.protocol.md) + +## HttpServerInfo.protocol property + +The protocol used by the server + +Signature: + +```typescript +protocol: 'http' | 'https' | 'socket'; +``` diff --git a/docs/development/core/server/kibana-plugin-server.httpservicesetup.getserverinfo.md b/docs/development/core/server/kibana-plugin-server.httpservicesetup.getserverinfo.md new file mode 100644 index 00000000000000..4501a7e26f75fa --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.httpservicesetup.getserverinfo.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HttpServiceSetup](./kibana-plugin-server.httpservicesetup.md) > [getServerInfo](./kibana-plugin-server.httpservicesetup.getserverinfo.md) + +## HttpServiceSetup.getServerInfo property + +Provides common [information](./kibana-plugin-server.httpserverinfo.md) about the running http server. + +Signature: + +```typescript +getServerInfo: () => HttpServerInfo; +``` diff --git a/docs/development/core/server/kibana-plugin-server.httpservicesetup.md b/docs/development/core/server/kibana-plugin-server.httpservicesetup.md index 2a4b0e09977c1c..c2d53ec1eaf52e 100644 --- a/docs/development/core/server/kibana-plugin-server.httpservicesetup.md +++ b/docs/development/core/server/kibana-plugin-server.httpservicesetup.md @@ -86,6 +86,7 @@ async (context, request, response) => { | [createCookieSessionStorageFactory](./kibana-plugin-server.httpservicesetup.createcookiesessionstoragefactory.md) | <T>(cookieOptions: SessionStorageCookieOptions<T>) => Promise<SessionStorageFactory<T>> | Creates cookie based session storage factory [SessionStorageFactory](./kibana-plugin-server.sessionstoragefactory.md) | | [createRouter](./kibana-plugin-server.httpservicesetup.createrouter.md) | () => IRouter | Provides ability to declare a handler function for a particular path and HTTP request method. | | [csp](./kibana-plugin-server.httpservicesetup.csp.md) | ICspConfig | The CSP config used for Kibana. | +| [getServerInfo](./kibana-plugin-server.httpservicesetup.getserverinfo.md) | () => HttpServerInfo | Provides common [information](./kibana-plugin-server.httpserverinfo.md) about the running http server. | | [isTlsEnabled](./kibana-plugin-server.httpservicesetup.istlsenabled.md) | boolean | Flag showing whether a server was configured to use TLS connection. | | [registerAuth](./kibana-plugin-server.httpservicesetup.registerauth.md) | (handler: AuthenticationHandler) => void | To define custom authentication and/or authorization mechanism for incoming requests. | | [registerOnPostAuth](./kibana-plugin-server.httpservicesetup.registeronpostauth.md) | (handler: OnPostAuthHandler) => void | To define custom logic to perform for incoming requests. | diff --git a/docs/development/core/server/kibana-plugin-server.md b/docs/development/core/server/kibana-plugin-server.md index e7b13346525406..a3abeff44c25cb 100644 --- a/docs/development/core/server/kibana-plugin-server.md +++ b/docs/development/core/server/kibana-plugin-server.md @@ -64,6 +64,7 @@ The plugin integrates with the core system via lifecycle events: `setup` | [ErrorHttpResponseOptions](./kibana-plugin-server.errorhttpresponseoptions.md) | HTTP response parameters | | [FakeRequest](./kibana-plugin-server.fakerequest.md) | Fake request object created manually by Kibana plugins. | | [HttpResponseOptions](./kibana-plugin-server.httpresponseoptions.md) | HTTP response parameters | +| [HttpServerInfo](./kibana-plugin-server.httpserverinfo.md) | | | [HttpServiceSetup](./kibana-plugin-server.httpservicesetup.md) | Kibana HTTP Service provides own abstraction for work with HTTP stack. Plugins don't have direct access to hapi server and its primitives anymore. Moreover, plugins shouldn't rely on the fact that HTTP Service uses one or another library under the hood. This gives the platform flexibility to upgrade or changing our internal HTTP stack without breaking plugins. If the HTTP Service lacks functionality you need, we are happy to discuss and support your needs. | | [HttpServiceStart](./kibana-plugin-server.httpservicestart.md) | | | [IContextContainer](./kibana-plugin-server.icontextcontainer.md) | An object that handles registration of context providers and configuring handlers with context. | diff --git a/src/core/server/http/http_server.test.ts b/src/core/server/http/http_server.test.ts index f8ef49b0f6d18b..a9fc80c86d878e 100644 --- a/src/core/server/http/http_server.test.ts +++ b/src/core/server/http/http_server.test.ts @@ -62,6 +62,7 @@ beforeAll(() => { beforeEach(() => { config = { + name: 'kibana', host: '127.0.0.1', maxPayload: new ByteSizeValue(1024), port: 10002, @@ -1077,4 +1078,37 @@ describe('setup contract', () => { expect(isTlsEnabled).toBe(false); }); }); + + describe('#getServerInfo', () => { + it('returns correct information', async () => { + let { getServerInfo } = await server.setup(config); + + expect(getServerInfo()).toEqual({ + host: '127.0.0.1', + name: 'kibana', + port: 10002, + protocol: 'http', + }); + + ({ getServerInfo } = await server.setup({ + ...config, + port: 12345, + name: 'custom-name', + host: 'localhost', + })); + + expect(getServerInfo()).toEqual({ + host: 'localhost', + name: 'custom-name', + port: 12345, + protocol: 'http', + }); + }); + + it('returns correct protocol when ssl is enabled', async () => { + const { getServerInfo } = await server.setup(configWithSSL); + + expect(getServerInfo().protocol).toEqual('https'); + }); + }); }); diff --git a/src/core/server/http/http_server.ts b/src/core/server/http/http_server.ts index fdc272041ce354..025ab2bf56ac2d 100644 --- a/src/core/server/http/http_server.ts +++ b/src/core/server/http/http_server.ts @@ -35,7 +35,7 @@ import { import { IsAuthenticated, AuthStateStorage, GetAuthState } from './auth_state_storage'; import { AuthHeadersStorage, GetAuthHeaders } from './auth_headers_storage'; import { BasePath } from './base_path_service'; -import { HttpServiceSetup } from './types'; +import { HttpServiceSetup, HttpServerInfo } from './types'; /** @internal */ export interface HttpServerSetup { @@ -58,6 +58,7 @@ export interface HttpServerSetup { get: GetAuthState; isAuthenticated: IsAuthenticated; }; + getServerInfo: () => HttpServerInfo; } /** @internal */ @@ -122,6 +123,12 @@ export class HttpServer { isAuthenticated: this.authState.isAuthenticated, }, getAuthHeaders: this.authRequestHeaders.get, + getServerInfo: () => ({ + name: config.name, + host: config.host, + port: config.port, + protocol: this.server!.info.protocol, + }), isTlsEnabled: config.ssl.enabled, // Return server instance with the connection options so that we can properly // bridge core and the "legacy" Kibana internally. Once this bridge isn't diff --git a/src/core/server/http/http_service.mock.ts b/src/core/server/http/http_service.mock.ts index 2b2d98d937e859..30032ff5da7968 100644 --- a/src/core/server/http/http_service.mock.ts +++ b/src/core/server/http/http_service.mock.ts @@ -77,12 +77,19 @@ const createSetupContractMock = () => { auth: createAuthMock(), getAuthHeaders: jest.fn(), isTlsEnabled: false, + getServerInfo: jest.fn(), }; setupContract.createCookieSessionStorageFactory.mockResolvedValue( sessionStorageMock.createFactory() ); setupContract.createRouter.mockImplementation(() => mockRouter.create()); setupContract.getAuthHeaders.mockReturnValue({ authorization: 'authorization-header' }); + setupContract.getServerInfo.mockReturnValue({ + host: 'localhost', + name: 'kibana', + port: 80, + protocol: 'http', + }); return setupContract; }; diff --git a/src/core/server/http/types.ts b/src/core/server/http/types.ts index 01b852c26ec934..63278441080556 100644 --- a/src/core/server/http/types.ts +++ b/src/core/server/http/types.ts @@ -252,6 +252,11 @@ export interface HttpServiceSetup { contextName: T, provider: RequestHandlerContextProvider ) => RequestHandlerContextContainer; + + /** + * Provides common {@link HttpServerInfo | information} about the running http server. + */ + getServerInfo: () => HttpServerInfo; } /** @internal */ @@ -273,3 +278,15 @@ export interface HttpServiceStart { /** Indicates if http server is listening on a given port */ isListening: (port: number) => boolean; } + +/** @public */ +export interface HttpServerInfo { + /** The name of the Kibana server */ + name: string; + /** The hostname of the server */ + host: string; + /** The port the server is listening on */ + port: number; + /** The protocol used by the server */ + protocol: 'http' | 'https' | 'socket'; +} diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 91f38c9f2ddbe9..c45acd7f0129a1 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -103,6 +103,7 @@ export { GetAuthState, HttpResponseOptions, HttpResponsePayload, + HttpServerInfo, HttpServiceSetup, HttpServiceStart, ErrorHttpResponseOptions, diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index d0e0453564f943..f9b18afadc9382 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -292,6 +292,7 @@ export class LegacyService implements CoreService { }, csp: setupDeps.core.http.csp, isTlsEnabled: setupDeps.core.http.isTlsEnabled, + getServerInfo: setupDeps.core.http.getServerInfo, }, savedObjects: { setClientFactoryProvider: setupDeps.core.savedObjects.setClientFactoryProvider, diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts index 7d6f09b5232c0c..97f836f8ef37d7 100644 --- a/src/core/server/mocks.ts +++ b/src/core/server/mocks.ts @@ -105,6 +105,7 @@ function createCoreSetupMock() { get: httpService.auth.get, isAuthenticated: httpService.auth.isAuthenticated, }, + getServerInfo: httpService.getServerInfo, }; httpMock.createRouter.mockImplementation(() => httpService.createRouter('')); diff --git a/src/core/server/plugins/plugin_context.ts b/src/core/server/plugins/plugin_context.ts index 30e5209b2fc6a1..77300900e84f33 100644 --- a/src/core/server/plugins/plugin_context.ts +++ b/src/core/server/plugins/plugin_context.ts @@ -164,6 +164,7 @@ export function createPluginSetupContext( auth: { get: deps.http.auth.get, isAuthenticated: deps.http.auth.isAuthenticated }, csp: deps.http.csp, isTlsEnabled: deps.http.isTlsEnabled, + getServerInfo: deps.http.getServerInfo, }, savedObjects: { setClientFactoryProvider: deps.savedObjects.setClientFactoryProvider, diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 20d9692391a691..fb27fcccc2abe1 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -736,6 +736,14 @@ export interface HttpResponseOptions { // @public export type HttpResponsePayload = undefined | string | Record | Buffer | Stream; +// @public (undocumented) +export interface HttpServerInfo { + host: string; + name: string; + port: number; + protocol: 'http' | 'https' | 'socket'; +} + // @public export interface HttpServiceSetup { // (undocumented) @@ -747,6 +755,7 @@ export interface HttpServiceSetup { createCookieSessionStorageFactory: (cookieOptions: SessionStorageCookieOptions) => Promise>; createRouter: () => IRouter; csp: ICspConfig; + getServerInfo: () => HttpServerInfo; isTlsEnabled: boolean; registerAuth: (handler: AuthenticationHandler) => void; registerOnPostAuth: (handler: OnPostAuthHandler) => void; From 79ecc408df62a796f6d1ceecb912e30d430c8d53 Mon Sep 17 00:00:00 2001 From: Aleh Zasypkin Date: Tue, 4 Feb 2020 09:18:52 +0100 Subject: [PATCH 06/11] Mention changed SAML ACS endpoint URL in breaking changes doc. (#56613) --- docs/migration/migrate_8_0.asciidoc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/migration/migrate_8_0.asciidoc b/docs/migration/migrate_8_0.asciidoc index 146d4e97b6cf4a..a34f956ace263d 100644 --- a/docs/migration/migrate_8_0.asciidoc +++ b/docs/migration/migrate_8_0.asciidoc @@ -74,6 +74,12 @@ specified explicitly. *Impact:* Define `xpack.security.authc.saml.realm` when using the SAML authentication provider instead. +[float] +==== `/api/security/v1/saml` endpoint is no longer supported +*Details:* The deprecated `/api/security/v1/saml` endpoint is no longer supported. + +*Impact:* Rely on `/api/security/saml/callback` endpoint when using SAML instead. This change should be reflected in Kibana `server.xsrf.whitelist` config as well as in Elasticsearch and Identity Provider SAML settings. + [float] === `optimize` directory is now in the `data` folder *Details:* Generated bundles have moved to the configured `path.data` folder. From 05edbdac78fae883fada5a5744fdf0f2d5402f41 Mon Sep 17 00:00:00 2001 From: patrykkopycinski Date: Tue, 4 Feb 2020 11:22:40 +0100 Subject: [PATCH 07/11] [SIEM] Add eslint-plugin-react-perf (#55960) Co-authored-by: Elastic Machine --- .eslintrc.js | 14 ++++++++++++-- package.json | 1 + yarn.lock | 5 +++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 97a35d8b50e565..199f3743fd621e 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -643,6 +643,18 @@ module.exports = { // '@typescript-eslint/unbound-method': 'error', }, }, + // { + // // will introduced after the other warns are fixed + // // typescript and javascript for front end react performance + // files: ['x-pack/legacy/plugins/siem/public/**/!(*.test).{js,ts,tsx}'], + // plugins: ['react-perf'], + // rules: { + // // 'react-perf/jsx-no-new-object-as-prop': 'error', + // // 'react-perf/jsx-no-new-array-as-prop': 'error', + // // 'react-perf/jsx-no-new-function-as-prop': 'error', + // // 'react/jsx-no-bind': 'error', + // }, + // }, { // typescript and javascript for front and back end files: ['x-pack/legacy/plugins/siem/**/*.{js,ts,tsx}'], @@ -747,8 +759,6 @@ module.exports = { // will introduced after the other warns are fixed // 'react/sort-comp': 'error', 'react/void-dom-elements-no-children': 'error', - // will introduced after the other warns are fixed - // 'react/jsx-no-bind': 'error', 'react/jsx-no-comment-textnodes': 'error', 'react/jsx-no-literals': 'error', 'react/jsx-no-target-blank': 'error', diff --git a/package.json b/package.json index ff6d32bfc39e51..f9a3bfd99b1098 100644 --- a/package.json +++ b/package.json @@ -414,6 +414,7 @@ "eslint-plugin-prettier": "^3.1.2", "eslint-plugin-react": "^7.17.0", "eslint-plugin-react-hooks": "^2.3.0", + "eslint-plugin-react-perf": "^3.2.3", "exit-hook": "^2.2.0", "faker": "1.1.0", "fetch-mock": "^7.3.9", diff --git a/yarn.lock b/yarn.lock index 4b56ec6460775b..caa5587a0bbd03 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12591,6 +12591,11 @@ eslint-plugin-react-hooks@^2.3.0: resolved "https://registry.yarnpkg.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-2.3.0.tgz#53e073961f1f5ccf8dd19558036c1fac8c29d99a" integrity sha512-gLKCa52G4ee7uXzdLiorca7JIQZPPXRAQDXV83J4bUEeUuc5pIEyZYAZ45Xnxe5IuupxEqHS+hUhSLIimK1EMw== +eslint-plugin-react-perf@^3.2.3: + version "3.2.3" + resolved "https://registry.yarnpkg.com/eslint-plugin-react-perf/-/eslint-plugin-react-perf-3.2.3.tgz#e28d42d3a1f7ec3c8976a94735d8e17e7d652a45" + integrity sha512-bMiPt7uywwS1Ly25n752NE3Ei0XBZ3igplTkZ8GPJKyZVVUd3cHgzILGeQW2HIeAkzQ9zwk9HM6EcYDipdFk3Q== + eslint-plugin-react@^7.17.0: version "7.17.0" resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.17.0.tgz#a31b3e134b76046abe3cd278e7482bd35a1d12d7" From a36ec324a69288c1f4df9204a5c07b0f86be11b9 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 4 Feb 2020 12:38:15 +0100 Subject: [PATCH 08/11] Start consuming np logging config (#56480) * pass config to the new platform * add default appenders * remove receiveAllAppenders flag it breaks legacy-appender compatibility with legacy flags: silent, quiet, verbose * add integration tests * use console mocks to simplify test setup * update tests * improve names * validate that default appender always presents on root level required during migration period to make sure logs are sent to the LP logging system * do not check condition in the loop * fix integration tests --- ...gacy_object_to_config_adapter.test.ts.snap | 2 + .../config/legacy_object_to_config_adapter.ts | 15 +- .../legacy/integration_tests/logging.test.ts | 239 ++++++++++++++++++ .../__snapshots__/logging_config.test.ts.snap | 2 + .../server/logging/appenders/appenders.ts | 6 - .../logging/integration_tests/logging.test.ts | 114 +++++++++ .../server/logging/integration_tests/utils.ts | 68 +++++ src/core/server/logging/logger.test.ts | 82 ------ src/core/server/logging/logger.ts | 8 +- .../server/logging/logging_config.test.ts | 22 +- src/core/server/logging/logging_config.ts | 39 ++- src/legacy/server/config/schema.js | 4 + 12 files changed, 495 insertions(+), 106 deletions(-) create mode 100644 src/core/server/legacy/integration_tests/logging.test.ts create mode 100644 src/core/server/logging/integration_tests/logging.test.ts create mode 100644 src/core/server/logging/integration_tests/utils.ts diff --git a/src/core/server/legacy/config/__snapshots__/legacy_object_to_config_adapter.test.ts.snap b/src/core/server/legacy/config/__snapshots__/legacy_object_to_config_adapter.test.ts.snap index 74ecaa9f09c0e1..3b16bed92df976 100644 --- a/src/core/server/legacy/config/__snapshots__/legacy_object_to_config_adapter.test.ts.snap +++ b/src/core/server/legacy/config/__snapshots__/legacy_object_to_config_adapter.test.ts.snap @@ -72,6 +72,7 @@ Object { }, }, }, + "loggers": undefined, "root": Object { "level": "off", }, @@ -90,6 +91,7 @@ Object { }, }, }, + "loggers": undefined, "root": Object { "level": "all", }, diff --git a/src/core/server/legacy/config/legacy_object_to_config_adapter.ts b/src/core/server/legacy/config/legacy_object_to_config_adapter.ts index 30bb150e6c15a8..3e496648c3af90 100644 --- a/src/core/server/legacy/config/legacy_object_to_config_adapter.ts +++ b/src/core/server/legacy/config/legacy_object_to_config_adapter.ts @@ -19,12 +19,13 @@ import { ConfigPath } from '../../config'; import { ObjectToConfigAdapter } from '../../config/object_to_config_adapter'; +import { LoggingConfigType } from '../../logging/logging_config'; import { LegacyVars } from '../types'; /** * Represents logging config supported by the legacy platform. */ -interface LegacyLoggingConfig { +export interface LegacyLoggingConfig { silent?: boolean; verbose?: boolean; quiet?: boolean; @@ -33,18 +34,24 @@ interface LegacyLoggingConfig { events?: Record; } +type MixedLoggingConfig = LegacyLoggingConfig & Partial; + /** * Represents adapter between config provided by legacy platform and `Config` * supported by the current platform. * @internal */ export class LegacyObjectToConfigAdapter extends ObjectToConfigAdapter { - private static transformLogging(configValue: LegacyLoggingConfig = {}) { + private static transformLogging(configValue: MixedLoggingConfig = {}) { + const { appenders, root, loggers, ...legacyLoggingConfig } = configValue; + const loggingConfig = { appenders: { - default: { kind: 'legacy-appender', legacyLoggingConfig: configValue }, + ...appenders, + default: { kind: 'legacy-appender', legacyLoggingConfig }, }, - root: { level: 'info' }, + root: { level: 'info', ...root }, + loggers, }; if (configValue.silent) { diff --git a/src/core/server/legacy/integration_tests/logging.test.ts b/src/core/server/legacy/integration_tests/logging.test.ts new file mode 100644 index 00000000000000..66234f677903f8 --- /dev/null +++ b/src/core/server/legacy/integration_tests/logging.test.ts @@ -0,0 +1,239 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import * as kbnTestServer from '../../../../test_utils/kbn_server'; + +import { + getPlatformLogsFromMock, + getLegacyPlatformLogsFromMock, +} from '../../logging/integration_tests/utils'; + +import { LegacyLoggingConfig } from '../config/legacy_object_to_config_adapter'; + +function createRoot(legacyLoggingConfig: LegacyLoggingConfig = {}) { + return kbnTestServer.createRoot({ + migrations: { skip: true }, // otherwise stuck in polling ES + logging: { + // legacy platform config + silent: false, + json: false, + ...legacyLoggingConfig, + events: { + log: ['test-file-legacy'], + }, + // platform config + appenders: { + 'test-console': { + kind: 'console', + layout: { + highlight: false, + kind: 'pattern', + }, + }, + }, + loggers: [ + { + context: 'test-file', + appenders: ['test-console'], + level: 'info', + }, + ], + }, + }); +} + +describe('logging service', () => { + let mockConsoleLog: jest.SpyInstance; + let mockStdout: jest.SpyInstance; + + beforeAll(async () => { + mockConsoleLog = jest.spyOn(global.console, 'log'); + mockStdout = jest.spyOn(global.process.stdout, 'write'); + }); + + afterAll(async () => { + mockConsoleLog.mockRestore(); + mockStdout.mockRestore(); + }); + + describe('compatibility', () => { + describe('uses configured loggers', () => { + let root: ReturnType; + beforeAll(async () => { + root = createRoot(); + + await root.setup(); + await root.start(); + }, 30000); + + afterAll(async () => { + await root.shutdown(); + }); + + beforeEach(() => { + mockConsoleLog.mockClear(); + mockStdout.mockClear(); + }); + + it('when context matches', async () => { + root.logger.get('test-file').info('handled by NP'); + + expect(mockConsoleLog).toHaveBeenCalledTimes(1); + const loggedString = getPlatformLogsFromMock(mockConsoleLog); + expect(loggedString).toMatchInlineSnapshot(` + Array [ + "[xxxx-xx-xxTxx:xx:xx.xxxZ][INFO ][test-file] handled by NP", + ] + `); + }); + + it('falls back to the root legacy logger otherwise', async () => { + root.logger.get('test-file-legacy').info('handled by LP'); + + expect(mockStdout).toHaveBeenCalledTimes(1); + + const loggedString = getLegacyPlatformLogsFromMock(mockStdout); + expect(loggedString).toMatchInlineSnapshot(` + Array [ + " log [xx:xx:xx.xxx] [info][test-file-legacy] handled by LP + ", + ] + `); + }); + }); + + describe('logging config respects legacy logging settings', () => { + let root: ReturnType; + + afterEach(async () => { + mockConsoleLog.mockClear(); + mockStdout.mockClear(); + await root.shutdown(); + }); + + it('"silent": true', async () => { + root = createRoot({ silent: true }); + + await root.setup(); + await root.start(); + + const platformLogger = root.logger.get('test-file'); + platformLogger.info('info'); + platformLogger.warn('warn'); + platformLogger.error('error'); + + expect(mockConsoleLog).toHaveBeenCalledTimes(3); + + expect(getPlatformLogsFromMock(mockConsoleLog)).toMatchInlineSnapshot(` + Array [ + "[xxxx-xx-xxTxx:xx:xx.xxxZ][INFO ][test-file] info", + "[xxxx-xx-xxTxx:xx:xx.xxxZ][WARN ][test-file] warn", + "[xxxx-xx-xxTxx:xx:xx.xxxZ][ERROR][test-file] error", + ] + `); + + mockStdout.mockClear(); + + const legacyPlatformLogger = root.logger.get('test-file-legacy'); + legacyPlatformLogger.info('info'); + legacyPlatformLogger.warn('warn'); + legacyPlatformLogger.error('error'); + + expect(mockStdout).toHaveBeenCalledTimes(0); + }); + + it('"quiet": true', async () => { + root = createRoot({ quiet: true }); + + await root.setup(); + await root.start(); + + const platformLogger = root.logger.get('test-file'); + platformLogger.info('info'); + platformLogger.warn('warn'); + platformLogger.error('error'); + + expect(mockConsoleLog).toHaveBeenCalledTimes(3); + + expect(getPlatformLogsFromMock(mockConsoleLog)).toMatchInlineSnapshot(` + Array [ + "[xxxx-xx-xxTxx:xx:xx.xxxZ][INFO ][test-file] info", + "[xxxx-xx-xxTxx:xx:xx.xxxZ][WARN ][test-file] warn", + "[xxxx-xx-xxTxx:xx:xx.xxxZ][ERROR][test-file] error", + ] + `); + + mockStdout.mockClear(); + + const legacyPlatformLogger = root.logger.get('test-file-legacy'); + legacyPlatformLogger.info('info'); + legacyPlatformLogger.warn('warn'); + legacyPlatformLogger.error('error'); + + expect(mockStdout).toHaveBeenCalledTimes(1); + expect(getLegacyPlatformLogsFromMock(mockStdout)).toMatchInlineSnapshot(` + Array [ + " log [xx:xx:xx.xxx] [error][test-file-legacy] error + ", + ] + `); + }); + + it('"verbose": true', async () => { + root = createRoot({ verbose: true }); + + await root.setup(); + await root.start(); + + const platformLogger = root.logger.get('test-file'); + platformLogger.info('info'); + platformLogger.warn('warn'); + platformLogger.error('error'); + + expect(mockConsoleLog).toHaveBeenCalledTimes(3); + + expect(getPlatformLogsFromMock(mockConsoleLog)).toMatchInlineSnapshot(` + Array [ + "[xxxx-xx-xxTxx:xx:xx.xxxZ][INFO ][test-file] info", + "[xxxx-xx-xxTxx:xx:xx.xxxZ][WARN ][test-file] warn", + "[xxxx-xx-xxTxx:xx:xx.xxxZ][ERROR][test-file] error", + ] + `); + + mockStdout.mockClear(); + + const legacyPlatformLogger = root.logger.get('test-file-legacy'); + legacyPlatformLogger.info('info'); + legacyPlatformLogger.warn('warn'); + legacyPlatformLogger.error('error'); + + expect(mockStdout).toHaveBeenCalledTimes(3); + expect(getLegacyPlatformLogsFromMock(mockStdout)).toMatchInlineSnapshot(` + Array [ + " log [xx:xx:xx.xxx] [info][test-file-legacy] info + ", + " log [xx:xx:xx.xxx] [warning][test-file-legacy] warn + ", + " log [xx:xx:xx.xxx] [error][test-file-legacy] error + ", + ] + `); + }); + }); + }); +}); diff --git a/src/core/server/logging/__snapshots__/logging_config.test.ts.snap b/src/core/server/logging/__snapshots__/logging_config.test.ts.snap index 10509b20e89423..fe1407563a6351 100644 --- a/src/core/server/logging/__snapshots__/logging_config.test.ts.snap +++ b/src/core/server/logging/__snapshots__/logging_config.test.ts.snap @@ -13,6 +13,8 @@ Object { } `; +exports[`\`schema\` throws if \`root\` logger does not have "default" appender configured. 1`] = `"[root]: \\"default\\" appender required for migration period till the next major release"`; + exports[`\`schema\` throws if \`root\` logger does not have appenders configured. 1`] = `"[root.appenders]: array size is [0], but cannot be smaller than [1]"`; exports[`fails if loggers use unknown appenders. 1`] = `"Logger \\"some.nested.context\\" contains unsupported appender key \\"unknown\\"."`; diff --git a/src/core/server/logging/appenders/appenders.ts b/src/core/server/logging/appenders/appenders.ts index 871acb8c465ca8..3aa86495e4d825 100644 --- a/src/core/server/logging/appenders/appenders.ts +++ b/src/core/server/logging/appenders/appenders.ts @@ -42,12 +42,6 @@ export type AppenderConfigType = TypeOf; */ export interface Appender { append(record: LogRecord): void; - - /** - * Used to signal to `Logger` that log level filtering should be ignored for this appender. Defaults to `false`. - * @deprecated Should be removed once the `LegacyAppender` is removed. - */ - receiveAllLevels?: boolean; } /** diff --git a/src/core/server/logging/integration_tests/logging.test.ts b/src/core/server/logging/integration_tests/logging.test.ts new file mode 100644 index 00000000000000..7142f91300f124 --- /dev/null +++ b/src/core/server/logging/integration_tests/logging.test.ts @@ -0,0 +1,114 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import * as kbnTestServer from '../../../../test_utils/kbn_server'; + +function createRoot() { + return kbnTestServer.createRoot({ + logging: { + silent: true, // set "true" in kbnTestServer + appenders: { + 'test-console': { + kind: 'console', + layout: { + highlight: false, + kind: 'pattern', + pattern: '{level}|{context}|{message}', + }, + }, + }, + loggers: [ + { + context: 'parent', + appenders: ['test-console'], + level: 'warn', + }, + { + context: 'parent.child', + appenders: ['test-console'], + level: 'error', + }, + ], + }, + }); +} + +describe('logging service', () => { + describe('logs according to context hierarchy', () => { + let root: ReturnType; + let mockConsoleLog: jest.SpyInstance; + beforeAll(async () => { + mockConsoleLog = jest.spyOn(global.console, 'log'); + root = createRoot(); + + await root.setup(); + }, 30000); + + beforeEach(() => { + mockConsoleLog.mockClear(); + }); + + afterAll(async () => { + mockConsoleLog.mockRestore(); + await root.shutdown(); + }); + + it('uses the most specific context', () => { + const logger = root.logger.get('parent.child'); + + logger.error('error from "parent.child" context'); + logger.warn('warning from "parent.child" context'); + logger.info('info from "parent.child" context'); + + expect(mockConsoleLog).toHaveBeenCalledTimes(1); + expect(mockConsoleLog).toHaveBeenCalledWith( + 'ERROR|parent.child|error from "parent.child" context' + ); + }); + + it('uses parent context', () => { + const logger = root.logger.get('parent.another-child'); + + logger.error('error from "parent.another-child" context'); + logger.warn('warning from "parent.another-child" context'); + logger.info('info from "parent.another-child" context'); + + expect(mockConsoleLog).toHaveBeenCalledTimes(2); + expect(mockConsoleLog).toHaveBeenNthCalledWith( + 1, + 'ERROR|parent.another-child|error from "parent.another-child" context' + ); + expect(mockConsoleLog).toHaveBeenNthCalledWith( + 2, + 'WARN |parent.another-child|warning from "parent.another-child" context' + ); + }); + + it('falls back to the root settings', () => { + const logger = root.logger.get('fallback'); + + logger.error('error from "fallback" context'); + logger.warn('warning from fallback" context'); + logger.info('info from "fallback" context'); + + // output muted by silent: true + expect(mockConsoleLog).toHaveBeenCalledTimes(0); + }); + }); +}); diff --git a/src/core/server/logging/integration_tests/utils.ts b/src/core/server/logging/integration_tests/utils.ts new file mode 100644 index 00000000000000..81a76ce76ad733 --- /dev/null +++ b/src/core/server/logging/integration_tests/utils.ts @@ -0,0 +1,68 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import Fs from 'fs'; +import Util from 'util'; +const readFile = Util.promisify(Fs.readFile); + +function replaceAllNumbers(input: string) { + return input.replace(/\d/g, 'x'); +} + +function replaceTimestamp(input: string) { + return input.replace(/\[(.*?)\]/, (full, key) => `[${replaceAllNumbers(key)}]`); +} + +function stripColors(input: string) { + return input.replace(/\u001b[^m]+m/g, ''); +} + +function normalizePlatformLogging(input: string) { + return replaceTimestamp(input); +} + +function normalizeLegacyPlatformLogging(input: string) { + return replaceTimestamp(stripColors(input)); +} + +export function getPlatformLogsFromMock(logMock: jest.SpyInstance) { + return logMock.mock.calls.map(([message]) => message).map(normalizePlatformLogging); +} + +export function getLegacyPlatformLogsFromMock(stdoutMock: jest.SpyInstance) { + return stdoutMock.mock.calls + .map(([message]) => message) + .map(String) + .map(normalizeLegacyPlatformLogging); +} + +export async function getPlatformLogsFromFile(path: string) { + const fileContent = await readFile(path, 'utf-8'); + return fileContent + .split('\n') + .map(s => normalizePlatformLogging(s)) + .join('\n'); +} + +export async function getLegacyPlatformLogsFromFile(path: string) { + const fileContent = await readFile(path, 'utf-8'); + return fileContent + .split('\n') + .map(s => normalizeLegacyPlatformLogging(s)) + .join('\n'); +} diff --git a/src/core/server/logging/logger.test.ts b/src/core/server/logging/logger.test.ts index eeebb8ad5a0fa7..026e24fc5df543 100644 --- a/src/core/server/logging/logger.test.ts +++ b/src/core/server/logging/logger.test.ts @@ -410,85 +410,3 @@ test('passes log record to appenders only if log level is supported.', () => { }); } }); - -test('passes log record to appender with receiveAllLevels: true, regardless if log level is supported', () => { - const receiveAllAppender = { append: jest.fn(), receiveAllLevels: true }; - const warnLogger = new BaseLogger(context, LogLevel.Warn, [receiveAllAppender], factory); - - warnLogger.trace('trace-message'); - expect(receiveAllAppender.append).toHaveBeenCalledTimes(1); - expect(receiveAllAppender.append.mock.calls[0][0]).toMatchObject({ - level: LogLevel.Trace, - message: 'trace-message', - }); - - warnLogger.debug('debug-message'); - expect(receiveAllAppender.append).toHaveBeenCalledTimes(2); - expect(receiveAllAppender.append.mock.calls[1][0]).toMatchObject({ - level: LogLevel.Debug, - message: 'debug-message', - }); - - warnLogger.info('info-message'); - expect(receiveAllAppender.append).toHaveBeenCalledTimes(3); - expect(receiveAllAppender.append.mock.calls[2][0]).toMatchObject({ - level: LogLevel.Info, - message: 'info-message', - }); - - warnLogger.warn('warn-message'); - expect(receiveAllAppender.append).toHaveBeenCalledTimes(4); - expect(receiveAllAppender.append.mock.calls[3][0]).toMatchObject({ - level: LogLevel.Warn, - message: 'warn-message', - }); - - warnLogger.error('error-message'); - expect(receiveAllAppender.append).toHaveBeenCalledTimes(5); - expect(receiveAllAppender.append.mock.calls[4][0]).toMatchObject({ - level: LogLevel.Error, - message: 'error-message', - }); - - warnLogger.fatal('fatal-message'); - expect(receiveAllAppender.append).toHaveBeenCalledTimes(6); - expect(receiveAllAppender.append.mock.calls[5][0]).toMatchObject({ - level: LogLevel.Fatal, - message: 'fatal-message', - }); -}); - -test('passes log record to appender with receiveAllLevels: false, only if log level is supported', () => { - const notReceiveAllAppender = { append: jest.fn(), receiveAllLevels: false }; - const warnLogger = new BaseLogger(context, LogLevel.Warn, [notReceiveAllAppender], factory); - - warnLogger.trace('trace-message'); - expect(notReceiveAllAppender.append).toHaveBeenCalledTimes(0); - - warnLogger.debug('debug-message'); - expect(notReceiveAllAppender.append).toHaveBeenCalledTimes(0); - - warnLogger.info('info-message'); - expect(notReceiveAllAppender.append).toHaveBeenCalledTimes(0); - - warnLogger.warn('warn-message'); - expect(notReceiveAllAppender.append).toHaveBeenCalledTimes(1); - expect(notReceiveAllAppender.append.mock.calls[0][0]).toMatchObject({ - level: LogLevel.Warn, - message: 'warn-message', - }); - - warnLogger.error('error-message'); - expect(notReceiveAllAppender.append).toHaveBeenCalledTimes(2); - expect(notReceiveAllAppender.append.mock.calls[1][0]).toMatchObject({ - level: LogLevel.Error, - message: 'error-message', - }); - - warnLogger.fatal('fatal-message'); - expect(notReceiveAllAppender.append).toHaveBeenCalledTimes(3); - expect(notReceiveAllAppender.append.mock.calls[2][0]).toMatchObject({ - level: LogLevel.Fatal, - message: 'fatal-message', - }); -}); diff --git a/src/core/server/logging/logger.ts b/src/core/server/logging/logger.ts index ab6906ff5d6847..ac79c1916c07ba 100644 --- a/src/core/server/logging/logger.ts +++ b/src/core/server/logging/logger.ts @@ -136,12 +136,12 @@ export class BaseLogger implements Logger { } public log(record: LogRecord) { - const supportedLevel = this.level.supports(record.level); + if (!this.level.supports(record.level)) { + return; + } for (const appender of this.appenders) { - if (supportedLevel || appender.receiveAllLevels) { - appender.append(record); - } + appender.append(record); } } diff --git a/src/core/server/logging/logging_config.test.ts b/src/core/server/logging/logging_config.test.ts index 8eb79ac46e499a..b3631abb9ff002 100644 --- a/src/core/server/logging/logging_config.test.ts +++ b/src/core/server/logging/logging_config.test.ts @@ -33,6 +33,16 @@ test('`schema` throws if `root` logger does not have appenders configured.', () ).toThrowErrorMatchingSnapshot(); }); +test('`schema` throws if `root` logger does not have "default" appender configured.', () => { + expect(() => + config.schema.validate({ + root: { + appenders: ['console'], + }, + }) + ).toThrowErrorMatchingSnapshot(); +}); + test('`getParentLoggerContext()` returns correct parent context name.', () => { expect(LoggingConfig.getParentLoggerContext('a.b.c')).toEqual('a.b'); expect(LoggingConfig.getParentLoggerContext('a.b')).toEqual('a'); @@ -46,15 +56,23 @@ test('`getLoggerContext()` returns correct joined context name.', () => { expect(LoggingConfig.getLoggerContext([])).toEqual('root'); }); -test('correctly fills in default `appenders` config.', () => { +test('correctly fills in default config.', () => { const configValue = new LoggingConfig(config.schema.validate({})); - expect(configValue.appenders.size).toBe(1); + expect(configValue.appenders.size).toBe(3); expect(configValue.appenders.get('default')).toEqual({ kind: 'console', layout: { kind: 'pattern', highlight: true }, }); + expect(configValue.appenders.get('console')).toEqual({ + kind: 'console', + layout: { kind: 'pattern', highlight: true }, + }); + expect(configValue.appenders.get('file')).toEqual({ + kind: 'file', + layout: { kind: 'pattern', highlight: false }, + }); }); test('correctly fills in custom `appenders` config.', () => { diff --git a/src/core/server/logging/logging_config.ts b/src/core/server/logging/logging_config.ts index 84d707a3247e67..f1fbf787737b4a 100644 --- a/src/core/server/logging/logging_config.ts +++ b/src/core/server/logging/logging_config.ts @@ -72,13 +72,22 @@ export const config = { loggers: schema.arrayOf(createLoggerSchema, { defaultValue: [], }), - root: schema.object({ - appenders: schema.arrayOf(schema.string(), { - defaultValue: [DEFAULT_APPENDER_NAME], - minSize: 1, - }), - level: createLevelSchema, - }), + root: schema.object( + { + appenders: schema.arrayOf(schema.string(), { + defaultValue: [DEFAULT_APPENDER_NAME], + minSize: 1, + }), + level: createLevelSchema, + }, + { + validate(rawConfig) { + if (!rawConfig.appenders.includes(DEFAULT_APPENDER_NAME)) { + return `"${DEFAULT_APPENDER_NAME}" appender required for migration period till the next major release`; + } + }, + } + ), }), }; @@ -118,12 +127,26 @@ export class LoggingConfig { */ public readonly appenders: Map = new Map([ [ - DEFAULT_APPENDER_NAME, + 'default', + { + kind: 'console', + layout: { kind: 'pattern', highlight: true }, + } as AppenderConfigType, + ], + [ + 'console', { kind: 'console', layout: { kind: 'pattern', highlight: true }, } as AppenderConfigType, ], + [ + 'file', + { + kind: 'file', + layout: { kind: 'pattern', highlight: false }, + } as AppenderConfigType, + ], ]); /** diff --git a/src/legacy/server/config/schema.js b/src/legacy/server/config/schema.js index f2a14df1d1eb38..a24ffcbaaa49f0 100644 --- a/src/legacy/server/config/schema.js +++ b/src/legacy/server/config/schema.js @@ -103,6 +103,10 @@ export default () => logging: Joi.object() .keys({ + appenders: HANDLED_IN_NEW_PLATFORM, + loggers: HANDLED_IN_NEW_PLATFORM, + root: HANDLED_IN_NEW_PLATFORM, + silent: Joi.boolean().default(false), quiet: Joi.boolean().when('silent', { From 55e0e8d746ba360f5f2282187a9f2479badded6c Mon Sep 17 00:00:00 2001 From: patrykkopycinski Date: Tue, 4 Feb 2020 13:00:08 +0100 Subject: [PATCH 09/11] [SIEM] Enable flow_target_select_connected unit tests (#55618) Co-authored-by: Elastic Machine --- .../index.test.tsx | 22 ++++++++++++++----- .../flow_target_select_connected/index.tsx | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.test.tsx index 006587d8fc294b..e71be5a51e5053 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.test.tsx @@ -6,27 +6,37 @@ import { mount } from 'enzyme'; import React from 'react'; +import { MemoryRouter } from 'react-router-dom'; import { TestProviders } from '../../../../mock'; -import { FlowTargetSelectConnected } from './index'; +import { FlowTargetSelectConnectedComponent } from './index'; import { FlowTarget } from '../../../../graphql/types'; -describe.skip('Flow Target Select Connected', () => { +describe('Flow Target Select Connected', () => { test('renders correctly against snapshot flowTarget source', () => { const wrapper = mount( - + + + ); - expect(wrapper.find('FlowTargetSelectConnected')).toMatchSnapshot(); + expect(wrapper.find('Memo(FlowTargetSelectComponent)').prop('selectedTarget')).toEqual( + FlowTarget.source + ); }); test('renders correctly against snapshot flowTarget destination', () => { const wrapper = mount( - + + + ); - expect(wrapper.find('FlowTargetSelectConnected')).toMatchSnapshot(); + + expect(wrapper.find('Memo(FlowTargetSelectComponent)').prop('selectedTarget')).toEqual( + FlowTarget.destination + ); }); }); diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.tsx index 1b87c36902159b..2651c31e0a2c9e 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/flow_target_select_connected/index.tsx @@ -36,7 +36,7 @@ const getUpdatedFlowTargetPath = ( return `${newPathame}${location.search}`; }; -const FlowTargetSelectConnectedComponent: React.FC = ({ flowTarget }) => { +export const FlowTargetSelectConnectedComponent: React.FC = ({ flowTarget }) => { const history = useHistory(); const location = useLocation(); From 661bb6b438138889f45270517cc8779fb20f2cab Mon Sep 17 00:00:00 2001 From: Matthias Wilhelm Date: Tue, 4 Feb 2020 13:08:52 +0100 Subject: [PATCH 10/11] [Discover] Migrate get_sort.js test from mocha to TypeScript (#56011) * Migrate get_sort.js test from mocha to jest and convert to TypeScript * Add jest test --- .../__tests__/doc_table/lib/get_sort.js | 104 ------------------ .../discover/np_ready/angular/discover.js | 11 +- .../angular/doc_table/lib/get_sort.d.ts | 27 ----- .../angular/doc_table/lib/get_sort.js | 62 ----------- .../angular/doc_table/lib/get_sort.test.ts | 91 +++++++++++++++ .../angular/doc_table/lib/get_sort.ts | 71 ++++++++++++ .../lib/get_sort_for_search_source.ts | 10 +- .../data/public/search/search_source/types.ts | 7 +- 8 files changed, 177 insertions(+), 206 deletions(-) delete mode 100644 src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/get_sort.js delete mode 100644 src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.d.ts delete mode 100644 src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.js create mode 100644 src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.test.ts create mode 100644 src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/get_sort.js b/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/get_sort.js deleted file mode 100644 index d5485bca33cf50..00000000000000 --- a/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/get_sort.js +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import expect from '@kbn/expect'; -import ngMock from 'ng_mock'; - -import { getSort } from '../../../np_ready/angular/doc_table/lib/get_sort'; -import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; - -let indexPattern; - -describe('docTable', function() { - beforeEach(ngMock.module('kibana')); - - beforeEach( - ngMock.inject(function(Private) { - indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - }) - ); - - describe('getSort function', function() { - it('should be a function', function() { - expect(getSort).to.be.a(Function); - }); - - it('should return an array of objects', function() { - expect(getSort([['bytes', 'desc']], indexPattern)).to.eql([{ bytes: 'desc' }]); - - delete indexPattern.timeFieldName; - expect(getSort([['bytes', 'desc']], indexPattern)).to.eql([{ bytes: 'desc' }]); - }); - - it('should passthrough arrays of objects', () => { - expect(getSort([{ bytes: 'desc' }], indexPattern)).to.eql([{ bytes: 'desc' }]); - }); - - it('should return an empty array when passed an unsortable field', function() { - expect(getSort(['non-sortable', 'asc'], indexPattern)).to.eql([]); - expect(getSort(['lol_nope', 'asc'], indexPattern)).to.eql([]); - - delete indexPattern.timeFieldName; - expect(getSort(['non-sortable', 'asc'], indexPattern)).to.eql([]); - }); - - it('should return an empty array ', function() { - expect(getSort([], indexPattern)).to.eql([]); - expect(getSort(['foo'], indexPattern)).to.eql([]); - expect(getSort({ foo: 'bar' }, indexPattern)).to.eql([]); - }); - - it('should return an empty array on non-time patterns', function() { - delete indexPattern.timeFieldName; - - expect(getSort([], indexPattern)).to.eql([]); - expect(getSort(['foo'], indexPattern)).to.eql([]); - expect(getSort({ foo: 'bar' }, indexPattern)).to.eql([]); - }); - }); - - describe('getSort.array function', function() { - it('should have an array method', function() { - expect(getSort.array).to.be.a(Function); - }); - - it('should return an array of arrays for sortable fields', function() { - expect(getSort.array([['bytes', 'desc']], indexPattern)).to.eql([['bytes', 'desc']]); - }); - - it('should return an array of arrays from an array of elasticsearch sort objects', function() { - expect(getSort.array([{ bytes: 'desc' }], indexPattern)).to.eql([['bytes', 'desc']]); - }); - - it('should sort by an empty array when an unsortable field is given', function() { - expect(getSort.array([{ 'non-sortable': 'asc' }], indexPattern)).to.eql([]); - expect(getSort.array([{ lol_nope: 'asc' }], indexPattern)).to.eql([]); - - delete indexPattern.timeFieldName; - expect(getSort.array([{ 'non-sortable': 'asc' }], indexPattern)).to.eql([]); - }); - - it('should return an empty array when passed an empty sort array', () => { - expect(getSort.array([], indexPattern)).to.eql([]); - - delete indexPattern.timeFieldName; - expect(getSort.array([], indexPattern)).to.eql([]); - }); - }); -}); diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js index 5e99cab1b32975..2f73af2ab77e47 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js @@ -28,7 +28,7 @@ import '../components/field_chooser/field_chooser'; import { RequestAdapter } from '../../../../../../../plugins/inspector/public'; // doc table import './doc_table'; -import { getSort } from './doc_table/lib/get_sort'; +import { getSortArray } from './doc_table/lib/get_sort'; import { getSortForSearchSource } from './doc_table/lib/get_sort_for_search_source'; import * as columnActions from './doc_table/actions/columns'; @@ -525,7 +525,7 @@ function discoverController( language: localStorage.get('kibana.userQueryLanguage') || config.get('search:queryLanguage'), }, - sort: getSort.array(savedSearch.sort, $scope.indexPattern), + sort: getSortArray(savedSearch.sort, $scope.indexPattern), columns: savedSearch.columns.length > 0 ? savedSearch.columns : config.get('defaultColumns').slice(), index: $scope.indexPattern.id, @@ -537,7 +537,7 @@ function discoverController( } $state.index = $scope.indexPattern.id; - $state.sort = getSort.array($state.sort, $scope.indexPattern); + $state.sort = getSortArray($state.sort, $scope.indexPattern); $scope.getBucketIntervalToolTipText = () => { return i18n.translate('kbn.discover.bucketIntervalTooltip', { @@ -619,10 +619,7 @@ function discoverController( if (!sort) return; // get the current sort from searchSource as array of arrays - const currentSort = getSort.array( - $scope.searchSource.getField('sort'), - $scope.indexPattern - ); + const currentSort = getSortArray($scope.searchSource.getField('sort'), $scope.indexPattern); // if the searchSource doesn't know, tell it so if (!angular.equals(sort, currentSort)) $scope.fetch(); diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.d.ts b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.d.ts deleted file mode 100644 index 0bf8a93a883673..00000000000000 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { IIndexPattern } from '../../../../../../../../../plugins/data/public'; -import { SortOrder } from '../components/table_header/helpers'; - -export function getSort( - sort?: SortOrder[], - indexPattern?: IIndexPattern, - defaultSortOrder?: SortOrder -): any; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.js b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.js deleted file mode 100644 index ce32fdaeda2375..00000000000000 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.js +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import _ from 'lodash'; - -export function isSortable(field, indexPattern) { - return indexPattern.fields.getByName(field) && indexPattern.fields.getByName(field).sortable; -} - -function createSortObject(sortPair, indexPattern) { - if (Array.isArray(sortPair) && sortPair.length === 2 && isSortable(sortPair[0], indexPattern)) { - const [field, direction] = sortPair; - return { [field]: direction }; - } else if (_.isPlainObject(sortPair) && isSortable(Object.keys(sortPair)[0], indexPattern)) { - return sortPair; - } else { - return undefined; - } -} - -/** - * Take a sorting array and make it into an object - * @param {array} sort two dimensional array [[fieldToSort, directionToSort]] - * or an array of objects [{fieldToSort: directionToSort}] - * @param {object} indexPattern used for determining default sort - * @returns {object} a sort object suitable for returning to elasticsearch - */ -export function getSort(sort, indexPattern) { - let sortObjects; - if (Array.isArray(sort)) { - sortObjects = _.compact(sort.map(sortPair => createSortObject(sortPair, indexPattern))); - } - - if (!_.isEmpty(sortObjects)) { - return sortObjects; - } - return []; -} - -getSort.array = function(sort, indexPattern) { - return getSort(sort, indexPattern).map(sortPair => - _(sortPair) - .pairs() - .pop() - ); -}; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.test.ts b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.test.ts new file mode 100644 index 00000000000000..c9cbad245f5e41 --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.test.ts @@ -0,0 +1,91 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { getSort, getSortArray } from './get_sort'; +// @ts-ignore +import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; +import { IndexPattern } from '../../../../kibana_services'; + +describe('docTable', function() { + let indexPattern: IndexPattern; + + beforeEach(() => { + indexPattern = FixturesStubbedLogstashIndexPatternProvider() as IndexPattern; + }); + + describe('getSort function', function() { + test('should be a function', function() { + expect(typeof getSort === 'function').toBeTruthy(); + }); + + test('should return an array of objects', function() { + expect(getSort([['bytes', 'desc']], indexPattern)).toEqual([{ bytes: 'desc' }]); + + delete indexPattern.timeFieldName; + expect(getSort([['bytes', 'desc']], indexPattern)).toEqual([{ bytes: 'desc' }]); + }); + + test('should passthrough arrays of objects', () => { + expect(getSort([{ bytes: 'desc' }], indexPattern)).toEqual([{ bytes: 'desc' }]); + }); + + test('should return an empty array when passed an unsortable field', function() { + expect(getSort([['non-sortable', 'asc']], indexPattern)).toEqual([]); + expect(getSort([['lol_nope', 'asc']], indexPattern)).toEqual([]); + + delete indexPattern.timeFieldName; + expect(getSort([['non-sortable', 'asc']], indexPattern)).toEqual([]); + }); + + test('should return an empty array ', function() { + expect(getSort([], indexPattern)).toEqual([]); + expect(getSort([['foo', 'bar']], indexPattern)).toEqual([]); + expect(getSort([{ foo: 'bar' }], indexPattern)).toEqual([]); + }); + }); + + describe('getSortArray function', function() { + test('should have an array method', function() { + expect(getSortArray).toBeInstanceOf(Function); + }); + + test('should return an array of arrays for sortable fields', function() { + expect(getSortArray([['bytes', 'desc']], indexPattern)).toEqual([['bytes', 'desc']]); + }); + + test('should return an array of arrays from an array of elasticsearch sort objects', function() { + expect(getSortArray([{ bytes: 'desc' }], indexPattern)).toEqual([['bytes', 'desc']]); + }); + + test('should sort by an empty array when an unsortable field is given', function() { + expect(getSortArray([{ 'non-sortable': 'asc' }], indexPattern)).toEqual([]); + expect(getSortArray([{ lol_nope: 'asc' }], indexPattern)).toEqual([]); + + delete indexPattern.timeFieldName; + expect(getSortArray([{ 'non-sortable': 'asc' }], indexPattern)).toEqual([]); + }); + + test('should return an empty array when passed an empty sort array', () => { + expect(getSortArray([], indexPattern)).toEqual([]); + + delete indexPattern.timeFieldName; + expect(getSortArray([], indexPattern)).toEqual([]); + }); + }); +}); diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.ts b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.ts new file mode 100644 index 00000000000000..a8dbaa50e5aa87 --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort.ts @@ -0,0 +1,71 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import _ from 'lodash'; +import { IndexPattern } from '../../../../../../../../../plugins/data/public'; + +export type SortPairObj = Record; +export type SortPairArr = [string, string]; +export type SortPair = SortPairArr | SortPairObj; +export type SortInput = SortPair | SortPair[]; + +export function isSortable(fieldName: string, indexPattern: IndexPattern) { + const field = indexPattern.getFieldByName(fieldName); + return field && field.sortable; +} + +function createSortObject( + sortPair: SortInput, + indexPattern: IndexPattern +): SortPairObj | undefined { + if ( + Array.isArray(sortPair) && + sortPair.length === 2 && + isSortable(String(sortPair[0]), indexPattern) + ) { + const [field, direction] = sortPair as SortPairArr; + return { [field]: direction }; + } else if (_.isPlainObject(sortPair) && isSortable(Object.keys(sortPair)[0], indexPattern)) { + return sortPair as SortPairObj; + } +} + +/** + * Take a sorting array and make it into an object + * @param {array} sort two dimensional array [[fieldToSort, directionToSort]] + * or an array of objects [{fieldToSort: directionToSort}] + * @param {object} indexPattern used for determining default sort + * @returns Array<{object}> an array of sort objects + */ +export function getSort(sort: SortPair[], indexPattern: IndexPattern): SortPairObj[] { + if (Array.isArray(sort)) { + return sort + .map((sortPair: SortPair) => createSortObject(sortPair, indexPattern)) + .filter(sortPairObj => typeof sortPairObj === 'object') as SortPairObj[]; + } + return []; +} + +/** + * compared to getSort it doesn't return an array of objects, it returns an array of arrays + * [[fieldToSort: directionToSort]] + */ +export function getSortArray(sort: SortPair[], indexPattern: IndexPattern) { + return getSort(sort, indexPattern).map(sortPair => Object.entries(sortPair).pop()); +} diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort_for_search_source.ts b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort_for_search_source.ts index 62a44d30adfd55..6721f7a03584cd 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort_for_search_source.ts +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/lib/get_sort_for_search_source.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { IndexPattern } from '../../../../kibana_services'; +import { EsQuerySortValue, IndexPattern } from '../../../../kibana_services'; import { SortOrder } from '../components/table_header/helpers'; import { getSort } from './get_sort'; import { getDefaultSort } from './get_default_sort'; @@ -31,8 +31,8 @@ import { getDefaultSort } from './get_default_sort'; export function getSortForSearchSource( sort?: SortOrder[], indexPattern?: IndexPattern, - defaultDirection: 'asc' | 'desc' = 'desc' -) { + defaultDirection: string = 'desc' +): EsQuerySortValue[] { if (!sort || !indexPattern) { return []; } else if (Array.isArray(sort) && sort.length === 0) { @@ -46,8 +46,8 @@ export function getSortForSearchSource( order: sortPair[timeFieldName], numeric_type: 'date_nanos', }, - }; + } as EsQuerySortValue; } - return sortPair; + return sortPair as EsQuerySortValue; }); } diff --git a/src/plugins/data/public/search/search_source/types.ts b/src/plugins/data/public/search/search_source/types.ts index 17337c905db877..268d24aaa6df11 100644 --- a/src/plugins/data/public/search/search_source/types.ts +++ b/src/plugins/data/public/search/search_source/types.ts @@ -26,7 +26,12 @@ export enum SortDirection { desc = 'desc', } -export type EsQuerySortValue = Record; +export interface SortDirectionNumeric { + order: SortDirection; + numeric_type?: 'double' | 'long' | 'date' | 'date_nanos'; +} + +export type EsQuerySortValue = Record; export interface SearchSourceFields { type?: string; From d73e15f4147d1de9a7ee15517cbf6a90f4d4b213 Mon Sep 17 00:00:00 2001 From: Matthias Wilhelm Date: Tue, 4 Feb 2020 14:16:41 +0100 Subject: [PATCH 11/11] [Discover] Inline angular directives only used in this plugin (#56119) * Migrate field_name directive * Migrate collapsible_sidebar directive * Fix FieldName import at table_row.tsx * Migrate css_truncate directive * Migrate fixed_scroll & debounce directives * Migrate render_complete directive * Fix css_truncate test * Use shortenDottedString in the TypesScript version --- .../__tests__/directives}/css_truncate.js | 6 +++-- .../__tests__/directives}/fixed_scroll.js | 7 +++--- .../public/discover/get_inner_angular.ts | 24 ++++++++----------- .../kibana/public/discover/kibana_services.ts | 5 ---- .../np_ready/angular/directives/_index.scss | 3 ++- .../_collapsible_sidebar.scss | 0 .../collapsible_sidebar}/_depth.scss | 0 .../collapsible_sidebar/_index.scss | 2 ++ .../collapsible_sidebar.ts} | 14 ++++++----- .../angular/directives/css_truncate.ts} | 10 ++------ .../directives/debounce/__tests__/debounce.js | 7 ++++-- .../angular}/directives/debounce/debounce.js | 5 ---- .../angular}/directives/debounce/index.js | 0 .../angular}/directives/field_name.js | 6 +---- .../__snapshots__/field_name.test.tsx.snap | 0 .../directives/field_name/field_name.test.tsx | 0 .../directives/field_name/field_name.tsx | 5 ++-- .../directives/field_name/field_type_name.ts | 24 +++++++++---------- .../angular/directives}/fixed_scroll.js | 15 +++++------- .../angular/directives/render_complete.ts} | 9 +++---- .../components/table_header/helpers.tsx | 3 +-- .../np_ready/components/table/table_row.tsx | 2 +- src/legacy/ui/public/_index.scss | 1 - .../ui/public/collapsible_sidebar/_index.scss | 3 --- .../ui/public/collapsible_sidebar/index.js | 20 ---------------- .../ui/public/styles/_legacy/_index.scss | 1 - .../translations/translations/ja-JP.json | 22 ++++++++--------- .../translations/translations/zh-CN.json | 22 ++++++++--------- 28 files changed, 85 insertions(+), 131 deletions(-) rename src/legacy/{ui/public/directives/__tests__ => core_plugins/kibana/public/discover/__tests__/directives}/css_truncate.js (92%) rename src/legacy/{ui/public/directives/__tests__ => core_plugins/kibana/public/discover/__tests__/directives}/fixed_scroll.js (96%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular/directives}/collapsible_sidebar/_collapsible_sidebar.scss (100%) rename src/legacy/{ui/public/styles/_legacy => core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar}/_depth.scss (100%) create mode 100644 src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_index.scss rename src/legacy/{ui/public/collapsible_sidebar/collapsible_sidebar.js => core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar.ts} (91%) rename src/legacy/{ui/public/directives/css_truncate.js => core_plugins/kibana/public/discover/np_ready/angular/directives/css_truncate.ts} (89%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/debounce/__tests__/debounce.js (95%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/debounce/debounce.js (92%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/debounce/index.js (100%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/field_name.js (86%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/field_name/__snapshots__/field_name.test.tsx.snap (100%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/field_name/field_name.test.tsx (100%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/field_name/field_name.tsx (91%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular}/directives/field_name/field_type_name.ts (62%) rename src/legacy/{ui/public => core_plugins/kibana/public/discover/np_ready/angular/directives}/fixed_scroll.js (96%) rename src/legacy/{ui/public/render_complete/directive.js => core_plugins/kibana/public/discover/np_ready/angular/directives/render_complete.ts} (81%) delete mode 100644 src/legacy/ui/public/collapsible_sidebar/_index.scss delete mode 100644 src/legacy/ui/public/collapsible_sidebar/index.js diff --git a/src/legacy/ui/public/directives/__tests__/css_truncate.js b/src/legacy/core_plugins/kibana/public/discover/__tests__/directives/css_truncate.js similarity index 92% rename from src/legacy/ui/public/directives/__tests__/css_truncate.js rename to src/legacy/core_plugins/kibana/public/discover/__tests__/directives/css_truncate.js index bf102f5a29fdb9..8dea9c61475dbe 100644 --- a/src/legacy/ui/public/directives/__tests__/css_truncate.js +++ b/src/legacy/core_plugins/kibana/public/discover/__tests__/directives/css_truncate.js @@ -20,7 +20,7 @@ import angular from 'angular'; import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -import 'plugins/kibana/discover/legacy'; +import { pluginInstance } from 'plugins/kibana/discover/legacy'; let $parentScope; @@ -30,7 +30,9 @@ let $elem; const init = function(expandable) { // Load the application - ngMock.module('kibana'); + pluginInstance.initializeServices(); + pluginInstance.initializeInnerAngular(); + ngMock.module('app/discover'); // Create the scope ngMock.inject(function($rootScope, $compile) { diff --git a/src/legacy/ui/public/directives/__tests__/fixed_scroll.js b/src/legacy/core_plugins/kibana/public/discover/__tests__/directives/fixed_scroll.js similarity index 96% rename from src/legacy/ui/public/directives/__tests__/fixed_scroll.js rename to src/legacy/core_plugins/kibana/public/discover/__tests__/directives/fixed_scroll.js index b35836967c3f38..49a0df54079ea5 100644 --- a/src/legacy/ui/public/directives/__tests__/fixed_scroll.js +++ b/src/legacy/core_plugins/kibana/public/discover/__tests__/directives/fixed_scroll.js @@ -18,8 +18,8 @@ */ import expect from '@kbn/expect'; +import { pluginInstance } from 'plugins/kibana/discover/legacy'; import ngMock from 'ng_mock'; -import '../../fixed_scroll'; import $ from 'jquery'; import sinon from 'sinon'; @@ -29,8 +29,9 @@ describe('FixedScroll directive', function() { let compile; let flushPendingTasks; const trash = []; - - beforeEach(ngMock.module('kibana')); + beforeEach(() => pluginInstance.initializeServices()); + beforeEach(() => pluginInstance.initializeInnerAngular()); + beforeEach(ngMock.module('app/discover')); beforeEach( ngMock.inject(function($compile, $rootScope, $timeout) { flushPendingTasks = function flushPendingTasks() { diff --git a/src/legacy/core_plugins/kibana/public/discover/get_inner_angular.ts b/src/legacy/core_plugins/kibana/public/discover/get_inner_angular.ts index fea834686eb4f0..36a6c8eaef40ec 100644 --- a/src/legacy/core_plugins/kibana/public/discover/get_inner_angular.ts +++ b/src/legacy/core_plugins/kibana/public/discover/get_inner_angular.ts @@ -42,22 +42,10 @@ import { registerListenEventListener } from 'ui/directives/listen/listen'; // @ts-ignore import { KbnAccessibleClickProvider } from 'ui/accessibility/kbn_accessible_click'; // @ts-ignore -import { FieldNameDirectiveProvider } from 'ui/directives/field_name'; -// @ts-ignore -import { CollapsibleSidebarProvider } from 'ui/collapsible_sidebar/collapsible_sidebar'; -// @ts-ignore -import { CssTruncateProvide } from 'ui/directives/css_truncate'; -// @ts-ignore -import { FixedScrollProvider } from 'ui/fixed_scroll'; -// @ts-ignore -import { DebounceProviderTimeout } from 'ui/directives/debounce/debounce'; -// @ts-ignore import { AppStateProvider } from 'ui/state_management/app_state'; // @ts-ignore import { GlobalStateProvider } from 'ui/state_management/global_state'; // @ts-ignore -import { createRenderCompleteDirective } from 'ui/render_complete/directive'; -// @ts-ignore import { StateManagementConfigProvider } from 'ui/state_management/config_provider'; // @ts-ignore import { KbnUrlProvider, RedirectWhenMissingProvider } from 'ui/url'; @@ -81,11 +69,19 @@ import { createFieldSearchDirective } from './np_ready/components/field_chooser/ import { createIndexPatternSelectDirective } from './np_ready/components/field_chooser/discover_index_pattern_directive'; import { createStringFieldProgressBarDirective } from './np_ready/components/field_chooser/string_progress_bar'; // @ts-ignore +import { FieldNameDirectiveProvider } from './np_ready/angular/directives/field_name'; +// @ts-ignore import { createFieldChooserDirective } from './np_ready/components/field_chooser/field_chooser'; - // @ts-ignore import { createDiscoverFieldDirective } from './np_ready/components/field_chooser/discover_field'; +import { CollapsibleSidebarProvider } from './np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar'; import { DiscoverStartPlugins } from './plugin'; +import { createCssTruncateDirective } from './np_ready/angular/directives/css_truncate'; +// @ts-ignore +import { FixedScrollProvider } from './np_ready/angular/directives/fixed_scroll'; +// @ts-ignore +import { DebounceProviderTimeout } from './np_ready/angular/directives/debounce/debounce'; +import { createRenderCompleteDirective } from './np_ready/angular/directives/render_complete'; /** * returns the main inner angular module, it contains all the parts of Angular Discover @@ -181,7 +177,7 @@ export function initializeInnerAngularModule( .directive('kbnAccessibleClick', KbnAccessibleClickProvider) .directive('fieldName', FieldNameDirectiveProvider) .directive('collapsibleSidebar', CollapsibleSidebarProvider) - .directive('cssTruncate', CssTruncateProvide) + .directive('cssTruncate', createCssTruncateDirective) .directive('fixedScroll', FixedScrollProvider) .directive('renderComplete', createRenderCompleteDirective) .directive('discoverFieldSearch', createFieldSearchDirective) diff --git a/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts b/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts index 9a0b0731b6b111..d1e1dafe7c8783 100644 --- a/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts +++ b/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts @@ -47,10 +47,6 @@ export function setServices(newServices: any) { services = newServices; } -// import directives that -import 'ui/directives/css_truncate'; -import 'ui/directives/field_name'; - // EXPORT legacy static dependencies, should be migrated when available in a new version; export { angular }; export { wrapInI18nContext } from 'ui/i18n'; @@ -90,7 +86,6 @@ export { } from '../../../../../plugins/data/public'; export { ElasticSearchHit } from './np_ready/doc_views/doc_views_types'; export { registerTimefilterWithGlobalStateFactory } from 'ui/timefilter/setup_router'; -export { FieldName } from 'ui/directives/field_name/field_name'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; // @ts-ignore export { buildPointSeriesData } from 'ui/agg_response/point_series/point_series'; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_index.scss b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_index.scss index c65243d99c8f49..2bfc74ffa02790 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_index.scss +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_index.scss @@ -1,2 +1,3 @@ @import 'no_results'; -@import 'histogram'; \ No newline at end of file +@import 'histogram'; +@import './collapsible_sidebar/index'; diff --git a/src/legacy/ui/public/collapsible_sidebar/_collapsible_sidebar.scss b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_collapsible_sidebar.scss similarity index 100% rename from src/legacy/ui/public/collapsible_sidebar/_collapsible_sidebar.scss rename to src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_collapsible_sidebar.scss diff --git a/src/legacy/ui/public/styles/_legacy/_depth.scss b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_depth.scss similarity index 100% rename from src/legacy/ui/public/styles/_legacy/_depth.scss rename to src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_depth.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_index.scss b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_index.scss new file mode 100644 index 00000000000000..1409920d11aa7f --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_index.scss @@ -0,0 +1,2 @@ +@import 'depth'; +@import 'collapsible_sidebar'; diff --git a/src/legacy/ui/public/collapsible_sidebar/collapsible_sidebar.js b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar.ts similarity index 91% rename from src/legacy/ui/public/collapsible_sidebar/collapsible_sidebar.js rename to src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar.ts index 98b8f310bb82f0..5b6de7f16d4446 100644 --- a/src/legacy/ui/public/collapsible_sidebar/collapsible_sidebar.js +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar.ts @@ -19,7 +19,11 @@ import _ from 'lodash'; import $ from 'jquery'; -import { uiModules } from '../modules'; +import { IScope } from 'angular'; + +interface LazyScope extends IScope { + [key: string]: any; +} export function CollapsibleSidebarProvider() { // simply a list of all of all of angulars .col-md-* classes except 12 @@ -29,7 +33,7 @@ export function CollapsibleSidebarProvider() { return { restrict: 'C', - link: function($scope, $elem) { + link: ($scope: LazyScope, $elem: any) => { let isCollapsed = false; const $collapser = $( `