From 6d6a0a83280937c3992095ba5c9d3c8d1af392ef Mon Sep 17 00:00:00 2001 From: spalger Date: Mon, 30 Mar 2020 18:20:11 -0700 Subject: [PATCH] [ftr] add support for docker services --- packages/kbn-dev-utils/src/index.ts | 1 + .../kbn-dev-utils/src/proc_runner/proc.ts | 2 +- packages/kbn-dev-utils/src/stdio/index.ts | 21 +++ .../{proc_runner => stdio}/observe_lines.ts | 0 .../observe_readable.ts | 0 packages/kbn-test/package.json | 27 ++-- .../src/functional_test_runner/cli.ts | 6 +- .../functional_test_runner.ts | 19 ++- .../src/functional_test_runner/index.ts | 1 + .../lib/config/schema.ts | 15 ++ .../lib/docker_servers/README.md | 81 ++++++++++ .../lib/docker_servers/container_logs.ts | 39 +++++ .../lib/docker_servers/container_running.ts | 65 ++++++++ .../define_docker_servers_config.ts | 41 +++++ .../docker_servers/docker_servers_service.ts | 152 ++++++++++++++++++ .../lib/docker_servers/index.ts | 21 +++ .../src/functional_test_runner/lib/index.ts | 1 + .../lib/lifecycle_phase.ts | 26 +-- packages/kbn-test/src/index.ts | 8 +- packages/kbn-test/types/ftr.d.ts | 12 +- test/functional/config.js | 24 +++ 21 files changed, 529 insertions(+), 33 deletions(-) create mode 100644 packages/kbn-dev-utils/src/stdio/index.ts rename packages/kbn-dev-utils/src/{proc_runner => stdio}/observe_lines.ts (100%) rename packages/kbn-dev-utils/src/{proc_runner => stdio}/observe_readable.ts (100%) create mode 100644 packages/kbn-test/src/functional_test_runner/lib/docker_servers/README.md create mode 100644 packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_logs.ts create mode 100644 packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_running.ts create mode 100644 packages/kbn-test/src/functional_test_runner/lib/docker_servers/define_docker_servers_config.ts create mode 100644 packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts create mode 100644 packages/kbn-test/src/functional_test_runner/lib/docker_servers/index.ts diff --git a/packages/kbn-dev-utils/src/index.ts b/packages/kbn-dev-utils/src/index.ts index 305e29a0e41df..a217cc8444b67 100644 --- a/packages/kbn-dev-utils/src/index.ts +++ b/packages/kbn-dev-utils/src/index.ts @@ -37,3 +37,4 @@ export { run, createFailError, createFlagError, combineErrors, isFailError, Flag export { REPO_ROOT } from './repo_root'; export { KbnClient } from './kbn_client'; export * from './axios'; +export * from './stdio'; diff --git a/packages/kbn-dev-utils/src/proc_runner/proc.ts b/packages/kbn-dev-utils/src/proc_runner/proc.ts index c899293191f2a..c29e881c55cfa 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc.ts @@ -29,7 +29,7 @@ import { promisify } from 'util'; const treeKillAsync = promisify((...args: [number, string, any]) => treeKill(...args)); import { ToolingLog } from '../tooling_log'; -import { observeLines } from './observe_lines'; +import { observeLines } from '../stdio'; import { createCliError } from './errors'; const SECOND = 1000; diff --git a/packages/kbn-dev-utils/src/stdio/index.ts b/packages/kbn-dev-utils/src/stdio/index.ts new file mode 100644 index 0000000000000..3436d971b879a --- /dev/null +++ b/packages/kbn-dev-utils/src/stdio/index.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from './observe_lines'; +export * from './observe_readable'; diff --git a/packages/kbn-dev-utils/src/proc_runner/observe_lines.ts b/packages/kbn-dev-utils/src/stdio/observe_lines.ts similarity index 100% rename from packages/kbn-dev-utils/src/proc_runner/observe_lines.ts rename to packages/kbn-dev-utils/src/stdio/observe_lines.ts diff --git a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts b/packages/kbn-dev-utils/src/stdio/observe_readable.ts similarity index 100% rename from packages/kbn-dev-utils/src/proc_runner/observe_readable.ts rename to packages/kbn-dev-utils/src/stdio/observe_readable.ts diff --git a/packages/kbn-test/package.json b/packages/kbn-test/package.json index 0ab0048619358..46c50a7484698 100644 --- a/packages/kbn-test/package.json +++ b/packages/kbn-test/package.json @@ -1,35 +1,38 @@ { "name": "@kbn/test", - "main": "./target/index.js", "version": "1.0.0", - "license": "Apache-2.0", "private": true, + "license": "Apache-2.0", + "main": "./target/index.js", "scripts": { "build": "babel src --out-dir target --delete-dir-on-start --extensions .ts,.js,.tsx --ignore *.test.js,**/__tests__/** --source-maps=inline", "kbn:bootstrap": "yarn build", "kbn:watch": "yarn build --watch" }, - "devDependencies": { - "@babel/cli": "^7.8.4", - "@kbn/babel-preset": "1.0.0", - "@kbn/dev-utils": "1.0.0", - "@types/parse-link-header": "^1.0.0", - "@types/strip-ansi": "^5.2.1", - "@types/xml2js": "^0.4.5", - "diff": "^4.0.1" - }, "dependencies": { "chalk": "^2.4.2", "dedent": "^0.7.0", "del": "^5.1.0", + "exit-hook": "^2.2.0", "getopts": "^2.2.4", "glob": "^7.1.2", + "joi": "^13.5.2", "parse-link-header": "^1.0.1", - "strip-ansi": "^5.2.0", "rxjs": "^6.5.3", + "strip-ansi": "^5.2.0", "tar-fs": "^1.16.3", "tmp": "^0.1.0", "xml2js": "^0.4.22", "zlib": "^1.0.5" + }, + "devDependencies": { + "@babel/cli": "^7.8.4", + "@kbn/babel-preset": "1.0.0", + "@kbn/dev-utils": "1.0.0", + "@types/joi": "^13.4.2", + "@types/parse-link-header": "^1.0.0", + "@types/strip-ansi": "^5.2.1", + "@types/xml2js": "^0.4.5", + "diff": "^4.0.1" } } diff --git a/packages/kbn-test/src/functional_test_runner/cli.ts b/packages/kbn-test/src/functional_test_runner/cli.ts index 276a51c3a6a99..3d0a23497fddb 100644 --- a/packages/kbn-test/src/functional_test_runner/cli.ts +++ b/packages/kbn-test/src/functional_test_runner/cli.ts @@ -19,7 +19,10 @@ import { resolve } from 'path'; import { inspect } from 'util'; + import { run, createFlagError, Flags } from '@kbn/dev-utils'; +import exitHook from 'exit-hook'; + import { FunctionalTestRunner } from './functional_test_runner'; const makeAbsolutePath = (v: string) => resolve(process.cwd(), v); @@ -92,8 +95,7 @@ export function runFtrCli() { err instanceof Error ? err : new Error(`non-Error type rejection value: ${inspect(err)}`) ) ); - process.on('SIGTERM', () => teardown()); - process.on('SIGINT', () => teardown()); + exitHook(teardown); try { if (flags['test-stats']) { diff --git a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts index 03075dd4081fd..bc8be3383567a 100644 --- a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts +++ b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts @@ -29,6 +29,7 @@ import { readProviderSpec, setupMocha, runTests, + DockerServersService, Config, } from './lib'; @@ -94,7 +95,16 @@ export class FunctionalTestRunner { })); const providers = new ProviderCollection(this.log, [ - ...coreProviders, + ...coreProviders.map(p => + p.name !== 'dockerServers' + ? p + : { + ...p, + fn: () => ({ + then: () => {}, + }), + } + ), ...readStubbedProviderSpec('Service', config.get('services')), ...readStubbedProviderSpec('PageObject', config.get('pageObjects')), ]); @@ -127,12 +137,19 @@ export class FunctionalTestRunner { throw new Error('No tests defined.'); } + const dockerServers = new DockerServersService( + config.get('dockerServers'), + this.log, + this.lifecycle + ); + // base level services that functional_test_runner exposes const coreProviders = readProviderSpec('Service', { lifecycle: () => this.lifecycle, log: () => this.log, failureMetadata: () => this.failureMetadata, config: () => config, + dockerServers: () => dockerServers, }); return await handler(config, coreProviders); diff --git a/packages/kbn-test/src/functional_test_runner/index.ts b/packages/kbn-test/src/functional_test_runner/index.ts index c783117a0ba42..cf65ceb51df8e 100644 --- a/packages/kbn-test/src/functional_test_runner/index.ts +++ b/packages/kbn-test/src/functional_test_runner/index.ts @@ -20,3 +20,4 @@ export { FunctionalTestRunner } from './functional_test_runner'; export { readConfigFile } from './lib'; export { runFtrCli } from './cli'; +export * from './lib/docker_servers'; diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts index 66f17ab579ec3..1db4a435d164f 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts @@ -53,6 +53,17 @@ const appUrlPartsSchema = () => }) .default(); +const dockerServerSchema = () => + Joi.object() + .keys({ + image: Joi.string().required(), + port: Joi.number().required(), + portInContainer: Joi.number().required(), + waitForLogLine: Joi.alternatives(Joi.object().type(RegExp), Joi.string()).optional(), + waitFor: Joi.func().optional(), + }) + .default(); + const defaultRelativeToConfigPath = (path: string) => { const makeDefault: any = (_: any, options: any) => resolve(dirname(options.context.path), path); makeDefault.description = `/${path}`; @@ -270,5 +281,9 @@ export const schema = Joi.object() disableTestUser: Joi.boolean(), }) .default(), + + dockerServers: Joi.object() + .pattern(Joi.string(), dockerServerSchema()) + .default(), }) .default(); diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/README.md b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/README.md new file mode 100644 index 0000000000000..ef1dcd0fa6bd3 --- /dev/null +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/README.md @@ -0,0 +1,81 @@ +# Functional Test Runner - Docker Servers + +In order to make it simpler to run some services while the functional tests are running, we've added the ability to execute docker containers while the tests execute for the purpose of exposing services to the tests. These containers are expected to expose an application via a single HTTP port and live for the life of the tests. If the application exits for any reason before the tests complete the tests will abort. + +To configure docker servers in your FTR config add the `dockerServers` key to your config like so: + +```ts +// import this helper to get TypeScript support for this section of the config +import { defineDockerServersConfig } from '@kbn/test'; + +export default function () { + return { + ... + + dockerServers: defineDockerServersConfig({ + // unique names are used in logging and to get the details of this server in the tests + helloWorld: { + /** the docker image to pull and run */ + image: 'hello-world', + /** The port that this application will be accessible via locally */ + port: 8080, + /** The port that the container binds to in the container */ + portInContainer: 8080, + /** + * OPTIONAL: string/regex to look for in the log, when specified the + * tests won't start until a line containing this string, or matching + * this expression is found. + */ + waitForLogLine: 'hello', + waitForLogLine: /hello/, + /** + * OPTIONAL: function that is called when server is started, when defined + * it is called to give the configuration an option to write custom delay + * logic. The function is passed a DockerServer object, which is described + * below, and an observable of the log lines produced by the application + */ + async waitFor(server, logLine$) { + await logLine$.pipe( + filter(line => line.includes('...')), + tap((line) => { + console.log('marking server ready because this line was logged:', line); + console.log('server accessible from url', server.url); + }) + ).toPromise() + } + } + }) + } +} +``` + +## `DockerServersService` + +The docker servers service is a core service that is always available in functional test runner tests. When you call `getService('dockerServers')` you will receive an instance of the `DockerServersService` class which has to methods: + +### `has(name: string): boolean` + +Determine if a name resolves to a known docker server + + +### `get(name: string): DockerServer` + +Get a `DockerServer` object for the server with the given name. + + +## `DockerServer` + +The object passed to the `waitFor()` config function and returned by `DockerServersService#get()` + +```ts +{ + url: string; + name: string; + + portInContainer: number; + port: number; + image: string; + waitForLogLine?: RegExp | string; + waitFor?: (server: DockerServer, logLine$: Rx.Observable) => Promise; +} +``` diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_logs.ts b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_logs.ts new file mode 100644 index 0000000000000..fdcb4ae7d8a13 --- /dev/null +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_logs.ts @@ -0,0 +1,39 @@ +/* + * 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 execa from 'execa'; +import * as Rx from 'rxjs'; +import { tap } from 'rxjs/operators'; +import { ToolingLog, observeLines } from '@kbn/dev-utils'; + +export function observeContainerLogs(name: string, containerId: string, log: ToolingLog) { + log.debug(`[docker:${name}] streaming logs from container [id=${containerId}]`); + const logsProc = execa('docker', ['logs', '--follow', containerId], { + stdio: ['ignore', 'pipe', 'pipe'], + }); + + const logLine$ = new Rx.Subject(); + + Rx.merge( + observeLines(logsProc.stdout).pipe(tap(line => log.info(`[docker:${name}] ${line}`))), + observeLines(logsProc.stderr).pipe(tap(line => log.error(`[docker:${name}] ${line}`))) + ).subscribe(logLine$); + + return logLine$; +} diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_running.ts b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_running.ts new file mode 100644 index 0000000000000..00d259fe76d14 --- /dev/null +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/container_running.ts @@ -0,0 +1,65 @@ +/* + * 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 execa from 'execa'; +import * as Rx from 'rxjs'; +import { ToolingLog } from '@kbn/dev-utils'; + +/** + * Create an observable that errors if a docker + * container exits before being unsubscribed + */ +export function observeContainerRunning(name: string, containerId: string, log: ToolingLog) { + return new Rx.Observable(subscriber => { + log.debug(`[docker:${name}] watching container for exit status [${containerId}]`); + + const exitCodeProc = execa('docker', ['wait', containerId]); + + let exitCode: Error | number | null = null; + exitCodeProc + .then(({ stdout }) => { + exitCode = Number.parseInt(stdout.trim(), 10); + + if (Number.isFinite(exitCode)) { + subscriber.error( + new Error(`container [id=${containerId}] unexpectedly exitted with code ${exitCode}`) + ); + } else { + subscriber.error( + new Error(`unable to parse exit code from output of "docker wait": ${stdout}`) + ); + } + }) + .catch(error => { + if (error?.killed) { + // ignore errors thrown because the process was killed + subscriber.complete(); + return; + } + + subscriber.error( + new Error(`failed to monitor process with "docker wait": ${error.message}`) + ); + }); + + return () => { + exitCodeProc.kill('SIGKILL'); + }; + }); +} diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/define_docker_servers_config.ts b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/define_docker_servers_config.ts new file mode 100644 index 0000000000000..9cf70d56c027a --- /dev/null +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/define_docker_servers_config.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 * as Rx from 'rxjs'; + +export interface DockerServiceConfig { + portInContainer: number; + port: number; + image: string; + waitForLogLine?: RegExp | string; + waitFor?: (server: DockerServer, logLine$: Rx.Observable) => Promise; +} + +export interface DockerServer extends DockerServiceConfig { + name: string; + url: string; +} + +/** + * Helper that helps authors use the type definitions for the section of the FTR config + * under the `dockerServers` key. + */ +export function defineDockerServersConfig(config: { [name: string]: DockerServiceConfig }) { + return config; +} diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts new file mode 100644 index 0000000000000..c5c974f117908 --- /dev/null +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/docker_servers_service.ts @@ -0,0 +1,152 @@ +/* + * 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 Url from 'url'; +import execa from 'execa'; +import { filter, take } from 'rxjs/operators'; +import { ToolingLog } from '@kbn/dev-utils'; + +import { Lifecycle } from '../lifecycle'; +import { observeContainerRunning } from './container_running'; +import { observeContainerLogs } from './container_logs'; +import { DockerServer, DockerServiceConfig } from './define_docker_servers_config'; + +export class DockerServersService { + private servers: DockerServer[]; + + constructor( + configs: { + [name: string]: DockerServiceConfig; + }, + private log: ToolingLog, + private lifecycle: Lifecycle + ) { + this.servers = Object.entries(configs).map(([name, config]) => { + return { + ...config, + name, + url: Url.format({ + protocol: 'http:', + hostname: 'localhost', + port: config.port, + }), + }; + }); + + this.lifecycle.beforeTests.add(async () => { + await this.startServers(); + }); + } + + has(name: string) { + return this.servers.some(s => s.name === name); + } + + get(name: string) { + const server = this.servers.find(s => s.name === name); + if (!server) { + throw new Error(`no server with name "${name}"`); + } + return { ...server }; + } + + private async startServer(server: DockerServer) { + const { log, lifecycle } = this; + const { image, name, port, portInContainer, waitFor, waitForLogLine } = server; + + // pull image from registry + log.info(`[docker:${name}] pulling docker image "${image}"`); + await execa('docker', ['pull', image]); + + // run the image that we just pulled + log.info(`[docker:${name}] running image "${image}"`); + const containerId = ( + await execa('docker', ['run', '-dit', '-p', `${port}:${portInContainer}`, image]) + ).stdout.trim(); + lifecycle.cleanup.add(() => { + try { + execa.sync('docker', ['kill', containerId]); + } catch (error) { + if (error.message.includes(`Container ${containerId} is not running`)) { + return; + } + + throw error; + } + }); + + // push the logs from the container to our logger, and expose an observable of those lines for testing + const logLine$ = observeContainerLogs(name, containerId, log); + lifecycle.cleanup.add(async () => { + await logLine$.toPromise(); + }); + + // ensure container stays running, error if it exits + lifecycle.cleanup.addSub( + observeContainerRunning(name, containerId, log).subscribe({ + error: error => { + lifecycle.cleanup.after$.subscribe(() => { + log.error(`[docker:${name}] Error ensuring that the container is running`); + log.error(error); + process.exit(1); + }); + + lifecycle.cleanup.trigger(); + }, + }) + ); + + // wait for conditions before completing + if (waitForLogLine instanceof RegExp) { + log.info(`[docker:${name}] Waiting for log line matching /${waitForLogLine.source}/`); + } + if (typeof waitForLogLine === 'string') { + log.info(`[docker:${name}] Waiting for log line containing "${waitForLogLine}"`); + } + if (waitFor !== undefined) { + log.info(`[docker:${name}] Waiting for waitFor() promise to resolve`); + } + if (waitForLogLine === undefined && waitFor === undefined) { + log.warning( + `[docker:${name}] No "waitFor*" condition defined, you should always ` + + `define a wait condition to avoid race conditions that are more likely ` + + `to fail on CI because we're not waiting for the contained server to be ready.` + ); + } + + await Promise.all([ + waitFor !== undefined && waitFor(server, logLine$.asObservable()), + waitForLogLine !== undefined && + logLine$ + .pipe( + filter(line => + waitForLogLine instanceof RegExp + ? waitForLogLine.test(line) + : line.includes(waitForLogLine) + ), + take(1) + ) + .toPromise(), + ]); + } + + private async startServers() { + await Promise.all(this.servers.map(async server => this.startServer(server))); + } +} diff --git a/packages/kbn-test/src/functional_test_runner/lib/docker_servers/index.ts b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/index.ts new file mode 100644 index 0000000000000..23df9df0458d7 --- /dev/null +++ b/packages/kbn-test/src/functional_test_runner/lib/docker_servers/index.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from './docker_servers_service'; +export * from './define_docker_servers_config'; diff --git a/packages/kbn-test/src/functional_test_runner/lib/index.ts b/packages/kbn-test/src/functional_test_runner/lib/index.ts index 8940eccad503a..7f1c229e27e0d 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/index.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/index.ts @@ -23,3 +23,4 @@ export { readConfigFile, Config } from './config'; export { readProviderSpec, ProviderCollection, Provider } from './providers'; export { runTests, setupMocha } from './mocha'; export { FailureMetadata } from './failure_metadata'; +export * from './docker_servers'; diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.ts index 5c7fdb532faa1..66b4b82f862f1 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.ts @@ -46,6 +46,12 @@ export class LifecyclePhase { this.handlers.push(fn); } + public addSub(sub: Rx.Subscription) { + this.handlers.push(() => { + sub.unsubscribe(); + }); + } + public async trigger(...args: Args) { if (this.beforeSubj.isStopped) { throw new Error(`singular lifecycle event can only be triggered once`); @@ -57,18 +63,20 @@ export class LifecyclePhase { } // catch the first error but still execute all handlers - let error; + let error: Error | undefined; // shuffle the handlers to prevent relying on their order - for (const fn of shuffle(this.handlers)) { - try { - await fn(...args); - } catch (_error) { - if (!error) { - error = _error; + await Promise.all( + shuffle(this.handlers).map(async fn => { + try { + await fn(...args); + } catch (_error) { + if (!error) { + error = _error; + } } - } - } + }) + ); this.afterSubj.next(undefined); if (this.options.singular) { diff --git a/packages/kbn-test/src/index.ts b/packages/kbn-test/src/index.ts index 57cdc8ffd494f..0a64d140edfec 100644 --- a/packages/kbn-test/src/index.ts +++ b/packages/kbn-test/src/index.ts @@ -42,12 +42,6 @@ export { kbnTestConfig, kibanaServerTestUser, kibanaTestUser, adminTestUser } fr // @ts-ignore not typed yet export { setupUsers, DEFAULT_SUPERUSER_PASS } from './functional_tests/lib/auth'; -// @ts-ignore not typed yet -export { readConfigFile } from './functional_test_runner/lib/config/read_config_file'; - -// @ts-ignore not typed yet -export { runFtrCli } from './functional_test_runner/cli'; - export { createAutoJUnitReporter, runMochaCli, @@ -60,3 +54,5 @@ export { runFailedTestsReporterCli } from './failed_tests_reporter'; export { makeJunitReportPath } from './junit_report_path'; export { CI_PARALLEL_PROCESS_PREFIX } from './ci_parallel_process_prefix'; + +export * from './functional_test_runner'; diff --git a/packages/kbn-test/types/ftr.d.ts b/packages/kbn-test/types/ftr.d.ts index 8beecab88878d..38eb69d3e6811 100644 --- a/packages/kbn-test/types/ftr.d.ts +++ b/packages/kbn-test/types/ftr.d.ts @@ -18,7 +18,12 @@ */ import { ToolingLog } from '@kbn/dev-utils'; -import { Config, Lifecycle, FailureMetadata } from '../src/functional_test_runner/lib'; +import { + Config, + Lifecycle, + FailureMetadata, + DockerServersService, +} from '../src/functional_test_runner/lib'; export { Lifecycle, Config, FailureMetadata }; @@ -61,7 +66,9 @@ export interface GenericFtrProviderContext< * Determine if a service is avaliable * @param serviceName */ - hasService(serviceName: 'config' | 'log' | 'lifecycle' | 'failureMetadata'): true; + hasService( + serviceName: 'config' | 'log' | 'lifecycle' | 'failureMetadata' | 'dockerServers' + ): true; hasService(serviceName: K): serviceName is K; hasService(serviceName: string): serviceName is Extract; @@ -73,6 +80,7 @@ export interface GenericFtrProviderContext< getService(serviceName: 'config'): Config; getService(serviceName: 'log'): ToolingLog; getService(serviceName: 'lifecycle'): Lifecycle; + getService(serviceName: 'dockerServers'): DockerServersService; getService(serviceName: 'failureMetadata'): FailureMetadata; getService(serviceName: T): ServiceMap[T]; diff --git a/test/functional/config.js b/test/functional/config.js index 0fbde95afe12c..807746b8a75a2 100644 --- a/test/functional/config.js +++ b/test/functional/config.js @@ -17,6 +17,9 @@ * under the License. */ +import { defineDockerServersConfig } from '@kbn/test'; +import { first, tap } from 'rxjs/operators'; + import { pageObjects } from './page_objects'; import { services } from './services'; @@ -39,6 +42,27 @@ export default async function({ readConfigFile }) { ], pageObjects, services, + + dockerServers: defineDockerServersConfig({ + helloWorld: { + image: 'docker.elastic.co/package-registry/package-registry:master', + portInContainer: '8080', + port: 8080, + waitForLogLine: 'package manifests loaded into memory', + async waitFor(server, logLine$) { + await logLine$ + .pipe( + first(line => line.includes('Package registry started')), + tap(line => { + console.log(`waitFor found log line "${line}"`); + console.log('marking server ready', server); + }) + ) + .toPromise(); + }, + }, + }), + servers: commonConfig.get('servers'), esTestCluster: commonConfig.get('esTestCluster'),