diff --git a/app/config.php b/app/config.php index cb047456..5e9ab06f 100644 --- a/app/config.php +++ b/app/config.php @@ -72,9 +72,9 @@ use PhpSchool\PhpWorkshop\Output\StdOutput; use PhpSchool\PhpWorkshop\Patch; use PhpSchool\PhpWorkshop\Process\Composer; -use PhpSchool\PhpWorkshop\Process\DockerSandbox; -use PhpSchool\PhpWorkshop\Process\HostSandbox; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\Docker\DockerSandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\Host\HostSandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\GenericFailure as CgiGenericFailure; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure as CgiRequestFailure; @@ -199,27 +199,27 @@ $manager = new RunnerManager(); $manager->addFactory(new CliRunnerFactory( $c->get(EventDispatcher::class), - $c->get(Sandbox::class), + $c->get(SandboxFactory::class), $c->get(EnvironmentManager::class), )); $manager->addFactory(new CgiRunnerFactory( $c->get(EventDispatcher::class), - $c->get(Sandbox::class), + $c->get(SandboxFactory::class), $c->get(EnvironmentManager::class), )); $manager->addFactory(new CustomVerifyingRunnerFactory()); return $manager; }, - Sandbox::class => function (ContainerInterface $c) { + SandboxFactory::class => function (ContainerInterface $c) { $sandbox = getenv('SANDBOX'); return match ($sandbox) { - 'docker' => new DockerSandbox( + 'docker' => new DockerSandboxFactory( $c->get('basePath'), $c->get('appName'), ), - default => new HostSandbox(), + default => new HostSandboxFactory(), }; }, diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index 2ce351c9..7a745fac 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -6,7 +6,8 @@ use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; use PhpSchool\PhpWorkshop\Utils\Collection; /** @@ -58,7 +59,7 @@ public function appendArg(string $arg): void } /** - * The running program, eg. to connect to a port it listens on with getAddress(). Only on the executing events. + * The running program, eg. to connect to the port it listens on with getAddress(). Only on the executing events. */ public function getExecution(): SandboxExecution { @@ -68,6 +69,17 @@ public function getExecution(): SandboxExecution return $execution; } + /** + * Where the solution runs, eg. to pass its port in the args. Only on the pre events. + */ + public function getSandbox(): Sandbox + { + /** @var Sandbox $sandbox */ + $sandbox = $this->getParameter('sandbox'); + + return $sandbox; + } + /** * Get the arguments to be passed to the program. * diff --git a/src/Exception/CodeExecutionException.php b/src/Exception/CodeExecutionException.php index fbff58be..0f022374 100644 --- a/src/Exception/CodeExecutionException.php +++ b/src/Exception/CodeExecutionException.php @@ -5,7 +5,7 @@ namespace PhpSchool\PhpWorkshop\Exception; use RuntimeException; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; /** * Represents the situation where some PHP code could not be executed successfully. diff --git a/src/Exercise/Scenario/ExerciseScenario.php b/src/Exercise/Scenario/ExerciseScenario.php index c0ef1caf..90c6b700 100644 --- a/src/Exercise/Scenario/ExerciseScenario.php +++ b/src/Exercise/Scenario/ExerciseScenario.php @@ -9,10 +9,7 @@ abstract class ExerciseScenario */ private array $files = []; - /** - * @var list - */ - private array $exposedPorts = []; + private bool $exposesPort = false; public function withFile(string $relativeFileName, string $content): static { @@ -29,18 +26,19 @@ public function getFiles(): array return $this->files; } - public function exposePort(int $port): static + /** + * The code listens on a port, eg. a server the check connects to. The sandbox picks it, listeners get it from the + * pre execute events with getSandbox()->getPort(). + */ + public function exposePort(): static { - $this->exposedPorts[] = $port; + $this->exposesPort = true; return $this; } - /** - * @return list - */ - public function getExposedPorts(): array + public function exposesPort(): bool { - return $this->exposedPorts; + return $this->exposesPort; } } diff --git a/src/ExerciseRunner/CgiRunner.php b/src/ExerciseRunner/CgiRunner.php index 981a9602..189d0d1a 100644 --- a/src/ExerciseRunner/CgiRunner.php +++ b/src/ExerciseRunner/CgiRunner.php @@ -21,9 +21,10 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult; use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure; use PhpSchool\PhpWorkshop\Result\Cgi\GenericFailure; @@ -59,7 +60,7 @@ class CgiRunner implements ExerciseRunnerInterface public function __construct( private CgiExercise $exercise, private EventDispatcher $eventDispatcher, - private Sandbox $sandbox, + private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager, ) {} @@ -109,10 +110,13 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.verify.start', $context, $scenario)); + $reference = $this->sandboxFactory->create($context->getReferenceExecutionDirectory(), $scenario); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); + $result = new CgiResult( array_map( - function (RequestInterface $request) use ($context, $scenario) { - return $this->doVerify($context, $scenario, $request); + function (RequestInterface $request) use ($context, $scenario, $reference, $student) { + return $this->doVerify($context, $scenario, $request, $reference, $student); }, $scenario->getExecutions(), ), @@ -122,7 +126,7 @@ function (RequestInterface $request) use ($context, $scenario) { return $result; } - private function doVerify(ExecutionContext $context, CgiScenario $scenario, RequestInterface $request): CgiResultInterface + private function doVerify(ExecutionContext $context, CgiScenario $scenario, RequestInterface $request, Sandbox $reference, Sandbox $student): CgiResultInterface { try { /** @var CgiExecuteEvent $event */ @@ -132,7 +136,7 @@ private function doVerify(ExecutionContext $context, CgiScenario $scenario, Requ $solutionResponse = $this->executePhpFile( $context, $scenario, - $context->getReferenceExecutionDirectory(), + $reference, $this->exercise->getSolution()->getEntryPoint()->getRelativePath(), $event->getRequest(), 'reference', @@ -158,7 +162,7 @@ private function doVerify(ExecutionContext $context, CgiScenario $scenario, Requ $userResponse = $this->executePhpFile( $context, $scenario, - $context->getStudentExecutionDirectory(), + $student, basename($context->getEntryPoint()), $event->getRequest(), 'student', @@ -210,12 +214,12 @@ private function getHeaders(ResponseInterface $response): array private function executePhpFile( ExecutionContext $context, CgiScenario $scenario, - string $workingDirectory, + Sandbox $sandbox, string $fileName, RequestInterface $request, string $type, ): ResponseInterface { - $execution = $this->getPhpExecution($workingDirectory, $fileName, $request, $scenario->getExposedPorts()); + $execution = $this->getPhpExecution($sandbox, $fileName, $request); $execution->start(); $this->eventDispatcher->dispatch( @@ -237,10 +241,7 @@ private function executePhpFile( return Message::parseResponse($output); } - /** - * @param list $exposedPorts - */ - private function getPhpExecution(string $workingDirectory, string $fileName, RequestInterface $request, array $exposedPorts): SandboxExecution + private function getPhpExecution(Sandbox $sandbox, string $fileName, RequestInterface $request): SandboxExecution { $env = [ 'REQUEST_METHOD' => $request->getMethod(), @@ -266,13 +267,11 @@ private function getPhpExecution(string $workingDirectory, string $fileName, Req '-dhtml_errors=0', '-dexpose_php=0', ], - $workingDirectory, $env, - $exposedPorts, $content, ); - return $this->sandbox->create($processInput); + return $sandbox->execute($processInput); } /** @@ -302,18 +301,15 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.run.start', $context, $scenario)); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); + $success = true; foreach ($scenario->getExecutions() as $i => $request) { /** @var CgiExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( new CgiExecuteEvent('cgi.run.student-execute.pre', $context, $scenario, $request), ); - $execution = $this->getPhpExecution( - $context->getStudentExecutionDirectory(), - basename($context->getEntryPoint()), - $event->getRequest(), - $scenario->getExposedPorts(), - ); + $execution = $this->getPhpExecution($student, basename($context->getEntryPoint()), $event->getRequest()); $execution->start(); $this->eventDispatcher->dispatch( diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index 76a3a7b6..82c953b1 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -20,9 +20,10 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use PhpSchool\PhpWorkshop\Result\Cli\RequestFailure; use PhpSchool\PhpWorkshop\Result\Cli\CliResult; use PhpSchool\PhpWorkshop\Result\Cli\GenericFailure; @@ -59,7 +60,7 @@ class CliRunner implements ExerciseRunnerInterface public function __construct( private CliExercise $exercise, private EventDispatcher $eventDispatcher, - private Sandbox $sandbox, + private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager, ) {} @@ -108,10 +109,13 @@ public function verify(ExecutionContext $context): ResultInterface $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.verify.start', $context, $scenario)); + $reference = $this->sandboxFactory->create($context->getReferenceExecutionDirectory(), $scenario); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); + $result = new CliResult( array_map( - function (Collection $args) use ($context, $scenario) { - return $this->doVerify($context, $scenario, $args); + function (Collection $args) use ($context, $scenario, $reference, $student) { + return $this->doVerify($context, $scenario, $args, $reference, $student); }, $scenario->getExecutions(), ), @@ -125,17 +129,17 @@ function (Collection $args) use ($context, $scenario) { /** * @param Collection $args */ - private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args): CliResultInterface + private function doVerify(ExecutionContext $context, CliScenario $scenario, Collection $args, Sandbox $reference, Sandbox $student): CliResultInterface { try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args), + new CliExecuteEvent('cli.verify.reference-execute.pre', $context, $scenario, $args, ['sandbox' => $reference]), ); $solutionOutput = $this->executePhpFile( $context, $scenario, - $context->getReferenceExecutionDirectory(), + $reference, $this->exercise->getSolution()->getEntryPoint()->getRelativePath(), $event->getArgs(), 'reference', @@ -156,12 +160,12 @@ private function doVerify(ExecutionContext $context, CliScenario $scenario, Coll try { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args), + new CliExecuteEvent('cli.verify.student-execute.pre', $context, $scenario, $args, ['sandbox' => $student]), ); $userOutput = $this->executePhpFile( $context, $scenario, - $context->getStudentExecutionDirectory(), + $student, basename($context->getEntryPoint()), $event->getArgs(), 'student', @@ -211,21 +215,18 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $this->eventDispatcher->dispatch(new CliExerciseRunnerEvent('cli.run.start', $context, $scenario)); + $student = $this->sandboxFactory->create($context->getStudentExecutionDirectory(), $scenario); + $success = true; foreach ($scenario->getExecutions() as $i => $args) { /** @var CliExecuteEvent $event */ $event = $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args), + new CliExecuteEvent('cli.run.student-execute.pre', $context, $scenario, $args, ['sandbox' => $student]), ); $args = $event->getArgs(); - $execution = $this->getPhpExecution( - $context->getStudentExecutionDirectory(), - basename($context->getEntryPoint()), - $args, - $scenario->getExposedPorts(), - ); + $execution = $this->getPhpExecution($student, basename($context->getEntryPoint()), $args); $execution->start(); $this->eventDispatcher->dispatch( @@ -256,9 +257,9 @@ public function run(ExecutionContext $context, OutputInterface $output): bool /** * @param Collection $args */ - private function executePhpFile(ExecutionContext $context, CliScenario $scenario, string $workingDirectory, string $fileName, Collection $args, string $type): string + private function executePhpFile(ExecutionContext $context, CliScenario $scenario, Sandbox $sandbox, string $fileName, Collection $args, string $type): string { - $execution = $this->getPhpExecution($workingDirectory, $fileName, $args, $scenario->getExposedPorts()); + $execution = $this->getPhpExecution($sandbox, $fileName, $args); $execution->start(); $this->eventDispatcher->dispatch( @@ -275,12 +276,9 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario /** * @param Collection $args - * @param list $exposedPorts */ - private function getPhpExecution(string $workingDirectory, string $fileName, Collection $args, array $exposedPorts): SandboxExecution + private function getPhpExecution(Sandbox $sandbox, string $fileName, Collection $args): SandboxExecution { - return $this->sandbox->create( - new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], $workingDirectory, [], $exposedPorts), - ); + return $sandbox->execute(new ProcessInput('php', [$fileName, ...$args->getArrayCopy()], [])); } } diff --git a/src/ExerciseRunner/Factory/CgiRunnerFactory.php b/src/ExerciseRunner/Factory/CgiRunnerFactory.php index 52eebeb9..374921c2 100644 --- a/src/ExerciseRunner/Factory/CgiRunnerFactory.php +++ b/src/ExerciseRunner/Factory/CgiRunnerFactory.php @@ -13,7 +13,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CgiRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\ExerciseRunnerInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; /** * Factory class for `CgiRunner` @@ -25,7 +25,7 @@ class CgiRunnerFactory implements ExerciseRunnerFactoryInterface */ private static string $type = ExerciseType::CGI; - public function __construct(private EventDispatcher $eventDispatcher, private Sandbox $sandbox, private EnvironmentManager $environmentManager) {} + public function __construct(private EventDispatcher $eventDispatcher, private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager) {} /** * Whether the factory supports this exercise type. @@ -56,6 +56,6 @@ public function configureInput(CommandDefinition $commandDefinition): void */ public function create(ExerciseInterface $exercise): ExerciseRunnerInterface { - return new CgiRunner($exercise, $this->eventDispatcher, $this->sandbox, $this->environmentManager); + return new CgiRunner($exercise, $this->eventDispatcher, $this->sandboxFactory, $this->environmentManager); } } diff --git a/src/ExerciseRunner/Factory/CliRunnerFactory.php b/src/ExerciseRunner/Factory/CliRunnerFactory.php index 8a584d16..621ecf4d 100644 --- a/src/ExerciseRunner/Factory/CliRunnerFactory.php +++ b/src/ExerciseRunner/Factory/CliRunnerFactory.php @@ -13,7 +13,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CliRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\ExerciseRunnerInterface; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; /** * Factory class for `CliRunner` @@ -25,7 +25,7 @@ class CliRunnerFactory implements ExerciseRunnerFactoryInterface */ private static string $type = ExerciseType::CLI; - public function __construct(private EventDispatcher $eventDispatcher, private Sandbox $sandbox, private EnvironmentManager $environmentManager) {} + public function __construct(private EventDispatcher $eventDispatcher, private SandboxFactory $sandboxFactory, private EnvironmentManager $environmentManager) {} /** * Whether the factory supports this exercise type. @@ -56,6 +56,6 @@ public function configureInput(CommandDefinition $commandDefinition): void */ public function create(ExerciseInterface $exercise): ExerciseRunnerInterface { - return new CliRunner($exercise, $this->eventDispatcher, $this->sandbox, $this->environmentManager); + return new CliRunner($exercise, $this->eventDispatcher, $this->sandboxFactory, $this->environmentManager); } } diff --git a/src/Process/DockerExecution.php b/src/Process/DockerExecution.php deleted file mode 100644 index bee68a6c..00000000 --- a/src/Process/DockerExecution.php +++ /dev/null @@ -1,88 +0,0 @@ - $before - * @param list $after - * @param string $host the docker host's address that ports are published on, eg. 10.0.0.5 - * @param array $ports container port => published port on the host, eg. [54321 => 47213] - */ - public function __construct( - public readonly Process $process, - public readonly array $before = [], - public readonly array $after = [], - private string $host = '127.0.0.1', - private array $ports = [], - ) {} - - public function start(): void - { - foreach ($this->before as $step) { - $step->mustRun(); - } - - $this->process->start(); - } - - public function wait(?callable $callback = null): int - { - try { - return $this->process->wait($callback); - } finally { - $this->runAfter(); - } - } - - public function mustRun(): void - { - $this->start(); - $this->wait(); - - if (!$this->process->isSuccessful()) { - throw new ProcessFailedException($this->process); - } - } - - public function isSuccessful(): bool - { - return $this->process->isSuccessful(); - } - - public function getOutput(): string - { - return $this->process->getOutput(); - } - - public function getErrorOutput(): string - { - return $this->process->getErrorOutput(); - } - - public function getAddress(int $port): string - { - if (!isset($this->ports[$port])) { - throw new \RuntimeException(sprintf('Port %d is not published', $port)); - } - - return $this->host . ':' . $this->ports[$port]; - } - - private function runAfter(): void - { - foreach ($this->after as $step) { - //cleanup, so keep going if one fails - $step->run(); - } - } -} diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php deleted file mode 100644 index 82a09cc3..00000000 --- a/src/Process/DockerSandbox.php +++ /dev/null @@ -1,141 +0,0 @@ -executableFinder = $executableFinder ?? new ExecutableFinder(); - $this->basePath = $basePath; - $this->projectName = $projectName; - //for exercises that expose ports, eg a server the check connects to. Pass a network without internet access - //to stop student code reaching out, the published ports still work - $this->portsNetwork = $portsNetwork; - //the address ports are published on, the docker host's private address when it is remote. IPv6 in brackets, - //eg. [fdaa::2] - $this->portsHost = $portsHost; - $this->portPicker = $portPicker ?? new FreePortPicker(); - } - - public function getImageName(): string - { - return strtolower($this->projectName) . '-runtime'; - } - - /** - * The process that builds the runtime image. Run it once on install/deploy, not per request. - */ - public function createBuildProcess(): Process - { - return new Process( - [$this->findDocker(), 'build', '-t', $this->getImageName(), '.docker/runtime'], - $this->basePath, - null, - null, - 300, - ); - } - - public function create(ProcessInput $processInput): DockerExecution - { - $network = ['--network', 'none']; - $ports = []; - if (count($processInput->getExposedPorts()) > 0) { - $network = ['--network', $this->portsNetwork]; - foreach ($processInput->getExposedPorts() as $port) { - $hostPort = $this->portPicker->pick(); - $network[] = '-p'; - $network[] = $this->portsHost . ':' . $hostPort . ':' . $port; - $ports[$port] = $hostPort; - } - } - - $envArgs = []; - foreach ($processInput->getEnv() as $key => $value) { - $envArgs[] = '-e'; - $envArgs[] = $key . '=' . $value; - } - - //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', - '--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, - '-v', - $processInput->getWorkingDirectory() . ':/solution', - '-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(), - ...$processInput->getArgs(), - ], - $this->basePath, - null, - $processInput->getInput(), - self::TIMEOUT + 5, - ), [], [], $this->portsHost, $ports); - } - - private function findDocker(): string - { - $dockerPath = $this->executableFinder->find('docker'); - if ($dockerPath === null) { - throw ProcessNotFoundException::fromExecutable('docker'); - } - - return $dockerPath; - } -} diff --git a/src/Process/HostExecution.php b/src/Process/HostExecution.php deleted file mode 100644 index 9e4b3799..00000000 --- a/src/Process/HostExecution.php +++ /dev/null @@ -1,47 +0,0 @@ -process->start(); - } - - public function wait(?callable $callback = null): int - { - return $this->process->wait($callback); - } - - public function mustRun(): void - { - $this->process->mustRun(); - } - - public function isSuccessful(): bool - { - return $this->process->isSuccessful(); - } - - public function getOutput(): string - { - return $this->process->getOutput(); - } - - public function getErrorOutput(): string - { - return $this->process->getErrorOutput(); - } - - public function getAddress(int $port): string - { - return '127.0.0.1:' . $port; - } -} diff --git a/src/Process/FreePortPicker.php b/src/Process/Port/FreePortPicker.php similarity index 93% rename from src/Process/FreePortPicker.php rename to src/Process/Port/FreePortPicker.php index 1ace14f4..09d1de5e 100644 --- a/src/Process/FreePortPicker.php +++ b/src/Process/Port/FreePortPicker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Port; use PhpSchool\PhpWorkshop\Exception\RuntimeException; diff --git a/src/Process/LockPortPicker.php b/src/Process/Port/LockPortPicker.php similarity index 95% rename from src/Process/LockPortPicker.php rename to src/Process/Port/LockPortPicker.php index 018a65db..b73bf175 100644 --- a/src/Process/LockPortPicker.php +++ b/src/Process/Port/LockPortPicker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Port; use PhpSchool\PhpWorkshop\Exception\RuntimeException; use Symfony\Component\Lock\LockFactory; diff --git a/src/Process/PortPicker.php b/src/Process/Port/PortPicker.php similarity index 81% rename from src/Process/PortPicker.php rename to src/Process/Port/PortPicker.php index 97e3fb89..daf9337a 100644 --- a/src/Process/PortPicker.php +++ b/src/Process/Port/PortPicker.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Port; /** * Picks a port, eg. the one an exercise's code listens on, or the one DockerSandbox publishes it on. diff --git a/src/Process/Sandbox.php b/src/Process/Sandbox.php deleted file mode 100644 index 784281f4..00000000 --- a/src/Process/Sandbox.php +++ /dev/null @@ -1,10 +0,0 @@ -port !== null) { + //the same port on the docker host, the factory picked one free there + $network = ['--network', $this->portsNetwork, '-p', $this->portsHost . ':' . $this->port . ':' . $this->port]; + } + + $envArgs = []; + foreach ($processInput->getEnv() as $key => $value) { + $envArgs[] = '-e'; + $envArgs[] = $key . '=' . $value; + } + + return new SandboxExecution(new Process( + [ + $this->docker, + '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, + '-v', + $this->directory . ':/solution', + '-w', + '/solution', + $this->image, + //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(), + ...$processInput->getArgs(), + ], + $this->basePath, + null, + $processInput->getInput(), + self::TIMEOUT + 5, + ), $this->portsHost, $this->port); + } + + public function getPort(): int + { + return $this->port ?? throw new \RuntimeException('The scenario does not expose a port'); + } +} diff --git a/src/Process/Sandbox/Docker/DockerSandboxFactory.php b/src/Process/Sandbox/Docker/DockerSandboxFactory.php new file mode 100644 index 00000000..0d9f4b2b --- /dev/null +++ b/src/Process/Sandbox/Docker/DockerSandboxFactory.php @@ -0,0 +1,82 @@ +executableFinder = $executableFinder ?? new ExecutableFinder(); + $this->basePath = $basePath; + $this->projectName = $projectName; + //for exercises that expose ports, eg a server the check connects to. Pass a network without internet access + //to stop student code reaching out, the published ports still work + $this->portsNetwork = $portsNetwork; + //the address ports are published on, the docker host's private address when it is remote. IPv6 in brackets, + //eg. [fdaa::2] + $this->portsHost = $portsHost; + $this->portPicker = $portPicker ?? new FreePortPicker(); + } + + public function getImageName(): string + { + return strtolower($this->projectName) . '-runtime'; + } + + /** + * The process that builds the runtime image. Run it once on install/deploy, not per request. + */ + public function createBuildProcess(): Process + { + return new Process( + [$this->findDocker(), 'build', '-t', $this->getImageName(), '.docker/runtime'], + $this->basePath, + null, + null, + 300, + ); + } + + public function create(string $directory, ExerciseScenario $scenario): DockerSandbox + { + $port = $scenario->exposesPort() ? $this->portPicker->pick() : null; + + return new DockerSandbox($directory, $port, $this->findDocker(), $this->basePath, $this->getImageName(), $this->portsNetwork, $this->portsHost); + } + + private function findDocker(): string + { + $dockerPath = $this->executableFinder->find('docker'); + if ($dockerPath === null) { + throw ProcessNotFoundException::fromExecutable('docker'); + } + + return $dockerPath; + } +} diff --git a/src/Process/HostSandbox.php b/src/Process/Sandbox/Host/HostSandbox.php similarity index 62% rename from src/Process/HostSandbox.php rename to src/Process/Sandbox/Host/HostSandbox.php index 8351e2fa..15cc308f 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/Sandbox/Host/HostSandbox.php @@ -2,11 +2,18 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshop\Process; +namespace PhpSchool\PhpWorkshop\Process\Sandbox\Host; +use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; +/** + * Runs the code straight on this machine, in the solution's directory. + */ final class HostSandbox implements Sandbox { /** @@ -14,14 +21,9 @@ final class HostSandbox implements Sandbox */ private const ALLOWED_ENV = ['PATH', 'HOME', 'COMPOSER_HOME']; - private ExecutableFinder $executableFinder; + public function __construct(private string $directory, private ?int $port, private ExecutableFinder $executableFinder) {} - public function __construct(?ExecutableFinder $executableFinder = null) - { - $this->executableFinder = $executableFinder ?? new ExecutableFinder(); - } - - public function create(ProcessInput $processInput): HostExecution + public function execute(ProcessInput $processInput): SandboxExecution { $executablePath = $this->executableFinder->find($processInput->getExecutable()); @@ -29,13 +31,18 @@ public function create(ProcessInput $processInput): HostExecution throw ProcessNotFoundException::fromExecutable($processInput->getExecutable()); } - return new HostExecution(new Process( + return new SandboxExecution(new Process( [$executablePath, ...$processInput->getArgs()], - $processInput->getWorkingDirectory(), + $this->directory, array_merge($this->getDefaultEnv(), $processInput->getEnv()), $processInput->getInput(), 10, - )); + ), '127.0.0.1', $this->port); + } + + public function getPort(): int + { + return $this->port ?? throw new \RuntimeException('The scenario does not expose a port'); } /** diff --git a/src/Process/Sandbox/Host/HostSandboxFactory.php b/src/Process/Sandbox/Host/HostSandboxFactory.php new file mode 100644 index 00000000..ef592fcb --- /dev/null +++ b/src/Process/Sandbox/Host/HostSandboxFactory.php @@ -0,0 +1,22 @@ +exposesPort() ? (new FreePortPicker())->pick() : null; + + return new HostSandbox($directory, $port, $this->executableFinder); + } +} diff --git a/src/Process/ProcessInput.php b/src/Process/Sandbox/ProcessInput.php similarity index 57% rename from src/Process/ProcessInput.php rename to src/Process/Sandbox/ProcessInput.php index 731e146b..beb45fae 100644 --- a/src/Process/ProcessInput.php +++ b/src/Process/Sandbox/ProcessInput.php @@ -1,20 +1,22 @@ $args - * @param array $env - * @param list $exposedPorts + * @param string $executable eg. php or php-cgi + * @param list $args eg. ['solution.php', '0.0.0.0', '54321'] + * @param array $env extra env vars, eg. the request for php-cgi + * @param string|null $input written to stdin, eg. the request body for php-cgi */ public function __construct( private string $executable, private array $args, - private string $workingDirectory, private array $env, - private array $exposedPorts, private ?string $input = null, ) {} @@ -31,11 +33,6 @@ public function getArgs(): array return $this->args; } - public function getWorkingDirectory(): string - { - return $this->workingDirectory; - } - /** * @return array */ @@ -44,14 +41,6 @@ public function getEnv(): array return $this->env; } - /** - * @return list - */ - public function getExposedPorts(): array - { - return $this->exposedPorts; - } - public function getInput(): ?string { return $this->input; diff --git a/src/Process/Sandbox/Sandbox.php b/src/Process/Sandbox/Sandbox.php new file mode 100644 index 00000000..6ca24647 --- /dev/null +++ b/src/Process/Sandbox/Sandbox.php @@ -0,0 +1,18 @@ +process->start(); + } + + /** + * @param (callable(string, string): void)|null $callback receives the output as it comes + */ + public function wait(?callable $callback = null): int + { + return $this->process->wait($callback); + } + + /** + * @throws \Symfony\Component\Process\Exception\ProcessFailedException if it fails + */ + public function mustRun(): void + { + $this->process->mustRun(); + } + + public function isSuccessful(): bool + { + return $this->process->isSuccessful(); + } + + public function getOutput(): string + { + return $this->process->getOutput(); + } + + public function getErrorOutput(): string + { + return $this->process->getErrorOutput(); + } + + /** + * Where to connect to the port the code listens on, once it has started. + * + * @return string eg. '127.0.0.1:54321' + */ + public function getAddress(): string + { + return $this->host . ':' . ($this->port ?? throw new \RuntimeException('The code does not listen on a port')); + } +} diff --git a/src/Process/Sandbox/SandboxFactory.php b/src/Process/Sandbox/SandboxFactory.php new file mode 100644 index 00000000..52cd2f45 --- /dev/null +++ b/src/Process/Sandbox/SandboxFactory.php @@ -0,0 +1,18 @@ +getMockBuilder(CliRunner::class) - ->setConstructorArgs([$exercise, $eventDispatcher, new HostSandbox(), new EnvironmentManager(new Filesystem(), $eventDispatcher)]) + ->setConstructorArgs([$exercise, $eventDispatcher, new HostSandboxFactory(), new EnvironmentManager(new Filesystem(), $eventDispatcher)]) ->onlyMethods(['getRequiredChecks']) ->getMock(); diff --git a/test/Exception/CodeExecutionExceptionTest.php b/test/Exception/CodeExecutionExceptionTest.php index 63788ba2..542a8515 100644 --- a/test/Exception/CodeExecutionExceptionTest.php +++ b/test/Exception/CodeExecutionExceptionTest.php @@ -4,7 +4,8 @@ use PhpSchool\PhpWorkshop\Exception\CodeExecutionException; use PHPUnit\Framework\TestCase; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; +use Symfony\Component\Process\Process; class CodeExecutionExceptionTest extends TestCase { @@ -16,31 +17,19 @@ public function testException(): void public function testFromProcessUsesErrorOutputIfNotEmpty(): void { - $process = $this->createMock(SandboxExecution::class); + $execution = new SandboxExecution(Process::fromShellCommandline('echo "Std Output"; echo "Error Output" >&2')); + $execution->mustRun(); - $process - ->expects($this->once()) - ->method('getErrorOutput') - ->willReturn('Error Output'); - - $e = CodeExecutionException::fromExecution($process); + $e = CodeExecutionException::fromExecution($execution); $this->assertEquals('PHP Code failed to execute. Error: "Error Output"', $e->getMessage()); } public function testFromProcessUsesStdOutputIfErrorOutputEmpty(): void { - $process = $this->createMock(SandboxExecution::class); - $process - ->expects($this->once()) - ->method('getErrorOutput') - ->willReturn(''); - - $process - ->expects($this->once()) - ->method('getOutput') - ->willReturn('Std Output'); + $execution = new SandboxExecution(Process::fromShellCommandline('echo "Std Output"')); + $execution->mustRun(); - $e = CodeExecutionException::fromExecution($process); + $e = CodeExecutionException::fromExecution($execution); $this->assertEquals('PHP Code failed to execute. Error: "Std Output"', $e->getMessage()); } } diff --git a/test/ExerciseRunner/CgiRunnerTest.php b/test/ExerciseRunner/CgiRunnerTest.php index ff9cb020..d50e2b96 100644 --- a/test/ExerciseRunner/CgiRunnerTest.php +++ b/test/ExerciseRunner/CgiRunnerTest.php @@ -9,7 +9,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\Listener\OutputRunInfoListener; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\Host\HostSandboxFactory; use PhpSchool\PhpWorkshopTest\Asset\CgiExerciseImpl; use PhpSchool\Terminal\Terminal; use PhpSchool\PhpWorkshop\Check\CodeParseCheck; @@ -38,7 +38,7 @@ public function setUp(): void { $this->exercise = new CgiExerciseImpl(); $this->eventDispatcher = new EventDispatcher(new ResultAggregator()); - $this->runner = new CgiRunner($this->exercise, $this->eventDispatcher, new HostSandbox(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); + $this->runner = new CgiRunner($this->exercise, $this->eventDispatcher, new HostSandboxFactory(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); $this->assertEquals('CGI Program Runner', $this->runner->getName()); } diff --git a/test/ExerciseRunner/CliRunnerTest.php b/test/ExerciseRunner/CliRunnerTest.php index f3418d81..30a2ece3 100644 --- a/test/ExerciseRunner/CliRunnerTest.php +++ b/test/ExerciseRunner/CliRunnerTest.php @@ -5,14 +5,16 @@ use Colors\Color; use PhpSchool\PhpWorkshop\Check\CodeExistsCheck; use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; +use PhpSchool\PhpWorkshop\Exercise\Scenario\ExerciseScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\Listener\OutputRunInfoListener; -use PhpSchool\PhpWorkshop\Process\HostSandbox; -use PhpSchool\PhpWorkshop\Process\SandboxExecution; +use PhpSchool\PhpWorkshop\Process\Sandbox\Host\HostSandboxFactory; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxExecution; use PhpSchool\PhpWorkshop\Output\NullOutput; -use PhpSchool\PhpWorkshop\Process\ProcessInput; -use PhpSchool\PhpWorkshop\Process\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\ProcessInput; +use PhpSchool\PhpWorkshop\Process\Sandbox\Sandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\SandboxFactory; use PhpSchool\PhpWorkshop\Utils\RequestRenderer; use PhpSchool\PhpWorkshopTest\Asset\CliExerciseImpl; use PhpSchool\Terminal\Terminal; @@ -42,7 +44,7 @@ public function setUp(): void { $this->exercise = new CliExerciseImpl(); $this->eventDispatcher = new EventDispatcher(new ResultAggregator()); - $this->runner = new CliRunner($this->exercise, $this->eventDispatcher, new HostSandbox(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); + $this->runner = new CliRunner($this->exercise, $this->eventDispatcher, new HostSandboxFactory(), new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); $this->assertEquals('CLI Program Runner', $this->runner->getName()); } @@ -108,6 +110,28 @@ function (CliExecuteEvent $event) use (&$executions) { $this->assertContainsOnlyInstancesOf(SandboxExecution::class, $executions); } + public function testSandboxPicksOnePortForEachFolder(): void + { + $solution = SingleFileSolution::fromFile(realpath(__DIR__ . '/../res/cli/solution.php')); + $this->exercise->setSolution($solution); + $this->exercise->setScenario((new CliScenario())->exposePort()->withExecution([1, 2, 3])->withExecution([4, 5, 6])); + + $ports = []; + $this->eventDispatcher->listen( + ['cli.verify.reference-execute.pre', 'cli.verify.student-execute.pre'], + function (CliExecuteEvent $event) use (&$ports) { + $ports[$event->getName()][] = $event->getSandbox()->getPort(); + }, + ); + + $context = TestContext::fromExerciseAndStudentSolution($this->exercise, __DIR__ . '/../res/cli/user.php'); + $this->runner->verify($context); + + //the same port for every run of a folder + $this->assertCount(1, array_unique($ports['cli.verify.reference-execute.pre'])); + $this->assertCount(1, array_unique($ports['cli.verify.student-execute.pre'])); + } + public function testSuccessWithSingleSetOfArgsForBC(): void { $solution = SingleFileSolution::fromFile(realpath(__DIR__ . '/../res/cli/solution.php')); @@ -198,15 +222,26 @@ public function testRunPassesTheEntryPointRelativeToTheWorkingDirectory(): void $sandbox = new class implements Sandbox { /** @var array */ public array $inputs = []; + public Sandbox $host; - public function create(ProcessInput $processInput): SandboxExecution + public function execute(ProcessInput $processInput): SandboxExecution { $this->inputs[] = $processInput; - return (new HostSandbox())->create($processInput); + return $this->host->execute($processInput); + } + + public function getPort(): int + { + return 54321; } }; - $runner = new CliRunner($this->exercise, $this->eventDispatcher, $sandbox, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); + $factory = $this->createMock(SandboxFactory::class); + $factory->method('create')->willReturnCallback(function (string $directory, ExerciseScenario $scenario) use ($sandbox) { + $sandbox->host = (new HostSandboxFactory())->create($directory, $scenario); + return $sandbox; + }); + $runner = new CliRunner($this->exercise, $this->eventDispatcher, $factory, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); $this->exercise->setScenario((new CliScenario())->withExecution([1, 2, 3])); diff --git a/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php b/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php index 6bf45d40..0c5bb713 100644 --- a/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php +++ b/test/ExerciseRunner/Factory/CgiRunnerFactoryTest.php @@ -9,7 +9,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CgiRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\Factory\CgiRunnerFactory; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\Host\HostSandboxFactory; use PhpSchool\PhpWorkshopTest\Asset\CgiExerciseImpl; use PHPUnit\Framework\TestCase; @@ -21,7 +21,7 @@ class CgiRunnerFactoryTest extends TestCase public function setUp(): void { $this->eventDispatcher = $this->createMock(EventDispatcher::class); - $this->factory = new CgiRunnerFactory($this->eventDispatcher, new HostSandbox(), $this->createMock(EnvironmentManager::class)); + $this->factory = new CgiRunnerFactory($this->eventDispatcher, new HostSandboxFactory(), $this->createMock(EnvironmentManager::class)); } public function testSupports(): void diff --git a/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php b/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php index c057ef8d..efae80b5 100644 --- a/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php +++ b/test/ExerciseRunner/Factory/CliRunnerFactoryTest.php @@ -9,7 +9,7 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\CliRunner; use PhpSchool\PhpWorkshop\ExerciseRunner\EnvironmentManager; use PhpSchool\PhpWorkshop\ExerciseRunner\Factory\CliRunnerFactory; -use PhpSchool\PhpWorkshop\Process\HostSandbox; +use PhpSchool\PhpWorkshop\Process\Sandbox\Host\HostSandboxFactory; use PhpSchool\PhpWorkshopTest\Asset\CliExerciseImpl; use PHPUnit\Framework\TestCase; @@ -21,7 +21,7 @@ class CliRunnerFactoryTest extends TestCase public function setUp(): void { $this->eventDispatcher = $this->createMock(EventDispatcher::class); - $this->factory = new CliRunnerFactory($this->eventDispatcher, new HostSandbox(), $this->createMock(EnvironmentManager::class)); + $this->factory = new CliRunnerFactory($this->eventDispatcher, new HostSandboxFactory(), $this->createMock(EnvironmentManager::class)); } public function testSupports(): void diff --git a/test/Process/DockerExecutionTest.php b/test/Process/DockerExecutionTest.php deleted file mode 100644 index 88444e1b..00000000 --- a/test/Process/DockerExecutionTest.php +++ /dev/null @@ -1,47 +0,0 @@ -> ' . $log), - [Process::fromShellCommandline('echo before >> ' . $log)], - [Process::fromShellCommandline('echo after >> ' . $log)], - ); - - $execution->start(); - $execution->wait(); - - $this->assertSame("before\nmain\nafter\n", file_get_contents($log)); - unlink($log); - } - - public function testAfterStepsRunWhenTheMainProcessFails(): void - { - $log = tempnam(sys_get_temp_dir(), 'steps'); - - $execution = new DockerExecution( - Process::fromShellCommandline('exit 1'), - [], - [Process::fromShellCommandline('echo after >> ' . $log)], - ); - - $execution->start(); - $execution->wait(); - - $this->assertFalse($execution->isSuccessful()); - $this->assertSame("after\n", file_get_contents($log)); - unlink($log); - } -} diff --git a/test/Process/FreePortPickerTest.php b/test/Process/Port/FreePortPickerTest.php similarity index 76% rename from test/Process/FreePortPickerTest.php rename to test/Process/Port/FreePortPickerTest.php index 7ead740e..f178bcb7 100644 --- a/test/Process/FreePortPickerTest.php +++ b/test/Process/Port/FreePortPickerTest.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshopTest\Process; +namespace PhpSchool\PhpWorkshopTest\Process\Port; -use PhpSchool\PhpWorkshop\Process\FreePortPicker; +use PhpSchool\PhpWorkshop\Process\Port\FreePortPicker; use PHPUnit\Framework\TestCase; class FreePortPickerTest extends TestCase diff --git a/test/Process/LockPortPickerTest.php b/test/Process/Port/LockPortPickerTest.php similarity index 85% rename from test/Process/LockPortPickerTest.php rename to test/Process/Port/LockPortPickerTest.php index 3d05075e..7f88300f 100644 --- a/test/Process/LockPortPickerTest.php +++ b/test/Process/Port/LockPortPickerTest.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace PhpSchool\PhpWorkshopTest\Process; +namespace PhpSchool\PhpWorkshopTest\Process\Port; -use PhpSchool\PhpWorkshop\Process\LockPortPicker; +use PhpSchool\PhpWorkshop\Process\Port\LockPortPicker; use PHPUnit\Framework\TestCase; use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\Store\InMemoryStore; diff --git a/test/Process/DockerSandboxTest.php b/test/Process/Sandbox/Docker/DockerSandboxTest.php similarity index 66% rename from test/Process/DockerSandboxTest.php rename to test/Process/Sandbox/Docker/DockerSandboxTest.php index cd42f043..9fe5f1d6 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/Sandbox/Docker/DockerSandboxTest.php @@ -1,17 +1,18 @@ with('docker') ->willReturn('/usr/local/bin/docker'); - return new DockerSandbox('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost, $ports); + return new DockerSandboxFactory('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost, $ports); } /** @@ -60,15 +61,15 @@ public function testCreateThrowsExceptionIfDockerNotFound(): void ->with('docker') ->willReturn(null); - $factory = new DockerSandbox('/docker-dir', 'php8appreciate', $finder); - $input = new ProcessInput('php', [], __DIR__, [], []); + $factory = new DockerSandboxFactory('/docker-dir', 'php8appreciate', $finder); + $input = new ProcessInput('php', [], []); - $factory->create($input); + $factory->create(__DIR__, new CliScenario())->execute($input); } public function testCreateIsIsolatedWithNoNetwork(): void { - $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], []))->process; + $process = $this->factory()->create(__DIR__, new CliScenario())->execute(new ProcessInput('php', ['one', 'two'], []))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -82,10 +83,10 @@ public function testCreateIsIsolatedWithNoNetwork(): void public function testExposedPortsArePublishedOnLoopbackOnly(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $process = $this->factory()->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '127.0.0.1:47213:8000'], + ['--network', 'bridge', '-p', '127.0.0.1:47213:47213'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -94,10 +95,10 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void public function testExposedPortsUseTheGivenNetwork(): void { - $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $process = $this->factory('php-school-sandbox')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( - ['--network', 'php-school-sandbox', '-p', '127.0.0.1:47213:8000'], + ['--network', 'php-school-sandbox', '-p', '127.0.0.1:47213:47213'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -106,29 +107,37 @@ public function testExposedPortsUseTheGivenNetwork(): void public function testExposedPortsArePublishedOnTheGivenHost(): void { - $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; + $process = $this->factory('bridge', '172.19.0.2')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], []))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '172.19.0.2:47213:8000'], + ['--network', 'bridge', '-p', '172.19.0.2:47213:47213'], ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); } - public function testAddressIsThePickedPortOnTheGivenHost(): void + public function testPortsArePickedWithThePortPicker(): void { - $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000])); - static::assertSame('172.19.0.2:47213', $execution->getAddress(8000)); + $ports = $this->createMock(PortPicker::class); + $ports->method('pick')->willReturn(47213); - $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], [8000])); - static::assertStringContainsString("'-p' '[fdaa::2]:47213:8000'", $execution->process->getCommandLine()); - static::assertSame('[fdaa::2]:47213', $execution->getAddress(8000)); + static::assertSame(47213, (new DockerSandboxFactory('/docker-dir', 'php8appreciate', portPicker: $ports))->create(__DIR__, (new CliScenario())->exposePort())->getPort()); + } + + public function testAddressIsTheSamePortOnTheGivenHost(): void + { + $execution = $this->factory('bridge', '172.19.0.2')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], [])); + static::assertSame('172.19.0.2:47213', $execution->getAddress()); + + $execution = $this->factory('bridge', '[fdaa::2]')->create(__DIR__, (new CliScenario())->exposePort())->execute(new ProcessInput('php', [], [])); + static::assertStringContainsString("'-p' '[fdaa::2]:47213:47213'", $execution->process->getCommandLine()); + static::assertSame('[fdaa::2]:47213', $execution->getAddress()); } public function testCreateWithEnv(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], []))->process; + $process = $this->factory()->create(__DIR__, new CliScenario())->execute(new ProcessInput('php', [], ['SOME_VAR' => 'value']))->process; $expected = $this->expectedCommand( ['--network', 'none'], @@ -140,7 +149,7 @@ public function testCreateWithEnv(): void public function testWithInput(): void { - $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [], 'someinput'))->process; + $process = $this->factory()->create(__DIR__, new CliScenario())->execute(new ProcessInput('php', [], [], 'someinput'))->process; static::assertSame('someinput', $process->getInput()); } diff --git a/test/Process/HostSandboxTest.php b/test/Process/Sandbox/Host/HostSandboxTest.php similarity index 55% rename from test/Process/HostSandboxTest.php rename to test/Process/Sandbox/Host/HostSandboxTest.php index bc0ecbc0..f5cc622f 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/Sandbox/Host/HostSandboxTest.php @@ -1,11 +1,12 @@ with('composer') ->willReturn(null); - $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], []); + $factory = new HostSandboxFactory($finder); + $input = new ProcessInput('composer', [], []); - $factory->create($input); + $factory->create(__DIR__, new CliScenario())->execute($input); } public function testCreate(): void @@ -34,18 +35,25 @@ public function testCreate(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], []); + $factory = new HostSandboxFactory($finder); + $input = new ProcessInput('composer', [], []); - $process = $factory->create($input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame("'/usr/local/bin/composer'", $process->getCommandLine()); } + public function testPickedPortIsFreeOnThisMachine(): void + { + $server = stream_socket_server('tcp://127.0.0.1:' . (new HostSandboxFactory())->create(__DIR__, (new CliScenario())->exposePort())->getPort()); + static::assertNotFalse($server); + fclose($server); + } + public function testAddressIsThePortOnThisMachine(): void { - $execution = (new HostSandbox())->create(new ProcessInput('php', [], __DIR__, [], [54321])); + $sandbox = (new HostSandboxFactory())->create(__DIR__, (new CliScenario())->exposePort()); - static::assertSame('127.0.0.1:54321', $execution->getAddress(54321)); + static::assertSame('127.0.0.1:' . $sandbox->getPort(), $sandbox->execute(new ProcessInput('php', [], []))->getAddress()); } public function testCreateWithArgs(): void @@ -56,10 +64,10 @@ public function testCreateWithArgs(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, [], []); + $factory = new HostSandboxFactory($finder); + $input = new ProcessInput('composer', ['one', 'two'], []); - $process = $factory->create($input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame("'/usr/local/bin/composer' 'one' 'two'", $process->getCommandLine()); } @@ -71,10 +79,10 @@ public function testCreateWithEnv(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', ['one', 'two'], __DIR__, ['SOME_VAR' => 'value'], []); + $factory = new HostSandboxFactory($finder); + $input = new ProcessInput('composer', ['one', 'two'], ['SOME_VAR' => 'value']); - $process = $factory->create($input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame('value', $process->getEnv()['SOME_VAR']); } @@ -83,8 +91,8 @@ public function testInheritedEnvIsRemovedExceptAllowed(): void putenv('PHPSCHOOL_SECRET=secret'); try { - $process = (new HostSandbox())->create( - new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], __DIR__, [], []), + $process = (new HostSandboxFactory())->create(__DIR__, new CliScenario())->execute( + new ProcessInput('php', ['-r', 'echo json_encode([getenv("PHPSCHOOL_SECRET"), getenv("PATH") !== false]);'], []), ); $process->mustRun(); @@ -102,10 +110,10 @@ public function testWithInput(): void ->with('composer') ->willReturn('/usr/local/bin/composer'); - $factory = new HostSandbox($finder); - $input = new ProcessInput('composer', [], __DIR__, [], [], 'someinput'); + $factory = new HostSandboxFactory($finder); + $input = new ProcessInput('composer', [], [], 'someinput'); - $process = $factory->create($input)->process; + $process = $factory->create(__DIR__, new CliScenario())->execute($input)->process; static::assertSame('someinput', $process->getInput()); } } diff --git a/test/Process/ProcessInputTest.php b/test/Process/Sandbox/ProcessInputTest.php similarity index 54% rename from test/Process/ProcessInputTest.php rename to test/Process/Sandbox/ProcessInputTest.php index 84453cae..2a227f52 100644 --- a/test/Process/ProcessInputTest.php +++ b/test/Process/Sandbox/ProcessInputTest.php @@ -1,21 +1,19 @@ 'value'], [], 'input'); + $input = new ProcessInput('composer', ['one', 'two'], ['SOME_VAR' => 'value'], 'input'); static::assertSame('composer', $input->getExecutable()); static::assertSame(['one', 'two'], $input->getArgs()); - static::assertSame(__DIR__, $input->getWorkingDirectory()); static::assertSame(['SOME_VAR' => 'value'], $input->getEnv()); - static::assertSame([], $input->getExposedPorts()); static::assertSame('input', $input->getInput()); } }