Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions app/controllers.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,11 @@ function logError(Log $log, Throwable $error, string $action, Logger $logger = n
->param('memory', 512, new Integer(), 'Container RAM memory.', true)
->param('version', 'v5', new WhiteList(\explode(',', Http::getEnv('OPR_EXECUTOR_RUNTIME_VERSIONS', 'v5') ?? 'v5')), 'Runtime Open Runtime version.', true)
->param('restartPolicy', DockerAPI::RESTART_NO, new WhiteList([DockerAPI::RESTART_NO, DockerAPI::RESTART_ALWAYS, DockerAPI::RESTART_ON_FAILURE, DockerAPI::RESTART_UNLESS_STOPPED], true), 'Define restart policy for the runtime once an exit code is returned. Default value is "no". Possible values are "no", "always", "on-failure", "unless-stopped".', true)
->inject('request')
->inject('response')
->inject('log')
->inject('runner')
->action(function (string $runtimeId, string $image, string $entrypoint, string $source, string $destination, string $outputDirectory, array $variables, string $runtimeEntrypoint, string $command, int $timeout, bool $remove, float $cpus, int $memory, string $version, string $restartPolicy, Response $response, Log $log, Runner $runner) {
->action(function (string $runtimeId, string $image, string $entrypoint, string $source, string $destination, string $outputDirectory, array $variables, string $runtimeEntrypoint, string $command, int $timeout, bool $remove, float $cpus, int $memory, string $version, string $restartPolicy, Request $request, Response $response, Log $log, Runner $runner) {
$secret = \bin2hex(\random_bytes(16));

/**
Expand Down Expand Up @@ -150,8 +151,26 @@ function logError(Log $log, Throwable $error, string $action, Logger $logger = n

$variables = array_map(fn ($v) => strval($v), $variables);

$isStream = str_contains($request->getAccept(), 'text/event-stream');
if ($isStream) {
// send first byte to avoid first byte timeouts
$response->sendHeader('Content-Type', 'text/event-stream');
$response->write(' ');
}

$container = $runner->createRuntime($runtimeId, $secret, $image, $entrypoint, $source, $destination, $variables, $runtimeEntrypoint, $command, $timeout, $remove, $cpus, $memory, $version, $restartPolicy, $log);
$response->setStatusCode(Response::STATUS_CODE_CREATED)->json($container);

$response->setStatusCode(Response::STATUS_CODE_CREATED);
if ($isStream) {
$json = json_encode($container, JSON_UNESCAPED_UNICODE);
if ($json === false) {
throw new Exception('failed to encode container', 400);
}
$response->write($json);
$response->end();
} else {
$response->json($container);
}
});

Http::get('/v1/runtimes')
Expand Down Expand Up @@ -363,9 +382,10 @@ function (
->inject('route')
->inject('error')
->inject('logger')
->inject('request')
->inject('response')
->inject('log')
->action(function (?Route $route, Throwable $error, ?Logger $logger, Response $response, Log $log) {
->action(function (?Route $route, Throwable $error, ?Logger $logger, Request $request, Response $response, Log $log) {
try {
logError($log, $error, "httpError", $logger, $route);
} catch (Throwable) {
Expand Down Expand Up @@ -410,6 +430,18 @@ function (
'version' => $version
];

// workaround for streaming
$isStream = str_contains($request->getAccept(), 'text/event-stream');
if ($isStream) {
$json = json_encode($output, JSON_UNESCAPED_UNICODE);
if ($json === false) {
throw new Exception('failed to encode container', 400);
}
$response->write($json);
$response->end();
return;
}

$response
->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
->addHeader('Expires', '0')
Expand Down
75 changes: 75 additions & 0 deletions tests/ExecutorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,81 @@ public function testBuild(): void
$this->assertEquals(500, $response['headers']['status-code']);
}

public function testBuildStream(): void
{
$output = '';
Console::execute('cd /app/tests/resources/functions/php && tar --exclude code.tar.gz -czf code.tar.gz .', '', $output);

$runtimeId = \bin2hex(\random_bytes(4));

/** Build runtime */
$params = [
'runtimeId' => 'test-build-' . $runtimeId,
'source' => '/storage/functions/php/code.tar.gz',
'destination' => '/storage/builds/test',
'entrypoint' => 'index.php',
'image' => 'openruntimes/php:v5-8.1',
'command' => 'tar -zxf /tmp/code.tar.gz -C /mnt/code && bash helpers/build.sh "composer install"',
];

$response = '';
$this->client->call(Client::METHOD_POST, '/runtimes', [], $params, decode: true, callback: function ($chunk) use (&$response) {
$response .= $chunk;
});
$body = json_decode($response, true);
$status = $body['code'] ?? 201;
$this->assertEquals(201, $status);
$this->assertIsString($body['path']);
$this->assertIsArray($body['output']);
$this->assertIsFloat($body['duration']);
$this->assertIsFloat($body['startTime']);
$this->assertIsInt($body['size']);

/** Get runtime */
$response = $this->client->call(Client::METHOD_GET, '/runtimes/test-build-' . $runtimeId, [], []);
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertStringEndsWith('test-build-' . $runtimeId, $response['body']['name']);

/** User error in build command */
$params = [
'runtimeId' => 'test-build-fail-400-' . $runtimeId,
'source' => '/storage/functions/php/code.tar.gz',
'destination' => '/storage/builds/test',
'entrypoint' => 'index.php',
'image' => 'openruntimes/php:v5-8.1',
'command' => 'cp doesnotexist.js doesnotexist2.js',
'remove' => true
];

$response = '';
$this->client->call(Client::METHOD_POST, '/runtimes', params: $params, callback: function ($chunk) use (&$response) {
$response .= $chunk;
});
$body = json_decode($response, true);
$status = $body['code'] ?? 201;

$this->assertEquals(400, $status);

/** Test invalid path */
$params = [
'runtimeId' => 'test-build-fail-500-' . $runtimeId,
'source' => '/storage/fake_path/code.tar.gz',
'destination' => '/storage/builds/test',
'entrypoint' => 'index.php',
'image' => 'openruntimes/php:v5-8.1',
'command' => 'tar -zxf /tmp/code.tar.gz -C /mnt/code && bash helpers/build.sh "composer install"',
'remove' => true
];

$response = '';
$this->client->call(Client::METHOD_POST, '/runtimes', [], $params, callback: function ($chunk) use (&$response) {
$response .= $chunk;
});
$body = json_decode($response, true);
$status = $body['code'] ?? 201;
$this->assertEquals(500, $status);
}

public function testBuildOutputDirectory(): void
{
$output = '';
Expand Down