[ftr] add support for docker servers (#68173)

Co-authored-by: spalger <spalger@users.noreply.github.com>
This commit is contained in:
Spencer 2020-06-18 15:24:16 -07:00 committed by GitHub
parent 700f53d3a3
commit 051c93a6be
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 616 additions and 25 deletions

View file

@ -37,4 +37,5 @@ export { run, createFailError, createFlagError, combineErrors, isFailError, Flag
export { REPO_ROOT } from './repo_root';
export { KbnClient } from './kbn_client';
export * from './axios';
export * from './stdio';
export * from './ci_stats_reporter';

View file

@ -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;

View file

@ -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';

View file

@ -1,9 +1,9 @@
{
"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",
@ -13,6 +13,7 @@
"@babel/cli": "^7.10.1",
"@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/puppeteer": "^3.0.0",
"@types/strip-ansi": "^5.2.1",
@ -23,12 +24,14 @@
"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",
"puppeteer": "^3.3.0",
"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",

View file

@ -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']) {

View file

@ -29,6 +29,7 @@ import {
readProviderSpec,
setupMocha,
runTests,
DockerServersService,
Config,
SuiteTracker,
} from './lib';
@ -130,12 +131,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);

View file

@ -20,3 +20,4 @@
export { FunctionalTestRunner } from './functional_test_runner';
export { readConfigFile } from './lib';
export { runFtrCli } from './cli';
export * from './lib/docker_servers';

View file

@ -57,6 +57,27 @@ const appUrlPartsSchema = () =>
})
.default();
const requiredWhenEnabled = (schema: Joi.Schema) => {
return Joi.when('enabled', {
is: true,
then: schema.required(),
otherwise: schema.optional(),
});
};
const dockerServerSchema = () =>
Joi.object()
.keys({
enabled: Joi.boolean().required(),
image: requiredWhenEnabled(Joi.string()),
port: requiredWhenEnabled(Joi.number()),
portInContainer: requiredWhenEnabled(Joi.number()),
waitForLogLine: Joi.alternatives(Joi.object().type(RegExp), Joi.string()).optional(),
waitFor: Joi.func().optional(),
args: Joi.array().items(Joi.string()).optional(),
})
.default();
const defaultRelativeToConfigPath = (path: string) => {
const makeDefault: any = (_: any, options: any) => resolve(dirname(options.context.path), path);
makeDefault.description = `<config.js directory>/${path}`;
@ -259,5 +280,7 @@ export const schema = Joi.object()
disableTestUser: Joi.boolean(),
})
.default(),
dockerServers: Joi.object().pattern(Joi.string(), dockerServerSchema()).default(),
})
.default();

View file

@ -0,0 +1,113 @@
# 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: {
/** disable this docker server unless the user sets some flag/env var */
enabled: !!process.env.HELLO_WORLD_PORT,
/** the docker image to pull and run */
image: 'vad1mo/hello-world-rest',
/** The port that this application will be accessible via locally */
port: process.env.HELLO_WORLD_PORT,
/** The port that the container binds to in the container */
portInContainer: 5050,
/**
* 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/,
/**
* 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()
}
}
})
}
}
```
To consume the test server, use can use something like supertest to send request. Just make sure that you disable your test suite if the user doesn't choose to enable your docker server:
```ts
import makeSupertest from 'supertest-as-promised';
import { FtrProviderContext } from '../ftr_provider_context';
export default function ({ getService }: FtrProviderContext) {
const dockerServers = getService('dockerServers');
const log = getService('log');
const server = dockerServers.get('helloWorld');
const supertest = makeSupertest(server.url);
describe('test suite name', function () {
if (!server.enabled) {
log.warning(
'disabling tests because server is not enabled, set HELLO_WORLD_PORT to run them'
);
this.pending = true;
}
it('test name', async () => {
await supertest.get('/foo/bar').expect(200);
});
});
}
```
## `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.
### `isEnabled(name: string): boolean`
Determine if a named server is enabled.
### `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<string>) => Promise<boolean>;
}
```

View file

@ -0,0 +1,43 @@
/*
* 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';
/**
* Observe the logs for a container, reflecting the log lines
* to the ToolingLog and the returned Observable
*/
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<string>();
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$.asObservable();
}

View file

@ -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');
};
});
}

View file

@ -0,0 +1,45 @@
/*
* 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 DockerServerSpec {
enabled: boolean;
portInContainer: number;
port: number;
image: string;
waitForLogLine?: RegExp | string;
/** a function that should return an observable that will allow the tests to execute as soon as it emits anything */
waitFor?: (server: DockerServer, logLine$: Rx.Observable<string>) => Rx.Observable<unknown>;
/* additional command line arguments passed to docker run */
args?: string[];
}
export interface DockerServer extends DockerServerSpec {
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]: DockerServerSpec } | {}) {
return config;
}

View file

@ -0,0 +1,224 @@
/*
* 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 * as Rx from 'rxjs';
import { filter, take, map } 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, DockerServerSpec } from './define_docker_servers_config';
const SECOND = 1000;
export class DockerServersService {
private servers: DockerServer[];
constructor(
configs: {
[name: string]: DockerServerSpec;
},
private log: ToolingLog,
private lifecycle: Lifecycle
) {
this.servers = Object.entries(configs).map(([name, config]) => ({
...config,
name,
url: Url.format({
protocol: 'http:',
hostname: 'localhost',
port: config.port,
}),
}));
this.lifecycle.beforeTests.add(async () => {
await this.startServers();
});
}
isEnabled(name: string) {
return this.get(name).enabled;
}
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 dockerRun(server: DockerServer) {
const { args } = server;
try {
this.log.info(`[docker:${server.name}] running image "${server.image}"`);
const dockerArgs = [
'run',
'-dit',
args || [],
'-p',
`${server.port}:${server.portInContainer}`,
server.image,
].flat();
const res = await execa('docker', dockerArgs);
return res.stdout.trim();
} catch (error) {
if (error?.exitCode === 125 && error?.message.includes('port is already allocated')) {
throw new Error(`
[docker:${server.name}] Another process is already listening on port ${server.port}.
When this happens on CI it is usually because the port number isn't taking into
account parallel workers running on the same machine.
When this happens locally it is usually because the functional test runner didn't
have a chance to cleanup the running docker containers before being killed.
To see if this is the case:
1. make sure that there aren't other instances of the functional test runner running
2. run \`docker ps\` to see the containers running
3. if one of them lists that it is using port ${server.port} then kill it with \`docker kill "container ID"\`
`);
}
throw error;
}
}
private async startServer(server: DockerServer) {
const { log, lifecycle } = this;
const { image, name, 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
const containerId = await this.dockerRun(server);
lifecycle.cleanup.add(() => {
try {
execa.sync('docker', ['kill', containerId]);
execa.sync('docker', ['rm', containerId]);
} catch (error) {
if (
error.message.includes(`Container ${containerId} is not running`) ||
error.message.includes(`No such container: ${containerId}`)
) {
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);
});
if (!lifecycle.cleanup.triggered) {
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.
`);
}
function firstWithTimeout(source$: Rx.Observable<any>, errorMsg: string, ms = 30 * SECOND) {
return Rx.race(
source$.pipe(take(1)),
Rx.timer(ms).pipe(
map(() => {
throw new Error(`[docker:${name}] ${errorMsg} within ${ms / SECOND} seconds`);
})
)
);
}
await Rx.merge(
waitFor === undefined
? Rx.EMPTY
: firstWithTimeout(
waitFor(server, logLine$),
`didn't find a line containing "${waitForLogLine}"`
),
waitForLogLine === undefined
? Rx.EMPTY
: firstWithTimeout(
logLine$.pipe(
filter((line) =>
waitForLogLine instanceof RegExp
? waitForLogLine.test(line)
: line.includes(waitForLogLine)
)
),
`waitForLogLine didn't emit anything`
)
).toPromise();
}
private async startServers() {
await Promise.all(
this.servers.map(async (server) => {
if (server.enabled) {
await this.startServer(server);
}
})
);
}
}

View file

@ -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';

View file

@ -23,4 +23,5 @@ 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';
export { SuiteTracker } from './suite_tracker';

View file

@ -28,6 +28,8 @@ export type GetArgsType<T extends LifecyclePhase<any>> = T extends LifecyclePhas
export class LifecyclePhase<Args extends readonly any[]> {
private readonly handlers: Array<(...args: Args) => Promise<void> | void> = [];
public triggered = false;
private readonly beforeSubj = new Rx.Subject<void>();
public readonly before$ = this.beforeSubj.asObservable();
@ -46,29 +48,39 @@ export class LifecyclePhase<Args extends readonly any[]> {
this.handlers.push(fn);
}
public addSub(sub: Rx.Subscription) {
this.handlers.push(() => {
sub.unsubscribe();
});
}
public async trigger(...args: Args) {
if (this.beforeSubj.isStopped) {
if (this.options.singular && this.triggered) {
throw new Error(`singular lifecycle event can only be triggered once`);
}
this.triggered = true;
this.beforeSubj.next(undefined);
if (this.options.singular) {
this.beforeSubj.complete();
}
// 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) {

View file

@ -59,4 +59,5 @@ export { makeJunitReportPath } from './junit_report_path';
export { CI_PARALLEL_PROCESS_PREFIX } from './ci_parallel_process_prefix';
export * from './functional_test_runner';
export * from './page_load_metrics';

View file

@ -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<K extends keyof ServiceMap>(serviceName: K): serviceName is K;
hasService(serviceName: string): serviceName is Extract<keyof ServiceMap, string>;
@ -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<T extends keyof ServiceMap>(serviceName: T): ServiceMap[T];

View file

@ -40,6 +40,7 @@ export default async function ({ readConfigFile }) {
],
pageObjects,
services,
servers: commonConfig.get('servers'),
esTestCluster: commonConfig.get('esTestCluster'),

View file

@ -6,15 +6,15 @@ def label(size) {
case 'flyweight':
return 'flyweight'
case 's':
return 'linux && immutable'
return 'docker && linux && immutable'
case 's-highmem':
return 'tests-s'
return 'docker && tests-s'
case 'l':
return 'tests-l'
return 'docker && tests-l'
case 'xl':
return 'tests-xl'
return 'docker && tests-xl'
case 'xxl':
return 'tests-xxl'
return 'docker && tests-xxl'
}
error "unknown size '${size}'"

View file

@ -4,8 +4,6 @@
* you may not use this file except in compliance with the Elastic License.
*/
/* eslint-disable import/no-default-export */
import { resolve } from 'path';
import { services } from './services';