lasthourcloud/bootstrap/helpers.php

317 lines
12 KiB
PHP
Raw Normal View History

2023-03-20 12:04:22 +00:00
<?php
2023-05-03 05:15:45 +00:00
use App\Actions\CoolifyTask\PrepareCoolifyTask;
use App\Data\CoolifyTaskArgs;
2023-05-08 09:51:03 +00:00
use App\Models\GithubApp;
2023-03-24 14:48:57 +00:00
use App\Models\Server;
use Illuminate\Database\Eloquent\Model;
2023-05-05 12:20:10 +00:00
use Illuminate\Database\QueryException;
2023-03-30 13:52:19 +00:00
use Illuminate\Support\Collection;
2023-04-28 13:22:36 +00:00
use Illuminate\Support\Facades\Http;
2023-03-30 13:52:19 +00:00
use Illuminate\Support\Facades\Log;
2023-03-31 07:42:05 +00:00
use Illuminate\Support\Facades\Process;
2023-05-08 09:51:03 +00:00
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
2023-03-20 12:04:22 +00:00
use Spatie\Activitylog\Contracts\Activity;
2023-05-10 11:09:03 +00:00
use Illuminate\Support\Str;
2023-05-12 08:45:28 +00:00
use Visus\Cuid2\Cuid2;
2023-03-20 12:04:22 +00:00
2023-05-09 09:33:50 +00:00
if (!function_exists('generalErrorHandler')) {
2023-05-11 13:20:02 +00:00
function generalErrorHandler(\Throwable $e, $that = null, $isJson = false)
2023-05-05 12:20:10 +00:00
{
2023-05-11 13:20:02 +00:00
try {
2023-05-09 09:33:50 +00:00
if ($e instanceof QueryException) {
if ($e->errorInfo[0] === '23505') {
2023-05-11 13:20:02 +00:00
throw new \Exception('Duplicate entry found.', '23505');
2023-05-09 09:33:50 +00:00
} else if (count($e->errorInfo) === 4) {
2023-05-11 13:20:02 +00:00
throw new \Exception($e->errorInfo[3]);
2023-05-09 09:33:50 +00:00
} else {
2023-05-11 13:20:02 +00:00
throw new \Exception($e->errorInfo[2]);
2023-05-09 09:33:50 +00:00
}
2023-05-05 12:20:10 +00:00
} else {
2023-05-11 13:20:02 +00:00
throw new \Exception($e->getMessage());
}
} catch (\Throwable $error) {
if ($that) {
2023-05-15 12:54:03 +00:00
$that->emit('error', $error->getMessage());
2023-05-11 13:20:02 +00:00
} elseif ($isJson) {
return response()->json([
'code' => $error->getCode(),
'error' => $error->getMessage(),
]);
} else {
2023-05-15 11:45:37 +00:00
// dump($error);
2023-05-05 12:20:10 +00:00
}
}
}
}
2023-03-24 14:48:57 +00:00
if (!function_exists('remoteProcess')) {
2023-03-20 12:04:22 +00:00
/**
* Run a Remote Process, which SSH's asynchronously into a machine to run the command(s).
* @TODO Change 'root' to 'coolify' when it's able to run Docker commands without sudo
2023-03-20 12:04:22 +00:00
*
*/
function remoteProcess(
2023-05-03 05:15:45 +00:00
array $command,
Server $server,
2023-05-03 06:24:34 +00:00
string $type,
2023-05-03 05:15:45 +00:00
?string $type_uuid = null,
?Model $model = null,
2023-03-24 14:48:57 +00:00
): Activity {
2023-03-31 16:54:55 +00:00
$command_string = implode("\n", $command);
2023-03-31 16:54:55 +00:00
// @TODO: Check if the user has access to this server
// checkTeam($server->team_id);
2023-04-04 12:11:53 +00:00
$private_key_location = savePrivateKeyForServer($server);
2023-05-03 05:15:45 +00:00
return resolve(PrepareCoolifyTask::class, [
'remoteProcessArgs' => new CoolifyTaskArgs(
server_ip: $server->ip,
private_key_location: $private_key_location,
2023-03-28 13:47:37 +00:00
command: <<<EOT
{$command_string}
2023-03-28 13:47:37 +00:00
EOT,
port: $server->port,
user: $server->user,
2023-05-03 06:24:34 +00:00
type: $type,
2023-05-03 05:15:45 +00:00
type_uuid: $type_uuid,
2023-03-31 16:54:55 +00:00
model: $model,
),
])();
2023-03-20 12:04:22 +00:00
}
2023-03-30 13:52:19 +00:00
}
2023-03-31 11:32:07 +00:00
// function checkTeam(string $team_id)
// {
// $found_team = auth()->user()->teams->pluck('id')->contains($team_id);
// if (!$found_team) {
// throw new \RuntimeException('You do not have access to this server.');
// }
// }
2023-04-04 12:11:53 +00:00
if (!function_exists('savePrivateKeyForServer')) {
function savePrivateKeyForServer(Server $server)
2023-03-30 13:52:19 +00:00
{
$temp_file = "id.root@{$server->ip}";
Storage::disk('ssh-keys')->put($temp_file, $server->privateKey->private_key, 'private');
return '/var/www/html/storage/app/ssh-keys/' . $temp_file;
2023-03-30 13:52:19 +00:00
}
}
if (!function_exists('generateSshCommand')) {
2023-05-03 12:24:23 +00:00
function generateSshCommand(string $private_key_location, string $server_ip, string $user, string $port, string $command, bool $isMux = true)
2023-03-30 13:52:19 +00:00
{
$delimiter = 'EOF-COOLIFY-SSH';
Storage::disk('local')->makeDirectory('.ssh');
2023-03-31 06:36:17 +00:00
$ssh_command = "ssh ";
2023-05-05 15:56:03 +00:00
if ($isMux && config('coolify.mux_enabled')) {
2023-03-31 06:36:17 +00:00
$ssh_command .= '-o ControlMaster=auto -o ControlPersist=1m -o ControlPath=/var/www/html/storage/app/.ssh/ssh_mux_%h_%p_%r ';
}
$ssh_command .= "-i {$private_key_location} "
2023-03-30 13:52:19 +00:00
. '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '
. '-o PasswordAuthentication=no '
2023-05-02 17:15:17 +00:00
. '-o ConnectTimeout=3600 '
2023-05-03 09:28:13 +00:00
. '-o ServerAliveInterval=60 '
2023-03-30 13:52:19 +00:00
. '-o RequestTTY=no '
. '-o LogLevel=ERROR '
. "-p {$port} "
. "{$user}@{$server_ip} "
. " 'bash -se' << \\$delimiter" . PHP_EOL
. $command . PHP_EOL
. $delimiter;
2023-03-31 06:36:17 +00:00
2023-03-30 13:52:19 +00:00
return $ssh_command;
}
}
if (!function_exists('formatDockerCmdOutputToJson')) {
function formatDockerCmdOutputToJson($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->map(fn ($outputLine) => json_decode($outputLine, true, flags: JSON_THROW_ON_ERROR));
}
}
if (!function_exists('formatDockerLabelsToJson')) {
function formatDockerLabelsToJson($rawOutput): Collection
2023-03-28 13:47:37 +00:00
{
2023-03-30 13:52:19 +00:00
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->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-03-20 12:04:22 +00:00
}
2023-05-03 05:15:45 +00:00
if (!function_exists('instantRemoteProcess')) {
function instantRemoteProcess(array $command, Server $server, $throwError = true)
2023-04-04 12:11:53 +00:00
{
2023-03-31 07:42:05 +00:00
$command_string = implode("\n", $command);
2023-04-04 12:11:53 +00:00
$private_key_location = savePrivateKeyForServer($server);
2023-03-31 07:42:05 +00:00
$ssh_command = generateSshCommand($private_key_location, $server->ip, $server->user, $server->port, $command_string);
$process = Process::run($ssh_command);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
2023-05-02 10:47:52 +00:00
if (!$throwError) {
2023-05-15 11:45:37 +00:00
return null;
2023-05-02 10:47:52 +00:00
}
2023-05-15 11:45:37 +00:00
throw new \RuntimeException($process->errorOutput());
2023-03-31 07:42:05 +00:00
}
return $output;
}
}
2023-04-28 13:22:36 +00:00
if (!function_exists('getLatestVersionOfCoolify')) {
function getLatestVersionOfCoolify()
{
2023-05-11 13:28:34 +00:00
$response = Http::get('https://coolify-cdn.b-cdn.net/versions.json');
2023-04-28 13:22:36 +00:00
$versions = $response->json();
return data_get($versions, 'coolify.v4.version');
}
}
2023-05-02 07:11:22 +00:00
if (!function_exists('generateRandomName')) {
function generateRandomName()
{
2023-05-12 08:45:28 +00:00
$generator = \Nubs\RandomNameGenerator\All::create();
$cuid = new Cuid2(7);
return Str::kebab("{$generator->getName()}-{$cuid}");
2023-05-02 07:11:22 +00:00
}
}
2023-05-08 09:51:03 +00:00
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Token\Builder;
2023-05-15 11:45:37 +00:00
use Symfony\Component\Yaml\Yaml;
2023-05-08 09:51:03 +00:00
2023-05-09 12:42:10 +00:00
if (!function_exists('generate_github_installation_token')) {
function generate_github_installation_token(GithubApp $source)
2023-05-08 09:51:03 +00:00
{
$signingKey = InMemory::plainText($source->privateKey->private_key);
$algorithm = new Sha256();
$tokenBuilder = (new Builder(new JoseEncoder(), ChainedFormatter::default()));
$now = new DateTimeImmutable();
$now = $now->setTime($now->format('H'), $now->format('i'));
$issuedToken = $tokenBuilder
->issuedBy($source->app_id)
->issuedAt($now)
->expiresAt($now->modify('+10 minutes'))
->getToken($algorithm, $signingKey)
->toString();
$token = Http::withHeaders([
'Authorization' => "Bearer $issuedToken",
'Accept' => 'application/vnd.github.machine-man-preview+json'
])->post("{$source->api_url}/app/installations/{$source->installation_id}/access_tokens");
if ($token->failed()) {
throw new \Exception("Failed to get access token for " . $source->name . " with error: " . $token->json()['message']);
}
return $token->json()['token'];
}
}
2023-05-09 12:42:10 +00:00
if (!function_exists('generate_github_jwt_token')) {
function generate_github_jwt_token(GithubApp $source)
{
$signingKey = InMemory::plainText($source->privateKey->private_key);
$algorithm = new Sha256();
$tokenBuilder = (new Builder(new JoseEncoder(), ChainedFormatter::default()));
$now = new DateTimeImmutable();
$now = $now->setTime($now->format('H'), $now->format('i'));
$issuedToken = $tokenBuilder
->issuedBy($source->app_id)
->issuedAt($now->modify('-1 minute'))
->expiresAt($now->modify('+10 minutes'))
->getToken($algorithm, $signingKey)
->toString();
return $issuedToken;
}
}
2023-05-08 11:36:49 +00:00
if (!function_exists('getParameters')) {
function getParameters()
2023-05-08 09:51:03 +00:00
{
return Route::current()->parameters();
2023-05-02 07:11:22 +00:00
}
}
2023-05-15 11:45:37 +00:00
if (!function_exists('checkContainerStatus')) {
function checkContainerStatus(Server $server, string $container_id, bool $throwError = false)
{
$container = instantRemoteProcess(["docker inspect --format '{{json .State}}' {$container_id}"], $server, $throwError);
if (!$container) {
return 'exited';
}
$container = formatDockerCmdOutputToJson($container);
return $container[0]['Status'];
}
}
if (!function_exists('getProxyConfiguration')) {
function getProxyConfiguration(Server $server)
{
$proxy_config_path = config('coolify.proxy_config_path');
$networks = collect($server->standaloneDockers)->map(function ($docker) {
return $docker['network'];
})->unique();
if ($networks->count() === 0) {
$networks = collect(['coolify']);
}
$array_of_networks = collect([]);
$networks->map(function ($network) use ($array_of_networks) {
$array_of_networks[$network] = [
"external" => true,
];
});
return Yaml::dump([
"version" => "3.8",
"networks" => $array_of_networks->toArray(),
"services" => [
"traefik" => [
"container_name" => "coolify-proxy", # Do not modify this! You will break everything!
"image" => "traefik:v2.10",
"restart" => "always",
"extra_hosts" => [
"host.docker.internal:host-gateway",
],
"networks" => $networks->toArray(), # Do not modify this! You will break everything!
"ports" => [
"80:80",
"443:443",
"8080:8080",
],
"volumes" => [
"/var/run/docker.sock:/var/run/docker.sock:ro",
"{$proxy_config_path}/letsencrypt:/letsencrypt", # Do not modify this! You will break everything!
"{$proxy_config_path}/traefik.auth:/auth/traefik.auth", # Do not modify this! You will break everything!
],
"command" => [
"--api.dashboard=true",
"--api.insecure=true",
"--entrypoints.http.address=:80",
"--entrypoints.https.address=:443",
"--providers.docker=true",
"--providers.docker.exposedbydefault=false",
],
"labels" => [
"traefik.enable=true", # Do not modify this! You will break everything!
"traefik.http.routers.traefik.entrypoints=http",
'traefik.http.routers.traefik.rule=Host(`${TRAEFIK_DASHBOARD_HOST}`)',
"traefik.http.routers.traefik.service=api@internal",
"traefik.http.services.traefik.loadbalancer.server.port=8080",
"traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https",
],
],
],
], 4, 2);
}
}