Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ftr] add support for docker services #61920

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ target
/x-pack/legacy/plugins/infra/public/graphql/types.ts
/x-pack/legacy/plugins/infra/server/graphql/types.ts
/x-pack/legacy/plugins/maps/public/vendor/**

/x-pack/test/epm_api_integration/apis/fixtures/**
# package overrides
/packages/eslint-config-kibana
/packages/kbn-interpreter/src/common/lib/grammar.js
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-dev-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
2 changes: 1 addition & 1 deletion packages/kbn-dev-utils/src/proc_runner/proc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions packages/kbn-dev-utils/src/stdio/index.ts
Original file line number Diff line number Diff line change
@@ -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';
27 changes: 15 additions & 12 deletions packages/kbn-test/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
6 changes: 4 additions & 2 deletions packages/kbn-test/src/functional_test_runner/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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']) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
readProviderSpec,
setupMocha,
runTests,
DockerServersService,
Config,
SuiteTracker,
} from './lib';
Expand Down Expand Up @@ -97,7 +98,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')),
]);
Expand Down Expand Up @@ -130,12 +140,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);
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-test/src/functional_test_runner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@
export { FunctionalTestRunner } from './functional_test_runner';
export { readConfigFile } from './lib';
export { runFtrCli } from './cli';
export * from './lib/docker_servers';
18 changes: 18 additions & 0 deletions packages/kbn-test/src/functional_test_runner/lib/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@ 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(),
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}`;
Expand Down Expand Up @@ -270,5 +284,9 @@ export const schema = Joi.object()
disableTestUser: Joi.boolean(),
})
.default(),

dockerServers: Joi.object()
.pattern(Joi.string(), dockerServerSchema())
.default(),
})
.default();
Original file line number Diff line number Diff line change
@@ -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<string>) => Promise<boolean>;
}
```
Original file line number Diff line number Diff line change
@@ -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();
}
Original file line number Diff line number Diff line change
@@ -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');
};
});
}
Loading