Remove daemon command repo

This commit is contained in:
Lance Pioch 2024-03-16 15:11:10 -04:00
parent 4e42cd784a
commit 4969aed383
7 changed files with 53 additions and 57 deletions

View File

@ -15,14 +15,6 @@ use App\Exceptions\Http\Connection\DaemonConnectionException;
class CommandController extends ClientApiController class CommandController extends ClientApiController
{ {
/**
* CommandController constructor.
*/
public function __construct(private DaemonCommandRepository $repository)
{
parent::__construct();
}
/** /**
* Send a command to a running server. * Send a command to a running server.
* *
@ -31,7 +23,7 @@ class CommandController extends ClientApiController
public function index(SendCommandRequest $request, Server $server): Response public function index(SendCommandRequest $request, Server $server): Response
{ {
try { try {
$this->repository->setServer($server)->send($request->input('command')); $server->send($request->input('command'));
} catch (DaemonConnectionException $exception) { } catch (DaemonConnectionException $exception) {
$previous = $exception->getPrevious(); $previous = $exception->getPrevious();

View File

@ -3,19 +3,22 @@
namespace App\Http\Middleware\Api\Client; namespace App\Http\Middleware\Api\Client;
use App\Models\Server; use App\Models\Server;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Routing\Middleware\SubstituteBindings; use Illuminate\Routing\Middleware\SubstituteBindings;
class SubstituteClientBindings extends SubstituteBindings class SubstituteClientBindings extends SubstituteBindings
{ {
/** public function __construct(Registrar $router, private Server $server)
* @param \Illuminate\Http\Request $request {
*/ parent::__construct($router);
}
public function handle($request, \Closure $next): mixed public function handle($request, \Closure $next): mixed
{ {
// Override default behavior of the model binding to use a specific table // Override default behavior of the model binding to use a specific table
// column rather than the default 'id'. // column rather than the default 'id'.
$this->router->bind('server', function ($value) { $this->router->bind('server', function ($value) {
return Server::query()->where(strlen($value) === 8 ? 'uuidShort' : 'uuid', $value)->firstOrFail(); return $this->server->query()->where(strlen($value) === 8 ? 'uuidShort' : 'uuid', $value)->firstOrFail();
}); });
$this->router->bind('user', function ($value, $route) { $this->router->bind('user', function ($value, $route) {

View File

@ -2,7 +2,6 @@
namespace App\Jobs\Schedule; namespace App\Jobs\Schedule;
use Exception;
use App\Jobs\Job; use App\Jobs\Job;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use App\Models\Task; use App\Models\Task;
@ -12,7 +11,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Services\Backups\InitiateBackupService; use App\Services\Backups\InitiateBackupService;
use App\Repositories\Daemon\DaemonPowerRepository; use App\Repositories\Daemon\DaemonPowerRepository;
use App\Repositories\Daemon\DaemonCommandRepository;
use App\Exceptions\Http\Connection\DaemonConnectionException; use App\Exceptions\Http\Connection\DaemonConnectionException;
class RunTaskJob extends Job implements ShouldQueue class RunTaskJob extends Job implements ShouldQueue
@ -35,7 +33,6 @@ class RunTaskJob extends Job implements ShouldQueue
* @throws \Throwable * @throws \Throwable
*/ */
public function handle( public function handle(
DaemonCommandRepository $commandRepository,
InitiateBackupService $backupService, InitiateBackupService $backupService,
DaemonPowerRepository $powerRepository DaemonPowerRepository $powerRepository
) { ) {
@ -65,7 +62,7 @@ class RunTaskJob extends Job implements ShouldQueue
$powerRepository->setServer($server)->send($this->task->payload); $powerRepository->setServer($server)->send($this->task->payload);
break; break;
case Task::ACTION_COMMAND: case Task::ACTION_COMMAND:
$commandRepository->setServer($server)->send($this->task->payload); $server->send($this->task->payload);
break; break;
case Task::ACTION_BACKUP: case Task::ACTION_BACKUP:
$backupService->setIgnoredFiles(explode(PHP_EOL, $this->task->payload))->handle($server, null, true); $backupService->setIgnoredFiles(explode(PHP_EOL, $this->task->payload))->handle($server, null, true);

View File

@ -2,8 +2,13 @@
namespace App\Models; namespace App\Models;
use App\Exceptions\Http\Connection\DaemonConnectionException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\TransferException;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Query\JoinClause; use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Facades\Http;
use Psr\Http\Message\ResponseInterface;
use Znck\Eloquent\Traits\BelongsToThrough; use Znck\Eloquent\Traits\BelongsToThrough;
use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
@ -365,4 +370,20 @@ class Server extends Model
return $server; return $server;
} }
/**
* Sends a command or multiple commands to a running server instance.
*
* @throws DaemonConnectionException|GuzzleException
*/
public function send(array|string $command): ResponseInterface
{
try {
return Http::daemon($this->node)->post("/api/servers/{$this->uuid}/commands", [
'commands' => is_array($command) ? $command : [$command],
])->toPsrResponse();
} catch (TransferException $exception) {
throw new DaemonConnectionException($exception);
}
}
} }

View File

@ -3,6 +3,8 @@
namespace App\Providers; namespace App\Providers;
use App\Models; use App\Models;
use App\Models\Node;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\URL;
use Illuminate\Pagination\Paginator; use Illuminate\Pagination\Paginator;
@ -47,6 +49,17 @@ class AppServiceProvider extends ServiceProvider
'task' => Models\Task::class, 'task' => Models\Task::class,
'user' => Models\User::class, 'user' => Models\User::class,
]); ]);
Http::macro(
'daemon',
fn (Node $node, array $headers = []) => Http::acceptJson()->withHeaders([
'Authorization' => 'Bearer ' . $node->getDecryptedKey(),
] + $headers)
->withOptions(['verify' => (bool) app()->environment('production')])
->timeout(config('pterodactyl.guzzle.timeout'))
->connectTimeout(config('pterodactyl.guzzle.connect_timeout'))
->baseUrl($node->getConnectionAddress())
);
} }
/** /**

View File

@ -1,33 +0,0 @@
<?php
namespace App\Repositories\Daemon;
use Webmozart\Assert\Assert;
use App\Models\Server;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\TransferException;
use App\Exceptions\Http\Connection\DaemonConnectionException;
class DaemonCommandRepository extends DaemonRepository
{
/**
* Sends a command or multiple commands to a running server instance.
*
* @throws \App\Exceptions\Http\Connection\DaemonConnectionException
*/
public function send(array|string $command): ResponseInterface
{
Assert::isInstanceOf($this->server, Server::class);
try {
return $this->getHttpClient()->post(
sprintf('/api/servers/%s/commands', $this->server->uuid),
[
'json' => ['commands' => is_array($command) ? $command : [$command]],
]
);
} catch (TransferException $exception) {
throw new DaemonConnectionException($exception);
}
}
}

View File

@ -52,12 +52,12 @@ class CommandControllerTest extends ClientApiIntegrationTestCase
{ {
[$user, $server] = $this->generateTestAccount([Permission::ACTION_CONTROL_CONSOLE]); [$user, $server] = $this->generateTestAccount([Permission::ACTION_CONTROL_CONSOLE]);
$mock = $this->mock(DaemonCommandRepository::class); $server = \Mockery::mock($server)->makePartial();
$mock->expects('setServer') $server->expects('query->where->firstOrFail')->andReturns($server);
->with(\Mockery::on(fn (Server $value) => $value->is($server)))
->andReturnSelf();
$mock->expects('send')->with('say Test')->andReturn(new GuzzleResponse()); $this->instance(Server::class, $server);
$server->expects('send')->with('say Test')->andReturn(new GuzzleResponse());
$response = $this->actingAs($user)->postJson("/api/client/servers/$server->uuid/command", [ $response = $this->actingAs($user)->postJson("/api/client/servers/$server->uuid/command", [
'command' => 'say Test', 'command' => 'say Test',
@ -74,13 +74,16 @@ class CommandControllerTest extends ClientApiIntegrationTestCase
{ {
[$user, $server] = $this->generateTestAccount(); [$user, $server] = $this->generateTestAccount();
$mock = $this->mock(DaemonCommandRepository::class); $server = \Mockery::mock($server)->makePartial();
$mock->expects('setServer->send')->andThrows( $server->expects('query->where->firstOrFail')->andReturns($server);
$server->expects('send')->andThrows(
new DaemonConnectionException( new DaemonConnectionException(
new BadResponseException('', new Request('GET', 'test'), new GuzzleResponse(Response::HTTP_BAD_GATEWAY)) new BadResponseException('', new Request('GET', 'test'), new GuzzleResponse(Response::HTTP_BAD_GATEWAY))
) )
); );
$this->instance(Server::class, $server);
$response = $this->actingAs($user)->postJson("/api/client/servers/$server->uuid/command", [ $response = $this->actingAs($user)->postJson("/api/client/servers/$server->uuid/command", [
'command' => 'say Test', 'command' => 'say Test',
]); ]);