coolify/bootstrap/helpers/remoteProcess.php

271 lines
9.4 KiB
PHP
Raw Normal View History

2023-05-24 14:26:50 +02:00
<?php
2023-05-24 15:25:08 +02:00
use App\Actions\CoolifyTask\PrepareCoolifyTask;
2023-05-24 14:26:50 +02:00
use App\Data\CoolifyTaskArgs;
2023-05-25 14:40:47 +02:00
use App\Enums\ActivityTypes;
2023-06-30 15:57:40 +02:00
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\PrivateKey;
2023-05-24 14:26:50 +02:00
use App\Models\Server;
2023-08-16 17:18:50 +02:00
use App\Notifications\Server\NotReachable;
2023-06-30 15:57:40 +02:00
use Carbon\Carbon;
2023-05-24 14:26:50 +02:00
use Illuminate\Database\Eloquent\Model;
2023-06-30 15:57:40 +02:00
use Illuminate\Support\Collection;
2023-05-24 14:26:50 +02:00
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Storage;
2023-05-31 12:38:36 +02:00
use Illuminate\Support\Sleep;
2023-05-24 14:26:50 +02:00
use Spatie\Activitylog\Models\Activity;
2023-05-24 15:25:08 +02:00
function remote_process(
array $command,
Server $server,
string $type = ActivityTypes::INLINE->value,
2023-05-24 15:25:08 +02:00
?string $type_uuid = null,
?Model $model = null,
2023-06-30 22:24:39 +02:00
bool $ignore_errors = false,
2023-08-11 20:48:52 +02:00
): Activity {
2023-05-24 14:26:50 +02:00
2023-05-24 15:25:08 +02:00
$command_string = implode("\n", $command);
2023-06-30 22:24:39 +02:00
if (auth()->user()) {
$teams = auth()->user()->teams->pluck('id');
if (!$teams->contains($server->team_id) && !$teams->contains(0)) {
throw new \Exception("User is not part of the team that owns this server");
}
}
2023-05-24 14:26:50 +02:00
2023-05-24 15:25:08 +02:00
return resolve(PrepareCoolifyTask::class, [
'remoteProcessArgs' => new CoolifyTaskArgs(
server_ip: $server->ip,
command: <<<EOT
2023-05-24 14:26:50 +02:00
{$command_string}
EOT,
2023-05-24 15:25:08 +02:00
port: $server->port,
user: $server->user,
type: $type,
type_uuid: $type_uuid,
model: $model,
2023-06-07 15:39:08 +02:00
ignore_errors: $ignore_errors
2023-05-24 15:25:08 +02:00
),
])();
2023-05-24 14:26:50 +02:00
}
2023-09-15 12:30:25 +02:00
// function removePrivateKeyFromSshAgent(Server $server)
// {
// if (data_get($server, 'privateKey.private_key') === null) {
// throw new \Exception("Server {$server->name} does not have a private key");
// }
// // processWithEnv()->run("echo '{$server->privateKey->private_key}' | ssh-add -d -");
// }
2023-09-14 10:56:25 +02:00
function addPrivateKeyToSshAgent(Server $server)
2023-05-24 15:25:08 +02:00
{
2023-06-07 10:33:45 +02:00
if (data_get($server, 'privateKey.private_key') === null) {
throw new \Exception("Server {$server->name} does not have a private key");
}
2023-09-15 12:30:25 +02:00
$sshKeyFileLocation = "id.root@{$server->uuid}";
Storage::disk('ssh-keys')->makeDirectory('.');
Storage::disk('ssh-mux')->makeDirectory('.');
Storage::disk('ssh-keys')->put($sshKeyFileLocation, $server->privateKey->private_key);
return '/var/www/html/storage/app/ssh/keys/' . $sshKeyFileLocation;
2023-05-24 14:26:50 +02:00
}
function generateSshCommand(string $server_ip, string $user, string $port, string $command, bool $isMux = true)
2023-05-24 15:25:08 +02:00
{
$server = Server::where('ip', $server_ip)->first();
if (!$server) {
throw new \Exception("Server with ip {$server_ip} not found");
}
2023-09-15 12:30:25 +02:00
$privateKeyLocation = addPrivateKeyToSshAgent($server);
2023-09-13 13:00:16 +02:00
$timeout = config('constants.ssh.command_timeout');
$connectionTimeout = config('constants.ssh.connection_timeout');
$serverInterval = config('constants.ssh.server_interval');
2023-05-24 15:25:08 +02:00
$delimiter = 'EOF-COOLIFY-SSH';
2023-09-13 13:00:16 +02:00
$ssh_command = "timeout $timeout ssh ";
2023-05-24 14:26:50 +02:00
2023-05-24 15:25:08 +02:00
if ($isMux && config('coolify.mux_enabled')) {
2023-05-25 12:55:34 +02:00
$ssh_command .= '-o ControlMaster=auto -o ControlPersist=1m -o ControlPath=/var/www/html/storage/app/ssh/mux/%h_%p_%r ';
2023-05-24 14:26:50 +02:00
}
$command = "PATH=\$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/host/usr/local/sbin:/host/usr/local/bin:/host/usr/sbin:/host/usr/bin:/host/sbin:/host/bin && $command";
2023-09-15 12:30:25 +02:00
$ssh_command .= "-i {$privateKeyLocation} "
. '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '
2023-05-24 15:25:08 +02:00
. '-o PasswordAuthentication=no '
2023-09-13 13:00:16 +02:00
. "-o ConnectTimeout=$connectionTimeout "
. "-o ServerAliveInterval=$serverInterval "
2023-05-24 15:25:08 +02:00
. '-o RequestTTY=no '
. '-o LogLevel=ERROR '
. "-p {$port} "
. "{$user}@{$server_ip} "
. " 'bash -se' << \\$delimiter" . PHP_EOL
. $command . PHP_EOL
. $delimiter;
// ray($ssh_command);
2023-05-24 15:25:08 +02:00
return $ssh_command;
2023-05-24 14:26:50 +02:00
}
2023-09-15 12:30:25 +02:00
// function processWithEnv()
// {
// return Process::env(['SSH_AUTH_SOCK' => config('coolify.ssh_auth_sock')]);
// }
// function instantCommand(string $command, $throwError = true)
// {
// $process = Process::run($command);
// $output = trim($process->output());
// $exitCode = $process->exitCode();
// if ($exitCode !== 0) {
// if (!$throwError) {
// return null;
// }
// throw new \RuntimeException($process->errorOutput(), $exitCode);
// }
// return $output;
// }
2023-05-31 12:38:36 +02:00
function instant_remote_process(array $command, Server $server, $throwError = true, $repeat = 1)
2023-05-24 15:25:08 +02:00
{
$command_string = implode("\n", $command);
$ssh_command = generateSshCommand($server->ip, $server->user, $server->port, $command_string);
2023-09-15 12:30:25 +02:00
$process = Process::run($ssh_command);
2023-05-24 15:25:08 +02:00
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
2023-05-31 12:38:36 +02:00
if ($repeat > 1) {
2023-08-16 17:18:50 +02:00
ray("repeat: ", $repeat);
2023-05-31 12:38:36 +02:00
Sleep::for(200)->milliseconds();
return instant_remote_process($command, $server, $throwError, $repeat - 1);
}
2023-06-07 10:33:45 +02:00
// ray('ERROR OCCURED: ' . $process->errorOutput());
2023-05-24 15:25:08 +02:00
if (!$throwError) {
return null;
2023-05-24 14:26:50 +02:00
}
throw new \RuntimeException($process->errorOutput(), $exitCode);
2023-05-24 14:26:50 +02:00
}
2023-05-24 15:25:08 +02:00
return $output;
2023-05-24 14:26:50 +02:00
}
2023-06-30 15:57:40 +02:00
function decode_remote_command_output(?ApplicationDeploymentQueue $application_deployment_queue = null): Collection
{
$application = Application::find(data_get($application_deployment_queue, 'application_id'));
$is_debug_enabled = data_get($application, 'settings.is_debug_enabled');
if (is_null($application_deployment_queue)) {
return collect([]);
}
try {
$decoded = json_decode(
2023-06-30 21:22:14 +02:00
data_get($application_deployment_queue, 'logs'),
2023-06-30 15:57:40 +02:00
associative: true,
flags: JSON_THROW_ON_ERROR
);
} catch (\JsonException $exception) {
return collect([]);
}
$formatted = collect($decoded);
if (!$is_debug_enabled) {
2023-08-11 20:48:52 +02:00
$formatted = $formatted->filter(fn ($i) => $i['hidden'] === false ?? false);
2023-06-30 15:57:40 +02:00
}
2023-06-30 21:22:14 +02:00
$formatted = $formatted
2023-08-11 20:48:52 +02:00
->sortBy(fn ($i) => $i['order'])
2023-06-30 15:57:40 +02:00
->map(function ($i) {
$i['timestamp'] = Carbon::parse($i['timestamp'])->format('Y-M-d H:i:s.u');
return $i;
});
return $formatted;
}
2023-08-16 17:18:50 +02:00
function refresh_server_connection(PrivateKey $private_key)
{
foreach ($private_key->servers as $server) {
Storage::disk('ssh-mux')->delete($server->muxFilename());
}
2023-09-15 12:30:25 +02:00
// removePrivateKeyFromSshAgent($server);
}
function validateServer(Server $server)
{
try {
2023-08-16 17:18:50 +02:00
refresh_server_connection($server->privateKey);
2023-08-28 20:29:44 +02:00
$uptime = instant_remote_process(['uptime'], $server, false);
if (!$uptime) {
2023-08-28 20:29:44 +02:00
$server->settings->is_reachable = false;
return [
"uptime" => null,
"dockerVersion" => null,
];
}
$server->settings->is_reachable = true;
$dockerVersion = instant_remote_process(["docker version|head -2|grep -i version| awk '{print $2}'"], $server, false);
if (!$dockerVersion) {
2023-08-28 20:29:44 +02:00
$dockerVersion = null;
return [
"uptime" => $uptime,
"dockerVersion" => null,
];
}
$majorDockerVersion = Str::of($dockerVersion)->before('.')->value();
if ($majorDockerVersion <= 22) {
$dockerVersion = null;
$server->settings->is_usable = false;
} else {
$server->settings->is_usable = true;
}
return [
"uptime" => $uptime,
"dockerVersion" => $dockerVersion,
];
2023-09-11 17:36:30 +02:00
} catch (\Throwable $e) {
$server->settings->is_reachable = false;
$server->settings->is_usable = false;
throw $e;
} finally {
if (data_get($server, 'settings')) $server->settings->save();
}
}
2023-08-16 17:18:50 +02:00
2023-08-16 17:20:01 +02:00
function check_server_connection(Server $server)
{
2023-08-16 17:18:50 +02:00
try {
refresh_server_connection($server->privateKey);
instant_remote_process(['uptime'], $server);
$server->unreachable_count = 0;
$server->settings->is_reachable = true;
2023-09-11 17:36:30 +02:00
} catch (\Throwable $e) {
2023-08-16 17:18:50 +02:00
if ($server->unreachable_count == 2) {
$server->team->notify(new NotReachable($server));
$server->settings->is_reachable = false;
$server->settings->save();
} else {
$server->unreachable_count += 1;
}
throw $e;
} finally {
$server->settings->save();
$server->save();
}
}
function checkRequiredCommands(Server $server)
{
$commands = collect(["jq", "jc"]);
foreach ($commands as $command) {
$commandFound = instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'command -v {$command}'"], $server, false);
if ($commandFound) {
ray($command . ' found');
continue;
}
try {
instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'apt update && apt install -y {$command}'"], $server);
2023-09-11 17:36:30 +02:00
} catch (\Throwable $e) {
ray('could not install ' . $command);
ray($e);
break;
}
$commandFound = instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'command -v {$command}'"], $server, false);
if ($commandFound) {
ray($command . ' found');
continue;
}
ray('could not install ' . $command);
break;
}
}