lasthourcloud/bootstrap/helpers/docker.php

77 lines
2.3 KiB
PHP
Raw Normal View History

2023-05-24 12:26:50 +00:00
<?php
use App\Models\Server;
use Illuminate\Support\Collection;
function format_docker_command_output_to_json($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
2023-08-11 18:48:52 +00:00
->reject(fn ($line) => empty($line))
->map(fn ($outputLine) => json_decode($outputLine, true, flags: JSON_THROW_ON_ERROR));
2023-05-24 12:26:50 +00:00
}
2023-05-24 12:26:50 +00:00
function format_docker_labels_to_json($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
2023-08-11 18:48:52 +00:00
->reject(fn ($line) => empty($line))
2023-05-24 12:26:50 +00:00
->map(function ($outputLine) {
$outputArray = explode(',', $outputLine);
return collect($outputArray)
->map(function ($outputLine) {
return explode('=', $outputLine);
})
->mapWithKeys(function ($outputLine) {
return [$outputLine[0] => $outputLine[1]];
});
})[0];
}
2023-08-11 14:13:53 +00:00
function format_docker_envs_to_json($rawOutput)
{
try {
$outputLines = json_decode($rawOutput, true, flags: JSON_THROW_ON_ERROR);
return collect(data_get($outputLines[0], 'Config.Env', []))->mapWithKeys(function ($env) {
$env = explode('=', $env);
return [$env[0] => $env[1]];
});
} catch (\Throwable $th) {
return collect([]);
}
}
2023-06-02 13:15:12 +00:00
function get_container_status(Server $server, string $container_id, bool $all_data = false, bool $throwError = false)
2023-05-24 12:26:50 +00:00
{
2023-06-02 13:15:12 +00:00
$container = instant_remote_process(["docker inspect --format '{{json .}}' {$container_id}"], $server, $throwError);
2023-05-24 12:26:50 +00:00
if (!$container) {
return 'exited';
}
$container = format_docker_command_output_to_json($container);
2023-06-02 13:15:12 +00:00
if ($all_data) {
return $container[0];
}
return $container[0]['State']['Status'];
2023-05-24 12:26:50 +00:00
}
2023-05-30 13:52:17 +00:00
2023-06-30 20:24:39 +00:00
function generate_container_name(string $uuid, int $pull_request_id = 0)
2023-05-30 13:52:17 +00:00
{
2023-06-30 20:24:39 +00:00
if ($pull_request_id !== 0) {
2023-05-30 15:00:11 +00:00
return $uuid . '-pr-' . $pull_request_id;
2023-05-30 13:52:17 +00:00
} else {
return $uuid;
}
}
2023-08-11 20:41:47 +00:00
function get_port_from_dockerfile($dockerfile): int
{
$port = preg_grep('/EXPOSE\s+(\d+)/', explode("\n", $dockerfile));
if (count($port) > 0 && preg_match('/EXPOSE\s+(\d+)/', $port[1], $matches)) {
$port = $matches[1];
} else {
$port = 80;
}
return $port;
}