Skip to content

Commit 88d6003

Browse files
schlesseraclaude
andcommitted
Run parallel workers in throwaway Docker containers
With WP_CLI_TEST_DOCKER set and Docker available, every worker runs in its own container, next to its own database server container of the same type and version as the configured one. Workers share no network, temporary directory or database, so any of them can run any scenario, including the ones using fixed ports or fixed temporary paths. The database servers keep their data in memory. The containers run the same PHP version as the host, which the project's Composer dependencies are installed for, and use WordPress as downloaded once by the host. Where the image cannot be built or the database server cannot be identified, the scenarios run without Docker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 10e2ae7 commit 88d6003

4 files changed

Lines changed: 291 additions & 7 deletions

File tree

‎.readme-partials/USING.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,13 @@ Every worker but the first gets its own temporary directory, and with it its own
265265
266266
Scenarios that rely on resources shared across the system, such as a fixed port or a fixed path in the system's temporary directory, are all run by the first worker, one after the other. `composer behat-rerun` re-runs exactly the scenarios that failed in the last parallel run.
267267

268+
When Docker is available, set `WP_CLI_TEST_DOCKER` to run every worker in its own throwaway containers instead:
269+
```bash
270+
WP_CLI_TEST_DOCKER=1 WP_CLI_TEST_PARALLEL=4 composer behat
271+
```
272+
273+
Each worker then gets its own network, temporary directory and database server, of the same type and version as the one configured through the `WP_CLI_TEST_DB*` variables (or set the image through `WP_CLI_TEST_DOCKER_DB`, e.g. `mysql:8.0`). Nothing is shared between workers, so they can run any scenario. The database servers keep their data in memory. The containers run the same PHP version as the host, as the project's Composer dependencies are installed for it. Where the image cannot be built or the database server cannot be identified, the scenarios run without Docker.
274+
268275
### Linting the feature files
269276
270277
`composer lint-gherkin` checks `features/` with

‎bin/run-behat-tests‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,24 @@ done
286286

287287
case "$(uname -s)" in
288288
MINGW*|MSYS*|CYGWIN*)
289-
PARALLEL="";;
289+
PARALLEL=""
290+
unset WP_CLI_TEST_DOCKER;;
290291
esac
292+
293+
# With WP_CLI_TEST_DOCKER set, every worker runs in its own throwaway containers instead,
294+
# with a database server of the same type and version, so they share nothing.
295+
if [ -n "${WP_CLI_TEST_DOCKER-}" ]; then
296+
if ! docker info > /dev/null 2>&1; then
297+
echo "Warning: WP_CLI_TEST_DOCKER is set, but Docker is not available. Running the scenarios without it." >&2
298+
unset WP_CLI_TEST_DOCKER
299+
elif [[ "${WP_CLI_TEST_COVERAGE}" == "true" ]]; then
300+
echo "Code coverage is collected, running the scenarios without Docker." >&2
301+
unset WP_CLI_TEST_DOCKER
302+
else
303+
exec php "$WP_CLI_TESTS_ROOT"/utils/behat-parallel.php "${PARALLEL:-1}" --snippets-for="WP_CLI\Tests\Context\FeatureContext" "${FORMAT_ARGS[@]}" "$BEHAT_TAGS" --strict "${BEHAT_EXTRA_ARGS[@]}" -- "$@"
304+
fi
305+
fi
306+
291307
if [ -n "${PARALLEL}" ] && [ "${PARALLEL}" != "1" ]; then
292308
if ! is_numeric "${PARALLEL}"; then
293309
echo "Warning: WP_CLI_TEST_PARALLEL is not a number of workers, running the scenarios one after the other." >&2

‎utils/behat-parallel.php‎

Lines changed: 252 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,179 @@ static function ( $a, $b ) {
187187
return $shards;
188188
}
189189

190+
/**
191+
* Get the Docker image of the database server the tests run against on the host, so that the
192+
* containers test against the same type and version of database server.
193+
*
194+
* @return string|null Image name, or null if the server could not be identified.
195+
*/
196+
function wp_cli_tests_docker_db_image() {
197+
$image = getenv( 'WP_CLI_TEST_DOCKER_DB' );
198+
if ( is_string( $image ) && '' !== $image ) {
199+
return $image;
200+
}
201+
202+
$host = getenv( 'WP_CLI_TEST_DBHOST' ) ?: 'localhost';
203+
$parts = explode( ':', $host );
204+
$args = '-h' . escapeshellarg( $parts[0] );
205+
if ( isset( $parts[1] ) ) {
206+
$args .= is_numeric( $parts[1] ) ? ' --port=' . escapeshellarg( $parts[1] ) . ' --protocol=tcp' : ' --socket=' . escapeshellarg( $parts[1] );
207+
}
208+
$pass = getenv( 'WP_CLI_TEST_DBROOTPASS' );
209+
$args .= ' -u' . escapeshellarg( getenv( 'WP_CLI_TEST_DBROOTUSER' ) ?: 'root' ) . ( false !== $pass && '' !== $pass ? ' -p' . escapeshellarg( $pass ) : '' );
210+
211+
foreach ( [ 'mysql', 'mariadb' ] as $client ) {
212+
$version = (string) exec( "{$client} {$args} --skip-column-names -e 'SELECT VERSION()' 2>/dev/null" );
213+
if ( preg_match( '/^(\d+\.\d+)/', $version, $matches ) ) {
214+
return ( false !== stripos( $version, 'mariadb' ) ? 'mariadb:' : 'mysql:' ) . $matches[1];
215+
}
216+
}
217+
218+
return null;
219+
}
220+
221+
/**
222+
* Get the extra options a database server image needs to accept the test user's password.
223+
*
224+
* @param string $image
225+
* @return string
226+
*/
227+
function wp_cli_tests_docker_db_options( $image ) {
228+
// Throwaway databases do not need to wait for their writes to reach the disk.
229+
$options = '--innodb-flush-log-at-trx-commit=0 --sync-binlog=0';
230+
231+
if ( preg_match( '/^mysql:(\d+)\.(\d+)/', $image, $matches ) && (int) $matches[1] >= 8 ) {
232+
$options .= version_compare( "{$matches[1]}.{$matches[2]}", '8.4', '>=' )
233+
? ' --mysql-native-password=ON --authentication-policy=mysql_native_password'
234+
: ' --default-authentication-plugin=mysql_native_password';
235+
}
236+
237+
return $options;
238+
}
239+
240+
/**
241+
* Build the image the workers run in.
242+
*
243+
* @return string|null Image name, or null if it could not be built.
244+
*/
245+
function wp_cli_tests_docker_php_image() {
246+
$version = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;
247+
$image = "wp-cli-tests-php:{$version}";
248+
249+
exec( 'docker build -q -t ' . escapeshellarg( $image ) . ' --build-arg ' . escapeshellarg( "PHP_VERSION={$version}" ) . ' ' . escapeshellarg( __DIR__ . '/docker' ) . ' 2>&1', $output, $exit_code );
250+
251+
if ( 0 !== $exit_code ) {
252+
fwrite( STDERR, "Warning: Could not build the Docker image for PHP {$version}:\n" . implode( "\n", array_slice( $output, -5 ) ) . "\n" );
253+
return null;
254+
}
255+
256+
return $image;
257+
}
258+
259+
/**
260+
* Get the directories a container needs to see at their usual paths.
261+
*
262+
* @param string $base_dir
263+
* @return array<int|string, string> Paths to mount at the same path, and read-only sources keyed by source path.
264+
*/
265+
function wp_cli_tests_docker_mounts( $base_dir ) {
266+
$cwd = (string) getcwd();
267+
$mounts = [ $cwd, $base_dir ];
268+
269+
// Dependencies can be symlinked from outside the project, as in wp-cli/wp-cli-dev,
270+
// in which case the closest directory holding both has to be visible.
271+
foreach ( [ $cwd . '/vendor/autoload.php' ] as $path ) {
272+
$real = realpath( $path );
273+
if ( false === $real || 0 === strpos( $real . '/', $cwd . '/' ) ) {
274+
continue;
275+
}
276+
$common = $cwd;
277+
while ( 0 !== strpos( $real . '/', rtrim( $common, '/' ) . '/' ) && dirname( $common ) !== $common ) {
278+
$common = dirname( $common );
279+
}
280+
$mounts[] = '/' === $common ? dirname( $real ) : $common;
281+
}
282+
283+
$mounts = array_values( array_unique( $mounts ) );
284+
285+
// Download WordPress once for all containers, which only ever copy from it.
286+
$version = getenv( 'WP_VERSION' );
287+
if ( $version && ! getenv( 'WP_CLI_TEST_CORE_ZIP' ) ) {
288+
$cache = sys_get_temp_dir() . '/wp-cli-test-core-download-cache-' . $version;
289+
if ( ! is_readable( $cache . '/wp-includes/version.php' ) ) {
290+
exec( 'vendor/bin/wp core download --force --path=' . escapeshellarg( $cache ) . ' --version=' . escapeshellarg( $version ) . ' > /dev/null 2>&1' );
291+
}
292+
if ( is_readable( $cache . '/wp-includes/version.php' ) ) {
293+
$mounts[ $cache ] = '/tmp/wp-cli-test-core-download-cache-' . $version;
294+
}
295+
}
296+
297+
return $mounts;
298+
}
299+
300+
/**
301+
* Start the containers of a worker and get the command that runs its scenarios.
302+
*
303+
* @param string $name Name prefix of the worker's containers.
304+
* @param string $php_image
305+
* @param string|null $db_image Null when running on SQLite.
306+
* @param array<int|string, string> $mounts
307+
* @param array<string> $user_args
308+
* @param string $scenario_list File listing the worker's scenarios.
309+
* @return string
310+
*/
311+
function wp_cli_tests_docker_worker_command( $name, $php_image, $db_image, array $mounts, array $user_args, $scenario_list ) {
312+
$network = '';
313+
314+
if ( null !== $db_image ) {
315+
exec(
316+
'docker run -d --rm --name ' . escapeshellarg( "{$name}-db" )
317+
. ' --tmpfs /var/lib/mysql'
318+
. ' -e MYSQL_ROOT_PASSWORD=root -e MYSQL_USER=wp_cli_test -e MYSQL_PASSWORD=password1'
319+
. ' ' . escapeshellarg( $db_image ) . ' ' . wp_cli_tests_docker_db_options( $db_image ) . ' 2>&1'
320+
);
321+
// Share the database container's network, so the server is at 127.0.0.1 and nothing else is.
322+
$network = ' --network ' . escapeshellarg( "container:{$name}-db" );
323+
}
324+
325+
$env = [
326+
'HOME' => '/tmp/home',
327+
'WP_CLI_TEST_DBHOST' => '127.0.0.1:3306',
328+
'WP_CLI_TEST_DBROOTUSER' => 'root',
329+
'WP_CLI_TEST_DBROOTPASS' => 'root',
330+
];
331+
332+
foreach ( getenv() as $key => $value ) {
333+
if ( preg_match( '/^(WP_VERSION|NO_COLOR|CI|GITHUB_TOKEN|WP_CLI_TEST_(DBTYPE|OBJECT_CACHE|CORE_ZIP|QUIET|LOG_RUN_TIMES|PHP_TUNING|WP_VERSION_CACHE_TTL))$/', $key ) ) {
334+
$env[ $key ] = $value;
335+
}
336+
}
337+
338+
$command = 'docker run --rm --name ' . escapeshellarg( $name ) . $network
339+
. ' --tmpfs /tmp:exec,mode=1777'
340+
. ' -u ' . escapeshellarg( getmyuid() . ':' . getmygid() )
341+
. ' -w ' . escapeshellarg( (string) getcwd() );
342+
343+
foreach ( $mounts as $source => $target ) {
344+
if ( is_int( $source ) ) {
345+
$command .= ' -v ' . escapeshellarg( "{$target}:{$target}" );
346+
} else {
347+
$command .= ' -v ' . escapeshellarg( "{$source}:{$target}:ro" );
348+
}
349+
}
350+
351+
foreach ( $env as $key => $value ) {
352+
$command .= ' -e ' . escapeshellarg( "{$key}={$value}" );
353+
}
354+
355+
$inner = 'mkdir -p "$HOME"'
356+
// Wait for the database server, which takes a few seconds to start, before preparing it.
357+
. ( null !== $db_image ? ' && for i in $(seq 1 60); do mysql -h127.0.0.1 -P3306 --protocol=tcp -uroot -proot -e "SELECT 1" > /dev/null 2>&1 && break; sleep 1; done && vendor/bin/install-package-tests > /dev/null' : '' )
358+
. ' && vendor/bin/run-behat-tests ' . implode( ' ', array_map( 'escapeshellarg', array_merge( $user_args, [ $scenario_list ] ) ) );
359+
360+
return $command . ' ' . escapeshellarg( $php_image ) . ' sh -c ' . escapeshellarg( $inner );
361+
}
362+
190363
$args = array_slice( $argv, 1 );
191364

192365
$workers = (int) array_shift( $args );
@@ -196,9 +369,18 @@ static function ( $a, $b ) {
196369
$user_args = false === $separator ? [] : array_slice( $args, $separator + 1 );
197370
$all_args = array_merge( $behat_args, $user_args );
198371

372+
// Run every worker in its own throwaway containers, see run-behat-tests.
373+
$docker = (bool) getenv( 'WP_CLI_TEST_DOCKER' ) && DIRECTORY_SEPARATOR !== '\\';
374+
$rerun_paths = null;
375+
199376
// A rerun after a parallel run covers exactly the scenarios that failed in it.
200377
$rerun = array_search( '--rerun', $user_args, true );
201-
if ( false !== $rerun && file_exists( wp_cli_tests_failures_file() ) ) {
378+
if ( false !== $rerun && file_exists( wp_cli_tests_failures_file() ) && $docker ) {
379+
unset( $user_args[ $rerun ] );
380+
$user_args = array_values( $user_args );
381+
$rerun_paths = array_filter( explode( "\n", (string) file_get_contents( wp_cli_tests_failures_file() ) ) );
382+
unlink( wp_cli_tests_failures_file() );
383+
} elseif ( false !== $rerun && file_exists( wp_cli_tests_failures_file() ) ) {
202384
unset( $user_args[ $rerun ] );
203385
$failures = wp_cli_tests_failures_file();
204386
$copy = $failures . '.' . getmypid() . '.scenarios';
@@ -217,10 +399,25 @@ static function ( $a, $b ) {
217399
}
218400
}
219401

220-
if ( $workers < 2 || DIRECTORY_SEPARATOR === '\\' || $selects_scenarios ) {
402+
if ( ( $workers < 2 && ! $docker ) || DIRECTORY_SEPARATOR === '\\' || ( $selects_scenarios && null === $rerun_paths ) ) {
221403
wp_cli_tests_run_behat_and_exit( $all_args );
222404
}
223405

406+
$php_image = null;
407+
$db_image = null;
408+
if ( $docker ) {
409+
$php_image = wp_cli_tests_docker_php_image();
410+
$db_image = 'sqlite' === getenv( 'WP_CLI_TEST_DBTYPE' ) ? null : wp_cli_tests_docker_db_image();
411+
412+
if ( null === $php_image || ( null === $db_image && 'sqlite' !== getenv( 'WP_CLI_TEST_DBTYPE' ) ) ) {
413+
fwrite( STDERR, "Warning: Running the scenarios without Docker.\n" );
414+
$docker = false;
415+
if ( $workers < 2 || null !== $rerun_paths ) {
416+
wp_cli_tests_run_behat_and_exit( $all_args );
417+
}
418+
}
419+
}
420+
224421
require getcwd() . '/vendor/autoload.php';
225422

226423
$tags = '';
@@ -230,14 +427,43 @@ static function ( $a, $b ) {
230427
}
231428
}
232429

430+
// Containers check for PHP extensions themselves, as theirs can differ from the host's.
431+
if ( $docker ) {
432+
$tags = (string) preg_replace( '/(^|&&)~@require-extension-[A-Za-z0-9_]+/', '', $tags );
433+
$tags = trim( $tags, '&' );
434+
}
435+
233436
$features_folder = getenv( 'BEHAT_FEATURES_FOLDER' ) ?: 'features';
234-
$scenarios = wp_cli_tests_collect_scenarios( $features_folder, $tags );
235-
$workers = min( $workers, max( 1, count( $scenarios ) ) );
236437

237-
if ( $workers < 2 ) {
438+
if ( null !== $rerun_paths ) {
439+
$scenarios = array_map(
440+
static function ( $path ) {
441+
return [
442+
'path' => $path,
443+
'cost' => 1,
444+
'shared' => false,
445+
];
446+
},
447+
$rerun_paths
448+
);
449+
$workers = 1;
450+
} else {
451+
$scenarios = wp_cli_tests_collect_scenarios( $features_folder, $tags );
452+
}
453+
454+
$workers = min( max( 1, $workers ), max( 1, count( $scenarios ) ) );
455+
456+
if ( $workers < 2 && ! $docker ) {
238457
wp_cli_tests_run_behat_and_exit( $all_args );
239458
}
240459

460+
// Containers do not share ports or temporary directories, so any of them can run any scenario.
461+
if ( $docker ) {
462+
foreach ( $scenarios as $key => $scenario ) {
463+
$scenarios[ $key ]['shared'] = false;
464+
}
465+
}
466+
241467
$shards = wp_cli_tests_distribute( $scenarios, $workers );
242468
// Kept between runs, so that the workers' caches stay warm and failed scenarios can be inspected.
243469
$base_dir = sys_get_temp_dir() . '/wp-cli-test-parallel-' . substr( md5( (string) getcwd() ), 0, 8 );
@@ -247,7 +473,19 @@ static function ( $a, $b ) {
247473
mkdir( $base_dir, 0777, true );
248474
}
249475

250-
printf( "Running %d scenarios in %d parallel workers.\n", count( $scenarios ), $workers );
476+
printf( "Running %d scenarios in %d parallel workers%s.\n", count( $scenarios ), $workers, $docker ? ' in Docker containers' : '' );
477+
478+
$containers = [];
479+
if ( $docker ) {
480+
$mounts = wp_cli_tests_docker_mounts( $base_dir );
481+
register_shutdown_function(
482+
static function () use ( &$containers ) {
483+
foreach ( $containers as $container ) {
484+
exec( 'docker rm -f ' . escapeshellarg( $container ) . ' > /dev/null 2>&1' );
485+
}
486+
}
487+
);
488+
}
251489

252490
$procs = [];
253491
foreach ( $shards as $index => $paths ) {
@@ -267,6 +505,14 @@ static function ( $a, $b ) {
267505
$output = "{$base_dir}/worker-{$index}.log";
268506
$command = escapeshellarg( PHP_BINARY ) . ' vendor/bin/behat ' . implode( ' ', array_map( 'escapeshellarg', array_merge( $all_args, [ $list ] ) ) );
269507

508+
if ( $docker ) {
509+
$name = 'wp-cli-tests-' . substr( md5( $base_dir ), 0, 8 ) . "-{$index}";
510+
$containers[] = $name;
511+
$containers[] = "{$name}-db";
512+
$env = getenv();
513+
$command = wp_cli_tests_docker_worker_command( $name, (string) $php_image, $db_image, $mounts, array_values( $user_args ), $list );
514+
}
515+
270516
$procs[ $index ] = [
271517
'proc' => proc_open(
272518
$command,

‎utils/docker/Dockerfile‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Image for running the Behat scenarios of a WP-CLI package in throwaway containers.
2+
# Its PHP version has to match the one the package's Composer dependencies were installed for.
3+
ARG PHP_VERSION=8.3
4+
FROM php:${PHP_VERSION}-cli
5+
6+
RUN apt-get update \
7+
&& apt-get install -y --no-install-recommends \
8+
curl git jq less mariadb-client subversion unzip vim-tiny zip \
9+
libfreetype6-dev libjpeg-dev libpng-dev libzip-dev \
10+
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
11+
&& docker-php-ext-install exif gd mysqli pdo_mysql zip \
12+
&& ( php -m | grep -qi '^zend opcache$' || docker-php-ext-install opcache ) \
13+
&& rm -rf /var/lib/apt/lists/*
14+
15+
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

0 commit comments

Comments
 (0)