Remove server repository and interface

This commit is contained in:
Lance Pioch 2024-03-16 15:01:21 -04:00
parent 4ea5341e97
commit 4e42cd784a
19 changed files with 62 additions and 339 deletions

View File

@ -1,73 +0,0 @@
<?php
namespace App\Contracts\Repository;
use App\Models\Server;
use Illuminate\Support\Collection;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
interface ServerRepositoryInterface extends RepositoryInterface
{
/**
* Load the egg relations onto the server model.
*/
public function loadEggRelations(Server $server, bool $refresh = false): Server;
/**
* Return a collection of servers with their associated data for rebuild operations.
*/
public function getDataForRebuild(int $server = null, int $node = null): Collection;
/**
* Return a collection of servers with their associated data for reinstall operations.
*/
public function getDataForReinstall(int $server = null, int $node = null): Collection;
/**
* Return a server model and all variables associated with the server.
*
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/
public function findWithVariables(int $id): Server;
/**
* Get the primary allocation for a given server. If a model is passed into
* the function, load the allocation relationship onto it. Otherwise, find and
* return the server from the database.
*/
public function getPrimaryAllocation(Server $server, bool $refresh = false): Server;
/**
* Return enough data to be used for the creation of a server via the daemon.
*/
public function getDataForCreation(Server $server, bool $refresh = false): Server;
/**
* Load associated databases onto the server model.
*/
public function loadDatabaseRelations(Server $server, bool $refresh = false): Server;
/**
* Get data for use when updating a server on the Daemon. Returns an array of
* the egg which is used for build and rebuild. Only loads relations
* if they are missing, or refresh is set to true.
*/
public function getDaemonServiceData(Server $server, bool $refresh = false): array;
/**
* Return a server by UUID.
*
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/
public function getByUuid(string $uuid): Server;
/**
* Check if a given UUID and UUID-Short string are unique to a server.
*/
public function isUniqueUuidCombo(string $uuid, string $short): bool;
/**
* Returns all the servers that exist for a given node in a paginated response.
*/
public function loadAllServersForNode(int $node, int $limit): LengthAwarePaginator;
}

View File

@ -10,7 +10,6 @@ use App\Models\Allocation;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Contracts\View\Factory as ViewFactory;
use App\Repositories\Eloquent\NodeRepository; use App\Repositories\Eloquent\NodeRepository;
use App\Repositories\Eloquent\ServerRepository;
use App\Traits\Controllers\JavascriptInjection; use App\Traits\Controllers\JavascriptInjection;
use App\Services\Helpers\SoftwareVersionService; use App\Services\Helpers\SoftwareVersionService;
use App\Repositories\Eloquent\AllocationRepository; use App\Repositories\Eloquent\AllocationRepository;
@ -25,7 +24,6 @@ class NodeViewController extends Controller
public function __construct( public function __construct(
private AllocationRepository $allocationRepository, private AllocationRepository $allocationRepository,
private NodeRepository $repository, private NodeRepository $repository,
private ServerRepository $serverRepository,
private SoftwareVersionService $versionService, private SoftwareVersionService $versionService,
private ViewFactory $view private ViewFactory $view
) { ) {
@ -93,7 +91,7 @@ class NodeViewController extends Controller
return $this->view->make('admin.nodes.view.servers', [ return $this->view->make('admin.nodes.view.servers', [
'node' => $node, 'node' => $node,
'servers' => $this->serverRepository->loadAllServersForNode($node->id, 25), 'servers' => $node->servers()->with(['user', 'nest', 'egg'])->paginate(25),
]); ]);
} }
} }

View File

@ -19,7 +19,6 @@ use App\Services\Allocations\AssignmentService;
use App\Services\Helpers\SoftwareVersionService; use App\Services\Helpers\SoftwareVersionService;
use App\Http\Requests\Admin\Node\NodeFormRequest; use App\Http\Requests\Admin\Node\NodeFormRequest;
use App\Contracts\Repository\NodeRepositoryInterface; use App\Contracts\Repository\NodeRepositoryInterface;
use App\Contracts\Repository\ServerRepositoryInterface;
use App\Http\Requests\Admin\Node\AllocationFormRequest; use App\Http\Requests\Admin\Node\AllocationFormRequest;
use App\Services\Allocations\AllocationDeletionService; use App\Services\Allocations\AllocationDeletionService;
use App\Contracts\Repository\AllocationRepositoryInterface; use App\Contracts\Repository\AllocationRepositoryInterface;
@ -39,7 +38,6 @@ class NodesController extends Controller
protected NodeCreationService $creationService, protected NodeCreationService $creationService,
protected NodeDeletionService $deletionService, protected NodeDeletionService $deletionService,
protected NodeRepositoryInterface $repository, protected NodeRepositoryInterface $repository,
protected ServerRepositoryInterface $serverRepository,
protected NodeUpdateService $updateService, protected NodeUpdateService $updateService,
protected SoftwareVersionService $versionService, protected SoftwareVersionService $versionService,
protected ViewFactory $view protected ViewFactory $view

View File

@ -14,7 +14,6 @@ use App\Services\Servers\EnvironmentService;
use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Contracts\View\Factory as ViewFactory;
use App\Repositories\Eloquent\NodeRepository; use App\Repositories\Eloquent\NodeRepository;
use App\Repositories\Eloquent\MountRepository; use App\Repositories\Eloquent\MountRepository;
use App\Repositories\Eloquent\ServerRepository;
use App\Traits\Controllers\JavascriptInjection; use App\Traits\Controllers\JavascriptInjection;
use App\Repositories\Eloquent\DatabaseHostRepository; use App\Repositories\Eloquent\DatabaseHostRepository;
@ -30,7 +29,6 @@ class ServerViewController extends Controller
private MountRepository $mountRepository, private MountRepository $mountRepository,
private EggRepository $eggRepository, private EggRepository $eggRepository,
private NodeRepository $nodeRepository, private NodeRepository $nodeRepository,
private ServerRepository $repository,
private EnvironmentService $environmentService, private EnvironmentService $environmentService,
private ViewFactory $view private ViewFactory $view
) { ) {

View File

@ -27,7 +27,6 @@ use App\Services\Servers\StartupModificationService;
use App\Repositories\Eloquent\DatabaseHostRepository; use App\Repositories\Eloquent\DatabaseHostRepository;
use App\Services\Databases\DatabaseManagementService; use App\Services\Databases\DatabaseManagementService;
use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Config\Repository as ConfigRepository;
use App\Contracts\Repository\ServerRepositoryInterface;
use App\Contracts\Repository\DatabaseRepositoryInterface; use App\Contracts\Repository\DatabaseRepositoryInterface;
use App\Contracts\Repository\AllocationRepositoryInterface; use App\Contracts\Repository\AllocationRepositoryInterface;
use App\Services\Servers\ServerConfigurationStructureService; use App\Services\Servers\ServerConfigurationStructureService;
@ -51,7 +50,6 @@ class ServersController extends Controller
protected ServerDeletionService $deletionService, protected ServerDeletionService $deletionService,
protected DetailsModificationService $detailsModificationService, protected DetailsModificationService $detailsModificationService,
protected ReinstallServerService $reinstallService, protected ReinstallServerService $reinstallService,
protected ServerRepositoryInterface $repository,
protected MountRepository $mountRepository, protected MountRepository $mountRepository,
protected ServerConfigurationStructureService $serverConfigurationStructureService, protected ServerConfigurationStructureService $serverConfigurationStructureService,
protected StartupModificationService $startupModificationService, protected StartupModificationService $startupModificationService,
@ -89,9 +87,8 @@ class ServersController extends Controller
throw new DisplayException(trans('admin/server.exceptions.marked_as_failed')); throw new DisplayException(trans('admin/server.exceptions.marked_as_failed'));
} }
$this->repository->update($server->id, [ $server->status = $server->isInstalled() ? Server::STATUS_INSTALLING : null;
'status' => $server->isInstalled() ? Server::STATUS_INSTALLING : null, $server->save();
], true, true);
$this->alert->success(trans('admin/server.alerts.install_toggled'))->flash(); $this->alert->success(trans('admin/server.alerts.install_toggled'))->flash();

View File

@ -7,7 +7,6 @@ use Illuminate\Http\JsonResponse;
use App\Facades\Activity; use App\Facades\Activity;
use App\Models\Allocation; use App\Models\Allocation;
use App\Exceptions\DisplayException; use App\Exceptions\DisplayException;
use App\Repositories\Eloquent\ServerRepository;
use App\Transformers\Api\Client\AllocationTransformer; use App\Transformers\Api\Client\AllocationTransformer;
use App\Http\Controllers\Api\Client\ClientApiController; use App\Http\Controllers\Api\Client\ClientApiController;
use App\Services\Allocations\FindAssignableAllocationService; use App\Services\Allocations\FindAssignableAllocationService;
@ -24,7 +23,6 @@ class NetworkAllocationController extends ClientApiController
*/ */
public function __construct( public function __construct(
private FindAssignableAllocationService $assignableAllocationService, private FindAssignableAllocationService $assignableAllocationService,
private ServerRepository $serverRepository
) { ) {
parent::__construct(); parent::__construct();
} }
@ -72,7 +70,8 @@ class NetworkAllocationController extends ClientApiController
*/ */
public function setPrimary(SetPrimaryAllocationRequest $request, Server $server, Allocation $allocation): array public function setPrimary(SetPrimaryAllocationRequest $request, Server $server, Allocation $allocation): array
{ {
$this->serverRepository->update($server->id, ['allocation_id' => $allocation->id]); $server->allocation()->associate($allocation);
$server->save();
Activity::event('server:allocation.primary') Activity::event('server:allocation.primary')
->subject($allocation) ->subject($allocation)

View File

@ -6,7 +6,6 @@ use Illuminate\Http\Response;
use App\Models\Server; use App\Models\Server;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use App\Facades\Activity; use App\Facades\Activity;
use App\Repositories\Eloquent\ServerRepository;
use App\Services\Servers\ReinstallServerService; use App\Services\Servers\ReinstallServerService;
use App\Http\Controllers\Api\Client\ClientApiController; use App\Http\Controllers\Api\Client\ClientApiController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
@ -20,7 +19,6 @@ class SettingsController extends ClientApiController
* SettingsController constructor. * SettingsController constructor.
*/ */
public function __construct( public function __construct(
private ServerRepository $repository,
private ReinstallServerService $reinstallServerService private ReinstallServerService $reinstallServerService
) { ) {
parent::__construct(); parent::__construct();
@ -28,18 +26,15 @@ class SettingsController extends ClientApiController
/** /**
* Renames a server. * Renames a server.
*
* @throws \App\Exceptions\Model\DataValidationException
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/ */
public function rename(RenameServerRequest $request, Server $server): JsonResponse public function rename(RenameServerRequest $request, Server $server): JsonResponse
{ {
$name = $request->input('name'); $name = $request->input('name');
$description = $request->has('description') ? (string) $request->input('description') : $server->description; $description = $request->has('description') ? (string) $request->input('description') : $server->description;
$this->repository->update($server->id, [
'name' => $name, $server->name = $name;
'description' => $description, $server->description = $description;
]); $server->save();
if ($server->name !== $name) { if ($server->name !== $name) {
Activity::event('server:settings.rename') Activity::event('server:settings.rename')

View File

@ -2,18 +2,18 @@
namespace App\Http\Controllers\Api\Remote; namespace App\Http\Controllers\Api\Remote;
use App\Models\Server;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Services\Servers\EnvironmentService; use App\Services\Servers\EnvironmentService;
use App\Contracts\Repository\ServerRepositoryInterface;
class EggInstallController extends Controller class EggInstallController extends Controller
{ {
/** /**
* EggInstallController constructor. * EggInstallController constructor.
*/ */
public function __construct(private EnvironmentService $environment, private ServerRepositoryInterface $repository) public function __construct(private EnvironmentService $environment)
{ {
} }
@ -21,20 +21,18 @@ class EggInstallController extends Controller
* Handle request to get script and installation information for a server * Handle request to get script and installation information for a server
* that is being created on the node. * that is being created on the node.
* *
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/ */
public function index(Request $request, string $uuid): JsonResponse public function index(Request $request, string $uuid): JsonResponse
{ {
$node = $request->attributes->get('node'); $node = $request->attributes->get('node');
/** @var \App\Models\Server $server */ $server = Server::query()
$server = $this->repository->findFirstWhere([ ->with('egg.scriptFrom')
['uuid', '=', $uuid], ->where('uuid', $uuid)
['node_id', '=', $node->id], ->where('node_id', $node->id)
]); ->firstOrFail();
$this->repository->loadEggRelations($server); $egg = $server->egg;
$egg = $server->getRelation('egg');
return response()->json([ return response()->json([
'scripts' => [ 'scripts' => [

View File

@ -9,7 +9,6 @@ use App\Facades\Activity;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Services\Eggs\EggConfigurationService; use App\Services\Eggs\EggConfigurationService;
use App\Repositories\Eloquent\ServerRepository;
use App\Http\Resources\Daemon\ServerConfigurationCollection; use App\Http\Resources\Daemon\ServerConfigurationCollection;
use App\Services\Servers\ServerConfigurationStructureService; use App\Services\Servers\ServerConfigurationStructureService;
@ -20,7 +19,6 @@ class ServerDetailsController extends Controller
*/ */
public function __construct( public function __construct(
protected ConnectionInterface $connection, protected ConnectionInterface $connection,
private ServerRepository $repository,
private ServerConfigurationStructureService $configurationStructureService, private ServerConfigurationStructureService $configurationStructureService,
private EggConfigurationService $eggConfigurationService private EggConfigurationService $eggConfigurationService
) { ) {
@ -29,12 +27,10 @@ class ServerDetailsController extends Controller
/** /**
* Returns details about the server that allows daemon to self-recover and ensure * Returns details about the server that allows daemon to self-recover and ensure
* that the state of the server matches the Panel at all times. * that the state of the server matches the Panel at all times.
*
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/ */
public function __invoke(Request $request, string $uuid): JsonResponse public function __invoke(Request $request, string $uuid): JsonResponse
{ {
$server = $this->repository->getByUuid($uuid); $server = Server::findOrFailByUuid($uuid);
return new JsonResponse([ return new JsonResponse([
'settings' => $this->configurationStructureService->handle($server), 'settings' => $this->configurationStructureService->handle($server),

View File

@ -2,7 +2,6 @@
namespace App\Http\Controllers\Api\Remote\Servers; namespace App\Http\Controllers\Api\Remote\Servers;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use App\Models\Server; use App\Models\Server;
@ -18,14 +17,14 @@ class ServerInstallController extends Controller
/** /**
* ServerInstallController constructor. * ServerInstallController constructor.
*/ */
public function __construct(private ServerRepository $repository, private EventDispatcher $eventDispatcher) public function __construct(private EventDispatcher $eventDispatcher)
{ {
} }
/** /**
* Returns installation information for a server. * Returns installation information for a server.
* *
* @throws \App\Exceptions\Repository\RecordNotFoundException * @throws RecordNotFoundException
*/ */
public function index(Request $request, string $uuid): JsonResponse public function index(Request $request, string $uuid): JsonResponse
{ {
@ -47,7 +46,7 @@ class ServerInstallController extends Controller
*/ */
public function store(InstallationDataRequest $request, string $uuid): JsonResponse public function store(InstallationDataRequest $request, string $uuid): JsonResponse
{ {
$server = $this->repository->getByUuid($uuid); $server = Server::findOrFailByUuid($uuid);
$status = null; $status = null;
// Make sure the type of failure is accurate // Make sure the type of failure is accurate
@ -64,11 +63,15 @@ class ServerInstallController extends Controller
$status = Server::STATUS_SUSPENDED; $status = Server::STATUS_SUSPENDED;
} }
$this->repository->update($server->id, ['status' => $status, 'installed_at' => CarbonImmutable::now()], true, true); $previouslyInstalledAt = $server->installed_at;
$server->status = $status;
$server->installed_at = now();
$server->save();
// If the server successfully installed, fire installed event. // If the server successfully installed, fire installed event.
// This logic allows individually disabling install and reinstall notifications separately. // This logic allows individually disabling install and reinstall notifications separately.
$isInitialInstall = is_null($server->installed_at); $isInitialInstall = is_null($previouslyInstalledAt);
if ($isInitialInstall && config()->get('panel.email.send_install_notification', true)) { if ($isInitialInstall && config()->get('panel.email.send_install_notification', true)) {
$this->eventDispatcher->dispatch(new ServerInstalled($server)); $this->eventDispatcher->dispatch(new ServerInstalled($server));
} elseif (!$isInitialInstall && config()->get('panel.email.send_reinstall_notification', true)) { } elseif (!$isInitialInstall && config()->get('panel.email.send_reinstall_notification', true)) {

View File

@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Remote\Servers;
use App\Models\Server; use App\Models\Server;
use App\Repositories\Daemon\DaemonRepository; use App\Repositories\Daemon\DaemonRepository;
use App\Repositories\Daemon\DaemonServerRepository;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@ -12,7 +13,6 @@ use Illuminate\Support\Facades\Log;
use App\Models\ServerTransfer; use App\Models\ServerTransfer;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Repositories\Eloquent\ServerRepository;
use Lcobucci\JWT\Token\Plain; use Lcobucci\JWT\Token\Plain;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException; use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use App\Exceptions\Http\Connection\DaemonConnectionException; use App\Exceptions\Http\Connection\DaemonConnectionException;
@ -24,8 +24,8 @@ class ServerTransferController extends Controller
*/ */
public function __construct( public function __construct(
private ConnectionInterface $connection, private ConnectionInterface $connection,
private ServerRepository $repository,
private DaemonRepository $daemonRepository, private DaemonRepository $daemonRepository,
private DaemonServerRepository $daemonServerRepository,
) { ) {
} }
@ -55,7 +55,7 @@ class ServerTransferController extends Controller
*/ */
public function failure(string $uuid): JsonResponse public function failure(string $uuid): JsonResponse
{ {
$server = $this->repository->getByUuid($uuid); $server = Server::findOrFailByUuid($uuid);
$transfer = $server->transfer; $transfer = $server->transfer;
if (is_null($transfer)) { if (is_null($transfer)) {
throw new ConflictHttpException('Server is not being transferred.'); throw new ConflictHttpException('Server is not being transferred.');
@ -71,7 +71,7 @@ class ServerTransferController extends Controller
*/ */
public function success(string $uuid): JsonResponse public function success(string $uuid): JsonResponse
{ {
$server = $this->repository->getByUuid($uuid); $server = Server::findOrFailByUuid($uuid);
$transfer = $server->transfer; $transfer = $server->transfer;
if (is_null($transfer)) { if (is_null($transfer)) {
throw new ConflictHttpException('Server is not being transferred.'); throw new ConflictHttpException('Server is not being transferred.');

View File

@ -12,10 +12,7 @@ class IndexController extends Controller
/** /**
* IndexController constructor. * IndexController constructor.
*/ */
public function __construct( public function __construct(protected ViewFactory $view) {
protected ServerRepositoryInterface $repository,
protected ViewFactory $view
) {
} }
/** /**

View File

@ -228,9 +228,9 @@ class Server extends Model
/** /**
* Gets the default allocation for a server. * Gets the default allocation for a server.
*/ */
public function allocation(): HasOne public function allocation(): BelongsTo
{ {
return $this->hasOne(Allocation::class, 'id', 'allocation_id'); return $this->belongsTo(Allocation::class);
} }
/** /**
@ -311,7 +311,7 @@ class Server extends Model
} }
/** /**
* Returns all of the activity log entries where the server is the subject. * Returns all the activity log entries where the server is the subject.
*/ */
public function activity(): MorphToMany public function activity(): MorphToMany
{ {
@ -323,7 +323,7 @@ class Server extends Model
* exception is raised. This should be called whenever something needs to make * exception is raised. This should be called whenever something needs to make
* sure the server is not in a weird state that should block user access. * sure the server is not in a weird state that should block user access.
* *
* @throws \App\Exceptions\Http\Server\ServerStateConflictException * @throws ServerStateConflictException
*/ */
public function validateCurrentState() public function validateCurrentState()
{ {
@ -341,7 +341,7 @@ class Server extends Model
/** /**
* Checks if the server is currently in a transferable state. If not, an * Checks if the server is currently in a transferable state. If not, an
* exception is raised. This should be called whenever something needs to make * exception is raised. This should be called whenever something needs to make
* sure the server is able to be transferred and is not currently being transferred * sure the server can be transferred and is not currently being transferred
* or installed. * or installed.
*/ */
public function validateTransferState() public function validateTransferState()
@ -354,4 +354,15 @@ class Server extends Model
throw new ServerStateConflictException($this); throw new ServerStateConflictException($this);
} }
} }
public static function findOrFailByUuid(string $uuid): Server
{
/** @var Server $server */
$server = Server::with(['nest', 'node'])
->where('uuidShort', $uuid)
->orWhere('uuid', $uuid)
->firstOrFail();
return $server;
}
} }

View File

@ -8,7 +8,6 @@ use App\Repositories\Eloquent\NodeRepository;
use App\Repositories\Eloquent\TaskRepository; use App\Repositories\Eloquent\TaskRepository;
use App\Repositories\Eloquent\UserRepository; use App\Repositories\Eloquent\UserRepository;
use App\Repositories\Eloquent\ApiKeyRepository; use App\Repositories\Eloquent\ApiKeyRepository;
use App\Repositories\Eloquent\ServerRepository;
use App\Repositories\Eloquent\SessionRepository; use App\Repositories\Eloquent\SessionRepository;
use App\Repositories\Eloquent\SubuserRepository; use App\Repositories\Eloquent\SubuserRepository;
use App\Repositories\Eloquent\DatabaseRepository; use App\Repositories\Eloquent\DatabaseRepository;
@ -22,7 +21,6 @@ use App\Contracts\Repository\TaskRepositoryInterface;
use App\Contracts\Repository\UserRepositoryInterface; use App\Contracts\Repository\UserRepositoryInterface;
use App\Repositories\Eloquent\DatabaseHostRepository; use App\Repositories\Eloquent\DatabaseHostRepository;
use App\Contracts\Repository\ApiKeyRepositoryInterface; use App\Contracts\Repository\ApiKeyRepositoryInterface;
use App\Contracts\Repository\ServerRepositoryInterface;
use App\Repositories\Eloquent\ServerVariableRepository; use App\Repositories\Eloquent\ServerVariableRepository;
use App\Contracts\Repository\SessionRepositoryInterface; use App\Contracts\Repository\SessionRepositoryInterface;
use App\Contracts\Repository\SubuserRepositoryInterface; use App\Contracts\Repository\SubuserRepositoryInterface;
@ -50,7 +48,6 @@ class RepositoryServiceProvider extends ServiceProvider
$this->app->bind(EggVariableRepositoryInterface::class, EggVariableRepository::class); $this->app->bind(EggVariableRepositoryInterface::class, EggVariableRepository::class);
$this->app->bind(NodeRepositoryInterface::class, NodeRepository::class); $this->app->bind(NodeRepositoryInterface::class, NodeRepository::class);
$this->app->bind(ScheduleRepositoryInterface::class, ScheduleRepository::class); $this->app->bind(ScheduleRepositoryInterface::class, ScheduleRepository::class);
$this->app->bind(ServerRepositoryInterface::class, ServerRepository::class);
$this->app->bind(ServerVariableRepositoryInterface::class, ServerVariableRepository::class); $this->app->bind(ServerVariableRepositoryInterface::class, ServerVariableRepository::class);
$this->app->bind(SessionRepositoryInterface::class, SessionRepository::class); $this->app->bind(SessionRepositoryInterface::class, SessionRepository::class);
$this->app->bind(SettingsRepositoryInterface::class, SettingsRepository::class); $this->app->bind(SettingsRepositoryInterface::class, SettingsRepository::class);

View File

@ -1,179 +0,0 @@
<?php
namespace App\Repositories\Eloquent;
use App\Models\Server;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use App\Exceptions\Repository\RecordNotFoundException;
use App\Contracts\Repository\ServerRepositoryInterface;
class ServerRepository extends EloquentRepository implements ServerRepositoryInterface
{
/**
* Return the model backing this repository.
*/
public function model(): string
{
return Server::class;
}
/**
* Load the egg relations onto the server model.
*/
public function loadEggRelations(Server $server, bool $refresh = false): Server
{
if (!$server->relationLoaded('egg') || $refresh) {
$server->load('egg.scriptFrom');
}
return $server;
}
/**
* Return a collection of servers with their associated data for rebuild operations.
*/
public function getDataForRebuild(int $server = null, int $node = null): Collection
{
$instance = $this->getBuilder()->with(['allocation', 'allocations', 'egg', 'node']);
if (!is_null($server) && is_null($node)) {
$instance = $instance->where('id', '=', $server);
} elseif (is_null($server) && !is_null($node)) {
$instance = $instance->where('node_id', '=', $node);
}
return $instance->get($this->getColumns());
}
/**
* Return a collection of servers with their associated data for reinstall operations.
*/
public function getDataForReinstall(int $server = null, int $node = null): Collection
{
$instance = $this->getBuilder()->with(['allocation', 'allocations', 'egg', 'node']);
if (!is_null($server) && is_null($node)) {
$instance = $instance->where('id', '=', $server);
} elseif (is_null($server) && !is_null($node)) {
$instance = $instance->where('node_id', '=', $node);
}
return $instance->get($this->getColumns());
}
/**
* Return a server model and all variables associated with the server.
*
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/
public function findWithVariables(int $id): Server
{
try {
return $this->getBuilder()->with('egg.variables', 'variables')
->where($this->getModel()->getKeyName(), '=', $id)
->firstOrFail($this->getColumns());
} catch (ModelNotFoundException) {
throw new RecordNotFoundException();
}
}
/**
* Get the primary allocation for a given server. If a model is passed into
* the function, load the allocation relationship onto it. Otherwise, find and
* return the server from the database.
*/
public function getPrimaryAllocation(Server $server, bool $refresh = false): Server
{
if (!$server->relationLoaded('allocation') || $refresh) {
$server->load('allocation');
}
return $server;
}
/**
* Return enough data to be used for the creation of a server via the daemon.
*/
public function getDataForCreation(Server $server, bool $refresh = false): Server
{
foreach (['allocation', 'allocations', 'egg'] as $relation) {
if (!$server->relationLoaded($relation) || $refresh) {
$server->load($relation);
}
}
return $server;
}
/**
* Load associated databases onto the server model.
*/
public function loadDatabaseRelations(Server $server, bool $refresh = false): Server
{
if (!$server->relationLoaded('databases') || $refresh) {
$server->load('databases.host');
}
return $server;
}
/**
* Get data for use when updating a server on the Daemon. Returns an array of
* the egg which is used for build and rebuild. Only loads relations
* if they are missing, or refresh is set to true.
*/
public function getDaemonServiceData(Server $server, bool $refresh = false): array
{
if (!$server->relationLoaded('egg') || $refresh) {
$server->load('egg');
}
return [
'egg' => $server->getRelation('egg')->uuid,
];
}
/**
* Return a server by UUID.
*
* @throws \App\Exceptions\Repository\RecordNotFoundException
*/
public function getByUuid(string $uuid): Server
{
try {
/** @var \App\Models\Server $model */
$model = $this->getBuilder()
->with('egg', 'node')
->where(function (Builder $query) use ($uuid) {
$query->where('uuidShort', $uuid)->orWhere('uuid', $uuid);
})
->firstOrFail($this->getColumns());
return $model;
} catch (ModelNotFoundException) {
throw new RecordNotFoundException();
}
}
/**
* Check if a given UUID and UUID-Short string are unique to a server.
*/
public function isUniqueUuidCombo(string $uuid, string $short): bool
{
return !$this->getBuilder()->where('uuid', '=', $uuid)->orWhere('uuidShort', '=', $short)->exists();
}
/**
* Returns all the servers that exist for a given node in a paginated response.
*/
public function loadAllServersForNode(int $node, int $limit): LengthAwarePaginator
{
return $this->getBuilder()
->with(['user', 'egg'])
->where('node_id', '=', $node)
->paginate($limit);
}
}

View File

@ -5,7 +5,7 @@ namespace App\Services\Eggs;
use App\Contracts\Repository\EggRepositoryInterface; use App\Contracts\Repository\EggRepositoryInterface;
use App\Exceptions\Service\Egg\HasChildrenException; use App\Exceptions\Service\Egg\HasChildrenException;
use App\Exceptions\Service\HasActiveServersException; use App\Exceptions\Service\HasActiveServersException;
use App\Contracts\Repository\ServerRepositoryInterface; use App\Models\Server;
class EggDeletionService class EggDeletionService
{ {
@ -13,7 +13,6 @@ class EggDeletionService
* EggDeletionService constructor. * EggDeletionService constructor.
*/ */
public function __construct( public function __construct(
protected ServerRepositoryInterface $serverRepository,
protected EggRepositoryInterface $repository protected EggRepositoryInterface $repository
) { ) {
} }
@ -26,8 +25,7 @@ class EggDeletionService
*/ */
public function handle(int $egg): int public function handle(int $egg): int
{ {
$servers = $this->serverRepository->findCountWhere([['egg_id', '=', $egg]]); if (Server::query()->where('egg_id', $egg)->count()) {
if ($servers > 0) {
throw new HasActiveServersException(trans('exceptions.egg.delete_has_servers')); throw new HasActiveServersException(trans('exceptions.egg.delete_has_servers'));
} }

View File

@ -6,7 +6,6 @@ use App\Models\Node;
use Illuminate\Contracts\Translation\Translator; use Illuminate\Contracts\Translation\Translator;
use App\Contracts\Repository\NodeRepositoryInterface; use App\Contracts\Repository\NodeRepositoryInterface;
use App\Exceptions\Service\HasActiveServersException; use App\Exceptions\Service\HasActiveServersException;
use App\Contracts\Repository\ServerRepositoryInterface;
class NodeDeletionService class NodeDeletionService
{ {
@ -15,7 +14,6 @@ class NodeDeletionService
*/ */
public function __construct( public function __construct(
protected NodeRepositoryInterface $repository, protected NodeRepositoryInterface $repository,
protected ServerRepositoryInterface $serverRepository,
protected Translator $translator protected Translator $translator
) { ) {
} }
@ -23,16 +21,15 @@ class NodeDeletionService
/** /**
* Delete a node from the panel if no servers are attached to it. * Delete a node from the panel if no servers are attached to it.
* *
* @throws \App\Exceptions\Service\HasActiveServersException * @throws HasActiveServersException
*/ */
public function handle(int|Node $node): int public function handle(int|Node $node): int
{ {
if ($node instanceof Node) { if (is_int($node)) {
$node = $node->id; $node = Node::findOrFail($node);
} }
$servers = $this->serverRepository->setColumns('id')->findCountWhere([['node_id', '=', $node]]); if ($node->servers()->count() > 0) {
if ($servers > 0) {
throw new HasActiveServersException($this->translator->get('exceptions.node.servers_attached')); throw new HasActiveServersException($this->translator->get('exceptions.node.servers_attached'));
} }

View File

@ -11,7 +11,6 @@ use Illuminate\Support\Collection;
use App\Models\Allocation; use App\Models\Allocation;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use App\Models\Objects\DeploymentObject; use App\Models\Objects\DeploymentObject;
use App\Repositories\Eloquent\ServerRepository;
use App\Repositories\Daemon\DaemonServerRepository; use App\Repositories\Daemon\DaemonServerRepository;
use App\Services\Deployment\FindViableNodesService; use App\Services\Deployment\FindViableNodesService;
use App\Repositories\Eloquent\ServerVariableRepository; use App\Repositories\Eloquent\ServerVariableRepository;
@ -28,7 +27,6 @@ class ServerCreationService
private ConnectionInterface $connection, private ConnectionInterface $connection,
private DaemonServerRepository $daemonServerRepository, private DaemonServerRepository $daemonServerRepository,
private FindViableNodesService $findViableNodesService, private FindViableNodesService $findViableNodesService,
private ServerRepository $repository,
private ServerDeletionService $serverDeletionService, private ServerDeletionService $serverDeletionService,
private ServerVariableRepository $serverVariableRepository, private ServerVariableRepository $serverVariableRepository,
private VariableValidatorService $validatorService private VariableValidatorService $validatorService
@ -129,8 +127,7 @@ class ServerCreationService
{ {
$uuid = $this->generateUniqueUuidCombo(); $uuid = $this->generateUniqueUuidCombo();
/** @var \App\Models\Server $model */ return Server::create([
$model = $this->repository->create([
'external_id' => Arr::get($data, 'external_id'), 'external_id' => Arr::get($data, 'external_id'),
'uuid' => $uuid, 'uuid' => $uuid,
'uuidShort' => substr($uuid, 0, 8), 'uuidShort' => substr($uuid, 0, 8),
@ -155,8 +152,6 @@ class ServerCreationService
'allocation_limit' => Arr::get($data, 'allocation_limit') ?? 0, 'allocation_limit' => Arr::get($data, 'allocation_limit') ?? 0,
'backup_limit' => Arr::get($data, 'backup_limit') ?? 0, 'backup_limit' => Arr::get($data, 'backup_limit') ?? 0,
]); ]);
return $model;
} }
/** /**
@ -199,7 +194,8 @@ class ServerCreationService
{ {
$uuid = Uuid::uuid4()->toString(); $uuid = Uuid::uuid4()->toString();
if (!$this->repository->isUniqueUuidCombo($uuid, substr($uuid, 0, 8))) { $shortUuid = str($uuid)->substr(0, 8);
if (Server::query()->where('uuid', $uuid)->orWhere('uuidShort', $shortUuid)->exists()) {
return $this->generateUniqueUuidCombo(); return $this->generateUniqueUuidCombo();
} }

View File

@ -6,7 +6,6 @@ use App\Models\User;
use App\Exceptions\DisplayException; use App\Exceptions\DisplayException;
use Illuminate\Contracts\Translation\Translator; use Illuminate\Contracts\Translation\Translator;
use App\Contracts\Repository\UserRepositoryInterface; use App\Contracts\Repository\UserRepositoryInterface;
use App\Contracts\Repository\ServerRepositoryInterface;
class UserDeletionService class UserDeletionService
{ {
@ -15,7 +14,6 @@ class UserDeletionService
*/ */
public function __construct( public function __construct(
protected UserRepositoryInterface $repository, protected UserRepositoryInterface $repository,
protected ServerRepositoryInterface $serverRepository,
protected Translator $translator protected Translator $translator
) { ) {
} }
@ -23,19 +21,18 @@ class UserDeletionService
/** /**
* Delete a user from the panel only if they have no servers attached to their account. * Delete a user from the panel only if they have no servers attached to their account.
* *
* @throws \App\Exceptions\DisplayException * @throws DisplayException
*/ */
public function handle(int|User $user): ?bool public function handle(int|User $user): ?bool
{ {
if ($user instanceof User) { if (is_int($user)) {
$user = $user->id; $user = User::findOrFail($user);
} }
$servers = $this->serverRepository->setColumns('id')->findCountWhere([['owner_id', '=', $user]]); if ($user->servers()->count() > 0) {
if ($servers > 0) {
throw new DisplayException($this->translator->get('admin/user.exceptions.user_has_servers')); throw new DisplayException($this->translator->get('admin/user.exceptions.user_has_servers'));
} }
return $this->repository->delete($user); return $this->repository->delete($user->id);
} }
} }