2023-03-20 12:04:22 +00:00
|
|
|
<?php
|
|
|
|
|
2023-03-21 09:56:49 +00:00
|
|
|
use App\Actions\RemoteProcess\DispatchRemoteProcess;
|
2023-03-21 10:32:38 +00:00
|
|
|
use App\Data\RemoteProcessArgs;
|
2023-03-24 14:48:57 +00:00
|
|
|
use App\Models\Server;
|
2023-03-24 21:15:36 +00:00
|
|
|
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
|
|
|
/**
|
2023-03-24 21:15:36 +00:00
|
|
|
* Run a Remote Process, which SSH's asynchronously into a machine to run the command(s).
|
2023-03-21 10:32:38 +00:00
|
|
|
* @TODO Change 'root' to 'coolify' when it's able to run Docker commands without sudo
|
2023-03-20 12:04:22 +00:00
|
|
|
*
|
|
|
|
*/
|
2023-03-21 10:32:38 +00:00
|
|
|
function remoteProcess(
|
|
|
|
string $command,
|
2023-03-24 14:48:57 +00:00
|
|
|
string $destination
|
|
|
|
): Activity {
|
2023-03-24 21:15:36 +00:00
|
|
|
$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;
|
2023-03-21 09:56:49 +00:00
|
|
|
return resolve(DispatchRemoteProcess::class, [
|
2023-03-21 10:32:38 +00:00
|
|
|
'remoteProcessArgs' => new RemoteProcessArgs(
|
2023-03-24 14:48:57 +00:00
|
|
|
destination: $found_server->ip,
|
2023-03-24 21:15:36 +00:00
|
|
|
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-21 10:32:38 +00:00
|
|
|
),
|
2023-03-21 09:31:16 +00:00
|
|
|
])();
|
2023-03-20 12:04:22 +00:00
|
|
|
}
|
2023-03-28 13:47:37 +00:00
|
|
|
function checkServer(string $destination)
|
|
|
|
{
|
2023-03-24 21:15:36 +00:00
|
|
|
// @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)
|
|
|
|
{
|
2023-03-24 21:15:36 +00:00
|
|
|
$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
|
|
|
}
|