From 152c55ddfe25626ccbc27bb41b8198fbacbb1451 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sat, 31 Oct 2026 21:51:01 +0100 Subject: [PATCH 1/4] Copy files into one container per solution and docker exec each run Nothing is mounted from this machine any more, so the docker host can be another one. Runs of a folder share a container, removed with the sandbox. Composer and runs with exposed ports get their own, composer copies composer.lock (and vendor when there is no volume) back. --- src/Process/DockerSandbox.php | 173 ++++++++++++++++++++------ test/Process/DockerSandboxTest.php | 190 ++++++++++++++++++++--------- 2 files changed, 268 insertions(+), 95 deletions(-) diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index c4b9d9bf..eef9d1d7 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -19,6 +19,7 @@ final class DockerSandbox implements Sandbox private const COMPOSER_CACHE_VOLUME = 'php-school-composer-cache'; private ExecutableFinder $executableFinder; + private ?string $dockerPath = null; private string $basePath; private string $projectName; private string $portsNetwork; @@ -29,6 +30,11 @@ final class DockerSandbox implements Sandbox */ private array $vendorVolumes; + /** + * @var array folder => container + */ + private array $containers = []; + /** * @param array $vendorVolumes folder => volume, for runs in a folder directly inside it, so vendor * stays on the docker host between runs, eg. ['/tmp/php-school/' => 'php-school-vendor--'] @@ -78,23 +84,109 @@ public function getHost(): SandboxHost public function create(ProcessInput $processInput): DockerExecution { + $docker = $this->findDocker(); + $directory = $processInput->getWorkingDirectory(); $isComposer = $processInput->getExecutable() === 'composer'; + $vendorVolume = $this->vendorVolumes[dirname($directory)] ?? null; $args = $processInput->getArgs(); - $mounts = [$processInput->getWorkingDirectory() . ':/solution']; + $env = ['COMPOSER_HOME' => '/composer']; + if ($isComposer) { + //never run package plugins or scripts + $args = [...$args, '--no-plugins', '--no-scripts']; + } + + $envArgs = []; + foreach ([...$processInput->getEnv(), ...$env] as $key => $value) { + $envArgs[] = '-e'; + $envArgs[] = $key . '=' . $value; + } + + //composer needs the internet and exposed ports are set when the container is made, so they get their own. + //Other runs of a folder share one container, removed when the sandbox is + if ($isComposer || count($processInput->getExposedPorts()) > 0) { + $container = $this->containerName(); + $before = $this->startContainer($docker, $container, $processInput, $vendorVolume); + $after = [new Process([$docker, 'rm', '-f', '-v', $container])]; + + if ($isComposer) { + //ComposerCheck reads composer.lock and looks for vendor. Without a volume vendor comes back too, for + //the runs after + array_unshift($after, Process::fromShellCommandline(sprintf( + '%s exec %s tar -c -C /solution composer.lock %s | tar -x -C %s', + escapeshellarg($docker), + $container, + $vendorVolume === null ? 'vendor' : '', + escapeshellarg($directory), + ) . ($vendorVolume === null ? '' : sprintf('; mkdir -p %s', escapeshellarg($directory . '/vendor'))))); + } + } elseif (isset($this->containers[$directory])) { + $container = $this->containers[$directory]; + $before = []; + $after = []; + } else { + $container = $this->containerName(); + $this->containers[$directory] = $container; + $before = $this->startContainer($docker, $container, $processInput, $vendorVolume); + $after = []; + } + + $exec = new Process( + [ + $docker, + 'exec', + '-i', + ...$envArgs, + '-w', + '/solution', + $container, + //the docker client being killed does not stop the process, so enforce the timeout inside it too + 'timeout', + '-s', + 'KILL', + (string) self::TIMEOUT, + $processInput->getExecutable(), + ...$args, + ], + $this->basePath, + null, + $processInput->getInput(), + self::TIMEOUT + 5, + ); + + return new DockerExecution($exec, $before, $after); + } - $vendorVolume = $this->vendorVolumes[dirname($processInput->getWorkingDirectory())] ?? null; + public function __destruct() + { + foreach ($this->containers as $container) { + (new Process([$this->findDocker(), 'rm', '-f', '-v', $container]))->run(); + } + } + + private function containerName(): string + { + return 'php-school-' . bin2hex(random_bytes(8)); + } + + /** + * Steps that make an idle container and copy the folder into it. Nothing is mounted from this machine, so the + * docker host can be another one + * + * @return list + */ + private function startContainer(string $docker, string $container, ProcessInput $processInput, ?string $vendorVolume): array + { + $isComposer = $processInput->getExecutable() === 'composer'; + + $mounts = []; if ($vendorVolume !== null) { //only composer writes to it $mounts[] = $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro'); } - $env = ['COMPOSER_HOME' => '/composer']; - if ($isComposer) { - //we need to mount a volume for composer cache, and never run package plugins or scripts $mounts[] = self::COMPOSER_CACHE_VOLUME . ':/composer'; - $args = [...$args, '--no-plugins', '--no-scripts']; } $network = ['--network', 'none']; @@ -109,19 +201,27 @@ public function create(ProcessInput $processInput): DockerExecution } } - $envArgs = []; - foreach ([...$processInput->getEnv(), ...$env] as $key => $value) { - $envArgs[] = '-e'; - $envArgs[] = $key . '=' . $value; + //each entry rather than the folders, as tar would try to change the image's /solution and /solution/vendor, + //which it can not + $directory = $processInput->getWorkingDirectory(); + $files = []; + foreach (array_diff(scandir($directory) ?: [], ['.', '..']) as $file) { + if ($file !== 'vendor') { + $files[] = $file; + } elseif ($vendorVolume === null) { + //with a volume, vendor is already in it + foreach (array_diff(scandir($directory . '/vendor') ?: [], ['.', '..']) as $package) { + $files[] = 'vendor/' . $package; + } + } } - //no steps around it yet, create/cp/rm come when files are copied in instead of mounted - return new DockerExecution(new Process( - [ - $this->findDocker(), - 'run', - '--rm', - '-i', + return [ + new Process([ + $docker, + 'create', + '--name', + $container, '--init', '--user', getmyuid() . ':' . getmygid(), @@ -129,6 +229,11 @@ public function create(ProcessInput $processInput): DockerExecution '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', + //a volume of its own, so it can be written. It starts as the image's /solution, which a new vendor + //volume takes its permissions from. docker cp can not write to a read-only container, so files go + //in with tar + '-v', + '/solution', '--cap-drop', 'ALL', '--security-opt', @@ -141,33 +246,29 @@ public function create(ProcessInput $processInput): DockerExecution '256m', '--cpus', '1', - ...$envArgs, ...array_merge(...array_map(fn($mount) => ['-v', $mount], $mounts)), - '-w', - '/solution', $this->getImageName(), - //the docker client being killed does not stop the container, so enforce the timeout inside it too - 'timeout', - '-s', - 'KILL', - (string) self::TIMEOUT, - $processInput->getExecutable(), - ...$args, - ], - $this->basePath, - null, - $processInput->getInput(), - self::TIMEOUT + 5, - )); + 'sleep', + 'infinity', + ], $this->basePath), + new Process([$docker, 'start', $container], $this->basePath), + Process::fromShellCommandline(sprintf( + 'tar -c -C %s -- %s | %s exec -i %s tar -x -m -C /solution', + escapeshellarg($directory), + implode(' ', array_map('escapeshellarg', $files)), + escapeshellarg($docker), + $container, + ), $this->basePath), + ]; } private function findDocker(): string { - $dockerPath = $this->executableFinder->find('docker'); - if ($dockerPath === null) { + $this->dockerPath ??= $this->executableFinder->find('docker'); + if ($this->dockerPath === null) { throw ProcessNotFoundException::fromExecutable('docker'); } - return $dockerPath; + return $this->dockerPath; } } diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 399f27ab..eb42502e 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -2,6 +2,7 @@ namespace PhpSchool\PhpWorkshopTest\Process; +use PhpSchool\PhpWorkshop\Process\DockerExecution; use PhpSchool\PhpWorkshop\Process\DockerSandbox; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; @@ -23,25 +24,59 @@ private function factory(string $portsNetwork = 'bridge', string $portsHost = '1 /** * @param list $network - * @param list $extra env and mount args - * @param list $command + * @param list $mounts */ - private function expectedCommand(array $network, array $extra, array $command): string + private function expectedCreate(string $container, array $network, array $mounts = []): string { $parts = [ - '/usr/local/bin/docker', 'run', '--rm', '-i', '--init', '--user', getmyuid() . ':' . getmygid(), + '/usr/local/bin/docker', 'create', '--name', $container, '--init', '--user', getmyuid() . ':' . getmygid(), ...$network, - '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '--cap-drop', 'ALL', + '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-v', '/solution', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '64', '--memory', '256m', '--memory-swap', '256m', '--cpus', '1', - ...$extra, - '-w', '/solution', 'php8appreciate-runtime', 'timeout', '-s', 'KILL', '30', + ...array_merge(...array_map(fn($mount) => ['-v', $mount], $mounts)), + 'php8appreciate-runtime', 'sleep', 'infinity', + ]; + + return implode(' ', array_map(fn($p) => "'$p'", $parts)); + } + + /** + * @param list $env + * @param list $command + */ + private function expectedExec(string $container, array $env, array $command): string + { + $parts = [ + '/usr/local/bin/docker', 'exec', '-i', ...$env, '-e', 'COMPOSER_HOME=/composer', '-w', '/solution', + $container, 'timeout', '-s', 'KILL', '30', ...$command, ]; return implode(' ', array_map(fn($p) => "'$p'", $parts)); } + private function container(DockerExecution $execution): string + { + preg_match('/php-school-[0-9a-f]{16}/', $execution->process->getCommandLine(), $matches); + + return $matches[0]; + } + + /** + * @param list $files + */ + private function folder(array $files = ['solution.php']): string + { + $directory = sys_get_temp_dir() . '/' . bin2hex(random_bytes(4)) . '/' . bin2hex(random_bytes(4)); + foreach ($files as $file) { + @mkdir(dirname($directory . '/' . $file), 0777, true); + touch($directory . '/' . $file); + } + + return $directory; + } + public function testCreateThrowsExceptionIfDockerNotFound(): void { static::expectException(ProcessNotFoundException::class); @@ -60,50 +95,91 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void public function testCreateIsIsolatedWithNoNetwork(): void { - $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], []))->process; + $directory = $this->folder(); + $execution = $this->factory()->create(new ProcessInput('php', ['one', 'two'], $directory, [], [])); + $container = $this->container($execution); - $expected = $this->expectedCommand( - ['--network', 'none'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], - ['php', 'one', 'two'], + static::assertSame($this->expectedExec($container, [], ['php', 'one', 'two']), $execution->process->getCommandLine()); + static::assertSame('/docker-dir', $execution->process->getWorkingDirectory()); + static::assertSame(35.0, $execution->process->getTimeout()); + + static::assertSame($this->expectedCreate($container, ['--network', 'none']), $execution->before[0]->getCommandLine()); + static::assertSame("'/usr/local/bin/docker' 'start' '$container'", $execution->before[1]->getCommandLine()); + static::assertSame( + "tar -c -C '$directory' -- 'solution.php' | '/usr/local/bin/docker' exec -i $container tar -x -m -C /solution", + $execution->before[2]->getCommandLine(), ); - static::assertSame($expected, $process->getCommandLine()); - static::assertSame('/docker-dir', $process->getWorkingDirectory()); - static::assertSame(35.0, $process->getTimeout()); + static::assertSame([], $execution->after); } - public function testComposerGetsNetworkCacheAndNoPluginsOrScripts(): void + public function testRunsOfAFolderShareAContainerRemovedWithTheSandbox(): void { - $process = $this->factory()->create(new ProcessInput('composer', ['install'], __DIR__, [], []))->process; + $finder = $this->anyFinder(); + $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); + $directory = $this->folder(); + + $first = $sandbox->create(new ProcessInput('php', ['one'], $directory, [], [])); + $second = $sandbox->create(new ProcessInput('php', ['two'], $directory, [], [])); + $other = $sandbox->create(new ProcessInput('php', ['one'], $this->folder(), [], [])); + + static::assertSame($this->container($first), $this->container($second)); + static::assertSame([], $second->before); + static::assertNotSame($this->container($first), $this->container($other)); + } - $expected = $this->expectedCommand( - ['--network', 'bridge'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution', '-v', 'php-school-composer-cache:/composer'], - ['composer', 'install', '--no-plugins', '--no-scripts'], + public function testComposerGetsItsOwnContainerWithNetworkCacheAndNoPluginsOrScripts(): void + { + $directory = $this->folder(['composer.json']); + $execution = $this->factory()->create(new ProcessInput('composer', ['install'], $directory, [], [])); + $container = $this->container($execution); + + static::assertSame( + $this->expectedExec($container, [], ['composer', 'install', '--no-plugins', '--no-scripts']), + $execution->process->getCommandLine(), + ); + static::assertSame( + $this->expectedCreate($container, ['--network', 'bridge'], ['php-school-composer-cache:/composer']), + $execution->before[0]->getCommandLine(), ); - static::assertSame($expected, $process->getCommandLine()); + static::assertSame( + "'/usr/local/bin/docker' exec $container tar -c -C /solution composer.lock vendor | tar -x -C '$directory'", + $execution->after[0]->getCommandLine(), + ); + static::assertSame("'/usr/local/bin/docker' 'rm' '-f' '-v' '$container'", $execution->after[1]->getCommandLine()); } public function testVendorVolumeIsWritableForComposerOnly(): void { - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: ['/tmp/student' => 'vendor-student']); + $directory = $this->folder(['composer.json', 'vendor/autoload.php']); + $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: [dirname($directory) => 'vendor-student']); - $composer = $sandbox->create(new ProcessInput('composer', ['update'], '/tmp/student/abc', [], []))->process; - static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor' ", $composer->getCommandLine()); + $composer = $sandbox->create(new ProcessInput('composer', ['update'], $directory, [], [])); + static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor' ", $composer->before[0]->getCommandLine()); + //only the lock comes back, vendor stays in the volume + static::assertSame( + sprintf( + "'/usr/local/bin/docker' exec %s tar -c -C /solution composer.lock | tar -x -C '%s'; mkdir -p '%s/vendor'", + $this->container($composer), + $directory, + $directory, + ), + $composer->after[0]->getCommandLine(), + ); - $php = $sandbox->create(new ProcessInput('php', ['solution.php'], '/tmp/student/def', [], []))->process; - static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor:ro' ", $php->getCommandLine()); + $php = $sandbox->create(new ProcessInput('php', ['solution.php'], $directory, [], [])); + static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor:ro' ", $php->before[0]->getCommandLine()); + static::assertStringContainsString("-- 'composer.json' |", $php->before[2]->getCommandLine()); } public function testFoldersOutsideTheVendorVolumesKeepTheirOwnVendor(): void { $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: ['/tmp/student' => 'vendor-student']); - //eg. the reference solution, a sibling folder whose name starts the same, or the listed folder itself - foreach (['/tmp/reference/abc', '/tmp/student-2/abc', '/tmp/student'] as $directory) { - $process = $sandbox->create(new ProcessInput('composer', ['install'], $directory, [], []))->process; - static::assertStringNotContainsString('vendor-student', $process->getCommandLine()); - } + $directory = $this->folder(['solution.php', 'vendor/autoload.php']); + $execution = $sandbox->create(new ProcessInput('php', [], $directory, [], [])); + static::assertStringNotContainsString('vendor-student', $execution->before[0]->getCommandLine()); + //its contents, as tar can not change the image's vendor folder + static::assertStringContainsString("-- 'solution.php' 'vendor/autoload.php' |", $execution->before[2]->getCommandLine()); } private function anyFinder(): ExecutableFinder @@ -114,40 +190,38 @@ private function anyFinder(): ExecutableFinder return $finder; } - public function testExposedPortsArePublishedOnLoopbackOnly(): void + public function testExposedPortsGetTheirOwnContainerPublishedOnLoopbackOnly(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $sandbox = $this->factory(); + $directory = $this->folder(); + $execution = $sandbox->create(new ProcessInput('php', [], $directory, [], [8000])); + $container = $this->container($execution); - $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], - ['php'], + static::assertSame( + $this->expectedCreate($container, ['--network', 'bridge', '-p', '127.0.0.1:8000:8000']), + $execution->before[0]->getCommandLine(), ); - static::assertSame($expected, $process->getCommandLine()); + static::assertSame("'/usr/local/bin/docker' 'rm' '-f' '-v' '$container'", $execution->after[0]->getCommandLine()); + + $next = $sandbox->create(new ProcessInput('php', [], $directory, [], [8000])); + static::assertNotSame($container, $this->container($next)); } public function testExposedPortsUseTheGivenNetwork(): void { - $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $execution = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], $this->folder(), [], [8000])); - $expected = $this->expectedCommand( - ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], - ['php'], + static::assertStringContainsString( + "'--network' 'php-school-sandbox' '-p' '127.0.0.1:8000:8000'", + $execution->before[0]->getCommandLine(), ); - static::assertSame($expected, $process->getCommandLine()); } public function testExposedPortsArePublishedOnTheGivenHost(): void { - $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], $this->folder(), [], [8000])); - $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], - ['php'], - ); - static::assertSame($expected, $process->getCommandLine()); + static::assertStringContainsString("'-p' '172.19.0.2:8000:8000'", $execution->before[0]->getCommandLine()); } public function testHostIsWherePortsArePublished(): void @@ -159,19 +233,17 @@ public function testHostIsWherePortsArePublished(): void public function testCreateWithEnv(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], []))->process; + $execution = $this->factory()->create(new ProcessInput('php', [], $this->folder(), ['SOME_VAR' => 'value'], [])); - $expected = $this->expectedCommand( - ['--network', 'none'], - ['-e', 'SOME_VAR=value', '-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution'], - ['php'], + static::assertSame( + $this->expectedExec($this->container($execution), ['-e', 'SOME_VAR=value'], ['php']), + $execution->process->getCommandLine(), ); - static::assertSame($expected, $process->getCommandLine()); } public function testWithInput(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [], 'someinput'))->process; + $process = $this->factory()->create(new ProcessInput('php', [], $this->folder(), [], [], 'someinput'))->process; static::assertSame('someinput', $process->getInput()); } From a589ab9cf470758572b8ecfa8023b3b4d0ad47c4 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 08:05:08 +0100 Subject: [PATCH 2/4] Tidy DockerSandbox: isolation flags in a constant, copy in/out helpers, flag pairs on one line --- src/Process/DockerSandbox.php | 262 ++++++++++++++--------------- test/Process/DockerSandboxTest.php | 52 +++--- 2 files changed, 145 insertions(+), 169 deletions(-) diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index eef9d1d7..e00fa1bf 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -17,6 +17,17 @@ final class DockerSandbox implements Sandbox private const TIMEOUT = 30; //a named volume, so it lives on the docker host, which may not be this machine private const COMPOSER_CACHE_VOLUME = 'php-school-composer-cache'; + private const ISOLATION = [ + '--init', + '--read-only', + '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', + '--cap-drop', 'ALL', + '--security-opt', 'no-new-privileges', + '--pids-limit', '64', + '--memory', '256m', + '--memory-swap', '256m', + '--cpus', '1', + ]; private ExecutableFinder $executableFinder; private ?string $dockerPath = null; @@ -68,13 +79,7 @@ public function getImageName(): string */ public function createBuildProcess(): Process { - return new Process( - [$this->findDocker(), 'build', '-t', $this->getImageName(), '.docker/runtime'], - $this->basePath, - null, - null, - 300, - ); + return $this->docker(['build', '-t', $this->getImageName(), '.docker/runtime'], null, 300); } public function getHost(): SandboxHost @@ -84,72 +89,45 @@ public function getHost(): SandboxHost public function create(ProcessInput $processInput): DockerExecution { - $docker = $this->findDocker(); $directory = $processInput->getWorkingDirectory(); $isComposer = $processInput->getExecutable() === 'composer'; - $vendorVolume = $this->vendorVolumes[dirname($directory)] ?? null; - - $args = $processInput->getArgs(); - $env = ['COMPOSER_HOME' => '/composer']; - if ($isComposer) { - //never run package plugins or scripts - $args = [...$args, '--no-plugins', '--no-scripts']; - } - - $envArgs = []; - foreach ([...$processInput->getEnv(), ...$env] as $key => $value) { - $envArgs[] = '-e'; - $envArgs[] = $key . '=' . $value; - } - //composer needs the internet and exposed ports are set when the container is made, so they get their own. - //Other runs of a folder share one container, removed when the sandbox is + //composer needs the internet and ports are published when a container is made, so they get a container of + //their own. Other runs of a folder share one, removed with the sandbox if ($isComposer || count($processInput->getExposedPorts()) > 0) { - $container = $this->containerName(); - $before = $this->startContainer($docker, $container, $processInput, $vendorVolume); - $after = [new Process([$docker, 'rm', '-f', '-v', $container])]; - - if ($isComposer) { - //ComposerCheck reads composer.lock and looks for vendor. Without a volume vendor comes back too, for - //the runs after - array_unshift($after, Process::fromShellCommandline(sprintf( - '%s exec %s tar -c -C /solution composer.lock %s | tar -x -C %s', - escapeshellarg($docker), - $container, - $vendorVolume === null ? 'vendor' : '', - escapeshellarg($directory), - ) . ($vendorVolume === null ? '' : sprintf('; mkdir -p %s', escapeshellarg($directory . '/vendor'))))); - } + $container = $this->newContainerName(); + $before = $this->startContainer($container, $processInput); + $after = [$this->docker(['rm', '-f', '-v', $container])]; } elseif (isset($this->containers[$directory])) { $container = $this->containers[$directory]; $before = []; $after = []; } else { - $container = $this->containerName(); - $this->containers[$directory] = $container; - $before = $this->startContainer($docker, $container, $processInput, $vendorVolume); + $container = $this->containers[$directory] = $this->newContainerName(); + $before = $this->startContainer($container, $processInput); $after = []; } - $exec = new Process( + $args = $processInput->getArgs(); + if ($isComposer) { + //never run package plugins or scripts + $args = [...$args, '--no-plugins', '--no-scripts']; + array_unshift($after, $this->copyOut($container, $directory)); + } + + $env = []; + foreach ([...$processInput->getEnv(), 'COMPOSER_HOME' => '/composer'] as $key => $value) { + $env[] = '-e'; + $env[] = $key . '=' . $value; + } + + $exec = $this->docker( [ - $docker, - 'exec', - '-i', - ...$envArgs, - '-w', - '/solution', - $container, + 'exec', '-i', ...$env, '-w', '/solution', $container, //the docker client being killed does not stop the process, so enforce the timeout inside it too - 'timeout', - '-s', - 'KILL', - (string) self::TIMEOUT, - $processInput->getExecutable(), - ...$args, + 'timeout', '-s', 'KILL', (string) self::TIMEOUT, + $processInput->getExecutable(), ...$args, ], - $this->basePath, - null, $processInput->getInput(), self::TIMEOUT + 5, ); @@ -160,108 +138,116 @@ public function create(ProcessInput $processInput): DockerExecution public function __destruct() { foreach ($this->containers as $container) { - (new Process([$this->findDocker(), 'rm', '-f', '-v', $container]))->run(); + $this->docker(['rm', '-f', '-v', $container])->run(); } } - private function containerName(): string - { - return 'php-school-' . bin2hex(random_bytes(8)); - } - /** - * Steps that make an idle container and copy the folder into it. Nothing is mounted from this machine, so the - * docker host can be another one + * Make an idle container and copy the folder into it. Nothing is mounted from this machine, so the docker host + * can be another one. * * @return list */ - private function startContainer(string $docker, string $container, ProcessInput $processInput, ?string $vendorVolume): array + private function startContainer(string $container, ProcessInput $processInput): array { $isComposer = $processInput->getExecutable() === 'composer'; + $vendorVolume = $this->vendorVolume($processInput->getWorkingDirectory()); - $mounts = []; - if ($vendorVolume !== null) { - //only composer writes to it - $mounts[] = $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro'); - } - + $options = ['--network', 'none']; if ($isComposer) { - $mounts[] = self::COMPOSER_CACHE_VOLUME . ':/composer'; - } - - $network = ['--network', 'none']; - if ($isComposer) { - //composer needs to download packages - $network = ['--network', 'bridge']; + //composer downloads packages + $options = ['--network', 'bridge', '-v', self::COMPOSER_CACHE_VOLUME . ':/composer']; } elseif (count($processInput->getExposedPorts()) > 0) { - $network = ['--network', $this->portsNetwork]; + $options = ['--network', $this->portsNetwork]; foreach ($processInput->getExposedPorts() as $port) { - $network[] = '-p'; - $network[] = $this->portsHost . ':' . $port . ':' . $port; + array_push($options, '-p', $this->portsHost . ':' . $port . ':' . $port); } } - //each entry rather than the folders, as tar would try to change the image's /solution and /solution/vendor, - //which it can not - $directory = $processInput->getWorkingDirectory(); - $files = []; - foreach (array_diff(scandir($directory) ?: [], ['.', '..']) as $file) { - if ($file !== 'vendor') { - $files[] = $file; - } elseif ($vendorVolume === null) { - //with a volume, vendor is already in it - foreach (array_diff(scandir($directory . '/vendor') ?: [], ['.', '..']) as $package) { - $files[] = 'vendor/' . $package; - } - } + if ($vendorVolume !== null) { + //only composer writes to it + array_push($options, '-v', $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro')); } return [ - new Process([ - $docker, - 'create', - '--name', - $container, - '--init', - '--user', - getmyuid() . ':' . getmygid(), - ...$network, - '--read-only', - '--tmpfs', - '/tmp:rw,nosuid,nodev,size=64m', - //a volume of its own, so it can be written. It starts as the image's /solution, which a new vendor - //volume takes its permissions from. docker cp can not write to a read-only container, so files go - //in with tar - '-v', - '/solution', - '--cap-drop', - 'ALL', - '--security-opt', - 'no-new-privileges', - '--pids-limit', - '64', - '--memory', - '256m', - '--memory-swap', - '256m', - '--cpus', - '1', - ...array_merge(...array_map(fn($mount) => ['-v', $mount], $mounts)), - $this->getImageName(), - 'sleep', - 'infinity', - ], $this->basePath), - new Process([$docker, 'start', $container], $this->basePath), - Process::fromShellCommandline(sprintf( - 'tar -c -C %s -- %s | %s exec -i %s tar -x -m -C /solution', - escapeshellarg($directory), - implode(' ', array_map('escapeshellarg', $files)), - escapeshellarg($docker), - $container, - ), $this->basePath), + $this->docker([ + 'create', '--name', $container, '--user', getmyuid() . ':' . getmygid(), + ...self::ISOLATION, + //a volume of its own, so it can be written. It starts as the image's /solution, so a new vendor + //volume gets its permissions + '-v', '/solution', + ...$options, + $this->getImageName(), 'sleep', 'infinity', + ]), + $this->docker(['start', $container]), + $this->copyIn($container, $processInput->getWorkingDirectory()), ]; } + /** + * With tar, as docker cp can not write to a read-only container. + */ + private function copyIn(string $container, string $directory): Process + { + //each entry rather than the folders, as tar can not change the image's /solution and /solution/vendor. + //A vendor volume already has vendor + $files = array_diff(scandir($directory) ?: [], ['.', '..', 'vendor']); + if ($this->vendorVolume($directory) === null && is_dir($directory . '/vendor')) { + foreach (array_diff(scandir($directory . '/vendor') ?: [], ['.', '..']) as $package) { + $files[] = 'vendor/' . $package; + } + } + + return $this->pipe( + ['tar', '-c', '-C', $directory, '--', ...$files], + [$this->findDocker(), 'exec', '-i', $container, 'tar', '-x', '-m', '-C', '/solution'], + ); + } + + /** + * composer.lock for ComposerCheck, and vendor for the runs after. A vendor volume keeps vendor, so only the empty + * folder comes back, which ComposerCheck looks for. + */ + private function copyOut(string $container, string $directory): Process + { + $vendor = $this->vendorVolume($directory) === null ? ['vendor'] : ['--no-recursion', 'vendor']; + + return $this->pipe( + [$this->findDocker(), 'exec', $container, 'tar', '-c', '-C', '/solution', 'composer.lock', ...$vendor], + ['tar', '-x', '-C', $directory], + ); + } + + /** + * @param list $from + * @param list $to + */ + private function pipe(array $from, array $to): Process + { + //Process escapes each argument + $commandLine = (new Process($from))->getCommandLine() . ' | ' . (new Process($to))->getCommandLine(); + + return Process::fromShellCommandline($commandLine, $this->basePath); + } + + /** + * @param list $args + */ + private function docker(array $args, ?string $input = null, ?float $timeout = 60): Process + { + return new Process([$this->findDocker(), ...$args], $this->basePath, null, $input, $timeout); + } + + private function vendorVolume(string $directory): ?string + { + return $this->vendorVolumes[dirname($directory)] ?? null; + } + + private function newContainerName(): string + { + return 'php-school-' . bin2hex(random_bytes(8)); + } + private function findDocker(): string { $this->dockerPath ??= $this->executableFinder->find('docker'); diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index eb42502e..54de2514 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -19,22 +19,20 @@ private function factory(string $portsNetwork = 'bridge', string $portsHost = '1 ->with('docker') ->willReturn('/usr/local/bin/docker'); - return new DockerSandbox('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost); + return new DockerSandbox(__DIR__, 'PHP8Appreciate', $finder, $portsNetwork, $portsHost); } /** - * @param list $network - * @param list $mounts + * @param list $network network, ports and their volumes */ - private function expectedCreate(string $container, array $network, array $mounts = []): string + private function expectedCreate(string $container, array $network): string { $parts = [ - '/usr/local/bin/docker', 'create', '--name', $container, '--init', '--user', getmyuid() . ':' . getmygid(), - ...$network, - '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-v', '/solution', '--cap-drop', 'ALL', + '/usr/local/bin/docker', 'create', '--name', $container, '--user', getmyuid() . ':' . getmygid(), + '--init', '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '64', '--memory', '256m', '--memory-swap', '256m', - '--cpus', '1', - ...array_merge(...array_map(fn($mount) => ['-v', $mount], $mounts)), + '--cpus', '1', '-v', '/solution', + ...$network, 'php8appreciate-runtime', 'sleep', 'infinity', ]; @@ -87,7 +85,7 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void ->with('docker') ->willReturn(null); - $factory = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); + $factory = new DockerSandbox(__DIR__, 'php8appreciate', $finder); $input = new ProcessInput('composer', [], __DIR__, [], []); $factory->create($input); @@ -100,13 +98,13 @@ public function testCreateIsIsolatedWithNoNetwork(): void $container = $this->container($execution); static::assertSame($this->expectedExec($container, [], ['php', 'one', 'two']), $execution->process->getCommandLine()); - static::assertSame('/docker-dir', $execution->process->getWorkingDirectory()); + static::assertSame(__DIR__, $execution->process->getWorkingDirectory()); static::assertSame(35.0, $execution->process->getTimeout()); static::assertSame($this->expectedCreate($container, ['--network', 'none']), $execution->before[0]->getCommandLine()); static::assertSame("'/usr/local/bin/docker' 'start' '$container'", $execution->before[1]->getCommandLine()); static::assertSame( - "tar -c -C '$directory' -- 'solution.php' | '/usr/local/bin/docker' exec -i $container tar -x -m -C /solution", + "'tar' '-c' '-C' '$directory' '--' 'solution.php' | '/usr/local/bin/docker' 'exec' '-i' '$container' 'tar' '-x' '-m' '-C' '/solution'", $execution->before[2]->getCommandLine(), ); static::assertSame([], $execution->after); @@ -115,7 +113,7 @@ public function testCreateIsIsolatedWithNoNetwork(): void public function testRunsOfAFolderShareAContainerRemovedWithTheSandbox(): void { $finder = $this->anyFinder(); - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); + $sandbox = new DockerSandbox(__DIR__, 'php8appreciate', $finder); $directory = $this->folder(); $first = $sandbox->create(new ProcessInput('php', ['one'], $directory, [], [])); @@ -138,11 +136,11 @@ public function testComposerGetsItsOwnContainerWithNetworkCacheAndNoPluginsOrScr $execution->process->getCommandLine(), ); static::assertSame( - $this->expectedCreate($container, ['--network', 'bridge'], ['php-school-composer-cache:/composer']), + $this->expectedCreate($container, ['--network', 'bridge', '-v', 'php-school-composer-cache:/composer']), $execution->before[0]->getCommandLine(), ); static::assertSame( - "'/usr/local/bin/docker' exec $container tar -c -C /solution composer.lock vendor | tar -x -C '$directory'", + "'/usr/local/bin/docker' 'exec' '$container' 'tar' '-c' '-C' '/solution' 'composer.lock' 'vendor' | 'tar' '-x' '-C' '$directory'", $execution->after[0]->getCommandLine(), ); static::assertSame("'/usr/local/bin/docker' 'rm' '-f' '-v' '$container'", $execution->after[1]->getCommandLine()); @@ -151,35 +149,27 @@ public function testComposerGetsItsOwnContainerWithNetworkCacheAndNoPluginsOrScr public function testVendorVolumeIsWritableForComposerOnly(): void { $directory = $this->folder(['composer.json', 'vendor/autoload.php']); - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: [dirname($directory) => 'vendor-student']); + $sandbox = new DockerSandbox(__DIR__, 'php8appreciate', $this->anyFinder(), vendorVolumes: [dirname($directory) => 'vendor-student']); $composer = $sandbox->create(new ProcessInput('composer', ['update'], $directory, [], [])); static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor' ", $composer->before[0]->getCommandLine()); - //only the lock comes back, vendor stays in the volume - static::assertSame( - sprintf( - "'/usr/local/bin/docker' exec %s tar -c -C /solution composer.lock | tar -x -C '%s'; mkdir -p '%s/vendor'", - $this->container($composer), - $directory, - $directory, - ), - $composer->after[0]->getCommandLine(), - ); + //vendor stays in the volume, only the folder comes back + static::assertStringContainsString("'composer.lock' '--no-recursion' 'vendor' |", $composer->after[0]->getCommandLine()); $php = $sandbox->create(new ProcessInput('php', ['solution.php'], $directory, [], [])); static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor:ro' ", $php->before[0]->getCommandLine()); - static::assertStringContainsString("-- 'composer.json' |", $php->before[2]->getCommandLine()); + static::assertStringContainsString("'--' 'composer.json' |", $php->before[2]->getCommandLine()); } public function testFoldersOutsideTheVendorVolumesKeepTheirOwnVendor(): void { - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', $this->anyFinder(), vendorVolumes: ['/tmp/student' => 'vendor-student']); + $sandbox = new DockerSandbox(__DIR__, 'php8appreciate', $this->anyFinder(), vendorVolumes: ['/tmp/student' => 'vendor-student']); $directory = $this->folder(['solution.php', 'vendor/autoload.php']); $execution = $sandbox->create(new ProcessInput('php', [], $directory, [], [])); static::assertStringNotContainsString('vendor-student', $execution->before[0]->getCommandLine()); //its contents, as tar can not change the image's vendor folder - static::assertStringContainsString("-- 'solution.php' 'vendor/autoload.php' |", $execution->before[2]->getCommandLine()); + static::assertStringContainsString("'--' 'solution.php' 'vendor/autoload.php' |", $execution->before[2]->getCommandLine()); } private function anyFinder(): ExecutableFinder @@ -226,7 +216,7 @@ public function testExposedPortsArePublishedOnTheGivenHost(): void public function testHostIsWherePortsArePublished(): void { - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', null, 'bridge', '172.19.0.2'); + $sandbox = new DockerSandbox(__DIR__, 'php8appreciate', null, 'bridge', '172.19.0.2'); static::assertSame('172.19.0.2', $sandbox->getHost()->getAddress()); } @@ -256,6 +246,6 @@ public function testCreateBuildProcess(): void "'/usr/local/bin/docker' 'build' '-t' 'php8appreciate-runtime' '.docker/runtime'", $process->getCommandLine(), ); - static::assertSame('/docker-dir', $process->getWorkingDirectory()); + static::assertSame(__DIR__, $process->getWorkingDirectory()); } } From 74e0a22b204f5a6f86e1a251bb6a610fe1d809af Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 08:11:07 +0100 Subject: [PATCH 3/4] Simplify DockerSandbox: early returns, copy files only, always copy vendor back from composer --- src/Process/DockerSandbox.php | 146 ++++++++++++++--------------- test/Process/DockerSandboxTest.php | 14 +-- 2 files changed, 77 insertions(+), 83 deletions(-) diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index e00fa1bf..0eddbd37 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -90,55 +90,32 @@ public function getHost(): SandboxHost public function create(ProcessInput $processInput): DockerExecution { $directory = $processInput->getWorkingDirectory(); + $isComposer = $processInput->getExecutable() === 'composer'; - //composer needs the internet and ports are published when a container is made, so they get a container of - //their own. Other runs of a folder share one, removed with the sandbox + //composer needs the internet, and published ports would clash between folders, so they get a container just + //for the run if ($isComposer || count($processInput->getExposedPorts()) > 0) { $container = $this->newContainerName(); - $before = $this->startContainer($container, $processInput); - $after = [$this->docker(['rm', '-f', '-v', $container])]; - } elseif (isset($this->containers[$directory])) { - $container = $this->containers[$directory]; - $before = []; - $after = []; - } else { - $container = $this->containers[$directory] = $this->newContainerName(); - $before = $this->startContainer($container, $processInput); - $after = []; - } + $after = $isComposer ? [$this->copyOut($container, $directory), $this->remove($container)] : [$this->remove($container)]; - $args = $processInput->getArgs(); - if ($isComposer) { - //never run package plugins or scripts - $args = [...$args, '--no-plugins', '--no-scripts']; - array_unshift($after, $this->copyOut($container, $directory)); + return new DockerExecution($this->exec($container, $processInput), $this->start($container, $processInput), $after); } - $env = []; - foreach ([...$processInput->getEnv(), 'COMPOSER_HOME' => '/composer'] as $key => $value) { - $env[] = '-e'; - $env[] = $key . '=' . $value; + //other runs of a folder share one, removed with the sandbox + if (isset($this->containers[$directory])) { + return new DockerExecution($this->exec($this->containers[$directory], $processInput)); } - $exec = $this->docker( - [ - 'exec', '-i', ...$env, '-w', '/solution', $container, - //the docker client being killed does not stop the process, so enforce the timeout inside it too - 'timeout', '-s', 'KILL', (string) self::TIMEOUT, - $processInput->getExecutable(), ...$args, - ], - $processInput->getInput(), - self::TIMEOUT + 5, - ); + $container = $this->containers[$directory] = $this->newContainerName(); - return new DockerExecution($exec, $before, $after); + return new DockerExecution($this->exec($container, $processInput), $this->start($container, $processInput)); } public function __destruct() { foreach ($this->containers as $container) { - $this->docker(['rm', '-f', '-v', $container])->run(); + $this->remove($container)->run(); } } @@ -148,26 +125,24 @@ public function __destruct() * * @return list */ - private function startContainer(string $container, ProcessInput $processInput): array + private function start(string $container, ProcessInput $processInput): array { $isComposer = $processInput->getExecutable() === 'composer'; + $ports = $processInput->getExposedPorts(); $vendorVolume = $this->vendorVolume($processInput->getWorkingDirectory()); - $options = ['--network', 'none']; - if ($isComposer) { - //composer downloads packages - $options = ['--network', 'bridge', '-v', self::COMPOSER_CACHE_VOLUME . ':/composer']; - } elseif (count($processInput->getExposedPorts()) > 0) { - $options = ['--network', $this->portsNetwork]; - foreach ($processInput->getExposedPorts() as $port) { - array_push($options, '-p', $this->portsHost . ':' . $port . ':' . $port); - } - } + $network = match (true) { + $isComposer => ['--network', 'bridge', '-v', self::COMPOSER_CACHE_VOLUME . ':/composer'], + count($ports) > 0 => ['--network', $this->portsNetwork, ...$this->publish($ports)], + default => ['--network', 'none'], + }; - if ($vendorVolume !== null) { - //only composer writes to it - array_push($options, '-v', $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro')); - } + //only composer writes to it + $vendor = match (true) { + $vendorVolume === null => [], + $isComposer => ['-v', $vendorVolume . ':/solution/vendor'], + default => ['-v', $vendorVolume . ':/solution/vendor:ro'], + }; return [ $this->docker([ @@ -176,7 +151,8 @@ private function startContainer(string $container, ProcessInput $processInput): //a volume of its own, so it can be written. It starts as the image's /solution, so a new vendor //volume gets its permissions '-v', '/solution', - ...$options, + ...$network, + ...$vendor, $this->getImageName(), 'sleep', 'infinity', ]), $this->docker(['start', $container]), @@ -184,50 +160,68 @@ private function startContainer(string $container, ProcessInput $processInput): ]; } + private function exec(string $container, ProcessInput $processInput): Process + { + $args = $processInput->getArgs(); + if ($processInput->getExecutable() === 'composer') { + //never run package plugins or scripts + $args = [...$args, '--no-plugins', '--no-scripts']; + } + + $env = []; + foreach ([...$processInput->getEnv(), 'COMPOSER_HOME' => '/composer'] as $key => $value) { + array_push($env, '-e', $key . '=' . $value); + } + + return $this->docker( + [ + 'exec', '-i', ...$env, '-w', '/solution', $container, + //the docker client being killed does not stop the process, so enforce the timeout inside it too + 'timeout', '-s', 'KILL', (string) self::TIMEOUT, + $processInput->getExecutable(), ...$args, + ], + $processInput->getInput(), + self::TIMEOUT + 5, + ); + } + /** - * With tar, as docker cp can not write to a read-only container. + * With tar, as docker cp can not write to a read-only container. Files only, as tar can not change the folders + * the image made, /solution and /solution/vendor. A vendor volume already has vendor. */ private function copyIn(string $container, string $directory): Process { - //each entry rather than the folders, as tar can not change the image's /solution and /solution/vendor. - //A vendor volume already has vendor - $files = array_diff(scandir($directory) ?: [], ['.', '..', 'vendor']); - if ($this->vendorVolume($directory) === null && is_dir($directory . '/vendor')) { - foreach (array_diff(scandir($directory . '/vendor') ?: [], ['.', '..']) as $package) { - $files[] = 'vendor/' . $package; - } - } + $find = $this->vendorVolume($directory) === null ? 'find . ! -type d' : 'find . -path ./vendor -prune -o ! -type d -print'; - return $this->pipe( - ['tar', '-c', '-C', $directory, '--', ...$files], - [$this->findDocker(), 'exec', '-i', $container, 'tar', '-x', '-m', '-C', '/solution'], + return Process::fromShellCommandline( + sprintf('%s | tar -c -T - | %s exec -i %s tar -x -C /solution', $find, escapeshellarg($this->findDocker()), $container), + $directory, ); } /** - * composer.lock for ComposerCheck, and vendor for the runs after. A vendor volume keeps vendor, so only the empty - * folder comes back, which ComposerCheck looks for. + * composer.lock for ComposerCheck, and vendor for the runs after. */ private function copyOut(string $container, string $directory): Process { - $vendor = $this->vendorVolume($directory) === null ? ['vendor'] : ['--no-recursion', 'vendor']; - - return $this->pipe( - [$this->findDocker(), 'exec', $container, 'tar', '-c', '-C', '/solution', 'composer.lock', ...$vendor], - ['tar', '-x', '-C', $directory], + return Process::fromShellCommandline( + sprintf('%s exec %s tar -c -C /solution composer.lock vendor | tar -x', escapeshellarg($this->findDocker()), $container), + $directory, ); } + private function remove(string $container): Process + { + return $this->docker(['rm', '-f', '-v', $container]); + } + /** - * @param list $from - * @param list $to + * @param list $ports + * @return list eg. ['-p', '127.0.0.1:8000:8000'] */ - private function pipe(array $from, array $to): Process + private function publish(array $ports): array { - //Process escapes each argument - $commandLine = (new Process($from))->getCommandLine() . ' | ' . (new Process($to))->getCommandLine(); - - return Process::fromShellCommandline($commandLine, $this->basePath); + return array_merge(...array_map(fn(int $port) => ['-p', $this->portsHost . ':' . $port . ':' . $port], $ports)); } /** diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 54de2514..ffa22862 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -104,9 +104,10 @@ public function testCreateIsIsolatedWithNoNetwork(): void static::assertSame($this->expectedCreate($container, ['--network', 'none']), $execution->before[0]->getCommandLine()); static::assertSame("'/usr/local/bin/docker' 'start' '$container'", $execution->before[1]->getCommandLine()); static::assertSame( - "'tar' '-c' '-C' '$directory' '--' 'solution.php' | '/usr/local/bin/docker' 'exec' '-i' '$container' 'tar' '-x' '-m' '-C' '/solution'", + "find . ! -type d | tar -c -T - | '/usr/local/bin/docker' exec -i $container tar -x -C /solution", $execution->before[2]->getCommandLine(), ); + static::assertSame($directory, $execution->before[2]->getWorkingDirectory()); static::assertSame([], $execution->after); } @@ -140,9 +141,10 @@ public function testComposerGetsItsOwnContainerWithNetworkCacheAndNoPluginsOrScr $execution->before[0]->getCommandLine(), ); static::assertSame( - "'/usr/local/bin/docker' 'exec' '$container' 'tar' '-c' '-C' '/solution' 'composer.lock' 'vendor' | 'tar' '-x' '-C' '$directory'", + "'/usr/local/bin/docker' exec $container tar -c -C /solution composer.lock vendor | tar -x", $execution->after[0]->getCommandLine(), ); + static::assertSame($directory, $execution->after[0]->getWorkingDirectory()); static::assertSame("'/usr/local/bin/docker' 'rm' '-f' '-v' '$container'", $execution->after[1]->getCommandLine()); } @@ -153,12 +155,11 @@ public function testVendorVolumeIsWritableForComposerOnly(): void $composer = $sandbox->create(new ProcessInput('composer', ['update'], $directory, [], [])); static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor' ", $composer->before[0]->getCommandLine()); - //vendor stays in the volume, only the folder comes back - static::assertStringContainsString("'composer.lock' '--no-recursion' 'vendor' |", $composer->after[0]->getCommandLine()); $php = $sandbox->create(new ProcessInput('php', ['solution.php'], $directory, [], [])); static::assertStringContainsString("'-v' 'vendor-student:/solution/vendor:ro' ", $php->before[0]->getCommandLine()); - static::assertStringContainsString("'--' 'composer.json' |", $php->before[2]->getCommandLine()); + //vendor is already in the volume + static::assertStringStartsWith('find . -path ./vendor -prune -o ! -type d -print |', $php->before[2]->getCommandLine()); } public function testFoldersOutsideTheVendorVolumesKeepTheirOwnVendor(): void @@ -168,8 +169,7 @@ public function testFoldersOutsideTheVendorVolumesKeepTheirOwnVendor(): void $directory = $this->folder(['solution.php', 'vendor/autoload.php']); $execution = $sandbox->create(new ProcessInput('php', [], $directory, [], [])); static::assertStringNotContainsString('vendor-student', $execution->before[0]->getCommandLine()); - //its contents, as tar can not change the image's vendor folder - static::assertStringContainsString("'--' 'solution.php' 'vendor/autoload.php' |", $execution->before[2]->getCommandLine()); + static::assertStringStartsWith('find . ! -type d |', $execution->before[2]->getCommandLine()); } private function anyFinder(): ExecutableFinder From 7313ca505e4e87e69ae8315d07af7a522dec8e7d Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 08:11:37 +0100 Subject: [PATCH 4/4] Drop a stray blank line --- src/Process/DockerSandbox.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 0eddbd37..15fddd14 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -90,7 +90,6 @@ public function getHost(): SandboxHost public function create(ProcessInput $processInput): DockerExecution { $directory = $processInput->getWorkingDirectory(); - $isComposer = $processInput->getExecutable() === 'composer'; //composer needs the internet, and published ports would clash between folders, so they get a container just