diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index c4b9d9bf..15fddd14 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -17,8 +17,20 @@ 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; private string $basePath; private string $projectName; private string $portsNetwork; @@ -29,6 +41,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--'] @@ -62,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 @@ -78,96 +89,165 @@ public function getHost(): SandboxHost public function create(ProcessInput $processInput): DockerExecution { + $directory = $processInput->getWorkingDirectory(); $isComposer = $processInput->getExecutable() === 'composer'; - $args = $processInput->getArgs(); - $mounts = [$processInput->getWorkingDirectory() . ':/solution']; + //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(); + $after = $isComposer ? [$this->copyOut($container, $directory), $this->remove($container)] : [$this->remove($container)]; - $vendorVolume = $this->vendorVolumes[dirname($processInput->getWorkingDirectory())] ?? null; - if ($vendorVolume !== null) { - //only composer writes to it - $mounts[] = $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro'); + return new DockerExecution($this->exec($container, $processInput), $this->start($container, $processInput), $after); } - $env = ['COMPOSER_HOME' => '/composer']; + //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)); + } - 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']; + $container = $this->containers[$directory] = $this->newContainerName(); + + return new DockerExecution($this->exec($container, $processInput), $this->start($container, $processInput)); + } + + public function __destruct() + { + foreach ($this->containers as $container) { + $this->remove($container)->run(); } + } + + /** + * 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 start(string $container, ProcessInput $processInput): array + { + $isComposer = $processInput->getExecutable() === 'composer'; + $ports = $processInput->getExposedPorts(); + $vendorVolume = $this->vendorVolume($processInput->getWorkingDirectory()); + + $network = match (true) { + $isComposer => ['--network', 'bridge', '-v', self::COMPOSER_CACHE_VOLUME . ':/composer'], + count($ports) > 0 => ['--network', $this->portsNetwork, ...$this->publish($ports)], + default => ['--network', 'none'], + }; + + //only composer writes to it + $vendor = match (true) { + $vendorVolume === null => [], + $isComposer => ['-v', $vendorVolume . ':/solution/vendor'], + default => ['-v', $vendorVolume . ':/solution/vendor:ro'], + }; + + return [ + $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', + ...$network, + ...$vendor, + $this->getImageName(), 'sleep', 'infinity', + ]), + $this->docker(['start', $container]), + $this->copyIn($container, $processInput->getWorkingDirectory()), + ]; + } - $network = ['--network', 'none']; - if ($isComposer) { - //composer needs to download packages - $network = ['--network', 'bridge']; - } elseif (count($processInput->getExposedPorts()) > 0) { - $network = ['--network', $this->portsNetwork]; - foreach ($processInput->getExposedPorts() as $port) { - $network[] = '-p'; - $network[] = $this->portsHost . ':' . $port . ':' . $port; - } + 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']; } - $envArgs = []; - foreach ([...$processInput->getEnv(), ...$env] as $key => $value) { - $envArgs[] = '-e'; - $envArgs[] = $key . '=' . $value; + $env = []; + foreach ([...$processInput->getEnv(), 'COMPOSER_HOME' => '/composer'] as $key => $value) { + array_push($env, '-e', $key . '=' . $value); } - //no steps around it yet, create/cp/rm come when files are copied in instead of mounted - return new DockerExecution(new Process( + return $this->docker( [ - $this->findDocker(), - 'run', - '--rm', - '-i', - '--init', - '--user', - getmyuid() . ':' . getmygid(), - ...$network, - '--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', - ...$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, + '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, ], - $this->basePath, - null, $processInput->getInput(), self::TIMEOUT + 5, - )); + ); + } + + /** + * 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 + { + $find = $this->vendorVolume($directory) === null ? 'find . ! -type d' : 'find . -path ./vendor -prune -o ! -type d -print'; + + 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. + */ + private function copyOut(string $container, string $directory): Process + { + 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 $ports + * @return list eg. ['-p', '127.0.0.1:8000:8000'] + */ + private function publish(array $ports): array + { + return array_merge(...array_map(fn(int $port) => ['-p', $this->portsHost . ':' . $port . ':' . $port], $ports)); + } + + /** + * @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 { - $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..ffa22862 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; @@ -18,30 +19,62 @@ 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 $extra env and mount args - * @param list $command + * @param list $network network, ports and their volumes */ - private function expectedCommand(array $network, array $extra, array $command): string + private function expectedCreate(string $container, array $network): string { $parts = [ - '/usr/local/bin/docker', 'run', '--rm', '-i', '--init', '--user', getmyuid() . ':' . getmygid(), - ...$network, - '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '--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', - ...$extra, - '-w', '/solution', 'php8appreciate-runtime', 'timeout', '-s', 'KILL', '30', + '--cpus', '1', '-v', '/solution', + ...$network, + '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); @@ -52,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); @@ -60,50 +93,83 @@ 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(__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( + "find . ! -type d | tar -c -T - | '/usr/local/bin/docker' exec -i $container tar -x -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($directory, $execution->before[2]->getWorkingDirectory()); + static::assertSame([], $execution->after); + } + + public function testRunsOfAFolderShareAContainerRemovedWithTheSandbox(): void + { + $finder = $this->anyFinder(); + $sandbox = new DockerSandbox(__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)); } - public function testComposerGetsNetworkCacheAndNoPluginsOrScripts(): void + public function testComposerGetsItsOwnContainerWithNetworkCacheAndNoPluginsOrScripts(): void { - $process = $this->factory()->create(new ProcessInput('composer', ['install'], __DIR__, [], []))->process; + $directory = $this->folder(['composer.json']); + $execution = $this->factory()->create(new ProcessInput('composer', ['install'], $directory, [], [])); + $container = $this->container($execution); - $expected = $this->expectedCommand( - ['--network', 'bridge'], - ['-e', 'COMPOSER_HOME=/composer', '-v', __DIR__ . ':/solution', '-v', 'php-school-composer-cache:/composer'], - ['composer', 'install', '--no-plugins', '--no-scripts'], + static::assertSame( + $this->expectedExec($container, [], ['composer', 'install', '--no-plugins', '--no-scripts']), + $execution->process->getCommandLine(), + ); + static::assertSame( + $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", + $execution->after[0]->getCommandLine(), ); - static::assertSame($expected, $process->getCommandLine()); + static::assertSame($directory, $execution->after[0]->getWorkingDirectory()); + 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(__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()); - $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()); + //vendor is already in the volume + static::assertStringStartsWith('find . -path ./vendor -prune -o ! -type d -print |', $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']); - //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()); + static::assertStringStartsWith('find . ! -type d |', $execution->before[2]->getCommandLine()); } private function anyFinder(): ExecutableFinder @@ -114,64 +180,60 @@ 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 { - $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()); } 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()); } @@ -184,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()); } }