diff --git a/package.json b/package.json index 5eba8a9265d70..677e817cf11c9 100644 --- a/package.json +++ b/package.json @@ -193,7 +193,6 @@ "archiver": "^5.2.0", "axios": "^0.21.1", "base64-js": "^1.3.1", - "bluebird": "3.5.5", "brace": "0.11.1", "broadcast-channel": "^4.2.0", "chalk": "^4.1.0", @@ -494,7 +493,6 @@ "@types/archiver": "^5.1.0", "@types/babel__core": "^7.1.16", "@types/base64-js": "^1.2.5", - "@types/bluebird": "^3.1.1", "@types/chance": "^1.0.0", "@types/chroma-js": "^1.4.2", "@types/chromedriver": "^81.0.0", diff --git a/packages/kbn-es-archiver/BUILD.bazel b/packages/kbn-es-archiver/BUILD.bazel index 90c63f82b72fa..2dc311ed74406 100644 --- a/packages/kbn-es-archiver/BUILD.bazel +++ b/packages/kbn-es-archiver/BUILD.bazel @@ -34,7 +34,6 @@ RUNTIME_DEPS = [ "//packages/kbn-utils", "@npm//@elastic/elasticsearch", "@npm//aggregate-error", - "@npm//bluebird", "@npm//chance", "@npm//globby", "@npm//json-stable-stringify", @@ -51,7 +50,6 @@ TYPES_DEPS = [ "@npm//aggregate-error", "@npm//globby", "@npm//zlib", - "@npm//@types/bluebird", "@npm//@types/chance", "@npm//@types/jest", "@npm//@types/json-stable-stringify", diff --git a/packages/kbn-es-archiver/src/actions/rebuild_all.ts b/packages/kbn-es-archiver/src/actions/rebuild_all.ts index f286f9719bdf1..360fdb438f2db 100644 --- a/packages/kbn-es-archiver/src/actions/rebuild_all.ts +++ b/packages/kbn-es-archiver/src/actions/rebuild_all.ts @@ -7,9 +7,9 @@ */ import { resolve, relative } from 'path'; -import { stat, Stats, rename, createReadStream, createWriteStream } from 'fs'; +import { Stats, createReadStream, createWriteStream } from 'fs'; +import { stat, rename } from 'fs/promises'; import { Readable, Writable } from 'stream'; -import { fromNode } from 'bluebird'; import { ToolingLog, REPO_ROOT } from '@kbn/dev-utils'; import { createPromiseFromStreams } from '@kbn/utils'; import { @@ -21,7 +21,7 @@ import { } from '../lib'; async function isDirectory(path: string): Promise { - const stats: Stats = await fromNode((cb) => stat(path, cb)); + const stats: Stats = await stat(path); return stats.isDirectory(); } @@ -50,7 +50,7 @@ export async function rebuildAllAction({ dataDir, log }: { dataDir: string; log: createWriteStream(tempFile), ] as [Readable, ...Writable[]]); - await fromNode((cb) => rename(tempFile, childPath, cb)); + await rename(tempFile, childPath); log.info('[%s] Rebuilt %j', archiveName, childName); } } diff --git a/packages/kbn-es-archiver/src/lib/directory.ts b/packages/kbn-es-archiver/src/lib/directory.ts index f82e59a0ed252..2ff5b7e704edf 100644 --- a/packages/kbn-es-archiver/src/lib/directory.ts +++ b/packages/kbn-es-archiver/src/lib/directory.ts @@ -6,10 +6,9 @@ * Side Public License, v 1. */ -import { readdir } from 'fs'; -import { fromNode } from 'bluebird'; +import { readdir } from 'fs/promises'; export async function readDirectory(path: string) { - const allNames = await fromNode((cb) => readdir(path, cb)); + const allNames = await readdir(path); return allNames.filter((name) => !name.startsWith('.')); } diff --git a/packages/kbn-test/src/functional_test_runner/integration_tests/__fixtures__/failure_hooks/config.js b/packages/kbn-test/src/functional_test_runner/integration_tests/__fixtures__/failure_hooks/config.js index 0b9cfd88b4cbb..1375e5a3df2fd 100644 --- a/packages/kbn-test/src/functional_test_runner/integration_tests/__fixtures__/failure_hooks/config.js +++ b/packages/kbn-test/src/functional_test_runner/integration_tests/__fixtures__/failure_hooks/config.js @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; export default function () { return { @@ -22,13 +22,13 @@ export default function () { lifecycle.testFailure.add(async (err, test) => { log.info('testFailure %s %s', err.message, test.fullTitle()); - await delay(10); + await setTimeoutAsync(10); log.info('testFailureAfterDelay %s %s', err.message, test.fullTitle()); }); lifecycle.testHookFailure.add(async (err, test) => { log.info('testHookFailure %s %s', err.message, test.fullTitle()); - await delay(10); + await setTimeoutAsync(10); log.info('testHookFailureAfterDelay %s %s', err.message, test.fullTitle()); }); }, diff --git a/packages/kbn-test/src/jest/setup/polyfills.js b/packages/kbn-test/src/jest/setup/polyfills.js index 48b597d280b4a..ebe6178dbdd91 100644 --- a/packages/kbn-test/src/jest/setup/polyfills.js +++ b/packages/kbn-test/src/jest/setup/polyfills.js @@ -6,13 +6,6 @@ * Side Public License, v 1. */ -// bluebird < v3.3.5 does not work with MutationObserver polyfill -// when MutationObserver exists, bluebird avoids using node's builtin async schedulers -const bluebird = require('bluebird'); -bluebird.Promise.setScheduler(function (fn) { - global.setImmediate.call(global, fn); -}); - const MutationObserver = require('mutation-observer'); Object.defineProperty(window, 'MutationObserver', { value: MutationObserver }); diff --git a/packages/kbn-test/src/mocha/junit_report_generation.test.js b/packages/kbn-test/src/mocha/junit_report_generation.test.js index e4e4499f556fd..c19550349fd85 100644 --- a/packages/kbn-test/src/mocha/junit_report_generation.test.js +++ b/packages/kbn-test/src/mocha/junit_report_generation.test.js @@ -7,9 +7,9 @@ */ import { resolve } from 'path'; -import { readFileSync } from 'fs'; +import { readFile } from 'fs/promises'; +import { promisify } from 'util'; -import { fromNode as fcb } from 'bluebird'; import { parseString } from 'xml2js'; import del from 'del'; import Mocha from 'mocha'; @@ -22,6 +22,8 @@ const DURATION_REGEX = /^\d+\.\d{3}$/; const ISO_DATE_SEC_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/; const XML_PATH = getUniqueJunitReportPath(PROJECT_DIR, 'test'); +const parseStringAsync = promisify(parseString); + describe('dev/mocha/junit report generation', () => { afterEach(() => { del.sync(resolve(PROJECT_DIR, 'target')); @@ -39,7 +41,7 @@ describe('dev/mocha/junit report generation', () => { mocha.addFile(resolve(PROJECT_DIR, 'test.js')); await new Promise((resolve) => mocha.run(resolve)); - const report = await fcb((cb) => parseString(readFileSync(XML_PATH), cb)); + const report = await parseStringAsync(await readFile(XML_PATH)); // test case results are wrapped in expect(report).toEqual({ diff --git a/packages/kbn-utils/src/streams/map_stream.test.ts b/packages/kbn-utils/src/streams/map_stream.test.ts index 2c3df67fdf35c..94c01d04f7dc9 100644 --- a/packages/kbn-utils/src/streams/map_stream.test.ts +++ b/packages/kbn-utils/src/streams/map_stream.test.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { createPromiseFromStreams } from './promise_from_streams'; import { createListStream } from './list_stream'; @@ -39,7 +39,7 @@ describe('createMapStream()', () => { const result = await createPromiseFromStreams([ createListStream([1, 2, 3]), createMapStream(async (n: number, i: number) => { - await delay(n); + await setTimeoutAsync(n); return n * i; }), createConcatStream([]), diff --git a/src/dev/notice/bundled_notices.js b/src/dev/notice/bundled_notices.js index 7ab2a5b3f03fe..00b044e9053f7 100644 --- a/src/dev/notice/bundled_notices.js +++ b/src/dev/notice/bundled_notices.js @@ -7,18 +7,20 @@ */ import { resolve } from 'path'; -import { readFile } from 'fs'; +import { readFile } from 'fs/promises'; +import { promisify } from 'util'; -import { fromNode as fcb } from 'bluebird'; import glob from 'glob'; +const globAsync = promisify(glob); + export async function getBundledNotices(packageDirectory) { const pattern = resolve(packageDirectory, '*{LICENSE,NOTICE}*'); - const paths = await fcb((cb) => glob(pattern, cb)); + const paths = await globAsync(pattern); return Promise.all( paths.map(async (path) => ({ path, - text: await fcb((cb) => readFile(path, 'utf8', cb)), + text: await readFile(path, 'utf8'), })) ); } diff --git a/src/dev/precommit_hook/get_files_for_commit.js b/src/dev/precommit_hook/get_files_for_commit.js index 44c8c9d5e6bc0..366575ad15ae7 100644 --- a/src/dev/precommit_hook/get_files_for_commit.js +++ b/src/dev/precommit_hook/get_files_for_commit.js @@ -6,8 +6,7 @@ * Side Public License, v 1. */ -import SimpleGit from 'simple-git'; -import { fromNode as fcb } from 'bluebird'; +import SimpleGit from 'simple-git/promise'; import { REPO_ROOT } from '@kbn/utils'; import { File } from '../file'; @@ -22,7 +21,7 @@ import { File } from '../file'; export async function getFilesForCommit(gitRef) { const simpleGit = new SimpleGit(REPO_ROOT); const gitRefForDiff = gitRef ? gitRef : '--cached'; - const output = await fcb((cb) => simpleGit.diff(['--name-status', gitRefForDiff], cb)); + const output = await simpleGit.diff(['--name-status', gitRefForDiff]); return ( output diff --git a/src/plugins/saved_objects/public/saved_object/saved_object.test.ts b/src/plugins/saved_objects/public/saved_object/saved_object.test.ts index bd8d69d6b693e..01fc75df459bc 100644 --- a/src/plugins/saved_objects/public/saved_object/saved_object.test.ts +++ b/src/plugins/saved_objects/public/saved_object/saved_object.test.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import Bluebird from 'bluebird'; import { createSavedObjectClass } from './saved_object'; import { SavedObject, @@ -55,16 +54,16 @@ describe('Saved Object', () => { */ function stubESResponse(mockDocResponse: SimpleSavedObject) { // Stub out search for duplicate title: - savedObjectsClientStub.get = jest.fn().mockReturnValue(Bluebird.resolve(mockDocResponse)); - savedObjectsClientStub.update = jest.fn().mockReturnValue(Bluebird.resolve(mockDocResponse)); + savedObjectsClientStub.get = jest.fn().mockReturnValue(Promise.resolve(mockDocResponse)); + savedObjectsClientStub.update = jest.fn().mockReturnValue(Promise.resolve(mockDocResponse)); savedObjectsClientStub.find = jest .fn() - .mockReturnValue(Bluebird.resolve({ savedObjects: [], total: 0 })); + .mockReturnValue(Promise.resolve({ savedObjects: [], total: 0 })); savedObjectsClientStub.bulkGet = jest .fn() - .mockReturnValue(Bluebird.resolve({ savedObjects: [mockDocResponse] })); + .mockReturnValue(Promise.resolve({ savedObjects: [mockDocResponse] })); } function stubSavedObjectsClientCreate( @@ -73,7 +72,7 @@ describe('Saved Object', () => { ) { savedObjectsClientStub.create = jest .fn() - .mockReturnValue(resolve ? Bluebird.resolve(resp) : Bluebird.reject(resp)); + .mockReturnValue(resolve ? Promise.resolve(resp) : Promise.reject(resp)); } /** @@ -262,7 +261,7 @@ describe('Saved Object', () => { return createInitializedSavedObject({ type: 'dashboard', id: myId }).then((savedObject) => { savedObjectsClientStub.create = jest.fn().mockImplementation(() => { expect(savedObject.id).toBe(myId); - return Bluebird.resolve({ id: myId }); + return Promise.resolve({ id: myId }); }); savedObject.copyOnSave = false; @@ -296,7 +295,7 @@ describe('Saved Object', () => { return createInitializedSavedObject({ type: 'dashboard', id }).then((savedObject) => { savedObjectsClientStub.create = jest.fn().mockImplementation(() => { expect(savedObject.isSaving).toBe(true); - return Bluebird.resolve({ + return Promise.resolve({ type: 'dashboard', id, _version: 'foo', @@ -315,7 +314,7 @@ describe('Saved Object', () => { return createInitializedSavedObject({ type: 'dashboard' }).then((savedObject) => { savedObjectsClientStub.create = jest.fn().mockImplementation(() => { expect(savedObject.isSaving).toBe(true); - return Bluebird.reject(''); + return Promise.reject(''); }); expect(savedObject.isSaving).toBe(false); @@ -745,7 +744,7 @@ describe('Saved Object', () => { }, }); savedObject.searchSource!.setField('index', indexPattern); - return Bluebird.resolve(indexPattern); + return Promise.resolve(indexPattern); }); expect(!!savedObject.searchSource!.getField('index')).toBe(false); diff --git a/src/plugins/vis_types/timelion/server/handlers/chain_runner.js b/src/plugins/vis_types/timelion/server/handlers/chain_runner.js index 3710d015f3f69..fac1a68acc907 100644 --- a/src/plugins/vis_types/timelion/server/handlers/chain_runner.js +++ b/src/plugins/vis_types/timelion/server/handlers/chain_runner.js @@ -7,7 +7,6 @@ */ import _ from 'lodash'; -import Bluebird from 'bluebird'; import { i18n } from '@kbn/i18n'; import moment from 'moment'; @@ -42,7 +41,7 @@ export default function chainRunner(tlConfig) { function resolveArgument(item) { if (Array.isArray(item)) { - return Bluebird.all(_.map(item, resolveArgument)); + return Promise.all(_.map(item, resolveArgument)); } if (_.isObject(item)) { @@ -51,7 +50,7 @@ export default function chainRunner(tlConfig) { const itemFunctionDef = tlConfig.getFunction(item.function); if (itemFunctionDef.cacheKey && queryCache[itemFunctionDef.cacheKey(item)]) { stats.queryCount++; - return Bluebird.resolve(_.cloneDeep(queryCache[itemFunctionDef.cacheKey(item)])); + return Promise.resolve(_.cloneDeep(queryCache[itemFunctionDef.cacheKey(item)])); } return invoke(item.function, item.arguments); } @@ -94,7 +93,7 @@ export default function chainRunner(tlConfig) { args = _.map(args, resolveArgument); - return Bluebird.all(args).then(function (args) { + return Promise.all(args).then(function (args) { args.byName = indexArguments(functionDef, args); return functionDef.fn(args, tlConfig); }); @@ -128,7 +127,7 @@ export default function chainRunner(tlConfig) { return args; }); }); - return Bluebird.all(seriesList).then(function (args) { + return Promise.all(seriesList).then(function (args) { const list = _.chain(args).map('list').flatten().value(); const seriesList = _.merge.apply(this, _.flatten([{}, args])); seriesList.list = list; @@ -158,22 +157,22 @@ export default function chainRunner(tlConfig) { }) .value(); - return Bluebird.settle(promises).then(function (resolvedDatasources) { + return Promise.allSettled(promises).then(function (resolvedDatasources) { stats.queryTime = new Date().getTime(); _.each(queries, function (query, i) { const functionDef = tlConfig.getFunction(query.function); const resolvedDatasource = resolvedDatasources[i]; - if (resolvedDatasource.isRejected()) { - if (resolvedDatasource.reason().isBoom) { - throw resolvedDatasource.reason(); + if (resolvedDatasource.status === 'rejected') { + if (resolvedDatasource.reason.isBoom) { + throw resolvedDatasource.reason; } else { - throwWithCell(query.cell, resolvedDatasource.reason()); + throwWithCell(query.cell, resolvedDatasource.reason); } } - queryCache[functionDef.cacheKey(query)] = resolvedDatasource.value(); + queryCache[functionDef.cacheKey(query)] = resolvedDatasource.value; }); stats.cacheCount = _.keys(queryCache).length; diff --git a/src/plugins/vis_types/timelion/server/lib/alter.js b/src/plugins/vis_types/timelion/server/lib/alter.js index 2e234f3405c21..47a57f213cdbb 100644 --- a/src/plugins/vis_types/timelion/server/lib/alter.js +++ b/src/plugins/vis_types/timelion/server/lib/alter.js @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import Bluebird from 'bluebird'; import _ from 'lodash'; /* @param {Array} args @@ -18,7 +17,7 @@ import _ from 'lodash'; export default function alter(args, fn) { // In theory none of the args should ever be promises. This is probably a waste. - return Bluebird.all(args) + return Promise.all(args) .then(function (args) { const seriesList = args.shift(); diff --git a/src/plugins/vis_types/timelion/server/routes/run.ts b/src/plugins/vis_types/timelion/server/routes/run.ts index b8c0ce4ea6599..d615302253a1d 100644 --- a/src/plugins/vis_types/timelion/server/routes/run.ts +++ b/src/plugins/vis_types/timelion/server/routes/run.ts @@ -8,7 +8,6 @@ import { IRouter, Logger, CoreSetup } from 'kibana/server'; import { schema } from '@kbn/config-schema'; -import Bluebird from 'bluebird'; import _ from 'lodash'; // @ts-ignore import chainRunnerFn from '../handlers/chain_runner.js'; @@ -96,7 +95,7 @@ export function runRoute( }); try { const chainRunner = chainRunnerFn(tlConfig); - const sheet = await Bluebird.all(chainRunner.processRequest(request.body)); + const sheet = await Promise.all(await chainRunner.processRequest(request.body)); return response.ok({ body: { sheet, diff --git a/src/plugins/vis_types/timelion/server/series_functions/quandl.js b/src/plugins/vis_types/timelion/server/series_functions/quandl.js index 7e3a0f6de9aba..3c209879d7a4c 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/quandl.js +++ b/src/plugins/vis_types/timelion/server/series_functions/quandl.js @@ -10,7 +10,6 @@ import { i18n } from '@kbn/i18n'; import _ from 'lodash'; import fetch from 'node-fetch'; import moment from 'moment'; -fetch.Promise = require('bluebird'); import Datasource from '../lib/classes/datasource'; diff --git a/src/plugins/vis_types/timelion/server/series_functions/static.js b/src/plugins/vis_types/timelion/server/series_functions/static.js index b5e8dd6df6682..afc1bd5afbbb8 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/static.js +++ b/src/plugins/vis_types/timelion/server/series_functions/static.js @@ -9,7 +9,6 @@ import { i18n } from '@kbn/i18n'; import _ from 'lodash'; import Datasource from '../lib/classes/datasource'; -import Bluebird from 'bluebird'; export default new Datasource('static', { aliases: ['value'], @@ -51,7 +50,7 @@ export default new Datasource('static', { }); } - return Bluebird.resolve({ + return Promise.resolve({ type: 'seriesList', list: [ { diff --git a/src/plugins/vis_types/timelion/server/series_functions/worldbank_indicators.js b/src/plugins/vis_types/timelion/server/series_functions/worldbank_indicators.js index ba28a82345522..c2eb07890a102 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/worldbank_indicators.js +++ b/src/plugins/vis_types/timelion/server/series_functions/worldbank_indicators.js @@ -9,7 +9,6 @@ import { i18n } from '@kbn/i18n'; import _ from 'lodash'; import worldbank from './worldbank.js'; -import Bluebird from 'bluebird'; import Datasource from '../lib/classes/datasource'; export default new Datasource('worldbank_indicators', { @@ -61,9 +60,11 @@ export default new Datasource('worldbank_indicators', { return worldbank.timelionFn(wbArgs, tlConfig); }); - return Bluebird.map(seriesLists, function (seriesList) { - return seriesList.list[0]; - }).then(function (list) { + return Promise.all( + seriesLists.map(function (seriesList) { + return seriesList.list[0]; + }) + ).then(function (list) { return { type: 'seriesList', list: list, diff --git a/src/plugins/vis_types/timelion/server/series_functions/yaxis.test.js b/src/plugins/vis_types/timelion/server/series_functions/yaxis.test.js index 6d627832544de..d68aa7ac70117 100644 --- a/src/plugins/vis_types/timelion/server/series_functions/yaxis.test.js +++ b/src/plugins/vis_types/timelion/server/series_functions/yaxis.test.js @@ -7,7 +7,6 @@ */ import fn from './yaxis'; -import Bluebird from 'bluebird'; const expect = require('chai').expect; import invoke from './helpers/invoke_series_fn.js'; @@ -25,7 +24,7 @@ describe('yaxis.js', () => { }); it('puts odd numbers of the left, even on the right, by default', () => { - return Bluebird.all([ + return Promise.all([ invoke(fn, [seriesList, 1]).then((r) => { expect(r.output.list[0]._global.yaxes[0].position).to.equal('left'); }), @@ -39,7 +38,7 @@ describe('yaxis.js', () => { }); it('it lets you override default positions', () => { - return Bluebird.all([ + return Promise.all([ invoke(fn, [seriesList, 1, null, null, 'right']).then((r) => { expect(r.output.list[0]._global.yaxes[0].position).to.equal('right'); }), @@ -50,7 +49,7 @@ describe('yaxis.js', () => { }); it('sets the minimum (default: no min)', () => { - return Bluebird.all([ + return Promise.all([ invoke(fn, [seriesList, 1, null]).then((r) => { expect(r.output.list[0]._global.yaxes[0].min).to.equal(null); }), @@ -61,7 +60,7 @@ describe('yaxis.js', () => { }); it('sets the max (default: no max)', () => { - return Bluebird.all([ + return Promise.all([ invoke(fn, [seriesList, 1, null]).then((r) => { expect(r.output.list[0]._global.yaxes[0].max).to.equal(undefined); }), @@ -72,7 +71,7 @@ describe('yaxis.js', () => { }); it('sets the units (default: no unit', () => { - return Bluebird.all([ + return Promise.all([ invoke(fn, [seriesList, 1, null, null, null, null, null, null]).then((r) => { expect(r.output.list[0]._global.yaxes[0].units).to.equal(undefined); }), diff --git a/test/api_integration/apis/kql_telemetry/kql_telemetry.ts b/test/api_integration/apis/kql_telemetry/kql_telemetry.ts index 4825b454bc42f..310b99a5fb781 100644 --- a/test/api_integration/apis/kql_telemetry/kql_telemetry.ts +++ b/test/api_integration/apis/kql_telemetry/kql_telemetry.ts @@ -7,7 +7,6 @@ */ import expect from '@kbn/expect'; -import Bluebird from 'bluebird'; import { get } from 'lodash'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -89,7 +88,7 @@ export default function ({ getService }: FtrProviderContext) { }); it('should only accept literal boolean values for the opt_in POST body param', function () { - return Bluebird.all([ + return Promise.all([ supertest .post('/api/kibana/kql_opt_in_stats') .set('content-type', 'application/json') diff --git a/test/functional/page_objects/common_page.ts b/test/functional/page_objects/common_page.ts index 3955e457b5ffc..0150daec3afb5 100644 --- a/test/functional/page_objects/common_page.ts +++ b/test/functional/page_objects/common_page.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import expect from '@kbn/expect'; // @ts-ignore import fetch from 'node-fetch'; @@ -214,7 +214,7 @@ export class CommonPageObject extends FtrService { async sleep(sleepMilliseconds: number) { this.log.debug(`... sleep(${sleepMilliseconds}) start`); - await delay(sleepMilliseconds); + await setTimeoutAsync(sleepMilliseconds); this.log.debug(`... sleep(${sleepMilliseconds}) end`); } diff --git a/test/functional/page_objects/login_page.ts b/test/functional/page_objects/login_page.ts index 5318a2b2d0c15..74e85e60d1a69 100644 --- a/test/functional/page_objects/login_page.ts +++ b/test/functional/page_objects/login_page.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { FtrService } from '../ftr_provider_context'; export class LoginPageObject extends FtrService { @@ -40,7 +40,7 @@ export class LoginPageObject extends FtrService { async sleep(sleepMilliseconds: number) { this.log.debug(`... sleep(${sleepMilliseconds}) start`); - await delay(sleepMilliseconds); + await setTimeoutAsync(sleepMilliseconds); this.log.debug(`... sleep(${sleepMilliseconds}) end`); } diff --git a/test/functional/page_objects/management/saved_objects_page.ts b/test/functional/page_objects/management/saved_objects_page.ts index 21af7aa477abd..87d5537d53ca3 100644 --- a/test/functional/page_objects/management/saved_objects_page.ts +++ b/test/functional/page_objects/management/saved_objects_page.ts @@ -7,7 +7,6 @@ */ import { keyBy } from 'lodash'; -import { map as mapAsync } from 'bluebird'; import { FtrService } from '../../ftr_provider_context'; export class SavedObjectsPageObject extends FtrService { @@ -201,51 +200,55 @@ export class SavedObjectsPageObject extends FtrService { async getElementsInTable() { const rows = await this.testSubjects.findAll('~savedObjectsTableRow'); - return mapAsync(rows, async (row) => { - const checkbox = await row.findByCssSelector('[data-test-subj*="checkboxSelectRow"]'); - // return the object type aria-label="index patterns" - const objectType = await row.findByTestSubject('objectType'); - const titleElement = await row.findByTestSubject('savedObjectsTableRowTitle'); - // not all rows have inspect button - Advanced Settings objects don't - // Advanced Settings has 2 actions, - // data-test-subj="savedObjectsTableAction-relationships" - // data-test-subj="savedObjectsTableAction-copy_saved_objects_to_space" - // Some other objects have the ... - // data-test-subj="euiCollapsedItemActionsButton" - // Maybe some objects still have the inspect element visible? - // !!! Also note that since we don't have spaces on OSS, the actions for the same object can be different depending on OSS or not - let menuElement = null; - let inspectElement = null; - let relationshipsElement = null; - let copySaveObjectsElement = null; - const actions = await row.findByClassName('euiTableRowCell--hasActions'); - // getting the innerHTML and checking if it 'includes' a string is faster than a timeout looking for each element - const actionsHTML = await actions.getAttribute('innerHTML'); - if (actionsHTML.includes('euiCollapsedItemActionsButton')) { - menuElement = await row.findByTestSubject('euiCollapsedItemActionsButton'); - } - if (actionsHTML.includes('savedObjectsTableAction-inspect')) { - inspectElement = await row.findByTestSubject('savedObjectsTableAction-inspect'); - } - if (actionsHTML.includes('savedObjectsTableAction-relationships')) { - relationshipsElement = await row.findByTestSubject('savedObjectsTableAction-relationships'); - } - if (actionsHTML.includes('savedObjectsTableAction-copy_saved_objects_to_space')) { - copySaveObjectsElement = await row.findByTestSubject( - 'savedObjectsTableAction-copy_saved_objects_to_space' - ); - } - return { - checkbox, - objectType: await objectType.getAttribute('aria-label'), - titleElement, - title: await titleElement.getVisibleText(), - menuElement, - inspectElement, - relationshipsElement, - copySaveObjectsElement, - }; - }); + return await Promise.all( + rows.map(async (row) => { + const checkbox = await row.findByCssSelector('[data-test-subj*="checkboxSelectRow"]'); + // return the object type aria-label="index patterns" + const objectType = await row.findByTestSubject('objectType'); + const titleElement = await row.findByTestSubject('savedObjectsTableRowTitle'); + // not all rows have inspect button - Advanced Settings objects don't + // Advanced Settings has 2 actions, + // data-test-subj="savedObjectsTableAction-relationships" + // data-test-subj="savedObjectsTableAction-copy_saved_objects_to_space" + // Some other objects have the ... + // data-test-subj="euiCollapsedItemActionsButton" + // Maybe some objects still have the inspect element visible? + // !!! Also note that since we don't have spaces on OSS, the actions for the same object can be different depending on OSS or not + let menuElement = null; + let inspectElement = null; + let relationshipsElement = null; + let copySaveObjectsElement = null; + const actions = await row.findByClassName('euiTableRowCell--hasActions'); + // getting the innerHTML and checking if it 'includes' a string is faster than a timeout looking for each element + const actionsHTML = await actions.getAttribute('innerHTML'); + if (actionsHTML.includes('euiCollapsedItemActionsButton')) { + menuElement = await row.findByTestSubject('euiCollapsedItemActionsButton'); + } + if (actionsHTML.includes('savedObjectsTableAction-inspect')) { + inspectElement = await row.findByTestSubject('savedObjectsTableAction-inspect'); + } + if (actionsHTML.includes('savedObjectsTableAction-relationships')) { + relationshipsElement = await row.findByTestSubject( + 'savedObjectsTableAction-relationships' + ); + } + if (actionsHTML.includes('savedObjectsTableAction-copy_saved_objects_to_space')) { + copySaveObjectsElement = await row.findByTestSubject( + 'savedObjectsTableAction-copy_saved_objects_to_space' + ); + } + return { + checkbox, + objectType: await objectType.getAttribute('aria-label'), + titleElement, + title: await titleElement.getVisibleText(), + menuElement, + inspectElement, + relationshipsElement, + copySaveObjectsElement, + }; + }) + ); } async getRowTitles() { @@ -259,35 +262,39 @@ export class SavedObjectsPageObject extends FtrService { async getRelationshipFlyout() { const rows = await this.testSubjects.findAll('relationshipsTableRow'); - return mapAsync(rows, async (row) => { - const objectType = await row.findByTestSubject('relationshipsObjectType'); - const relationship = await row.findByTestSubject('directRelationship'); - const titleElement = await row.findByTestSubject('relationshipsTitle'); - const inspectElement = await row.findByTestSubject('relationshipsTableAction-inspect'); - return { - objectType: await objectType.getAttribute('aria-label'), - relationship: await relationship.getVisibleText(), - titleElement, - title: await titleElement.getVisibleText(), - inspectElement, - }; - }); + return await Promise.all( + rows.map(async (row) => { + const objectType = await row.findByTestSubject('relationshipsObjectType'); + const relationship = await row.findByTestSubject('directRelationship'); + const titleElement = await row.findByTestSubject('relationshipsTitle'); + const inspectElement = await row.findByTestSubject('relationshipsTableAction-inspect'); + return { + objectType: await objectType.getAttribute('aria-label'), + relationship: await relationship.getVisibleText(), + titleElement, + title: await titleElement.getVisibleText(), + inspectElement, + }; + }) + ); } async getInvalidRelations() { const rows = await this.testSubjects.findAll('invalidRelationshipsTableRow'); - return mapAsync(rows, async (row) => { - const objectType = await row.findByTestSubject('relationshipsObjectType'); - const objectId = await row.findByTestSubject('relationshipsObjectId'); - const relationship = await row.findByTestSubject('directRelationship'); - const error = await row.findByTestSubject('relationshipsError'); - return { - type: await objectType.getVisibleText(), - id: await objectId.getVisibleText(), - relationship: await relationship.getVisibleText(), - error: await error.getVisibleText(), - }; - }); + return await Promise.all( + rows.map(async (row) => { + const objectType = await row.findByTestSubject('relationshipsObjectType'); + const objectId = await row.findByTestSubject('relationshipsObjectId'); + const relationship = await row.findByTestSubject('directRelationship'); + const error = await row.findByTestSubject('relationshipsError'); + return { + type: await objectType.getVisibleText(), + id: await objectId.getVisibleText(), + relationship: await relationship.getVisibleText(), + error: await error.getVisibleText(), + }; + }) + ); } async getTableSummary() { diff --git a/test/functional/page_objects/settings_page.ts b/test/functional/page_objects/settings_page.ts index d3443f9cf4925..36040ad6aaa6c 100644 --- a/test/functional/page_objects/settings_page.ts +++ b/test/functional/page_objects/settings_page.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { map as mapAsync } from 'bluebird'; import expect from '@kbn/expect'; import { FtrService } from '../ftr_provider_context'; @@ -234,23 +233,29 @@ export class SettingsPageObject extends FtrService { async getFieldNames() { const fieldNameCells = await this.testSubjects.findAll('editIndexPattern > indexedFieldName'); - return await mapAsync(fieldNameCells, async (cell) => { - return (await cell.getVisibleText()).trim(); - }); + return await Promise.all( + fieldNameCells.map(async (cell) => { + return (await cell.getVisibleText()).trim(); + }) + ); } async getFieldTypes() { const fieldNameCells = await this.testSubjects.findAll('editIndexPattern > indexedFieldType'); - return await mapAsync(fieldNameCells, async (cell) => { - return (await cell.getVisibleText()).trim(); - }); + return await Promise.all( + fieldNameCells.map(async (cell) => { + return (await cell.getVisibleText()).trim(); + }) + ); } async getScriptedFieldLangs() { const fieldNameCells = await this.testSubjects.findAll('editIndexPattern > scriptedFieldLang'); - return await mapAsync(fieldNameCells, async (cell) => { - return (await cell.getVisibleText()).trim(); - }); + return await Promise.all( + fieldNameCells.map(async (cell) => { + return (await cell.getVisibleText()).trim(); + }) + ); } async setFieldTypeFilter(type: string) { @@ -327,9 +332,11 @@ export class SettingsPageObject extends FtrService { async getAllIndexPatternNames() { const indexPatterns = await this.getIndexPatternList(); - return await mapAsync(indexPatterns, async (index) => { - return await index.getVisibleText(); - }); + return await Promise.all( + indexPatterns.map(async (index) => { + return await index.getVisibleText(); + }) + ); } async isIndexPatternListEmpty() { @@ -565,9 +572,11 @@ export class SettingsPageObject extends FtrService { const table = await this.find.byClassName('euiTable'); await this.retry.waitFor('field filter to be added', async () => { const tableCells = await table.findAllByCssSelector('td'); - const fieldNames = await mapAsync(tableCells, async (cell) => { - return (await cell.getVisibleText()).trim(); - }); + const fieldNames = await Promise.all( + tableCells.map(async (cell) => { + return (await cell.getVisibleText()).trim(); + }) + ); return fieldNames.includes(name); }); } diff --git a/test/functional/services/common/browser.ts b/test/functional/services/common/browser.ts index 73d92f8ff722b..7581c17a58ebf 100644 --- a/test/functional/services/common/browser.ts +++ b/test/functional/services/common/browser.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { cloneDeepWith } from 'lodash'; import { Key, Origin, WebDriver } from 'selenium-webdriver'; // @ts-ignore internal modules are not typed @@ -303,7 +303,7 @@ class BrowserService extends FtrService { to ); // wait for 150ms to make sure the script has run - await delay(150); + await setTimeoutAsync(150); } /** diff --git a/test/functional/services/common/test_subjects.ts b/test/functional/services/common/test_subjects.ts index 3f47c6155f175..09c54af7b8811 100644 --- a/test/functional/services/common/test_subjects.ts +++ b/test/functional/services/common/test_subjects.ts @@ -7,7 +7,6 @@ */ import testSubjSelector from '@kbn/test-subj-selector'; -import { map as mapAsync } from 'bluebird'; import { WebElementWrapper } from '../lib/web_element_wrapper'; import { FtrService } from '../../ftr_provider_context'; @@ -271,11 +270,11 @@ export class TestSubjects extends FtrService { private async _mapAll( selectorAll: string, - mapFn: (element: WebElementWrapper, index?: number, arrayLength?: number) => Promise + mapFn: (element: WebElementWrapper, index: number, array: WebElementWrapper[]) => Promise ): Promise { return await this.retry.try(async () => { const elements = await this.findAll(selectorAll); - return await mapAsync(elements, mapFn); + return await Promise.all(elements.map(mapFn)); }); } diff --git a/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts b/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts index 4b164402bfb70..d4fe5080bdfef 100644 --- a/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts +++ b/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { WebElement, WebDriver, By, Key } from 'selenium-webdriver'; import { PNG } from 'pngjs'; import cheerio from 'cheerio'; @@ -121,7 +121,7 @@ export class WebElementWrapper { `finding element '${this.locator.toString()}' again, ${attemptsRemaining - 1} attempts left` ); - await delay(200); + await setTimeoutAsync(200); this._webElement = await this.driver.findElement(this.locator); return await this.retryCall(fn, attemptsRemaining - 1); } @@ -240,7 +240,7 @@ export class WebElementWrapper { const value = await this.getAttribute('value'); for (let i = 0; i <= value.length; i++) { await this.pressKeys(this.Keys.BACK_SPACE); - await delay(100); + await setTimeoutAsync(100); } } else { if (this.isChromium) { @@ -279,7 +279,7 @@ export class WebElementWrapper { for (const char of value) { await this.retryCall(async function type(wrapper) { await wrapper._webElement.sendKeys(char); - await delay(100); + await setTimeoutAsync(100); }); } } else { diff --git a/test/interactive_setup_api_integration/fixtures/test_helpers.ts b/test/interactive_setup_api_integration/fixtures/test_helpers.ts index f1e72785af02d..6001f12b0a551 100644 --- a/test/interactive_setup_api_integration/fixtures/test_helpers.ts +++ b/test/interactive_setup_api_integration/fixtures/test_helpers.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import expect from '@kbn/expect'; @@ -19,7 +19,7 @@ export async function hasKibanaBooted(context: FtrProviderContext) { // Run 30 consecutive requests with 1.5s delay to check if Kibana is up and running. let kibanaHasBooted = false; for (const counter of [...Array(30).keys()]) { - await delay(1500); + await setTimeoutAsync(1500); try { expect((await supertest.get('/api/status').expect(200)).body).to.have.keys([ diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index 37f00bef953b9..5f9ff51dadf65 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -7,7 +7,7 @@ import type { TypeOf } from '@kbn/config-schema'; import type { RequestHandler, ResponseHeaders } from 'src/core/server'; -import bluebird from 'bluebird'; +import pMap from 'p-map'; import { safeDump } from 'js-yaml'; import { fullAgentPolicyToYaml } from '../../../common/services'; @@ -57,7 +57,7 @@ export const getAgentPoliciesHandler: RequestHandler< perPage, }; - await bluebird.map( + await pMap( items, (agentPolicy: GetAgentPoliciesResponseItem) => getAgentsByKuery(esClient, { diff --git a/x-pack/plugins/monitoring/server/lib/details/get_metrics.ts b/x-pack/plugins/monitoring/server/lib/details/get_metrics.ts index 83bb18169ae1e..a8de5529d8ca6 100644 --- a/x-pack/plugins/monitoring/server/lib/details/get_metrics.ts +++ b/x-pack/plugins/monitoring/server/lib/details/get_metrics.ts @@ -6,7 +6,6 @@ */ import moment from 'moment'; -import Bluebird from 'bluebird'; import { checkParam } from '../error_missing_required'; import { getSeries } from './get_series'; import { calculateTimeseriesInterval } from '../calculate_timeseries_interval'; @@ -40,25 +39,29 @@ export async function getMetrics( min = max - numOfBuckets * bucketSize * 1000; } - return Bluebird.map(metricSet, (metric: Metric) => { - // metric names match the literal metric name, but they can be supplied in groups or individually - let metricNames; + return Promise.all( + metricSet.map((metric: Metric) => { + // metric names match the literal metric name, but they can be supplied in groups or individually + let metricNames; - if (typeof metric !== 'string') { - metricNames = metric.keys; - } else { - metricNames = [metric]; - } + if (typeof metric !== 'string') { + metricNames = typeof metric.keys === 'string' ? [metric.keys] : metric.keys; + } else { + metricNames = [metric]; + } - return Bluebird.map(metricNames, (metricName) => { - return getSeries(req, indexPattern, metricName, metricOptions, filters, groupBy, { - min, - max, - bucketSize, - timezone, - }); - }); - }).then((rows) => { + return Promise.all( + metricNames.map((metricName) => { + return getSeries(req, indexPattern, metricName, metricOptions, filters, groupBy, { + min, + max, + bucketSize, + timezone, + }); + }) + ); + }) + ).then((rows) => { const data: Record = {}; metricSet.forEach((key, index) => { // keyName must match the value stored in the html template diff --git a/x-pack/plugins/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts b/x-pack/plugins/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts index 4e806c07ee660..5326976ec99ac 100644 --- a/x-pack/plugins/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts +++ b/x-pack/plugins/monitoring/server/lib/kibana/get_kibanas_for_clusters.ts @@ -5,7 +5,6 @@ * 2.0. */ -import Bluebird from 'bluebird'; import { chain, find } from 'lodash'; import { LegacyRequest, Cluster, Bucket } from '../../types'; import { checkParam } from '../error_missing_required'; @@ -36,182 +35,184 @@ export function getKibanasForClusters( const start = req.payload.timeRange.min; const end = req.payload.timeRange.max; - return Bluebird.map(clusters, (cluster) => { - const clusterUuid = cluster.elasticsearch?.cluster?.id ?? cluster.cluster_uuid; - const metric = KibanaClusterMetric.getMetricFields(); - const params = { - index: kbnIndexPattern, - size: 0, - ignore_unavailable: true, - body: { - query: createQuery({ - types: ['stats', 'kibana_stats'], - start, - end, - clusterUuid, - metric, - }), - aggs: { - kibana_uuids: { - terms: { - field: 'kibana_stats.kibana.uuid', - size: config.get('monitoring.ui.max_bucket_size'), - }, - aggs: { - latest_report: { - terms: { - field: 'kibana_stats.timestamp', - size: 1, - order: { - _key: 'desc', - }, - }, - aggs: { - response_time_max: { - max: { - field: 'kibana_stats.response_times.max', + return Promise.all( + clusters.map((cluster) => { + const clusterUuid = cluster.elasticsearch?.cluster?.id ?? cluster.cluster_uuid; + const metric = KibanaClusterMetric.getMetricFields(); + const params = { + index: kbnIndexPattern, + size: 0, + ignore_unavailable: true, + body: { + query: createQuery({ + types: ['stats', 'kibana_stats'], + start, + end, + clusterUuid, + metric, + }), + aggs: { + kibana_uuids: { + terms: { + field: 'kibana_stats.kibana.uuid', + size: config.get('monitoring.ui.max_bucket_size'), + }, + aggs: { + latest_report: { + terms: { + field: 'kibana_stats.timestamp', + size: 1, + order: { + _key: 'desc', }, }, - memory_rss: { - max: { - field: 'kibana_stats.process.memory.resident_set_size_in_bytes', + aggs: { + response_time_max: { + max: { + field: 'kibana_stats.response_times.max', + }, }, - }, - memory_heap_size_limit: { - max: { - field: 'kibana_stats.process.memory.heap.size_limit', + memory_rss: { + max: { + field: 'kibana_stats.process.memory.resident_set_size_in_bytes', + }, }, - }, - concurrent_connections: { - max: { - field: 'kibana_stats.concurrent_connections', + memory_heap_size_limit: { + max: { + field: 'kibana_stats.process.memory.heap.size_limit', + }, }, - }, - requests_total: { - max: { - field: 'kibana_stats.requests.total', + concurrent_connections: { + max: { + field: 'kibana_stats.concurrent_connections', + }, + }, + requests_total: { + max: { + field: 'kibana_stats.requests.total', + }, }, }, }, - }, - response_time_max_per: { - max_bucket: { - buckets_path: 'latest_report>response_time_max', + response_time_max_per: { + max_bucket: { + buckets_path: 'latest_report>response_time_max', + }, }, - }, - memory_rss_per: { - max_bucket: { - buckets_path: 'latest_report>memory_rss', + memory_rss_per: { + max_bucket: { + buckets_path: 'latest_report>memory_rss', + }, }, - }, - memory_heap_size_limit_per: { - max_bucket: { - buckets_path: 'latest_report>memory_heap_size_limit', + memory_heap_size_limit_per: { + max_bucket: { + buckets_path: 'latest_report>memory_heap_size_limit', + }, }, - }, - concurrent_connections_per: { - max_bucket: { - buckets_path: 'latest_report>concurrent_connections', + concurrent_connections_per: { + max_bucket: { + buckets_path: 'latest_report>concurrent_connections', + }, }, - }, - requests_total_per: { - max_bucket: { - buckets_path: 'latest_report>requests_total', + requests_total_per: { + max_bucket: { + buckets_path: 'latest_report>requests_total', + }, }, }, }, - }, - response_time_max: { - max_bucket: { - buckets_path: 'kibana_uuids>response_time_max_per', - }, - }, - memory_rss: { - sum_bucket: { - buckets_path: 'kibana_uuids>memory_rss_per', + response_time_max: { + max_bucket: { + buckets_path: 'kibana_uuids>response_time_max_per', + }, }, - }, - memory_heap_size_limit: { - sum_bucket: { - buckets_path: 'kibana_uuids>memory_heap_size_limit_per', + memory_rss: { + sum_bucket: { + buckets_path: 'kibana_uuids>memory_rss_per', + }, }, - }, - concurrent_connections: { - sum_bucket: { - buckets_path: 'kibana_uuids>concurrent_connections_per', + memory_heap_size_limit: { + sum_bucket: { + buckets_path: 'kibana_uuids>memory_heap_size_limit_per', + }, }, - }, - requests_total: { - sum_bucket: { - buckets_path: 'kibana_uuids>requests_total_per', + concurrent_connections: { + sum_bucket: { + buckets_path: 'kibana_uuids>concurrent_connections_per', + }, }, - }, - status: { - terms: { - field: 'kibana_stats.kibana.status', - order: { - max_timestamp: 'desc', + requests_total: { + sum_bucket: { + buckets_path: 'kibana_uuids>requests_total_per', }, }, - aggs: { - max_timestamp: { - max: { - field: 'timestamp', + status: { + terms: { + field: 'kibana_stats.kibana.status', + order: { + max_timestamp: 'desc', + }, + }, + aggs: { + max_timestamp: { + max: { + field: 'timestamp', + }, }, }, }, }, }, - }, - }; + }; - const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); - return callWithRequest(req, 'search', params).then((result) => { - const aggregations = result.aggregations ?? {}; - const kibanaUuids = aggregations.kibana_uuids?.buckets ?? []; - const statusBuckets = aggregations.status?.buckets ?? []; + const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); + return callWithRequest(req, 'search', params).then((result) => { + const aggregations = result.aggregations ?? {}; + const kibanaUuids = aggregations.kibana_uuids?.buckets ?? []; + const statusBuckets = aggregations.status?.buckets ?? []; - // everything is initialized such that it won't impact any rollup - let status = null; - let requestsTotal = 0; - let connections = 0; - let responseTime = 0; - let memorySize = 0; - let memoryLimit = 0; + // everything is initialized such that it won't impact any rollup + let status = null; + let requestsTotal = 0; + let connections = 0; + let responseTime = 0; + let memorySize = 0; + let memoryLimit = 0; - // if the cluster has kibana instances at all - if (kibanaUuids.length) { - // get instance status by finding the latest status bucket - const latestTimestamp = chain(statusBuckets) - .map((bucket) => bucket.max_timestamp.value) - .max() - .value(); - const latestBucket = find( - statusBuckets, - (bucket) => bucket.max_timestamp.value === latestTimestamp - ); - status = latestBucket.key; + // if the cluster has kibana instances at all + if (kibanaUuids.length) { + // get instance status by finding the latest status bucket + const latestTimestamp = chain(statusBuckets) + .map((bucket) => bucket.max_timestamp.value) + .max() + .value(); + const latestBucket = find( + statusBuckets, + (bucket) => bucket.max_timestamp.value === latestTimestamp + ); + status = latestBucket.key; - requestsTotal = aggregations.requests_total?.value; - connections = aggregations.concurrent_connections?.value; - responseTime = aggregations.response_time_max?.value; - memorySize = aggregations.memory_rss?.value; - memoryLimit = aggregations.memory_heap_size_limit?.value; - } + requestsTotal = aggregations.requests_total?.value; + connections = aggregations.concurrent_connections?.value; + responseTime = aggregations.response_time_max?.value; + memorySize = aggregations.memory_rss?.value; + memoryLimit = aggregations.memory_heap_size_limit?.value; + } - return { - clusterUuid, - stats: { - uuids: kibanaUuids.map(({ key }: Bucket) => key), - status, - requests_total: requestsTotal, - concurrent_connections: connections, - response_time_max: responseTime, - memory_size: memorySize, - memory_limit: memoryLimit, - count: kibanaUuids.length, - }, - }; - }); - }); + return { + clusterUuid, + stats: { + uuids: kibanaUuids.map(({ key }: Bucket) => key), + status, + requests_total: requestsTotal, + concurrent_connections: connections, + response_time_max: responseTime, + memory_size: memorySize, + memory_limit: memoryLimit, + count: kibanaUuids.length, + }, + }; + }); + }) + ); } diff --git a/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.ts b/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.ts index 480b7176b7aba..03c87bfdde1ac 100644 --- a/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.ts +++ b/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.ts @@ -5,7 +5,6 @@ * 2.0. */ -import Bluebird from 'bluebird'; import { get } from 'lodash'; import { LegacyRequest, Cluster, Bucket } from '../../types'; import { LOGSTASH } from '../../../common/constants'; @@ -48,208 +47,210 @@ export function getLogstashForClusters( const end = req.payload.timeRange.max; const config = req.server.config(); - return Bluebird.map(clusters, (cluster) => { - const clusterUuid = get(cluster, 'elasticsearch.cluster.id', cluster.cluster_uuid); - const params = { - index: lsIndexPattern, - size: 0, - ignore_unavailable: true, - body: { - query: createQuery({ - types: ['stats', 'logstash_stats'], - start, - end, - clusterUuid, - metric: LogstashClusterMetric.getMetricFields(), - }), - aggs: { - logstash_uuids: { - terms: { - field: 'logstash_stats.logstash.uuid', - size: config.get('monitoring.ui.max_bucket_size'), - }, - aggs: { - latest_report: { - terms: { - field: 'logstash_stats.timestamp', - size: 1, - order: { - _key: 'desc', - }, - }, - aggs: { - memory_used: { - max: { - field: 'logstash_stats.jvm.mem.heap_used_in_bytes', + return Promise.all( + clusters.map((cluster) => { + const clusterUuid = get(cluster, 'elasticsearch.cluster.id', cluster.cluster_uuid); + const params = { + index: lsIndexPattern, + size: 0, + ignore_unavailable: true, + body: { + query: createQuery({ + types: ['stats', 'logstash_stats'], + start, + end, + clusterUuid, + metric: LogstashClusterMetric.getMetricFields(), + }), + aggs: { + logstash_uuids: { + terms: { + field: 'logstash_stats.logstash.uuid', + size: config.get('monitoring.ui.max_bucket_size'), + }, + aggs: { + latest_report: { + terms: { + field: 'logstash_stats.timestamp', + size: 1, + order: { + _key: 'desc', }, }, - memory: { - max: { - field: 'logstash_stats.jvm.mem.heap_max_in_bytes', + aggs: { + memory_used: { + max: { + field: 'logstash_stats.jvm.mem.heap_used_in_bytes', + }, }, - }, - events_in_total: { - max: { - field: 'logstash_stats.events.in', + memory: { + max: { + field: 'logstash_stats.jvm.mem.heap_max_in_bytes', + }, }, - }, - events_out_total: { - max: { - field: 'logstash_stats.events.out', + events_in_total: { + max: { + field: 'logstash_stats.events.in', + }, + }, + events_out_total: { + max: { + field: 'logstash_stats.events.out', + }, }, }, }, - }, - memory_used_per_node: { - max_bucket: { - buckets_path: 'latest_report>memory_used', + memory_used_per_node: { + max_bucket: { + buckets_path: 'latest_report>memory_used', + }, }, - }, - memory_per_node: { - max_bucket: { - buckets_path: 'latest_report>memory', + memory_per_node: { + max_bucket: { + buckets_path: 'latest_report>memory', + }, }, - }, - events_in_total_per_node: { - max_bucket: { - buckets_path: 'latest_report>events_in_total', + events_in_total_per_node: { + max_bucket: { + buckets_path: 'latest_report>events_in_total', + }, }, - }, - events_out_total_per_node: { - max_bucket: { - buckets_path: 'latest_report>events_out_total', + events_out_total_per_node: { + max_bucket: { + buckets_path: 'latest_report>events_out_total', + }, }, }, }, - }, - logstash_versions: { - terms: { - field: 'logstash_stats.logstash.version', - size: config.get('monitoring.ui.max_bucket_size'), - }, - }, - pipelines_nested: { - nested: { - path: 'logstash_stats.pipelines', + logstash_versions: { + terms: { + field: 'logstash_stats.logstash.version', + size: config.get('monitoring.ui.max_bucket_size'), + }, }, - aggs: { - pipelines: { - sum_bucket: { - buckets_path: 'queue_types>num_pipelines', - }, + pipelines_nested: { + nested: { + path: 'logstash_stats.pipelines', }, - queue_types: { - terms: { - field: 'logstash_stats.pipelines.queue.type', - size: config.get('monitoring.ui.max_bucket_size'), + aggs: { + pipelines: { + sum_bucket: { + buckets_path: 'queue_types>num_pipelines', + }, }, - aggs: { - num_pipelines: { - cardinality: { - field: 'logstash_stats.pipelines.id', + queue_types: { + terms: { + field: 'logstash_stats.pipelines.queue.type', + size: config.get('monitoring.ui.max_bucket_size'), + }, + aggs: { + num_pipelines: { + cardinality: { + field: 'logstash_stats.pipelines.id', + }, }, }, }, }, }, - }, - pipelines_nested_mb: { - nested: { - path: 'logstash.node.stats.pipelines', - }, - aggs: { - pipelines: { - sum_bucket: { - buckets_path: 'queue_types>num_pipelines', - }, + pipelines_nested_mb: { + nested: { + path: 'logstash.node.stats.pipelines', }, - queue_types: { - terms: { - field: 'logstash.node.stats.pipelines.queue.type', - size: config.get('monitoring.ui.max_bucket_size'), + aggs: { + pipelines: { + sum_bucket: { + buckets_path: 'queue_types>num_pipelines', + }, }, - aggs: { - num_pipelines: { - cardinality: { - field: 'logstash.node.stats.pipelines.id', + queue_types: { + terms: { + field: 'logstash.node.stats.pipelines.queue.type', + size: config.get('monitoring.ui.max_bucket_size'), + }, + aggs: { + num_pipelines: { + cardinality: { + field: 'logstash.node.stats.pipelines.id', + }, }, }, }, }, }, - }, - events_in_total: { - sum_bucket: { - buckets_path: 'logstash_uuids>events_in_total_per_node', + events_in_total: { + sum_bucket: { + buckets_path: 'logstash_uuids>events_in_total_per_node', + }, }, - }, - events_out_total: { - sum_bucket: { - buckets_path: 'logstash_uuids>events_out_total_per_node', + events_out_total: { + sum_bucket: { + buckets_path: 'logstash_uuids>events_out_total_per_node', + }, }, - }, - memory_used: { - sum_bucket: { - buckets_path: 'logstash_uuids>memory_used_per_node', + memory_used: { + sum_bucket: { + buckets_path: 'logstash_uuids>memory_used_per_node', + }, }, - }, - memory: { - sum_bucket: { - buckets_path: 'logstash_uuids>memory_per_node', + memory: { + sum_bucket: { + buckets_path: 'logstash_uuids>memory_per_node', + }, }, - }, - max_uptime: { - max: { - field: 'logstash_stats.jvm.uptime_in_millis', + max_uptime: { + max: { + field: 'logstash_stats.jvm.uptime_in_millis', + }, }, }, }, - }, - }; + }; - const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); - return callWithRequest(req, 'search', params).then((result) => { - const aggregations = get(result, 'aggregations', {}); - const logstashUuids = get(aggregations, 'logstash_uuids.buckets', []); - const logstashVersions = get(aggregations, 'logstash_versions.buckets', []); + const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); + return callWithRequest(req, 'search', params).then((result) => { + const aggregations = get(result, 'aggregations', {}); + const logstashUuids = get(aggregations, 'logstash_uuids.buckets', []); + const logstashVersions = get(aggregations, 'logstash_versions.buckets', []); - // everything is initialized such that it won't impact any rollup - let eventsInTotal = 0; - let eventsOutTotal = 0; - let memory = 0; - let memoryUsed = 0; - let maxUptime = 0; + // everything is initialized such that it won't impact any rollup + let eventsInTotal = 0; + let eventsOutTotal = 0; + let memory = 0; + let memoryUsed = 0; + let maxUptime = 0; - // if the cluster has logstash instances at all - if (logstashUuids.length) { - eventsInTotal = get(aggregations, 'events_in_total.value'); - eventsOutTotal = get(aggregations, 'events_out_total.value'); - memory = get(aggregations, 'memory.value'); - memoryUsed = get(aggregations, 'memory_used.value'); - maxUptime = get(aggregations, 'max_uptime.value'); - } + // if the cluster has logstash instances at all + if (logstashUuids.length) { + eventsInTotal = get(aggregations, 'events_in_total.value'); + eventsOutTotal = get(aggregations, 'events_out_total.value'); + memory = get(aggregations, 'memory.value'); + memoryUsed = get(aggregations, 'memory_used.value'); + maxUptime = get(aggregations, 'max_uptime.value'); + } - let types = get(aggregations, 'pipelines_nested_mb.queue_types.buckets', []); - if (!types || types.length === 0) { - types = aggregations.pipelines_nested?.queue_types.buckets ?? []; - } + let types = get(aggregations, 'pipelines_nested_mb.queue_types.buckets', []); + if (!types || types.length === 0) { + types = aggregations.pipelines_nested?.queue_types.buckets ?? []; + } - return { - clusterUuid, - stats: { - node_count: logstashUuids.length, - events_in_total: eventsInTotal, - events_out_total: eventsOutTotal, - avg_memory: memory, - avg_memory_used: memoryUsed, - max_uptime: maxUptime, - pipeline_count: - get(aggregations, 'pipelines_nested_mb.pipelines.value') || - get(aggregations, 'pipelines_nested.pipelines.value', 0), - queue_types: getQueueTypes(types), - versions: logstashVersions.map((versionBucket: Bucket) => versionBucket.key), - }, - }; - }); - }); + return { + clusterUuid, + stats: { + node_count: logstashUuids.length, + events_in_total: eventsInTotal, + events_out_total: eventsOutTotal, + avg_memory: memory, + avg_memory_used: memoryUsed, + max_uptime: maxUptime, + pipeline_count: + get(aggregations, 'pipelines_nested_mb.pipelines.value') || + get(aggregations, 'pipelines_nested.pipelines.value', 0), + queue_types: getQueueTypes(types), + versions: logstashVersions.map((versionBucket: Bucket) => versionBucket.key), + }, + }; + }); + }) + ); } diff --git a/x-pack/plugins/osquery/server/routes/fleet_wrapper/get_agent_policies.ts b/x-pack/plugins/osquery/server/routes/fleet_wrapper/get_agent_policies.ts index accfc2d9ef4da..06641cc60e13d 100644 --- a/x-pack/plugins/osquery/server/routes/fleet_wrapper/get_agent_policies.ts +++ b/x-pack/plugins/osquery/server/routes/fleet_wrapper/get_agent_policies.ts @@ -5,7 +5,7 @@ * 2.0. */ -import bluebird from 'bluebird'; +import pMap from 'p-map'; import { schema } from '@kbn/config-schema'; import { filter, uniq, map } from 'lodash'; import { satisfies } from 'semver'; @@ -47,7 +47,7 @@ export const getAgentPoliciesRoute = (router: IRouter, osqueryContext: OsqueryAp const agentPolicies = await agentPolicyService?.getByIds(soClient, agentPolicyIds); if (agentPolicies?.length) { - await bluebird.map( + await pMap( agentPolicies, (agentPolicy: GetAgentPoliciesResponseItem) => agentService diff --git a/x-pack/plugins/security_solution/scripts/endpoint/event_filters/index.ts b/x-pack/plugins/security_solution/scripts/endpoint/event_filters/index.ts index e0dd108769305..15758b5afd209 100644 --- a/x-pack/plugins/security_solution/scripts/endpoint/event_filters/index.ts +++ b/x-pack/plugins/security_solution/scripts/endpoint/event_filters/index.ts @@ -8,7 +8,7 @@ import { run, RunFn, createFailError } from '@kbn/dev-utils'; import { KbnClient } from '@kbn/test'; import { AxiosError } from 'axios'; -import bluebird from 'bluebird'; +import pMap from 'p-map'; import type { CreateExceptionListSchema } from '@kbn/securitysolution-io-ts-list-types'; import { ENDPOINT_EVENT_FILTERS_LIST_DESCRIPTION, @@ -70,7 +70,7 @@ const createEventFilters: RunFn = async ({ flags, log }) => { await ensureCreateEndpointEventFiltersList(kbn); - await bluebird.map( + await pMap( Array.from({ length: flags.count as unknown as number }), () => kbn diff --git a/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts b/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts index 15f0b2f65cb95..779aee0bb1dc1 100644 --- a/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts +++ b/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts @@ -8,7 +8,7 @@ import { run, RunFn, createFailError } from '@kbn/dev-utils'; import { KbnClient } from '@kbn/test'; import { AxiosError } from 'axios'; -import bluebird from 'bluebird'; +import pMap from 'p-map'; import type { CreateExceptionListSchema } from '@kbn/securitysolution-io-ts-list-types'; import { ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_DESCRIPTION, @@ -70,7 +70,7 @@ const createHostIsolationException: RunFn = async ({ flags, log }) => { await ensureCreateEndpointHostIsolationExceptionList(kbn); - await bluebird.map( + await pMap( Array.from({ length: flags.count as unknown as number }), () => kbn diff --git a/x-pack/plugins/security_solution/scripts/endpoint/trusted_apps/index.ts b/x-pack/plugins/security_solution/scripts/endpoint/trusted_apps/index.ts index d20d29a34754c..97695ec60062c 100644 --- a/x-pack/plugins/security_solution/scripts/endpoint/trusted_apps/index.ts +++ b/x-pack/plugins/security_solution/scripts/endpoint/trusted_apps/index.ts @@ -8,7 +8,7 @@ import minimist from 'minimist'; import { ToolingLog } from '@kbn/dev-utils'; import { KbnClient } from '@kbn/test'; -import bluebird from 'bluebird'; +import pMap from 'p-map'; import { basename } from 'path'; import { AxiosResponse } from 'axios'; import { TRUSTED_APPS_CREATE_API, TRUSTED_APPS_LIST_API } from '../../../common/endpoint/constants'; @@ -113,7 +113,7 @@ export const run: (options?: RunOptions) => Promise = async ({ return () => policyIds[randomN(policyIds.length)]; })(); - return bluebird.map( + return pMap( Array.from({ length: count }), async () => { const body = trustedAppGenerator.generateTrustedAppForCreate(); diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index 247dc607c0038..7f175b6d83ab6 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { FtrProviderContext } from '../ftr_provider_context'; import { logWrapper } from './log_wrapper'; @@ -1094,7 +1094,7 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont draggedOver, dropTarget ); - await delay(150); + await setTimeoutAsync(150); }, /** diff --git a/x-pack/test/functional/page_objects/rollup_page.ts b/x-pack/test/functional/page_objects/rollup_page.ts index 0740a8f015da1..28ad65f60a49b 100644 --- a/x-pack/test/functional/page_objects/rollup_page.ts +++ b/x-pack/test/functional/page_objects/rollup_page.ts @@ -6,7 +6,6 @@ */ import expect from '@kbn/expect'; -import { map as mapAsync } from 'bluebird'; import { FtrService } from '../ftr_provider_context'; export class RollupPageObject extends FtrService { @@ -111,26 +110,32 @@ export class RollupPageObject extends FtrService { async getJobList() { const jobs = await this.testSubjects.findAll('jobTableRow'); - return mapAsync(jobs, async (job) => { - const jobNameElement = await job.findByTestSubject('jobTableCell-id'); - const jobStatusElement = await job.findByTestSubject('jobTableCell-status'); - const jobIndexPatternElement = await job.findByTestSubject('jobTableCell-indexPattern'); - const jobRollUpIndexPatternElement = await job.findByTestSubject('jobTableCell-rollupIndex'); - const jobDelayElement = await job.findByTestSubject('jobTableCell-rollupDelay'); - const jobIntervalElement = await job.findByTestSubject('jobTableCell-dateHistogramInterval'); - const jobGroupElement = await job.findByTestSubject('jobTableCell-groups'); - const jobMetricsElement = await job.findByTestSubject('jobTableCell-metrics'); - - return { - jobName: await jobNameElement.getVisibleText(), - jobStatus: await jobStatusElement.getVisibleText(), - jobIndexPattern: await jobIndexPatternElement.getVisibleText(), - jobRollUpIndexPattern: await jobRollUpIndexPatternElement.getVisibleText(), - jobDelayElement: await jobDelayElement.getVisibleText(), - jobInterval: await jobIntervalElement.getVisibleText(), - jobGroup: await jobGroupElement.getVisibleText(), - jobMetrics: await jobMetricsElement.getVisibleText(), - }; - }); + return await Promise.all( + jobs.map(async (job) => { + const jobNameElement = await job.findByTestSubject('jobTableCell-id'); + const jobStatusElement = await job.findByTestSubject('jobTableCell-status'); + const jobIndexPatternElement = await job.findByTestSubject('jobTableCell-indexPattern'); + const jobRollUpIndexPatternElement = await job.findByTestSubject( + 'jobTableCell-rollupIndex' + ); + const jobDelayElement = await job.findByTestSubject('jobTableCell-rollupDelay'); + const jobIntervalElement = await job.findByTestSubject( + 'jobTableCell-dateHistogramInterval' + ); + const jobGroupElement = await job.findByTestSubject('jobTableCell-groups'); + const jobMetricsElement = await job.findByTestSubject('jobTableCell-metrics'); + + return { + jobName: await jobNameElement.getVisibleText(), + jobStatus: await jobStatusElement.getVisibleText(), + jobIndexPattern: await jobIndexPatternElement.getVisibleText(), + jobRollUpIndexPattern: await jobRollUpIndexPatternElement.getVisibleText(), + jobDelayElement: await jobDelayElement.getVisibleText(), + jobInterval: await jobIntervalElement.getVisibleText(), + jobGroup: await jobGroupElement.getVisibleText(), + jobMetrics: await jobMetricsElement.getVisibleText(), + }; + }) + ); } } diff --git a/x-pack/test/functional/page_objects/watcher_page.ts b/x-pack/test/functional/page_objects/watcher_page.ts index 5aeaddffff581..ad5153a933466 100644 --- a/x-pack/test/functional/page_objects/watcher_page.ts +++ b/x-pack/test/functional/page_objects/watcher_page.ts @@ -5,7 +5,6 @@ * 2.0. */ -import { map as mapAsync } from 'bluebird'; import { FtrService } from '../ftr_provider_context'; export class WatcherPageObject extends FtrService { @@ -51,16 +50,18 @@ export class WatcherPageObject extends FtrService { // get all the watches in the list async getWatches() { const watches = await this.find.allByCssSelector('.euiTableRow'); - return mapAsync(watches, async (watch) => { - const checkBox = await watch.findByCssSelector('td:nth-child(1)'); - const id = await watch.findByCssSelector('td:nth-child(2)'); - const name = await watch.findByCssSelector('td:nth-child(3)'); + return await Promise.all( + watches.map(async (watch) => { + const checkBox = await watch.findByCssSelector('td:nth-child(1)'); + const id = await watch.findByCssSelector('td:nth-child(2)'); + const name = await watch.findByCssSelector('td:nth-child(3)'); - return { - checkBox: (await checkBox.getAttribute('innerHTML')).includes('input'), - id: await id.getVisibleText(), - name: (await name.getVisibleText()).split(',').map((role) => role.trim()), - }; - }); + return { + checkBox: (await checkBox.getAttribute('innerHTML')).includes('input'), + id: await id.getVisibleText(), + name: (await name.getVisibleText()).split(',').map((role) => role.trim()), + }; + }) + ); } } diff --git a/x-pack/test/functional/services/ace_editor.js b/x-pack/test/functional/services/ace_editor.js index 589f05695e065..2b2adde74ecc7 100644 --- a/x-pack/test/functional/services/ace_editor.js +++ b/x-pack/test/functional/services/ace_editor.js @@ -5,8 +5,6 @@ * 2.0. */ -import { map as mapAsync } from 'bluebird'; - export function AceEditorProvider({ getService }) { const testSubjects = getService('testSubjects'); const find = getService('find'); @@ -35,7 +33,7 @@ export function AceEditorProvider({ getService }) { return await retry.try(async () => { const editor = await testSubjects.find(testSubjectSelector); const lines = await editor.findAllByClassName('ace_line'); - const linesText = await mapAsync(lines, (line) => line.getVisibleText()); + const linesText = await Promise.all(lines.map((line) => line.getVisibleText())); return linesText.join('\n'); }); } diff --git a/x-pack/test/functional/services/monitoring/cluster_alerts.js b/x-pack/test/functional/services/monitoring/cluster_alerts.js index cbeb537b08016..4f70903bda1c2 100644 --- a/x-pack/test/functional/services/monitoring/cluster_alerts.js +++ b/x-pack/test/functional/services/monitoring/cluster_alerts.js @@ -6,7 +6,6 @@ */ import { range } from 'lodash'; -import { map as mapAsync } from 'bluebird'; export function MonitoringClusterAlertsProvider({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); @@ -61,9 +60,11 @@ export function MonitoringClusterAlertsProvider({ getService, getPageObjects }) const listingRows = await this.getOverviewAlerts(); const alertIcons = await retry.try(async () => { const elements = await find.allByCssSelector(SUBJ_OVERVIEW_ICONS); - return await mapAsync(elements, async (element) => { - return await element.getVisibleText(); - }); + return await Promise.all( + elements.map(async (element) => { + return await element.getVisibleText(); + }) + ); }); return await this._getAlertSetAll({ diff --git a/x-pack/test/functional/services/pipeline_editor.js b/x-pack/test/functional/services/pipeline_editor.js index ece7ec5b3ecbc..bb1f122b988bd 100644 --- a/x-pack/test/functional/services/pipeline_editor.js +++ b/x-pack/test/functional/services/pipeline_editor.js @@ -6,7 +6,6 @@ */ import expect from '@kbn/expect'; -import { props as propsAsync } from 'bluebird'; export function PipelineEditorProvider({ getService }) { const retry = getService('retry'); @@ -125,20 +124,27 @@ export function PipelineEditorProvider({ getService }) { * @return {Promise} */ async assertInputs(expectedValues) { - const values = await propsAsync({ - id: testSubjects.getAttribute(SUBJ_INPUT_ID, 'value'), - description: testSubjects.getAttribute(SUBJ_INPUT_DESCRIPTION, 'value'), - pipeline: aceEditor.getValue(SUBJ_UI_ACE_PIPELINE), - workers: testSubjects.getAttribute(SUBJ_INPUT_WORKERS, 'value'), - batchSize: testSubjects.getAttribute(SUBJ_INPUT_BATCH_SIZE, 'value'), - queueType: testSubjects.getAttribute(SUBJ_SELECT_QUEUE_TYPE, 'value'), - queueMaxBytesNumber: testSubjects.getAttribute(SUBJ_INPUT_QUEUE_MAX_BYTES_NUMBER, 'value'), - queueMaxBytesUnits: testSubjects.getAttribute(SUBJ_SELECT_QUEUE_MAX_BYTES_UNITS, 'value'), - queueCheckpointWrites: testSubjects.getAttribute( - SUBJ_INPUT_QUEUE_CHECKPOINT_WRITES, - 'value' - ), - }); + const values = await Promise.all([ + testSubjects.getAttribute(SUBJ_INPUT_ID, 'value'), + testSubjects.getAttribute(SUBJ_INPUT_DESCRIPTION, 'value'), + aceEditor.getValue(SUBJ_UI_ACE_PIPELINE), + testSubjects.getAttribute(SUBJ_INPUT_WORKERS, 'value'), + testSubjects.getAttribute(SUBJ_INPUT_BATCH_SIZE, 'value'), + testSubjects.getAttribute(SUBJ_SELECT_QUEUE_TYPE, 'value'), + testSubjects.getAttribute(SUBJ_INPUT_QUEUE_MAX_BYTES_NUMBER, 'value'), + testSubjects.getAttribute(SUBJ_SELECT_QUEUE_MAX_BYTES_UNITS, 'value'), + testSubjects.getAttribute(SUBJ_INPUT_QUEUE_CHECKPOINT_WRITES, 'value'), + ]).then((values) => ({ + id: values[0], + description: values[1], + pipeline: values[2], + workers: values[3], + batchSize: values[4], + queueType: values[5], + queueMaxBytesNumber: values[6], + queueMaxBytesUnits: values[7], + queueCheckpointWrites: values[8], + })); expect(values).to.eql(expectedValues); } diff --git a/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts b/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts index f08867b445f75..d657db443e4ec 100644 --- a/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts +++ b/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -99,7 +99,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { let alert: any; await retry.tryForTime(60 * 1000, async () => { // add a delay before next call to not overload the server - await delay(1500); + await setTimeoutAsync(1500); const apiResponse = await supertest.get('/api/alerts/_find?search=uptime-test'); const alertsFromThisTest = apiResponse.body.data.filter( ({ name }: { name: string }) => name === 'uptime-test' diff --git a/x-pack/test/load/runner.ts b/x-pack/test/load/runner.ts index c48a8e33d6eef..e9750bd19881a 100644 --- a/x-pack/test/load/runner.ts +++ b/x-pack/test/load/runner.ts @@ -10,7 +10,7 @@ import { resolve } from 'path'; import { REPO_ROOT } from '@kbn/utils'; import Fs from 'fs'; import { createFlagError } from '@kbn/dev-utils'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { FtrProviderContext } from './../functional/ftr_provider_context'; const baseSimulationPath = 'src/test/scala/org/kibanaLoadTest/simulation'; @@ -82,7 +82,7 @@ export async function GatlingTestRunner({ getService }: FtrProviderContext) { }); // wait a minute between simulations, skip for the last one if (i < simulationClasses.length - 1) { - await delay(60 * 1000); + await setTimeoutAsync(60 * 1000); } } }); diff --git a/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts b/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts index ed1a1f3c16fcc..84673c7b68f2e 100644 --- a/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts +++ b/x-pack/test/security_api_integration/tests/kerberos/kerberos_login.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { parse as parseCookie, Cookie } from 'tough-cookie'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { adminTestUser } from '@kbn/test'; import { FtrProviderContext } from '../../ftr_provider_context'; import { @@ -319,7 +319,7 @@ export default function ({ getService }: FtrProviderContext) { // Access token expiration is set to 15s for API integration tests. // Let's wait for 20s to make sure token expires. - await delay(20000); + await setTimeoutAsync(20000); // This api call should succeed and automatically refresh token. Returned cookie will contain // the new access and refresh token pair. @@ -350,7 +350,7 @@ export default function ({ getService }: FtrProviderContext) { // Access token expiration is set to 15s for API integration tests. // Let's wait for 20s to make sure token expires. - await delay(20000); + await setTimeoutAsync(20000); // This request should succeed and automatically refresh token. Returned cookie will contain // the new access and refresh token pair. diff --git a/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts b/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts index a7a8702894482..eb12d4240a372 100644 --- a/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts +++ b/x-pack/test/security_api_integration/tests/oidc/authorization_code_flow/oidc_auth.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { parse as parseCookie, Cookie } from 'tough-cookie'; import url from 'url'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { adminTestUser } from '@kbn/test'; import { getStateAndNonce } from '../../../fixtures/oidc/oidc_tools'; import { FtrProviderContext } from '../../../ftr_provider_context'; @@ -494,7 +494,7 @@ export default function ({ getService }: FtrProviderContext) { // Access token expiration is set to 15s for API integration tests. // Let's wait for 20s to make sure token expires. - await delay(20000); + await setTimeoutAsync(20000); // This api call should succeed and automatically refresh token. Returned cookie will contain // the new access and refresh token pair. diff --git a/x-pack/test/security_api_integration/tests/pki/pki_auth.ts b/x-pack/test/security_api_integration/tests/pki/pki_auth.ts index f857e5c149be4..76e3cb2248815 100644 --- a/x-pack/test/security_api_integration/tests/pki/pki_auth.ts +++ b/x-pack/test/security_api_integration/tests/pki/pki_auth.ts @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { parse as parseCookie, Cookie } from 'tough-cookie'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import { readFileSync } from 'fs'; import { resolve } from 'path'; import { CA_CERT_PATH } from '@kbn/dev-utils'; @@ -358,7 +358,7 @@ export default function ({ getService }: FtrProviderContext) { // Access token expiration is set to 15s for API integration tests. // Let's wait for 20s to make sure token expires. - await delay(20000); + await setTimeoutAsync(20000); // This api call should succeed and automatically refresh token. Returned cookie will contain // the new access token. @@ -382,7 +382,7 @@ export default function ({ getService }: FtrProviderContext) { // Access token expiration is set to 15s for API integration tests. // Let's wait for 20s to make sure token expires. - await delay(20000); + await setTimeoutAsync(20000); // This request should succeed and automatically refresh token. Returned cookie will contain // the new access and refresh token pair. diff --git a/x-pack/test/security_api_integration/tests/saml/saml_login.ts b/x-pack/test/security_api_integration/tests/saml/saml_login.ts index 97fdcb77f4d66..c0ea296297fe6 100644 --- a/x-pack/test/security_api_integration/tests/saml/saml_login.ts +++ b/x-pack/test/security_api_integration/tests/saml/saml_login.ts @@ -7,7 +7,7 @@ import { stringify } from 'query-string'; import url from 'url'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import expect from '@kbn/expect'; import { parse as parseCookie, Cookie } from 'tough-cookie'; import { adminTestUser } from '@kbn/test'; @@ -468,7 +468,7 @@ export default function ({ getService }: FtrProviderContext) { // Access token expiration is set to 15s for API integration tests. // Let's wait for 20s to make sure token expires. - await delay(20000); + await setTimeoutAsync(20000); }); const expectNewSessionCookie = (cookie: Cookie) => { @@ -639,7 +639,7 @@ export default function ({ getService }: FtrProviderContext) { ['when access token is valid', async () => {}], // Scenario when active cookie has an expired access token. Access token expiration is set // to 15s for API integration tests so we need to wait for 20s to make sure token expires. - ['when access token is expired', async () => await delay(20000)], + ['when access token is expired', async () => await setTimeoutAsync(20000)], // Scenario when active cookie references to access/refresh token pair that were already // removed from Elasticsearch (to simulate 24h when expired tokens are removed). [ diff --git a/x-pack/test/security_api_integration/tests/session_idle/cleanup.ts b/x-pack/test/security_api_integration/tests/session_idle/cleanup.ts index beb7bdfbdfccc..39231df307a9e 100644 --- a/x-pack/test/security_api_integration/tests/session_idle/cleanup.ts +++ b/x-pack/test/security_api_integration/tests/session_idle/cleanup.ts @@ -6,7 +6,7 @@ */ import { parse as parseCookie, Cookie } from 'tough-cookie'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import expect from '@kbn/expect'; import { adminTestUser } from '@kbn/test'; import type { AuthenticationProvider } from '../../../../plugins/security/common/model'; @@ -101,7 +101,7 @@ export default function ({ getService }: FtrProviderContext) { // Cleanup routine runs every 10s, and idle timeout threshold is three times larger than 5s // idle timeout, let's wait for 40s to make sure cleanup routine runs when idle timeout // threshold is exceeded. - await delay(40000); + await setTimeoutAsync(40000); // Session info is removed from the index and cookie isn't valid anymore expect(await getNumberOfSessionDocuments()).to.be(0); @@ -143,7 +143,7 @@ export default function ({ getService }: FtrProviderContext) { // Cleanup routine runs every 10s, and idle timeout threshold is three times larger than 5s // idle timeout, let's wait for 40s to make sure cleanup routine runs when idle timeout // threshold is exceeded. - await delay(40000); + await setTimeoutAsync(40000); // Session for basic and SAML that used global session settings should not be valid anymore. expect(await getNumberOfSessionDocuments()).to.be(2); @@ -191,7 +191,7 @@ export default function ({ getService }: FtrProviderContext) { // least twice. for (const counter of [...Array(20).keys()]) { // Session idle timeout is 15s, let's wait 10s and make a new request that would extend the session. - await delay(1500); + await setTimeoutAsync(1500); sessionCookie = (await checkSessionCookie(sessionCookie, basicUsername, { type: 'basic', diff --git a/x-pack/test/security_api_integration/tests/session_lifespan/cleanup.ts b/x-pack/test/security_api_integration/tests/session_lifespan/cleanup.ts index 6b5308f623805..32222794ac23b 100644 --- a/x-pack/test/security_api_integration/tests/session_lifespan/cleanup.ts +++ b/x-pack/test/security_api_integration/tests/session_lifespan/cleanup.ts @@ -6,7 +6,7 @@ */ import { parse as parseCookie, Cookie } from 'tough-cookie'; -import { delay } from 'bluebird'; +import { setTimeout as setTimeoutAsync } from 'timers/promises'; import expect from '@kbn/expect'; import { adminTestUser } from '@kbn/test'; import type { AuthenticationProvider } from '../../../../plugins/security/common/model'; @@ -98,7 +98,7 @@ export default function ({ getService }: FtrProviderContext) { // Cleanup routine runs every 10s, let's wait for 40s to make sure it runs multiple times and // when lifespan is exceeded. - await delay(40000); + await setTimeoutAsync(40000); // Session info is removed from the index and cookie isn't valid anymore expect(await getNumberOfSessionDocuments()).to.be(0); @@ -138,7 +138,7 @@ export default function ({ getService }: FtrProviderContext) { // Cleanup routine runs every 10s, let's wait for 40s to make sure it runs multiple times and // when lifespan is exceeded. - await delay(40000); + await setTimeoutAsync(40000); // Session for basic and SAML that used global session settings should not be valid anymore. expect(await getNumberOfSessionDocuments()).to.be(2); diff --git a/yarn.lock b/yarn.lock index 533f1cbd89456..a4739826997ef 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5905,11 +5905,6 @@ resolved "https://registry.yarnpkg.com/@types/base64-js/-/base64-js-1.2.5.tgz#582b2476169a6cba460a214d476c744441d873d5" integrity sha1-WCskdhaabLpGCiFNR2x0REHYc9U= -"@types/bluebird@^3.1.1": - version "3.5.30" - resolved "https://registry.yarnpkg.com/@types/bluebird/-/bluebird-3.5.30.tgz#ee034a0eeea8b84ed868b1aa60d690b08a6cfbc5" - integrity sha512-8LhzvcjIoqoi1TghEkRMkbbmM+jhHnBokPGkJWjclMK+Ks0MxEBow3/p2/iFTZ+OIbJHQDSfpgdZEb+af3gfVw== - "@types/braces@*": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/braces/-/braces-3.0.0.tgz#7da1c0d44ff1c7eb660a36ec078ea61ba7eb42cb" @@ -9422,11 +9417,6 @@ bluebird@3.5.3: resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.3.tgz#7d01c6f9616c9a51ab0f8c549a79dfe6ec33efa7" integrity sha512-/qKPUQlaW1OyR51WeCPBvRnAlnZFUJkCSG5HzGnuIqhgyJtF+T94lFnn33eiazjRm2LAHVy2guNnaq48X9SJuw== -bluebird@3.5.5: - version "3.5.5" - resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.5.tgz#a8d0afd73251effbbd5fe384a77d73003c17a71f" - integrity sha512-5am6HnnfN+urzt4yfg7IgTbotDjIT/u8AJpEt0sIU9FtXfVeezXAPKswrG+xKUCOYAINpSdgZVDU6QFh+cuH3w== - bluebird@3.7.2, bluebird@^3.3.5, bluebird@^3.4.1, bluebird@^3.5.0, bluebird@^3.5.1, bluebird@^3.5.5, bluebird@^3.7.1, bluebird@^3.7.2: version "3.7.2" resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f"