lasthourcloud/bootstrap/helpers.php

54 lines
1.8 KiB
PHP
Raw Normal View History

2023-03-20 12:04:22 +00:00
<?php
use App\Actions\RemoteProcess\DispatchRemoteProcess;
use App\Data\RemoteProcessArgs;
2023-03-24 14:48:57 +00:00
use App\Models\Server;
use Illuminate\Support\Facades\Storage;
2023-03-20 12:04:22 +00:00
use Spatie\Activitylog\Contracts\Activity;
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(
string $command,
2023-03-24 14:48:57 +00:00
string $destination
): Activity {
$found_server = checkServer($destination);
checkTeam($found_server->team_id);
2023-03-28 13:47:37 +00:00
$temp_file = 'id.rsa_' . 'root' . '@' . $found_server->ip;
2023-03-27 18:18:20 +00:00
Storage::disk('local')->put($temp_file, $found_server->privateKey->private_key, 'private');
2023-03-28 13:47:37 +00:00
$private_key_location = '/var/www/html/storage/app/' . $temp_file;
return resolve(DispatchRemoteProcess::class, [
'remoteProcessArgs' => new RemoteProcessArgs(
2023-03-24 14:48:57 +00:00
destination: $found_server->ip,
private_key_location: $private_key_location,
2023-03-28 13:47:37 +00:00
command: <<<EOT
{$command}
EOT,
2023-03-24 14:48:57 +00:00
port: $found_server->port,
user: $found_server->user,
),
])();
2023-03-20 12:04:22 +00:00
}
2023-03-28 13:47:37 +00:00
function checkServer(string $destination)
{
// @TODO: Use UUID instead of name
$found_server = Server::where('name', $destination)->first();
if (!$found_server) {
throw new \RuntimeException('Server not found.');
};
return $found_server;
}
2023-03-28 13:47:37 +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-03-20 12:04:22 +00:00
}