coolify/bootstrap/helpers/remoteProcess.php

333 lines
11 KiB
PHP
Raw Normal View History

2023-05-24 12:26:50 +00:00
<?php
2023-05-24 13:25:08 +00:00
use App\Actions\CoolifyTask\PrepareCoolifyTask;
2023-05-24 12:26:50 +00:00
use App\Data\CoolifyTaskArgs;
2023-05-25 12:40:47 +00:00
use App\Enums\ActivityTypes;
2024-09-16 20:33:43 +00:00
use App\Helpers\SshMultiplexingHelper;
2023-06-30 13:57:40 +00:00
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\PrivateKey;
2023-05-24 12:26:50 +00:00
use App\Models\Server;
2023-06-30 13:57:40 +00:00
use Carbon\Carbon;
2023-05-24 12:26:50 +00:00
use Illuminate\Database\Eloquent\Model;
2023-06-30 13:57:40 +00:00
use Illuminate\Support\Collection;
2024-09-16 20:33:43 +00:00
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Process;
2023-09-15 10:43:03 +00:00
use Illuminate\Support\Str;
2023-09-18 09:49:26 +00:00
use Spatie\Activitylog\Contracts\Activity;
2023-05-24 12:26:50 +00:00
2023-05-24 13:25:08 +00:00
function remote_process(
2024-06-10 20:43:34 +00:00
Collection|array $command,
Server $server,
?string $type = null,
2023-05-24 13:25:08 +00:00
?string $type_uuid = null,
2024-06-10 20:43:34 +00:00
?Model $model = null,
bool $ignore_errors = false,
$callEventOnFinish = null,
$callEventData = null
2023-08-11 18:48:52 +00:00
): Activity {
$type = $type ?? ActivityTypes::INLINE->value;
$command = $command instanceof Collection ? $command->toArray() : $command;
2024-04-16 13:42:38 +00:00
if ($server->isNonRoot()) {
$command = parseCommandsByLineForSudo(collect($command), $server);
2024-04-16 13:42:38 +00:00
}
$command_string = implode("\n", $command);
2024-09-17 10:26:11 +00:00
if (Auth::check()) {
$teams = Auth::user()->teams->pluck('id');
if (! $teams->contains($server->team_id) && ! $teams->contains(0)) {
2024-06-10 20:43:34 +00:00
throw new \Exception('User is not part of the team that owns this server');
2023-06-30 20:24:39 +00:00
}
}
2024-06-10 20:43:34 +00:00
2024-09-16 20:33:43 +00:00
SshMultiplexingHelper::ensureMultiplexedConnection($server);
2023-05-24 13:25:08 +00:00
return resolve(PrepareCoolifyTask::class, [
'remoteProcessArgs' => new CoolifyTaskArgs(
server_uuid: $server->uuid,
command: $command_string,
2023-05-24 13:25:08 +00:00
type: $type,
type_uuid: $type_uuid,
model: $model,
ignore_errors: $ignore_errors,
call_event_on_finish: $callEventOnFinish,
call_event_data: $callEventData,
2023-05-24 13:25:08 +00:00
),
])();
2023-05-24 12:26:50 +00:00
}
2024-01-06 05:24:57 +00:00
function instant_scp(string $source, string $dest, Server $server, $throwError = true)
{
return \App\Helpers\SshRetryHandler::retry(
function () use ($source, $dest, $server) {
$scp_command = SshMultiplexingHelper::generateScpCommand($server, $source, $dest);
$process = Process::timeout(config('constants.ssh.command_timeout'))->run($scp_command);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
excludeCertainErrors($process->errorOutput(), $exitCode);
}
return $output === 'null' ? null : $output;
},
[
'server' => $server->ip,
'source' => $source,
'dest' => $dest,
'function' => 'instant_scp',
],
$throwError
);
2024-01-06 05:24:57 +00:00
}
function instant_remote_process_with_timeout(Collection|array $command, Server $server, bool $throwError = true, bool $no_sudo = false): ?string
{
$command = $command instanceof Collection ? $command->toArray() : $command;
if ($server->isNonRoot() && ! $no_sudo) {
$command = parseCommandsByLineForSudo(collect($command), $server);
}
$command_string = implode("\n", $command);
return \App\Helpers\SshRetryHandler::retry(
function () use ($server, $command_string) {
$sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string);
$process = Process::timeout(30)->run($sshCommand);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
excludeCertainErrors($process->errorOutput(), $exitCode);
}
// Sanitize output to ensure valid UTF-8 encoding
$output = $output === 'null' ? null : sanitize_utf8_text($output);
return $output;
},
[
'server' => $server->ip,
'command_preview' => substr($command_string, 0, 100),
'function' => 'instant_remote_process_with_timeout',
],
$throwError
);
}
function instant_remote_process(Collection|array $command, Server $server, bool $throwError = true, bool $no_sudo = false, ?int $timeout = null): ?string
2023-05-24 13:25:08 +00:00
{
2024-09-17 13:54:22 +00:00
$command = $command instanceof Collection ? $command->toArray() : $command;
if ($server->isNonRoot() && ! $no_sudo) {
$command = parseCommandsByLineForSudo(collect($command), $server);
2024-04-16 13:42:38 +00:00
}
$command_string = implode("\n", $command);
$effectiveTimeout = $timeout ?? config('constants.ssh.command_timeout');
2024-09-09 13:04:51 +00:00
return \App\Helpers\SshRetryHandler::retry(
function () use ($server, $command_string, $effectiveTimeout) {
$sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string);
$process = Process::timeout($effectiveTimeout)->run($sshCommand);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
excludeCertainErrors($process->errorOutput(), $exitCode);
}
// Sanitize output to ensure valid UTF-8 encoding
$output = $output === 'null' ? null : sanitize_utf8_text($output);
return $output;
},
[
'server' => $server->ip,
'command_preview' => substr($command_string, 0, 100),
'function' => 'instant_remote_process',
],
$throwError
);
2023-05-24 12:26:50 +00:00
}
function excludeCertainErrors(string $errorOutput, ?int $exitCode = null)
{
2023-09-18 09:49:26 +00:00
$ignoredErrors = collect([
'Permission denied (publickey',
'Could not resolve hostname',
]);
$ignored = $ignoredErrors->contains(fn ($error) => Str::contains($errorOutput, $error));
// Ensure we always have a meaningful error message
$errorMessage = trim($errorOutput);
if (empty($errorMessage)) {
$errorMessage = "SSH command failed with exit code: $exitCode";
}
2023-09-18 09:49:26 +00:00
if ($ignored) {
// TODO: Create new exception and disable in sentry
throw new \RuntimeException($errorMessage, $exitCode);
2023-09-18 09:49:26 +00:00
}
throw new \RuntimeException($errorMessage, $exitCode);
2023-09-18 09:49:26 +00:00
}
2023-06-30 13:57:40 +00:00
function decode_remote_command_output(?ApplicationDeploymentQueue $application_deployment_queue = null): Collection
{
if (is_null($application_deployment_queue)) {
return collect([]);
}
2024-09-17 13:54:22 +00:00
$application = Application::find(data_get($application_deployment_queue, 'application_id'));
$is_debug_enabled = data_get($application, 'settings.is_debug_enabled');
$logs = data_get($application_deployment_queue, 'logs');
if (empty($logs)) {
return collect([]);
}
2023-06-30 13:57:40 +00:00
try {
$decoded = json_decode(
$logs,
2023-06-30 13:57:40 +00:00
associative: true,
flags: JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
// If JSON decoding fails, try to clean up the logs and retry
try {
// Ensure valid UTF-8 encoding
$cleaned_logs = sanitize_utf8_text($logs);
$decoded = json_decode(
$cleaned_logs,
associative: true,
flags: JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
// If it still fails, return empty collection to prevent crashes
return collect([]);
}
}
if (! is_array($decoded)) {
2023-06-30 13:57:40 +00:00
return collect([]);
}
2024-09-03 18:06:03 +00:00
$seenCommands = collect();
2023-06-30 13:57:40 +00:00
$formatted = collect($decoded);
if (! $is_debug_enabled) {
2023-08-11 18:48:52 +00:00
$formatted = $formatted->filter(fn ($i) => $i['hidden'] === false ?? false);
2023-06-30 13:57:40 +00:00
}
2024-09-17 13:54:22 +00:00
return $formatted
2023-11-23 20:02:30 +00:00
->sortBy(fn ($i) => data_get($i, 'order'))
2023-06-30 13:57:40 +00:00
->map(function ($i) {
2023-11-23 20:02:30 +00:00
data_set($i, 'timestamp', Carbon::parse(data_get($i, 'timestamp'))->format('Y-M-d H:i:s.u'));
2023-06-30 13:57:40 +00:00
return $i;
2024-09-03 18:06:03 +00:00
})
->reduce(function ($deploymentLogLines, $logItem) use ($seenCommands) {
$command = data_get($logItem, 'command');
$isStderr = data_get($logItem, 'type') === 'stderr';
$isNewCommand = ! is_null($command) && ! $seenCommands->first(function ($seenCommand) use ($logItem) {
return data_get($seenCommand, 'command') === data_get($logItem, 'command') && data_get($seenCommand, 'batch') === data_get($logItem, 'batch');
2024-09-04 11:57:03 +00:00
});
2024-09-03 18:06:03 +00:00
2024-09-04 11:57:03 +00:00
if ($isNewCommand) {
2024-09-03 18:06:03 +00:00
$deploymentLogLines->push([
'line' => $command,
'timestamp' => data_get($logItem, 'timestamp'),
2024-09-03 18:06:03 +00:00
'stderr' => $isStderr,
'hidden' => data_get($logItem, 'hidden'),
2024-09-03 18:06:03 +00:00
'command' => true,
]);
2024-09-04 11:57:03 +00:00
$seenCommands->push([
'command' => $command,
'batch' => data_get($logItem, 'batch'),
2024-09-04 11:57:03 +00:00
]);
2024-09-03 18:06:03 +00:00
}
$lines = explode(PHP_EOL, data_get($logItem, 'output'));
2024-09-03 18:06:03 +00:00
foreach ($lines as $line) {
$deploymentLogLines->push([
'line' => $line,
'timestamp' => data_get($logItem, 'timestamp'),
2024-09-03 18:06:03 +00:00
'stderr' => $isStderr,
'hidden' => data_get($logItem, 'hidden'),
2024-09-03 18:06:03 +00:00
]);
}
return $deploymentLogLines;
}, collect());
2023-06-30 13:57:40 +00:00
}
function remove_iip($text)
{
// Ensure the input is valid UTF-8 before processing
$text = sanitize_utf8_text($text);
2024-06-10 20:43:34 +00:00
$text = preg_replace('/x-access-token:.*?(?=@)/', 'x-access-token:'.REDACTED, $text);
return preg_replace('/\x1b\[[0-9;]*m/', '', $text);
}
/**
* Sanitizes text to ensure it contains valid UTF-8 encoding.
*
* This function is crucial for preventing "Malformed UTF-8 characters" errors
* that can occur when Docker build output contains binary data mixed with text,
* especially during image processing or builds with many assets.
*
* @param string|null $text The text to sanitize
* @return string Valid UTF-8 encoded text
*/
function sanitize_utf8_text(?string $text): string
{
if (empty($text)) {
return '';
}
// Convert to UTF-8, replacing invalid sequences
$sanitized = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
// Additional fallback: use SUBSTITUTE flag to replace invalid sequences with substitution character
if (! mb_check_encoding($sanitized, 'UTF-8')) {
$sanitized = mb_convert_encoding($text, 'UTF-8', mb_detect_encoding($text, mb_detect_order(), true) ?: 'UTF-8');
}
return $sanitized;
}
2023-11-06 09:53:01 +00:00
function refresh_server_connection(?PrivateKey $private_key = null)
{
2023-11-06 09:53:01 +00:00
if (is_null($private_key)) {
return;
}
foreach ($private_key->servers as $server) {
2024-09-16 20:33:43 +00:00
SshMultiplexingHelper::removeMuxFile($server);
}
}
function checkRequiredCommands(Server $server)
{
2024-06-10 20:43:34 +00:00
$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) {
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);
} catch (\Throwable) {
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) {
2024-09-17 13:54:22 +00:00
break;
}
}
}