lasthourcloud/app/Actions/CoolifyTask/RunRemoteProcess.php

182 lines
5.4 KiB
PHP
Raw Normal View History

<?php
2023-05-03 05:15:45 +00:00
namespace App\Actions\CoolifyTask;
use App\Enums\ActivityTypes;
use App\Enums\ProcessStatus;
2023-05-24 12:26:50 +00:00
use App\Jobs\ApplicationDeploymentJob;
use Illuminate\Process\ProcessResult;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Process;
use Spatie\Activitylog\Models\Activity;
2023-05-24 13:19:39 +00:00
const TIMEOUT = 3600;
const IDLE_TIMEOUT = 3600;
class RunRemoteProcess
{
public Activity $activity;
2023-06-07 13:39:08 +00:00
public bool $hide_from_output;
2023-06-07 13:39:08 +00:00
public bool $is_finished;
2023-06-07 13:39:08 +00:00
public bool $ignore_errors;
2023-06-07 13:39:08 +00:00
protected $time_start;
2023-06-07 13:39:08 +00:00
protected $current_time;
2023-06-07 13:39:08 +00:00
protected $last_write_at = 0;
2023-06-07 13:39:08 +00:00
protected $throttle_interval_ms = 500;
2023-04-01 19:50:57 +00:00
protected int $counter = 1;
/**
* Create a new job instance.
*/
2023-06-07 13:39:08 +00:00
public function __construct(Activity $activity, bool $hide_from_output = false, bool $is_finished = false, bool $ignore_errors = false)
{
2023-06-30 20:24:39 +00:00
if ($activity->getExtraProperty('type') !== ActivityTypes::INLINE->value) {
throw new \RuntimeException('Incompatible Activity to run a remote command.');
}
$this->activity = $activity;
2023-06-07 13:39:08 +00:00
$this->hide_from_output = $hide_from_output;
$this->is_finished = $is_finished;
$this->ignore_errors = $ignore_errors;
}
public function __invoke(): ProcessResult
{
2023-06-07 13:39:08 +00:00
$this->time_start = hrtime(true);
$status = ProcessStatus::IN_PROGRESS;
2023-05-24 13:19:39 +00:00
$processResult = Process::timeout(TIMEOUT)->idleTimeout(IDLE_TIMEOUT)->run($this->getCommand(), $this->handleOutput(...));
if ($this->activity->properties->get('status') === ProcessStatus::ERROR->value) {
$status = ProcessStatus::ERROR;
} else {
2023-06-07 13:39:08 +00:00
if (($processResult->exitCode() == 0 && $this->is_finished) || $this->activity->properties->get('status') === ProcessStatus::FINISHED->value) {
$status = ProcessStatus::FINISHED;
}
2023-06-07 13:39:08 +00:00
if ($processResult->exitCode() != 0 && !$this->ignore_errors) {
$status = ProcessStatus::ERROR;
}
}
$this->activity->properties = $this->activity->properties->merge([
'exitCode' => $processResult->exitCode(),
'stdout' => $processResult->output(),
'stderr' => $processResult->errorOutput(),
'status' => $status->value,
]);
$this->activity->save();
2023-06-07 13:39:08 +00:00
if ($processResult->exitCode() != 0 && !$this->ignore_errors) {
throw new \RuntimeException($processResult->errorOutput());
2023-04-04 12:23:10 +00:00
}
return $processResult;
}
2023-04-12 11:09:27 +00:00
protected function getLatestCounter(): int
{
$description = json_decode($this->activity->description, associative: true, flags: JSON_THROW_ON_ERROR);
if ($description === null || count($description) === 0) {
return 1;
}
return end($description)['order'] + 1;
}
protected function getCommand(): string
{
$user = $this->activity->getExtraProperty('user');
$server_ip = $this->activity->getExtraProperty('server_ip');
$private_key_location = $this->activity->getExtraProperty('private_key_location');
$port = $this->activity->getExtraProperty('port');
$command = $this->activity->getExtraProperty('command');
2023-05-24 13:25:08 +00:00
return generate_ssh_command($private_key_location, $server_ip, $user, $port, $command);
}
protected function handleOutput(string $type, string $output)
{
2023-06-07 13:39:08 +00:00
if ($this->hide_from_output) {
return;
}
2023-06-07 13:39:08 +00:00
$this->current_time = $this->elapsedTime();
2023-04-07 14:58:45 +00:00
$this->activity->description = $this->encodeOutput($type, $output);
if ($this->isAfterLastThrottle()) {
// Let's write to database.
DB::transaction(function () {
$this->activity->save();
2023-06-07 13:39:08 +00:00
$this->last_write_at = $this->current_time;
});
}
}
2023-04-01 19:50:57 +00:00
public function encodeOutput($type, $output)
{
2023-04-07 14:58:45 +00:00
$outputStack = json_decode($this->activity->description, associative: true, flags: JSON_THROW_ON_ERROR);
$outputStack[] = [
'type' => $type,
'output' => $output,
2023-04-12 11:09:27 +00:00
'timestamp' => hrtime(true),
2023-05-24 12:26:50 +00:00
'batch' => ApplicationDeploymentJob::$batch_counter,
2023-04-12 11:09:27 +00:00
'order' => $this->getLatestCounter(),
2023-04-07 14:58:45 +00:00
];
return json_encode($outputStack, flags: JSON_THROW_ON_ERROR);
}
public static function decodeOutput(?Activity $activity = null): string
{
2023-04-12 11:09:27 +00:00
if (is_null($activity)) {
2023-04-07 14:58:45 +00:00
return '';
}
try {
2023-04-12 11:09:27 +00:00
$decoded = json_decode(
data_get($activity, 'description'),
2023-04-07 14:58:45 +00:00
associative: true,
flags: JSON_THROW_ON_ERROR
);
} catch (\JsonException $exception) {
return '';
}
return collect($decoded)
2023-04-12 11:09:27 +00:00
->sortBy(fn ($i) => $i['order'])
->map(fn ($i) => $i['output'])
->implode("");
2023-04-01 19:50:57 +00:00
}
/**
* Determines if it's time to write again to database.
*
* @return bool
*/
protected function isAfterLastThrottle()
{
// If DB was never written, then we immediately decide we have to write.
2023-06-07 13:39:08 +00:00
if ($this->last_write_at === 0) {
return true;
}
2023-06-07 13:39:08 +00:00
return ($this->current_time - $this->throttle_interval_ms) > $this->last_write_at;
}
protected function elapsedTime(): int
{
2023-06-07 13:39:08 +00:00
$timeMs = (hrtime(true) - $this->time_start) / 1_000_000;
return intval($timeMs);
}
}