$eggVariables
* @property-read int|null $egg_variables_count
@@ -143,11 +143,6 @@ class Server extends Model
'installed_at' => null,
];
- /**
- * The default relationships to load for all server models.
- */
- protected $with = ['allocation'];
-
/**
* Fields that are not mass assignable.
*/
@@ -167,7 +162,6 @@ class Server extends Model
'threads' => 'nullable|regex:/^[0-9-,]+$/',
'oom_killer' => 'sometimes|boolean',
'disk' => 'required|numeric|min:0',
- 'allocation_id' => 'required|bail|unique:servers|exists:allocations,id',
'egg_id' => 'required|exists:eggs,id',
'startup' => 'required|string',
'skip_scripts' => 'sometimes|boolean',
@@ -175,6 +169,7 @@ class Server extends Model
'database_limit' => 'present|nullable|integer|min:0',
'allocation_limit' => 'sometimes|nullable|integer|min:0',
'backup_limit' => 'present|nullable|integer|min:0',
+ 'ports' => 'nullable|array',
];
protected function casts(): array
@@ -190,27 +185,24 @@ protected function casts(): array
'io' => 'integer',
'cpu' => 'integer',
'oom_killer' => 'boolean',
- 'allocation_id' => 'integer',
'egg_id' => 'integer',
'database_limit' => 'integer',
'allocation_limit' => 'integer',
'backup_limit' => 'integer',
- self::CREATED_AT => 'datetime',
- self::UPDATED_AT => 'datetime',
'deleted_at' => 'datetime',
'installed_at' => 'datetime',
'docker_labels' => 'array',
+ 'ports' => EndpointCollection::class,
];
}
/**
- * Returns the format for server allocations when communicating with the Daemon.
+ * Returns the format for server's ports when communicating with the Daemon.
*/
- public function getAllocationMappings(): array
+ public function getPortMappings(): array
{
- return $this->allocations->where('node_id', $this->node_id)->groupBy('ip')->map(function ($item) {
- return $item->pluck('port');
- })->toArray();
+ return $this->ports->mapToGroups(fn (Endpoint $endpoint) => [$endpoint->ip => $endpoint->port]
+ )->toArray();
}
public function isInstalled(): bool
@@ -239,22 +231,6 @@ public function subusers(): HasMany
return $this->hasMany(Subuser::class, 'server_id', 'id');
}
- /**
- * Gets the default allocation for a server.
- */
- public function allocation(): BelongsTo
- {
- return $this->belongsTo(Allocation::class);
- }
-
- /**
- * Gets all allocations associated with this server.
- */
- public function allocations(): HasMany
- {
- return $this->hasMany(Allocation::class);
- }
-
/**
* Gets information for the egg associated with this server.
*/
@@ -454,4 +430,21 @@ public function conditionColor(): string
return $this->status->color();
}
+
+ public function getPrimaryEndpoint(): ?Endpoint
+ {
+ $endpoint = $this->ports->first();
+
+ $portEggVariable = $this->variables->firstWhere('env_variable', 'SERVER_PORT');
+ if ($portEggVariable) {
+ $portServerVariable = $this->serverVariables->firstWhere('variable_id', $portEggVariable->id);
+ if (!$portServerVariable) {
+ return null;
+ }
+
+ $endpoint = new Endpoint($portServerVariable->variable_value);
+ }
+
+ return $endpoint;
+ }
}
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index 4ead65cbbd..638fd9dc5b 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -3,10 +3,12 @@
namespace App\Providers;
use App\Extensions\Themes\Theme;
+use App\Livewire\EndpointSynth;
use App\Models;
use App\Models\ApiKey;
use App\Models\Node;
use App\Models\User;
+use App\Rules\Port;
use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
@@ -20,10 +22,13 @@
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\URL;
+use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
+use Illuminate\Validation\InvokableValidationRule;
use Laravel\Sanctum\Sanctum;
+use Livewire\Livewire;
class AppServiceProvider extends ServiceProvider
{
@@ -46,7 +51,6 @@ public function boot(Application $app): void
}
Relation::enforceMorphMap([
- 'allocation' => Models\Allocation::class,
'api_key' => Models\ApiKey::class,
'backup' => Models\Backup::class,
'database' => Models\Database::class,
@@ -74,6 +78,22 @@ public function boot(Application $app): void
$this->bootAuth();
$this->bootBroadcast();
+ Livewire::propertySynthesizer(EndpointSynth::class);
+
+ // Assign custom validation rules
+ Validator::extend('port', function ($attribute, $value, $parameters, $validator) {
+ $rule = InvokableValidationRule::make(new Port());
+ $rule->setValidator($validator); // @phpstan-ignore-line
+ $rule->setData($validator->getData()); // @phpstan-ignore-line
+
+ $result = $rule->passes($attribute, $value);
+ if (!$result) {
+ $validator->customMessages[$attribute] = $rule->message();
+ }
+
+ return $result;
+ });
+
$bearerTokens = fn (OpenApi $openApi) => $openApi->secure(SecurityScheme::http('bearer'));
Gate::define('viewApiDocs', fn () => true);
Scramble::registerApi('application', ['api_path' => 'api/application', 'info' => ['version' => '1.0']]);
diff --git a/app/Rules/Port.php b/app/Rules/Port.php
index 7225509c03..9f99ed6223 100644
--- a/app/Rules/Port.php
+++ b/app/Rules/Port.php
@@ -2,33 +2,38 @@
namespace App\Rules;
+use App\Models\Objects\Endpoint;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class Port implements ValidationRule
{
- /**
- * Run the validation rule.
- *
- * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
- */
public function validate(string $attribute, mixed $value, Closure $fail): void
{
+ // Allow port to be optional
+ if (empty($value)) {
+ return;
+ }
+
+ // Require port to be a number
if (!is_numeric($value)) {
$fail('The :attribute must be numeric.');
}
+ // Require port to be an integer
$value = intval($value);
if (floatval($value) !== (float) $value) {
$fail('The :attribute must be an integer.');
}
- if ($value < 0) {
- $fail('The :attribute must be greater or equal to 0.');
+ // Require minimum valid port
+ if ($value <= Endpoint::PORT_FLOOR) {
+ $fail('The :attribute must be greater than 1024.');
}
- if ($value > 65535) {
- $fail('The :attribute must be less or equal to 65535.');
+ // Require maximum valid port
+ if ($value > Endpoint::PORT_CEIL) {
+ $fail('The :attribute must be less than 65535.');
}
}
}
diff --git a/app/Services/Allocations/AssignmentService.php b/app/Services/Allocations/AssignmentService.php
deleted file mode 100644
index 23f28e1224..0000000000
--- a/app/Services/Allocations/AssignmentService.php
+++ /dev/null
@@ -1,121 +0,0 @@
- self::CIDR_MIN_BITS || $explode[1] < self::CIDR_MAX_BITS)) {
- throw new CidrOutOfRangeException();
- }
- }
-
- try {
- // TODO: how should we approach supporting IPv6 with this?
- // gethostbyname only supports IPv4, but the alternative (dns_get_record) returns
- // an array of records, which is not ideal for this use case, we need a SINGLE
- // IP to use, not multiple.
- $underlying = gethostbyname($data['allocation_ip']);
- $parsed = Network::parse($underlying);
- } catch (\Exception $exception) {
- throw new DisplayException("Could not parse provided allocation IP address ({$data['allocation_ip']}): {$exception->getMessage()}", $exception);
- }
-
- $this->connection->beginTransaction();
-
- $ids = [];
- foreach ($parsed as $ip) {
- foreach ($data['allocation_ports'] as $port) {
- if (!is_digit($port) && !preg_match(self::PORT_RANGE_REGEX, $port)) {
- throw new InvalidPortMappingException($port);
- }
-
- $insertData = [];
- if (preg_match(self::PORT_RANGE_REGEX, $port, $matches)) {
- $block = range($matches[1], $matches[2]);
-
- if (count($block) > self::PORT_RANGE_LIMIT) {
- throw new TooManyPortsInRangeException();
- }
-
- if ((int) $matches[1] < self::PORT_FLOOR || (int) $matches[2] > self::PORT_CEIL) {
- throw new PortOutOfRangeException();
- }
-
- foreach ($block as $unit) {
- $insertData[] = [
- 'node_id' => $node->id,
- 'ip' => $ip->__toString(),
- 'port' => (int) $unit,
- 'ip_alias' => array_get($data, 'allocation_alias'),
- 'server_id' => $server->id ?? null,
- ];
- }
- } else {
- if ((int) $port < self::PORT_FLOOR || (int) $port > self::PORT_CEIL) {
- throw new PortOutOfRangeException();
- }
-
- $insertData[] = [
- 'node_id' => $node->id,
- 'ip' => $ip->__toString(),
- 'port' => (int) $port,
- 'ip_alias' => array_get($data, 'allocation_alias'),
- 'server_id' => $server->id ?? null,
- ];
- }
-
- foreach ($insertData as $insert) {
- $allocation = Allocation::query()->create($insert);
- $ids[] = $allocation->id;
- }
- }
- }
-
- $this->connection->commit();
-
- return $ids;
- }
-}
diff --git a/app/Services/Allocations/FindAssignableAllocationService.php b/app/Services/Allocations/FindAssignableAllocationService.php
index 5c62b7539e..dedfc65555 100644
--- a/app/Services/Allocations/FindAssignableAllocationService.php
+++ b/app/Services/Allocations/FindAssignableAllocationService.php
@@ -2,110 +2,48 @@
namespace App\Services\Allocations;
+use App\Models\Objects\Endpoint;
+use Illuminate\Support\Collection;
use Webmozart\Assert\Assert;
use App\Models\Server;
-use App\Models\Allocation;
-use App\Exceptions\Service\Allocation\AutoAllocationNotEnabledException;
-use App\Exceptions\Service\Allocation\NoAutoAllocationSpaceAvailableException;
class FindAssignableAllocationService
{
- /**
- * FindAssignableAllocationService constructor.
- */
- public function __construct(private AssignmentService $service)
+ public function __construct()
{
}
- /**
- * Finds an existing unassigned allocation and attempts to assign it to the given server. If
- * no allocation can be found, a new one will be created with a random port between the defined
- * range from the configuration.
- *
- * @throws \App\Exceptions\DisplayException
- * @throws \App\Exceptions\Service\Allocation\CidrOutOfRangeException
- * @throws \App\Exceptions\Service\Allocation\InvalidPortMappingException
- * @throws \App\Exceptions\Service\Allocation\PortOutOfRangeException
- * @throws \App\Exceptions\Service\Allocation\TooManyPortsInRangeException
- */
- public function handle(Server $server): Allocation
+ public function handle(Server $server): int
{
- if (!config('panel.client_features.allocations.enabled')) {
- throw new AutoAllocationNotEnabledException();
- }
-
- // Attempt to find a given available allocation for a server. If one cannot be found
- // we will fall back to attempting to create a new allocation that can be used for the
- // server.
- /** @var \App\Models\Allocation|null $allocation */
- $allocation = $server->node->allocations()
- ->where('ip', $server->allocation->ip)
- ->whereNull('server_id')
- ->inRandomOrder()
- ->first();
-
- $allocation = $allocation ?? $this->createNewAllocation($server);
+ abort_unless(config('panel.client_features.allocations.enabled'), 403, 'Auto Allocation is not enabled');
- $allocation->update(['server_id' => $server->id]);
-
- return $allocation->refresh();
+ return $this->createNewAllocation($server);
}
/**
* Create a new allocation on the server's node with a random port from the defined range
* in the settings. If there are no matches in that range, or something is wrong with the
* range information provided an exception will be raised.
- *
- * @throws \App\Exceptions\DisplayException
- * @throws \App\Exceptions\Service\Allocation\CidrOutOfRangeException
- * @throws \App\Exceptions\Service\Allocation\InvalidPortMappingException
- * @throws \App\Exceptions\Service\Allocation\PortOutOfRangeException
- * @throws \App\Exceptions\Service\Allocation\TooManyPortsInRangeException
*/
- protected function createNewAllocation(Server $server): Allocation
+ protected function createNewAllocation(Server $server): int
{
- $start = config('panel.client_features.allocations.range_start', null);
- $end = config('panel.client_features.allocations.range_end', null);
-
- if (!$start || !$end) {
- throw new NoAutoAllocationSpaceAvailableException();
- }
+ $start = config('panel.client_features.allocations.range_start');
+ $end = config('panel.client_features.allocations.range_end');
Assert::integerish($start);
Assert::integerish($end);
- // Get all of the currently allocated ports for the node so that we can figure out
- // which port might be available.
- $ports = $server->node->allocations()
- ->where('ip', $server->allocation->ip)
- ->whereBetween('port', [$start, $end])
- ->pluck('port');
+ $ports = $server->node->servers
+ ->reduce(fn (Collection $result, $value) => $result->merge($value), collect())
+ ->map(fn (Endpoint $endpoint) => $endpoint->port)
+ ->filter(fn (int $port): bool => $port >= $start && $port <= $end);
// Compute the difference of the range and the currently created ports, finding
// any port that does not already exist in the database. We will then use this
// array of ports to create a new allocation to assign to the server.
$available = array_diff(range($start, $end), $ports->toArray());
- // If we've already allocated all of the ports, just abort.
- if (empty($available)) {
- throw new NoAutoAllocationSpaceAvailableException();
- }
-
// Pick a random port out of the remaining available ports.
- /** @var int $port */
- $port = $available[array_rand($available)];
-
- $this->service->handle($server->node, [
- 'allocation_ip' => $server->allocation->ip,
- 'allocation_ports' => [$port],
- ]);
-
- /** @var \App\Models\Allocation $allocation */
- $allocation = $server->node->allocations()
- ->where('ip', $server->allocation->ip)
- ->where('port', $port)
- ->firstOrFail();
-
- return $allocation;
+ return $available[array_rand($available)];
}
}
diff --git a/app/Services/Deployment/AllocationSelectionService.php b/app/Services/Deployment/AllocationSelectionService.php
deleted file mode 100644
index 3868d0b383..0000000000
--- a/app/Services/Deployment/AllocationSelectionService.php
+++ /dev/null
@@ -1,150 +0,0 @@
-dedicated = $dedicated;
-
- return $this;
- }
-
- /**
- * A list of node IDs that should be used when selecting an allocation. If empty, all
- * nodes will be used to filter with.
- */
- public function setNodes(array $nodes): self
- {
- $this->nodes = $nodes;
-
- return $this;
- }
-
- /**
- * An array of individual ports or port ranges to use when selecting an allocation. If
- * empty, all ports will be considered when finding an allocation. If set, only ports appearing
- * in the array or range will be used.
- *
- * @throws \App\Exceptions\DisplayException
- */
- public function setPorts(array $ports): self
- {
- $stored = [];
- foreach ($ports as $port) {
- if (is_digit($port)) {
- $stored[] = $port;
- }
-
- // Ranges are stored in the ports array as an array which can be
- // better processed in the repository.
- if (preg_match(AssignmentService::PORT_RANGE_REGEX, $port, $matches)) {
- if (abs((int) $matches[2] - (int) $matches[1]) > AssignmentService::PORT_RANGE_LIMIT) {
- throw new DisplayException(trans('exceptions.allocations.too_many_ports'));
- }
-
- $stored[] = [$matches[1], $matches[2]];
- }
- }
-
- $this->ports = $stored;
-
- return $this;
- }
-
- /**
- * Return a single allocation that should be used as the default allocation for a server.
- *
- * @throws \App\Exceptions\Service\Deployment\NoViableAllocationException
- */
- public function handle(): Allocation
- {
- $allocation = $this->getRandomAllocation($this->nodes, $this->ports, $this->dedicated);
-
- if (is_null($allocation)) {
- throw new NoViableAllocationException(trans('exceptions.deployment.no_viable_allocations'));
- }
-
- return $allocation;
- }
-
- /**
- * Return a single allocation from those meeting the requirements.
- */
- private function getRandomAllocation(array $nodes = [], array $ports = [], bool $dedicated = false): ?Allocation
- {
- $query = Allocation::query()
- ->whereNull('server_id')
- ->whereIn('node_id', $nodes);
-
- if (!empty($ports)) {
- $query->where(function ($inner) use ($ports) {
- $whereIn = [];
- foreach ($ports as $port) {
- if (is_array($port)) {
- $inner->orWhereBetween('port', $port);
-
- continue;
- }
-
- $whereIn[] = $port;
- }
-
- if (!empty($whereIn)) {
- $inner->orWhereIn('port', $whereIn);
- }
- });
- }
-
- // If this allocation should not be shared with any other servers get
- // the data and modify the query as necessary,
- if ($dedicated) {
- $discard = $this->getDiscardableDedicatedAllocations($nodes);
-
- if (!empty($discard)) {
- $query->whereNotIn('ip', $discard);
- }
- }
-
- return $query->inRandomOrder()->first();
- }
-
- /**
- * Return a result set of node ips that already have at least one
- * server assigned to that IP. This allows for filtering out sets for
- * dedicated allocation IPs.
- *
- * If an array of nodes is passed the results will be limited to allocations
- * in those nodes.
- */
- private function getDiscardableDedicatedAllocations(array $nodes = []): array
- {
- $query = Allocation::query()->whereNotNull('server_id');
-
- if (!empty($nodes)) {
- $query->whereIn('node_id', $nodes);
- }
-
- return $query->groupBy('ip')
- ->get()
- ->pluck('ip')
- ->toArray();
- }
-}
diff --git a/app/Services/Deployment/FindViableNodesService.php b/app/Services/Deployment/FindViableNodesService.php
index d95c08c640..79dc624bec 100644
--- a/app/Services/Deployment/FindViableNodesService.php
+++ b/app/Services/Deployment/FindViableNodesService.php
@@ -8,8 +8,7 @@
class FindViableNodesService
{
/**
- * Returns a collection of nodes that meet the provided requirements and can then
- * be passed to the AllocationSelectionService to return a single allocation.
+ * Returns a collection of nodes that meet the provided requirements
*
* This functionality is used for automatic deployments of servers and will
* attempt to find all nodes in the defined locations that meet the memory, disk
diff --git a/app/Services/Servers/BuildModificationService.php b/app/Services/Servers/BuildModificationService.php
index f7c7403249..3b74af0657 100644
--- a/app/Services/Servers/BuildModificationService.php
+++ b/app/Services/Servers/BuildModificationService.php
@@ -4,9 +4,7 @@
use Illuminate\Support\Arr;
use App\Models\Server;
-use App\Models\Allocation;
use Illuminate\Database\ConnectionInterface;
-use App\Exceptions\DisplayException;
use App\Repositories\Daemon\DaemonServerRepository;
use App\Exceptions\Http\Connection\DaemonConnectionException;
@@ -32,20 +30,12 @@ public function handle(Server $server, array $data): Server
{
/** @var \App\Models\Server $server */
$server = $this->connection->transaction(function () use ($server, $data) {
- $this->processAllocations($server, $data);
-
- if (isset($data['allocation_id']) && $data['allocation_id'] != $server->allocation_id) {
- $existingAllocation = $server->allocations()->findOrFail($data['allocation_id']);
-
- throw_unless($existingAllocation, new DisplayException('The requested default allocation is not currently assigned to this server.'));
- }
-
if (!isset($data['oom_killer']) && isset($data['oom_disabled'])) {
$data['oom_killer'] = !$data['oom_disabled'];
}
// If any of these values are passed through in the data array go ahead and set them correctly on the server model.
- $merge = Arr::only($data, ['oom_killer', 'memory', 'swap', 'io', 'cpu', 'threads', 'disk', 'allocation_id']);
+ $merge = Arr::only($data, ['oom_killer', 'memory', 'swap', 'io', 'cpu', 'threads', 'disk', 'ports']);
$server->forceFill(array_merge($merge, [
'database_limit' => Arr::get($data, 'database_limit', 0) ?? null,
@@ -72,59 +62,4 @@ public function handle(Server $server, array $data): Server
return $server;
}
-
- /**
- * Process the allocations being assigned in the data and ensure they are available for a server.
- *
- * @throws \App\Exceptions\DisplayException
- */
- private function processAllocations(Server $server, array &$data): void
- {
- if (empty($data['add_allocations']) && empty($data['remove_allocations'])) {
- return;
- }
-
- // Handle the addition of allocations to this server. Only assign allocations that are not currently
- // assigned to a different server, and only allocations on the same node as the server.
- if (!empty($data['add_allocations'])) {
- $query = Allocation::query()
- ->where('node_id', $server->node_id)
- ->whereIn('id', $data['add_allocations'])
- ->whereNull('server_id');
-
- // Keep track of all the allocations we're just now adding so that we can use the first
- // one to reset the default allocation to.
- $freshlyAllocated = $query->first()?->id;
-
- $query->update(['server_id' => $server->id, 'notes' => null]);
- }
-
- if (!empty($data['remove_allocations'])) {
- foreach ($data['remove_allocations'] as $allocation) {
- // If we are attempting to remove the default allocation for the server, see if we can reassign
- // to the first provided value in add_allocations. If there is no new first allocation then we
- // will throw an exception back.
- if ($allocation === ($data['allocation_id'] ?? $server->allocation_id)) {
- if (empty($freshlyAllocated)) {
- throw new DisplayException('You are attempting to delete the default allocation for this server but there is no fallback allocation to use.');
- }
-
- // Update the default allocation to be the first allocation that we are creating.
- $data['allocation_id'] = $freshlyAllocated;
- }
- }
-
- // Remove any of the allocations we got that are currently assigned to this server on
- // this node. Also set the notes to null, otherwise when re-allocated to a new server those
- // notes will be carried over.
- Allocation::query()->where('node_id', $server->node_id)
- ->where('server_id', $server->id)
- // Only remove the allocations that we didn't also attempt to add to the server...
- ->whereIn('id', array_diff($data['remove_allocations'], $data['add_allocations'] ?? []))
- ->update([
- 'notes' => null,
- 'server_id' => null,
- ]);
- }
- }
}
diff --git a/app/Services/Servers/ServerConfigurationStructureService.php b/app/Services/Servers/ServerConfigurationStructureService.php
index 7ac714ed51..ca9e5455d6 100644
--- a/app/Services/Servers/ServerConfigurationStructureService.php
+++ b/app/Services/Servers/ServerConfigurationStructureService.php
@@ -17,8 +17,8 @@ public function __construct(private EnvironmentService $environment)
/**
* Return a configuration array for a specific server when passed a server model.
*
- * DO NOT MODIFY THIS FUNCTION. This powers legacy code handling for the new daemon
- * daemon, if you modify the structure eggs will break unexpectedly.
+ * DO NOT MODIFY THIS FUNCTION. This powers legacy code handling for wings
+ * if you modify the structure eggs will break unexpectedly.
*/
public function handle(Server $server, array $override = []): array
{
@@ -66,10 +66,10 @@ protected function returnFormat(Server $server): array
'allocations' => [
'force_outgoing_ip' => $server->egg->force_outgoing_ip,
'default' => [
- 'ip' => $server->allocation->ip,
- 'port' => $server->allocation->port,
+ 'ip' => $server->getPrimaryEndpoint()?->ip,
+ 'port' => $server->getPrimaryEndpoint()?->port,
],
- 'mappings' => $server->getAllocationMappings(),
+ 'mappings' => $server->getPortMappings(),
],
'egg' => [
'id' => $server->egg->uuid,
diff --git a/app/Services/Servers/ServerCreationService.php b/app/Services/Servers/ServerCreationService.php
index 18eb790e53..af9e06d8d1 100644
--- a/app/Services/Servers/ServerCreationService.php
+++ b/app/Services/Servers/ServerCreationService.php
@@ -10,85 +10,54 @@
use Webmozart\Assert\Assert;
use App\Models\Server;
use Illuminate\Support\Collection;
-use App\Models\Allocation;
use Illuminate\Database\ConnectionInterface;
use App\Models\Objects\DeploymentObject;
use App\Repositories\Daemon\DaemonServerRepository;
-use App\Services\Deployment\FindViableNodesService;
-use App\Services\Deployment\AllocationSelectionService;
use App\Exceptions\Http\Connection\DaemonConnectionException;
use App\Models\Egg;
class ServerCreationService
{
- /**
- * ServerCreationService constructor.
- */
public function __construct(
- private AllocationSelectionService $allocationSelectionService,
private ConnectionInterface $connection,
private DaemonServerRepository $daemonServerRepository,
- private FindViableNodesService $findViableNodesService,
private ServerDeletionService $serverDeletionService,
private VariableValidatorService $validatorService
) {
}
/**
- * Create a server on the Panel and trigger a request to the Daemon to begin the server
- * creation process. This function will attempt to set as many additional values
- * as possible given the input data. For example, if an allocation_id is passed with
- * no node_id the node_is will be picked from the allocation.
- *
- * @throws \Throwable
- * @throws \App\Exceptions\DisplayException
- * @throws \Illuminate\Validation\ValidationException
- * @throws \App\Exceptions\Service\Deployment\NoViableAllocationException
+ * Create a server on the Panel and trigger a request to the Daemon to begin the server creation process.
+ * This function will attempt to set as many additional values as possible given the input data.
*/
- public function handle(array $data, ?DeploymentObject $deployment = null): Server
+ public function handle(array $data, ?DeploymentObject $deployment = null, bool $validateVariables = true): Server
{
if (!isset($data['oom_killer']) && isset($data['oom_disabled'])) {
$data['oom_killer'] = !$data['oom_disabled'];
}
- /** @var Egg $egg */
$egg = Egg::query()->findOrFail($data['egg_id']);
// Fill missing fields from egg
$data['image'] = $data['image'] ?? collect($egg->docker_images)->first();
$data['startup'] = $data['startup'] ?? $egg->startup;
- // If a deployment object has been passed we need to get the allocation
- // that the server should use, and assign the node from that allocation.
- if ($deployment instanceof DeploymentObject) {
- $allocation = $this->configureDeployment($data, $deployment);
- $data['allocation_id'] = $allocation->id;
- $data['node_id'] = $allocation->node_id;
- }
-
- // Auto-configure the node based on the selected allocation
- // if no node was defined.
- if (empty($data['node_id'])) {
- Assert::false(empty($data['allocation_id']), 'Expected a non-empty allocation_id in server creation data.');
-
- $data['node_id'] = Allocation::query()->findOrFail($data['allocation_id'])->node_id;
- }
+ Assert::false(empty($data['node_id']));
$eggVariableData = $this->validatorService
->setUserLevel(User::USER_LEVEL_ADMIN)
- ->handle(Arr::get($data, 'egg_id'), Arr::get($data, 'environment', []));
+ ->handle(Arr::get($data, 'egg_id'), Arr::get($data, 'environment', []), $validateVariables);
// Due to the design of the Daemon, we need to persist this server to the disk
// before we can actually create it on the Daemon.
//
// If that connection fails out we will attempt to perform a cleanup by just
// deleting the server itself from the system.
- /** @var \App\Models\Server $server */
+ /** @var Server $server */
$server = $this->connection->transaction(function () use ($data, $eggVariableData) {
// Create the server and assign any additional allocations to it.
$server = $this->createModel($data);
- $this->storeAssignedAllocations($server, $data);
$this->storeEggVariables($server, $eggVariableData);
return $server;
@@ -96,7 +65,7 @@ public function handle(array $data, ?DeploymentObject $deployment = null): Serve
try {
$this->daemonServerRepository->setServer($server)->create(
- Arr::get($data, 'start_on_completion', false) ?? false
+ Arr::get($data, 'start_on_completion', true) ?? true,
);
} catch (DaemonConnectionException $exception) {
$this->serverDeletionService->withForce()->handle($server);
@@ -107,28 +76,6 @@ public function handle(array $data, ?DeploymentObject $deployment = null): Serve
return $server;
}
- /**
- * Gets an allocation to use for automatic deployment.
- *
- * @throws \App\Exceptions\DisplayException
- * @throws \App\Exceptions\Service\Deployment\NoViableAllocationException
- */
- private function configureDeployment(array $data, DeploymentObject $deployment): Allocation
- {
- /** @var Collection<\App\Models\Node> $nodes */
- $nodes = $this->findViableNodesService->handle(
- Arr::get($data, 'memory', 0),
- Arr::get($data, 'disk', 0),
- Arr::get($data, 'cpu', 0),
- Arr::get($data, 'tags', []),
- );
-
- return $this->allocationSelectionService->setDedicated($deployment->isDedicated())
- ->setNodes($nodes->pluck('id')->toArray())
- ->setPorts($deployment->getPorts())
- ->handle();
- }
-
/**
* Store the server in the database and return the model.
*
@@ -155,7 +102,7 @@ private function createModel(array $data): Server
'cpu' => Arr::get($data, 'cpu'),
'threads' => Arr::get($data, 'threads'),
'oom_killer' => Arr::get($data, 'oom_killer') ?? false,
- 'allocation_id' => Arr::get($data, 'allocation_id'),
+ 'ports' => Arr::get($data, 'ports') ?? [],
'egg_id' => Arr::get($data, 'egg_id'),
'startup' => Arr::get($data, 'startup'),
'image' => Arr::get($data, 'image'),
@@ -166,21 +113,6 @@ private function createModel(array $data): Server
]);
}
- /**
- * Configure the allocations assigned to this server.
- */
- private function storeAssignedAllocations(Server $server, array $data): void
- {
- $records = [$data['allocation_id']];
- if (isset($data['allocation_additional']) && is_array($data['allocation_additional'])) {
- $records = array_merge($records, $data['allocation_additional']);
- }
-
- Allocation::query()->whereIn('id', $records)->update([
- 'server_id' => $server->id,
- ]);
- }
-
/**
* Process environment variables passed for this server and store them in the database.
*/
diff --git a/app/Services/Servers/ServerDeletionService.php b/app/Services/Servers/ServerDeletionService.php
index 97e6995c77..71e9ee19ee 100644
--- a/app/Services/Servers/ServerDeletionService.php
+++ b/app/Services/Servers/ServerDeletionService.php
@@ -77,8 +77,6 @@ public function handle(Server $server): void
}
}
- $server->allocations()->update(['server_id' => null]);
-
$server->delete();
});
}
diff --git a/app/Services/Servers/StartupCommandService.php b/app/Services/Servers/StartupCommandService.php
index 4703eb0753..f75e613fc6 100644
--- a/app/Services/Servers/StartupCommandService.php
+++ b/app/Services/Servers/StartupCommandService.php
@@ -2,6 +2,7 @@
namespace App\Services\Servers;
+use App\Models\Objects\Endpoint;
use App\Models\Server;
class StartupCommandService
@@ -11,8 +12,10 @@ class StartupCommandService
*/
public function handle(Server $server, bool $hideAllValues = false): string
{
+ $endpoint = $server->getPrimaryEndpoint();
+
$find = ['{{SERVER_MEMORY}}', '{{SERVER_IP}}', '{{SERVER_PORT}}'];
- $replace = [$server->memory, $server->allocation->ip, $server->allocation->port];
+ $replace = [$server->memory, $endpoint->ip ?? Endpoint::INADDR_ANY, $endpoint->port ?? ''];
foreach ($server->variables as $variable) {
$find[] = '{{' . $variable->env_variable . '}}';
diff --git a/app/Services/Servers/TransferServerService.php b/app/Services/Servers/TransferServerService.php
index 8a7bcd3ea1..c948f3b9c5 100644
--- a/app/Services/Servers/TransferServerService.php
+++ b/app/Services/Servers/TransferServerService.php
@@ -3,7 +3,6 @@
namespace App\Services\Servers;
use App\Exceptions\Http\Connection\DaemonConnectionException;
-use App\Models\Allocation;
use App\Models\Node;
use App\Models\Server;
use App\Models\ServerTransfer;
@@ -52,8 +51,6 @@ private function notify(Server $server, Plain $token): void
public function handle(Server $server, array $data): bool
{
$node_id = $data['node_id'];
- $allocation_id = intval($data['allocation_id']);
- $additional_allocations = array_map(intval(...), $data['allocation_additional'] ?? []);
// Check if the node is viable for the transfer.
$node = Node::query()
@@ -71,23 +68,15 @@ public function handle(Server $server, array $data): bool
$server->validateTransferState();
- $this->connection->transaction(function () use ($server, $node_id, $allocation_id, $additional_allocations) {
- // Create a new ServerTransfer entry.
+ $this->connection->transaction(function () use ($server, $node_id) {
$transfer = new ServerTransfer();
$transfer->server_id = $server->id;
$transfer->old_node = $server->node_id;
$transfer->new_node = $node_id;
- $transfer->old_allocation = $server->allocation_id;
- $transfer->new_allocation = $allocation_id;
- $transfer->old_additional_allocations = $server->allocations->where('id', '!=', $server->allocation_id)->pluck('id')->all();
- $transfer->new_additional_allocations = $additional_allocations;
$transfer->save();
- // Add the allocations to the server, so they cannot be automatically assigned while the transfer is in progress.
- $this->assignAllocationsToServer($server, $node_id, $allocation_id, $additional_allocations);
-
// Generate a token for the destination node that the source node can use to authenticate with.
$token = $this->nodeJWTService
->setExpiresAt(CarbonImmutable::now()->addMinutes(15))
@@ -102,32 +91,4 @@ public function handle(Server $server, array $data): bool
return true;
}
-
- /**
- * Assigns the specified allocations to the specified server.
- */
- private function assignAllocationsToServer(Server $server, int $node_id, int $allocation_id, array $additional_allocations): void
- {
- $allocations = $additional_allocations;
- $allocations[] = $allocation_id;
-
- $node = Node::query()->findOrFail($node_id);
- $unassigned = $node->allocations()
- ->whereNull('server_id')
- ->pluck('id')
- ->toArray();
-
- $updateIds = [];
- foreach ($allocations as $allocation) {
- if (!in_array($allocation, $unassigned)) {
- continue;
- }
-
- $updateIds[] = $allocation;
- }
-
- if (!empty($updateIds)) {
- Allocation::query()->whereIn('id', $updateIds)->update(['server_id' => $server->id]);
- }
- }
}
diff --git a/app/Services/Servers/VariableValidatorService.php b/app/Services/Servers/VariableValidatorService.php
index 75f4a59b14..f8c59b6955 100644
--- a/app/Services/Servers/VariableValidatorService.php
+++ b/app/Services/Servers/VariableValidatorService.php
@@ -25,7 +25,7 @@ public function __construct(private ValidationFactory $validator)
*
* @throws \Illuminate\Validation\ValidationException
*/
- public function handle(int $egg, array $fields = []): Collection
+ public function handle(int $egg, array $fields = [], bool $validate = true): Collection
{
$query = EggVariable::query()->where('egg_id', $egg);
if (!$this->isUserLevel(User::USER_LEVEL_ADMIN)) {
@@ -44,9 +44,11 @@ public function handle(int $egg, array $fields = []): Collection
$customAttributes['environment.' . $variable->env_variable] = trans('validation.internal.variable_value', ['env' => $variable->name]);
}
- $validator = $this->validator->make($data, $rules, [], $customAttributes);
- if ($validator->fails()) {
- throw new ValidationException($validator);
+ if ($validate) {
+ $validator = $this->validator->make($data, $rules, [], $customAttributes);
+ if ($validator->fails()) {
+ throw new ValidationException($validator);
+ }
}
return Collection::make($variables)->map(function ($item) use ($fields) {
diff --git a/app/Transformers/Api/Application/AllocationTransformer.php b/app/Transformers/Api/Application/AllocationTransformer.php
deleted file mode 100644
index 7f5bf88270..0000000000
--- a/app/Transformers/Api/Application/AllocationTransformer.php
+++ /dev/null
@@ -1,77 +0,0 @@
- $allocation->id,
- 'ip' => $allocation->ip,
- 'alias' => $allocation->ip_alias,
- 'port' => $allocation->port,
- 'notes' => $allocation->notes,
- 'assigned' => !is_null($allocation->server_id),
- ];
- }
-
- /**
- * Load the node relationship onto a given transformation.
- *
- * @throws \App\Exceptions\Transformer\InvalidTransformerLevelException
- */
- public function includeNode(Allocation $allocation): Item|NullResource
- {
- if (!$this->authorize(AdminAcl::RESOURCE_NODES)) {
- return $this->null();
- }
-
- return $this->item(
- $allocation->node,
- $this->makeTransformer(NodeTransformer::class),
- Node::RESOURCE_NAME
- );
- }
-
- /**
- * Load the server relationship onto a given transformation.
- *
- * @throws \App\Exceptions\Transformer\InvalidTransformerLevelException
- */
- public function includeServer(Allocation $allocation): Item|NullResource
- {
- if (!$this->authorize(AdminAcl::RESOURCE_SERVERS) || !$allocation->server) {
- return $this->null();
- }
-
- return $this->item(
- $allocation->server,
- $this->makeTransformer(ServerTransformer::class),
- Server::RESOURCE_NAME
- );
- }
-}
diff --git a/app/Transformers/Api/Application/NodeTransformer.php b/app/Transformers/Api/Application/NodeTransformer.php
index 670e4bcac5..dabf8c40df 100644
--- a/app/Transformers/Api/Application/NodeTransformer.php
+++ b/app/Transformers/Api/Application/NodeTransformer.php
@@ -12,7 +12,7 @@ class NodeTransformer extends BaseTransformer
/**
* List of resources that can be included.
*/
- protected array $availableIncludes = ['allocations', 'servers'];
+ protected array $availableIncludes = ['servers'];
/**
* Return the resource name for the JSONAPI output.
@@ -45,26 +45,6 @@ public function transform(Node $node): array
return $response;
}
- /**
- * Return the nodes associated with this location.
- *
- * @throws \App\Exceptions\Transformer\InvalidTransformerLevelException
- */
- public function includeAllocations(Node $node): Collection|NullResource
- {
- if (!$this->authorize(AdminAcl::RESOURCE_ALLOCATIONS)) {
- return $this->null();
- }
-
- $node->loadMissing('allocations');
-
- return $this->collection(
- $node->getRelation('allocations'),
- $this->makeTransformer(AllocationTransformer::class),
- 'allocation'
- );
- }
-
/**
* Return the nodes associated with this location.
*
diff --git a/app/Transformers/Api/Application/ServerTransformer.php b/app/Transformers/Api/Application/ServerTransformer.php
index b81baf2794..378cea65f9 100644
--- a/app/Transformers/Api/Application/ServerTransformer.php
+++ b/app/Transformers/Api/Application/ServerTransformer.php
@@ -17,7 +17,6 @@ class ServerTransformer extends BaseTransformer
* List of resources that can be included.
*/
protected array $availableIncludes = [
- 'allocations',
'user',
'subusers',
'egg',
@@ -76,7 +75,6 @@ public function transform(Server $server): array
],
'user' => $server->owner_id,
'node' => $server->node_id,
- 'allocation' => $server->allocation_id,
'egg' => $server->egg_id,
'container' => [
'startup_command' => $server->startup,
@@ -87,23 +85,23 @@ public function transform(Server $server): array
],
$server->getUpdatedAtColumn() => $this->formatTimestamp($server->updated_at),
$server->getCreatedAtColumn() => $this->formatTimestamp($server->created_at),
- ];
- }
-
- /**
- * Return a generic array of allocations for this server.
- *
- * @throws \App\Exceptions\Transformer\InvalidTransformerLevelException
- */
- public function includeAllocations(Server $server): Collection|NullResource
- {
- if (!$this->authorize(AdminAcl::RESOURCE_ALLOCATIONS)) {
- return $this->null();
- }
-
- $server->loadMissing('allocations');
- return $this->collection($server->getRelation('allocations'), $this->makeTransformer(AllocationTransformer::class), 'allocation');
+ 'allocations' => collect($server->ports)->map(function ($port) {
+ $ip = '0.0.0.0';
+ if (str_contains($port, ':')) {
+ [$ip, $port] = explode(':', $port);
+ }
+
+ return [
+ 'id' => random_int(1, PHP_INT_MAX),
+ 'ip' => $ip,
+ 'alias' => null,
+ 'port' => (int) $port,
+ 'notes' => null,
+ 'assigned' => false,
+ ];
+ })->all(),
+ ];
}
/**
diff --git a/app/Transformers/Api/Client/AllocationTransformer.php b/app/Transformers/Api/Client/AllocationTransformer.php
deleted file mode 100644
index 4fd84ed61d..0000000000
--- a/app/Transformers/Api/Client/AllocationTransformer.php
+++ /dev/null
@@ -1,28 +0,0 @@
- $model->id,
- 'ip' => $model->ip,
- 'ip_alias' => $model->ip_alias,
- 'port' => $model->port,
- 'notes' => $model->notes,
- 'is_default' => $model->server->allocation_id === $model->id,
- ];
- }
-}
diff --git a/app/Transformers/Api/Client/ServerTransformer.php b/app/Transformers/Api/Client/ServerTransformer.php
index df8a36bb9b..2300b30aed 100644
--- a/app/Transformers/Api/Client/ServerTransformer.php
+++ b/app/Transformers/Api/Client/ServerTransformer.php
@@ -2,21 +2,20 @@
namespace App\Transformers\Api\Client;
-use App\Models\Allocation;
use App\Models\Egg;
use App\Models\EggVariable;
use App\Models\Permission;
use App\Models\Server;
use App\Models\Subuser;
-use App\Services\Servers\StartupCommandService;
-use Illuminate\Container\Container;
use League\Fractal\Resource\Collection;
-use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
+use League\Fractal\Resource\Item;
+use Illuminate\Container\Container;
+use App\Services\Servers\StartupCommandService;
class ServerTransformer extends BaseClientTransformer
{
- protected array $defaultIncludes = ['allocations', 'variables'];
+ protected array $defaultIncludes = ['variables'];
protected array $availableIncludes = ['egg', 'subusers'];
@@ -75,6 +74,7 @@ public function transform(Server $server): array
// This field is deprecated, please use "status".
'is_installing' => !$server->isInstalled(),
'is_transferring' => !is_null($server->transfer),
+ 'ports' => $user->can(Permission::ACTION_ALLOCATION_READ, $server) ? $server->ports : collect(),
];
if (!config('panel.editable_server_descriptions')) {
@@ -84,33 +84,6 @@ public function transform(Server $server): array
return $data;
}
- /**
- * Returns the allocations associated with this server.
- *
- * @throws \App\Exceptions\Transformer\InvalidTransformerLevelException
- */
- public function includeAllocations(Server $server): Collection
- {
- $transformer = $this->makeTransformer(AllocationTransformer::class);
-
- $user = $this->request->user();
- // While we include this permission, we do need to actually handle it slightly different here
- // for the purpose of keeping things functionally working. If the user doesn't have read permissions
- // for the allocations we'll only return the primary server allocation, and any notes associated
- // with it will be hidden.
- //
- // This allows us to avoid too much permission regression, without also hiding information that
- // is generally needed for the frontend to make sense when browsing or searching results.
- if (!$user->can(Permission::ACTION_ALLOCATION_READ, $server)) {
- $primary = clone $server->allocation;
- $primary->notes = null;
-
- return $this->collection([$primary], $transformer, Allocation::RESOURCE_NAME);
- }
-
- return $this->collection($server->allocations, $transformer, Allocation::RESOURCE_NAME);
- }
-
/**
* @throws \App\Exceptions\Transformer\InvalidTransformerLevelException
*/
diff --git a/composer.json b/composer.json
index 6b44652ffc..7e6394c079 100644
--- a/composer.json
+++ b/composer.json
@@ -16,7 +16,7 @@
"filament/filament": "^3.2",
"guzzlehttp/guzzle": "^7.8.1",
"laracasts/utilities": "~3.2.2",
- "laravel/framework": "^11.7",
+ "laravel/framework": "^11.28.1",
"laravel/helpers": "^1.7",
"laravel/sanctum": "^4.0.2",
"laravel/socialite": "^5.14",
diff --git a/composer.lock b/composer.lock
index ca8c6f54ab..da1c856972 100644
--- a/composer.lock
+++ b/composer.lock
@@ -2802,16 +2802,16 @@
},
{
"name": "laravel/framework",
- "version": "v11.10.0",
+ "version": "v11.28.1",
"source": {
"type": "git",
"url": "https://github.com/laravel/framework.git",
- "reference": "99b4255194912044b75ab72329f8c19e6345720e"
+ "reference": "3ef5c8a85b4c598d5ffaf98afd72f6a5d6a0be2c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel/framework/zipball/99b4255194912044b75ab72329f8c19e6345720e",
- "reference": "99b4255194912044b75ab72329f8c19e6345720e",
+ "url": "https://api.github.com/repos/laravel/framework/zipball/3ef5c8a85b4c598d5ffaf98afd72f6a5d6a0be2c",
+ "reference": "3ef5c8a85b4c598d5ffaf98afd72f6a5d6a0be2c",
"shasum": ""
},
"require": {
@@ -2830,7 +2830,7 @@
"fruitcake/php-cors": "^1.3",
"guzzlehttp/guzzle": "^7.8",
"guzzlehttp/uri-template": "^1.0",
- "laravel/prompts": "^0.1.18",
+ "laravel/prompts": "^0.1.18|^0.2.0|^0.3.0",
"laravel/serializable-closure": "^1.3",
"league/commonmark": "^2.2.1",
"league/flysystem": "^3.8.0",
@@ -2864,6 +2864,7 @@
},
"provide": {
"psr/container-implementation": "1.1|2.0",
+ "psr/log-implementation": "1.0|2.0|3.0",
"psr/simple-cache-implementation": "1.0|2.0|3.0"
},
"replace": {
@@ -2872,6 +2873,7 @@
"illuminate/bus": "self.version",
"illuminate/cache": "self.version",
"illuminate/collections": "self.version",
+ "illuminate/concurrency": "self.version",
"illuminate/conditionable": "self.version",
"illuminate/config": "self.version",
"illuminate/console": "self.version",
@@ -2914,9 +2916,9 @@
"league/flysystem-sftp-v3": "^3.0",
"mockery/mockery": "^1.6",
"nyholm/psr7": "^1.2",
- "orchestra/testbench-core": "^9.0.15",
+ "orchestra/testbench-core": "^9.5",
"pda/pheanstalk": "^5.0",
- "phpstan/phpstan": "^1.4.7",
+ "phpstan/phpstan": "^1.11.5",
"phpunit/phpunit": "^10.5|^11.0",
"predis/predis": "^2.0.2",
"resend/resend-php": "^0.10.0",
@@ -2972,6 +2974,8 @@
"src/Illuminate/Events/functions.php",
"src/Illuminate/Filesystem/functions.php",
"src/Illuminate/Foundation/helpers.php",
+ "src/Illuminate/Log/functions.php",
+ "src/Illuminate/Support/functions.php",
"src/Illuminate/Support/helpers.php"
],
"psr-4": {
@@ -3003,7 +3007,7 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
- "time": "2024-06-04T13:45:55+00:00"
+ "time": "2024-10-16T16:32:21+00:00"
},
{
"name": "laravel/helpers",
diff --git a/config/panel.php b/config/panel.php
index 487ee354b5..4ff4ee637a 100644
--- a/config/panel.php
+++ b/config/panel.php
@@ -166,5 +166,7 @@
'use_binary_prefix' => env('PANEL_USE_BINARY_PREFIX', true),
+ 'default_io_weight' => env('PANEL_IO_WEIGHT', 500),
+
'editable_server_descriptions' => env('PANEL_EDITABLE_SERVER_DESCRIPTIONS', true),
];
diff --git a/database/Factories/AllocationFactory.php b/database/Factories/AllocationFactory.php
deleted file mode 100644
index 19405b7024..0000000000
--- a/database/Factories/AllocationFactory.php
+++ /dev/null
@@ -1,36 +0,0 @@
- $this->faker->unique()->ipv4(),
- 'port' => $this->faker->unique()->numberBetween(1024, 65535),
- ];
- }
-
- /**
- * Attaches the allocation to a specific server model.
- */
- public function forServer(Server $server): self
- {
- return $this->for($server)->for($server->node);
- }
-}
diff --git a/database/Seeders/eggs/minecraft/egg-bungeecord.json b/database/Seeders/eggs/minecraft/egg-bungeecord.json
index e71b8d1ec1..66fcbc885f 100644
--- a/database/Seeders/eggs/minecraft/egg-bungeecord.json
+++ b/database/Seeders/eggs/minecraft/egg-bungeecord.json
@@ -65,6 +65,17 @@
],
"sort": 2,
"field_type": "text"
+ },
+ {
+ "name": "Server Port",
+ "description": "",
+ "env_variable": "SERVER_PORT",
+ "default_value": "25565",
+ "user_viewable": true,
+ "user_editable": false,
+ "rules": "required|port",
+ "sort": 3,
+ "field_type": "text"
}
]
}
diff --git a/database/Seeders/eggs/minecraft/egg-forge-minecraft.json b/database/Seeders/eggs/minecraft/egg-forge-minecraft.json
index 13afe9748a..cd7560a12a 100644
--- a/database/Seeders/eggs/minecraft/egg-forge-minecraft.json
+++ b/database/Seeders/eggs/minecraft/egg-forge-minecraft.json
@@ -94,6 +94,17 @@
],
"sort": 4,
"field_type": "text"
+ },
+ {
+ "name": "Server Port",
+ "description": "",
+ "env_variable": "SERVER_PORT",
+ "default_value": "25565",
+ "user_viewable": true,
+ "user_editable": false,
+ "rules": "required|port",
+ "sort": 5,
+ "field_type": "text"
}
]
-}
\ No newline at end of file
+}
diff --git a/database/Seeders/eggs/minecraft/egg-sponge--sponge-vanilla.json b/database/Seeders/eggs/minecraft/egg-sponge-sponge-vanilla.json
similarity index 100%
rename from database/Seeders/eggs/minecraft/egg-sponge--sponge-vanilla.json
rename to database/Seeders/eggs/minecraft/egg-sponge-sponge-vanilla.json
diff --git a/database/Seeders/eggs/rust/egg-rust.json b/database/Seeders/eggs/rust/egg-rust.json
index e74368604a..cd0367c3f0 100644
--- a/database/Seeders/eggs/rust/egg-rust.json
+++ b/database/Seeders/eggs/rust/egg-rust.json
@@ -168,7 +168,7 @@
"user_editable": false,
"rules": [
"required",
- "integer"
+ "port"
],
"sort": 10,
"field_type": "text"
@@ -182,7 +182,7 @@
"user_editable": false,
"rules": [
"required",
- "integer"
+ "port"
],
"sort": 11,
"field_type": "text"
@@ -239,7 +239,7 @@
"user_editable": false,
"rules": [
"required",
- "integer"
+ "port"
],
"sort": 15,
"field_type": "text"
@@ -288,4 +288,4 @@
"field_type": "text"
}
]
-}
\ No newline at end of file
+}
diff --git a/database/Seeders/eggs/source-engine/egg-counter--strike--global-offensive.json b/database/Seeders/eggs/source-engine/egg-counter-strike-global-offensive.json
similarity index 100%
rename from database/Seeders/eggs/source-engine/egg-counter--strike--global-offensive.json
rename to database/Seeders/eggs/source-engine/egg-counter-strike-global-offensive.json
diff --git a/database/Seeders/eggs/voice-servers/egg-teamspeak3-server.json b/database/Seeders/eggs/voice-servers/egg-teamspeak3-server.json
index 0543a16c04..d470ca3f20 100644
--- a/database/Seeders/eggs/voice-servers/egg-teamspeak3-server.json
+++ b/database/Seeders/eggs/voice-servers/egg-teamspeak3-server.json
@@ -53,8 +53,7 @@
"user_editable": false,
"rules": [
"required",
- "integer",
- "between:1025,65535"
+ "port"
],
"sort": 2,
"field_type": "text"
@@ -69,7 +68,7 @@
"rules": [
"required",
"integer",
- "between:1025,65535"
+ "port"
],
"sort": 3,
"field_type": "text"
@@ -96,10 +95,10 @@
"default_value": "10022",
"user_viewable": true,
"user_editable": false,
+ "rules": "required|port",
"rules": [
"required",
- "integer",
- "between:1025,65535"
+ "port"
],
"sort": 5,
"field_type": "text"
@@ -113,11 +112,10 @@
"user_editable": false,
"rules": [
"required",
- "integer",
- "between:1025,65535"
+ "port",
],
"sort": 6,
"field_type": "text"
}
]
-}
\ No newline at end of file
+}
diff --git a/database/migrations/2017_02_09_174834_SetupPermissionsPivotTable.php b/database/migrations/2017_02_09_174834_SetupPermissionsPivotTable.php
index ca2cabfd67..2c16118d42 100644
--- a/database/migrations/2017_02_09_174834_SetupPermissionsPivotTable.php
+++ b/database/migrations/2017_02_09_174834_SetupPermissionsPivotTable.php
@@ -31,6 +31,9 @@ public function up(): void
$table->dropIndex('permissions_server_id_foreign');
$table->dropForeign('permissions_user_id_foreign');
$table->dropIndex('permissions_user_id_foreign');
+ } else {
+ $table->dropForeign(['server_id']);
+ $table->dropForeign(['user_id']);
}
$table->dropColumn('server_id');
diff --git a/database/migrations/2020_09_13_110007_drop_packs_from_servers.php b/database/migrations/2020_09_13_110007_drop_packs_from_servers.php
index cc2695eddd..39f048b373 100644
--- a/database/migrations/2020_09_13_110007_drop_packs_from_servers.php
+++ b/database/migrations/2020_09_13_110007_drop_packs_from_servers.php
@@ -12,10 +12,7 @@
public function up(): void
{
Schema::table('servers', function (Blueprint $table) {
- if (Schema::getConnection()->getDriverName() !== 'sqlite') {
- $table->dropForeign(['pack_id']);
- }
-
+ $table->dropForeign(['pack_id']);
$table->dropColumn('pack_id');
});
}
diff --git a/database/migrations/2024_03_12_154408_remove_nests_table.php b/database/migrations/2024_03_12_154408_remove_nests_table.php
index cc95a5f8e1..42d1315b91 100644
--- a/database/migrations/2024_03_12_154408_remove_nests_table.php
+++ b/database/migrations/2024_03_12_154408_remove_nests_table.php
@@ -30,14 +30,15 @@ public function up(): void
Schema::table('eggs', function (Blueprint $table) {
if (Schema::getConnection()->getDriverName() !== 'sqlite') {
$table->dropForeign('service_options_nest_id_foreign');
+ } else {
+ $table->dropForeign(['nest_id']);
}
+
$table->dropColumn('nest_id');
});
Schema::table('servers', function (Blueprint $table) {
- if (Schema::getConnection()->getDriverName() !== 'sqlite') {
- $table->dropForeign('servers_nest_id_foreign');
- }
+ $table->dropForeign(['nest_id']);
$table->dropColumn('nest_id');
});
diff --git a/database/migrations/2024_03_14_055537_remove_locations_table.php b/database/migrations/2024_03_14_055537_remove_locations_table.php
index f06ded66fd..bdd0c382ad 100644
--- a/database/migrations/2024_03_14_055537_remove_locations_table.php
+++ b/database/migrations/2024_03_14_055537_remove_locations_table.php
@@ -27,10 +27,7 @@ public function up(): void
}
Schema::table('nodes', function (Blueprint $table) {
- if (Schema::getConnection()->getDriverName() !== 'sqlite') {
- $table->dropForeign('nodes_location_id_foreign');
- }
-
+ $table->dropForeign(['location_id']);
$table->dropColumn('location_id');
});
diff --git a/database/migrations/2024_09_18_043350_modify_allocations.php b/database/migrations/2024_09_18_043350_modify_allocations.php
new file mode 100644
index 0000000000..92e59495e3
--- /dev/null
+++ b/database/migrations/2024_09_18_043350_modify_allocations.php
@@ -0,0 +1,66 @@
+dropColumn(['old_allocation', 'new_allocation', 'old_additional_allocations', 'new_additional_allocations']);
+ });
+
+ Schema::table('servers', function (Blueprint $table) {
+ $table->json('ports')->nullable();
+ });
+
+ $portMappings = [];
+ foreach (DB::table('allocations')->get() as $allocation) {
+ $portMappings[$allocation->server_id][] = "$allocation->ip:$allocation->port";
+ }
+
+ foreach ($portMappings as $serverId => $ports) {
+ /** @var Server $server */
+ $server = Server::find($serverId);
+ if (!$server) {
+ // Orphaned Allocations
+
+ continue;
+ }
+
+ foreach ($ports as $port) {
+ $server->ports ??= collect();
+ $server->ports->add(new Endpoint($port));
+ }
+ $server->save();
+ }
+
+ Schema::table('servers', function (Blueprint $table) {
+ $table->dropForeign(['allocation_id']);
+ $table->dropUnique(['allocation_id']);
+ $table->dropColumn(['allocation_id']);
+ });
+
+ Schema::dropIfExists('allocations');
+
+ Schema::table('nodes', function (Blueprint $table) {
+ $table->boolean('strict_ports')->default(true);
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ // Too much time to ensure this works correctly, please take a backup if necessary
+ }
+};
diff --git a/resources/scripts/components/server/network/AllocationRow.tsx b/resources/scripts/components/server/network/AllocationRow.tsx
deleted file mode 100644
index e68bc3359f..0000000000
--- a/resources/scripts/components/server/network/AllocationRow.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import React, { memo, useCallback, useState } from 'react';
-import isEqual from 'react-fast-compare';
-import tw from 'twin.macro';
-import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
-import { faNetworkWired } from '@fortawesome/free-solid-svg-icons';
-import InputSpinner from '@/components/elements/InputSpinner';
-import { Textarea } from '@/components/elements/Input';
-import Can from '@/components/elements/Can';
-import { Button } from '@/components/elements/button/index';
-import GreyRowBox from '@/components/elements/GreyRowBox';
-import { Allocation } from '@/api/server/getServer';
-import styled from 'styled-components/macro';
-import { debounce } from 'debounce';
-import setServerAllocationNotes from '@/api/server/network/setServerAllocationNotes';
-import { useFlashKey } from '@/plugins/useFlash';
-import { ServerContext } from '@/state/server';
-import CopyOnClick from '@/components/elements/CopyOnClick';
-import DeleteAllocationButton from '@/components/server/network/DeleteAllocationButton';
-import setPrimaryServerAllocation from '@/api/server/network/setPrimaryServerAllocation';
-import getServerAllocations from '@/api/swr/getServerAllocations';
-import { ip } from '@/lib/formatters';
-import Code from '@/components/elements/Code';
-
-const Label = styled.label`
- ${tw`uppercase text-xs mt-1 text-neutral-400 block px-1 select-none transition-colors duration-150`}
-`;
-
-interface Props {
- allocation: Allocation;
-}
-
-const AllocationRow = ({ allocation }: Props) => {
- const [loading, setLoading] = useState(false);
- const { clearFlashes, clearAndAddHttpError } = useFlashKey('server:network');
- const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
- const { mutate } = getServerAllocations();
-
- const onNotesChanged = useCallback((id: number, notes: string) => {
- mutate((data) => data?.map((a) => (a.id === id ? { ...a, notes } : a)), false);
- }, []);
-
- const setAllocationNotes = debounce((notes: string) => {
- setLoading(true);
- clearFlashes();
-
- setServerAllocationNotes(uuid, allocation.id, notes)
- .then(() => onNotesChanged(allocation.id, notes))
- .catch((error) => clearAndAddHttpError(error))
- .then(() => setLoading(false));
- }, 750);
-
- const setPrimaryAllocation = () => {
- clearFlashes();
- mutate((data) => data?.map((a) => ({ ...a, isDefault: a.id === allocation.id })), false);
-
- setPrimaryServerAllocation(uuid, allocation.id).catch((error) => {
- clearAndAddHttpError(error);
- mutate();
- });
- };
-
- return (
-
-
-
-
-
-
- {allocation.alias ? (
-
-
- {allocation.alias}
-
-
- ) : (
-
- {ip(allocation.ip)}
-
- )}
- {allocation.alias ? 'Hostname' : 'IP Address'}
-
-
- {allocation.port}
- Port
-
-
-
-
-
-
-
- {allocation.isDefault ? (
-
- Primary
-
- ) : (
- <>
-
-
-
-
-
- Make Primary
-
-
- >
- )}
-
-
- );
-};
-
-export default memo(AllocationRow, isEqual);
diff --git a/resources/scripts/components/server/network/DeleteAllocationButton.tsx b/resources/scripts/components/server/network/DeleteAllocationButton.tsx
deleted file mode 100644
index c6804484e0..0000000000
--- a/resources/scripts/components/server/network/DeleteAllocationButton.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import React, { useState } from 'react';
-import { faTrashAlt } from '@fortawesome/free-solid-svg-icons';
-import tw from 'twin.macro';
-import Icon from '@/components/elements/Icon';
-import { ServerContext } from '@/state/server';
-import deleteServerAllocation from '@/api/server/network/deleteServerAllocation';
-import getServerAllocations from '@/api/swr/getServerAllocations';
-import { useFlashKey } from '@/plugins/useFlash';
-import { Dialog } from '@/components/elements/dialog';
-import { Button } from '@/components/elements/button/index';
-
-interface Props {
- allocation: number;
-}
-
-const DeleteAllocationButton = ({ allocation }: Props) => {
- const [confirm, setConfirm] = useState(false);
-
- const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
- const setServerFromState = ServerContext.useStoreActions((actions) => actions.server.setServerFromState);
-
- const { mutate } = getServerAllocations();
- const { clearFlashes, clearAndAddHttpError } = useFlashKey('server:network');
-
- const deleteAllocation = () => {
- clearFlashes();
-
- mutate((data) => data?.filter((a) => a.id !== allocation), false);
- setServerFromState((s) => ({ ...s, allocations: s.allocations.filter((a) => a.id !== allocation) }));
-
- deleteServerAllocation(uuid, allocation).catch((error) => {
- clearAndAddHttpError(error);
- mutate();
- });
- };
-
- return (
- <>
- setConfirm(false)}
- title={'Remove Allocation'}
- confirm={'Delete'}
- onConfirmed={deleteAllocation}
- >
- This allocation will be immediately removed from your server.
-
- setConfirm(true)}
- >
-
-
- >
- );
-};
-
-export default DeleteAllocationButton;
diff --git a/resources/scripts/components/server/network/NetworkContainer.tsx b/resources/scripts/components/server/network/NetworkContainer.tsx
deleted file mode 100644
index 182beaab8a..0000000000
--- a/resources/scripts/components/server/network/NetworkContainer.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import React, { useEffect, useState } from 'react';
-import Spinner from '@/components/elements/Spinner';
-import { useFlashKey } from '@/plugins/useFlash';
-import ServerContentBlock from '@/components/elements/ServerContentBlock';
-import { ServerContext } from '@/state/server';
-import AllocationRow from '@/components/server/network/AllocationRow';
-import Button from '@/components/elements/Button';
-import createServerAllocation from '@/api/server/network/createServerAllocation';
-import tw from 'twin.macro';
-import Can from '@/components/elements/Can';
-import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
-import getServerAllocations from '@/api/swr/getServerAllocations';
-import isEqual from 'react-fast-compare';
-import { useDeepCompareEffect } from '@/plugins/useDeepCompareEffect';
-
-const NetworkContainer = () => {
- const [loading, setLoading] = useState(false);
- const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
- const allocationLimit = ServerContext.useStoreState((state) => state.server.data!.featureLimits.allocations);
- const allocations = ServerContext.useStoreState((state) => state.server.data!.allocations, isEqual);
- const setServerFromState = ServerContext.useStoreActions((actions) => actions.server.setServerFromState);
-
- const { clearFlashes, clearAndAddHttpError } = useFlashKey('server:network');
- const { data, error, mutate } = getServerAllocations();
-
- useEffect(() => {
- mutate(allocations);
- }, []);
-
- useEffect(() => {
- clearAndAddHttpError(error);
- }, [error]);
-
- useDeepCompareEffect(() => {
- if (!data) return;
-
- setServerFromState((state) => ({ ...state, allocations: data }));
- }, [data]);
-
- const onCreateAllocation = () => {
- clearFlashes();
-
- setLoading(true);
- createServerAllocation(uuid)
- .then((allocation) => {
- setServerFromState((s) => ({ ...s, allocations: s.allocations.concat(allocation) }));
- return mutate(data?.concat(allocation), false);
- })
- .catch((error) => clearAndAddHttpError(error))
- .then(() => setLoading(false));
- };
-
- return (
-
- {!data ? (
-
- ) : (
- <>
- {data.map((allocation) => (
-
- ))}
- {allocationLimit > 0 && (
-
-
-
-
- You are currently using {data.length} of {allocationLimit} allowed allocations for
- this server.
-
- {allocationLimit > data.length && (
-
- Create Allocation
-
- )}
-
-
- )}
- >
- )}
-
- );
-};
-
-export default NetworkContainer;
diff --git a/resources/scripts/routers/routes.ts b/resources/scripts/routers/routes.ts
index 8fba642212..191c68eb33 100644
--- a/resources/scripts/routers/routes.ts
+++ b/resources/scripts/routers/routes.ts
@@ -4,7 +4,6 @@ import DatabasesContainer from '@/components/server/databases/DatabasesContainer
import ScheduleContainer from '@/components/server/schedules/ScheduleContainer';
import UsersContainer from '@/components/server/users/UsersContainer';
import BackupContainer from '@/components/server/backups/BackupContainer';
-import NetworkContainer from '@/components/server/network/NetworkContainer';
import StartupContainer from '@/components/server/startup/StartupContainer';
import FileManagerContainer from '@/components/server/files/FileManagerContainer';
import SettingsContainer from '@/components/server/settings/SettingsContainer';
@@ -116,12 +115,6 @@ export default {
name: 'Backups',
component: BackupContainer,
},
- {
- path: '/network',
- permission: 'allocation.*',
- name: 'Network',
- component: NetworkContainer,
- },
{
path: '/startup',
permission: 'startup.*',
diff --git a/resources/views/admin/servers/new.blade.php b/resources/views/admin/servers/new.blade.php
deleted file mode 100644
index 4aac49d397..0000000000
--- a/resources/views/admin/servers/new.blade.php
+++ /dev/null
@@ -1,375 +0,0 @@
-@extends('layouts.admin')
-
-@section('title')
- New Server
-@endsection
-
-@section('content-header')
- Create ServerAdd a new server to the panel.
-
- Admin
- Servers
- Create Server
-
-@endsection
-
-@section('content')
-
-@endsection
-
-@section('footer-scripts')
- @parent
- {!! Theme::js('vendor/lodash/lodash.js') !!}
-
-
-
- {!! Theme::js('js/admin/new-server.js?v=20220530') !!}
-
-
-@endsection
diff --git a/resources/views/admin/servers/view/manage.blade.php b/resources/views/admin/servers/view/manage.blade.php
deleted file mode 100644
index eba2f8ab7b..0000000000
--- a/resources/views/admin/servers/view/manage.blade.php
+++ /dev/null
@@ -1,194 +0,0 @@
-@extends('layouts.admin')
-
-@section('title')
- Server — {{ $server->name }}: Manage
-@endsection
-
-@section('content-header')
- {{ $server->name }}Additional actions to control this server.
-
- Admin
- Servers
- {{ $server->name }}
- Manage
-
-@endsection
-
-@section('content')
- @include('admin.servers.partials.navigation')
-
-
-
-
-
-
This will reinstall the server with the assigned egg scripts. Danger! This could overwrite server data.
-
-
-
-
-
-
-
-
-
If you need to change the install status from uninstalled to installed, or vice versa, you may do so with the button below.
-
-
-
-
-
- @if(! $server->isSuspended())
-
-
-
-
-
This will suspend the server, stop any running processes, and immediately block the user from being able to access their files or otherwise manage the server through the panel or API.
-
-
-
-
- @else
-
-
-
-
-
This will unsuspend the server and restore normal user access.
-
-
-
-
- @endif
-
- @if(is_null($server->transfer))
-
-
-
-
-
- Transfer this server to another node connected to this panel.
- Warning! This feature has not been fully tested and may have bugs.
-
-
-
-
-
-
- @else
-
-
-
-
-
- This server is currently being transferred to another node.
- Transfer was initiated at {{ $server->transfer->created_at }}
-
-
-
-
-
-
- @endif
-
-
-
-@endsection
-
-@section('footer-scripts')
- @parent
- {!! Theme::js('vendor/lodash/lodash.js') !!}
-
- @if($canTransfer)
- {!! Theme::js('js/admin/server/transfer.js') !!}
- @endif
-@endsection
diff --git a/resources/views/livewire/node-system-information.blade.php b/resources/views/livewire/node-system-information.blade.php
index 77436db06e..724e6282b9 100644
--- a/resources/views/livewire/node-system-information.blade.php
+++ b/resources/views/livewire/node-system-information.blade.php
@@ -1,8 +1,9 @@
- @switch($node->systemInformation()['version'] ?? 'false')
+ @switch($version = $node->systemInformation()['version'] ?? 'false')
@case('false')
true])
/>
@@ -10,6 +11,7 @@
@default
true])
@style([\Filament\Support\get_color_css_variables('success', shades: [400, 500], alias: 'tables::columns.icon-column.item') => true])
/>
diff --git a/routes/admin.php b/routes/admin.php
index 60d047e01f..ffac12d882 100644
--- a/routes/admin.php
+++ b/routes/admin.php
@@ -117,21 +117,14 @@
Route::get('/view/{node:id}', [Admin\Nodes\NodeViewController::class, 'index'])->name('admin.nodes.view');
Route::get('/view/{node:id}/settings', [Admin\Nodes\NodeViewController::class, 'settings'])->name('admin.nodes.view.settings');
Route::get('/view/{node:id}/configuration', [Admin\Nodes\NodeViewController::class, 'configuration'])->name('admin.nodes.view.configuration');
- Route::get('/view/{node:id}/allocation', [Admin\Nodes\NodeViewController::class, 'allocations'])->name('admin.nodes.view.allocation');
Route::get('/view/{node:id}/servers', [Admin\Nodes\NodeViewController::class, 'servers'])->name('admin.nodes.view.servers');
Route::get('/view/{node:id}/system-information', Admin\Nodes\SystemInformationController::class);
- Route::post('/new', [Admin\NodesController::class, 'store']);
- Route::post('/view/{node:id}/allocation', [Admin\NodesController::class, 'createAllocation']);
- Route::post('/view/{node:id}/allocation/remove', [Admin\NodesController::class, 'allocationRemoveBlock'])->name('admin.nodes.view.allocation.removeBlock');
- Route::post('/view/{node:id}/allocation/alias', [Admin\NodesController::class, 'allocationSetAlias'])->name('admin.nodes.view.allocation.setAlias');
Route::post('/view/{node:id}/settings/token', Admin\NodeAutoDeployController::class)->name('admin.nodes.view.configuration.token');
Route::patch('/view/{node:id}/settings', [Admin\NodesController::class, 'updateSettings']);
Route::delete('/view/{node:id}/delete', [Admin\NodesController::class, 'delete'])->name('admin.nodes.view.delete');
- Route::delete('/view/{node:id}/allocation/remove/{allocation:id}', [Admin\NodesController::class, 'allocationRemoveSingle'])->name('admin.nodes.view.allocation.removeSingle');
- Route::delete('/view/{node:id}/allocations', [Admin\NodesController::class, 'allocationRemoveMultiple'])->name('admin.nodes.view.allocation.removeMultiple');
});
/*
diff --git a/routes/api-application.php b/routes/api-application.php
index 1d7b8b8bef..bd3881f467 100644
--- a/routes/api-application.php
+++ b/routes/api-application.php
@@ -43,12 +43,6 @@
Route::patch('/{node:id}', [Application\Nodes\NodeController::class, 'update']);
Route::delete('/{node:id}', [Application\Nodes\NodeController::class, 'delete']);
-
- Route::prefix('/{node:id}/allocations')->group(function () {
- Route::get('/', [Application\Nodes\AllocationController::class, 'index'])->name('api.application.allocations');
- Route::post('/', [Application\Nodes\AllocationController::class, 'store']);
- Route::delete('/{allocation:id}', [Application\Nodes\AllocationController::class, 'delete'])->name('api.application.allocations.view');
- });
});
/*
@@ -75,7 +69,6 @@
Route::post('/{server:id}/transfer', [Application\Servers\ServerManagementController::class, 'startTransfer'])->name('api.application.servers.transfer');
Route::post('/{server:id}/transfer/cancel', [Application\Servers\ServerManagementController::class, 'cancelTransfer'])->name('api.application.servers.transfer.cancel');
- Route::delete('/{server:id}', [Application\Servers\ServerController::class, 'delete']);
Route::delete('/{server:id}/{force?}', [Application\Servers\ServerController::class, 'delete']);
// Database Management Endpoint
diff --git a/routes/api-client.php b/routes/api-client.php
index ed1190af64..7da1ecfa68 100644
--- a/routes/api-client.php
+++ b/routes/api-client.php
@@ -96,14 +96,6 @@
Route::delete('/{schedule}/tasks/{task}', [Client\Servers\ScheduleTaskController::class, 'delete']);
});
- Route::prefix('/network')->group(function () {
- Route::get('/allocations', [Client\Servers\NetworkAllocationController::class, 'index']);
- Route::post('/allocations', [Client\Servers\NetworkAllocationController::class, 'store']);
- Route::post('/allocations/{allocation}', [Client\Servers\NetworkAllocationController::class, 'update']);
- Route::post('/allocations/{allocation}/primary', [Client\Servers\NetworkAllocationController::class, 'setPrimary']);
- Route::delete('/allocations/{allocation}', [Client\Servers\NetworkAllocationController::class, 'delete']);
- });
-
Route::prefix('/users')->group(function () {
Route::get('/', [Client\Servers\SubuserController::class, 'index']);
Route::post('/', [Client\Servers\SubuserController::class, 'store']);
diff --git a/tests/Integration/Api/Client/ClientApiIntegrationTestCase.php b/tests/Integration/Api/Client/ClientApiIntegrationTestCase.php
index d6dee00da0..cc98921a75 100644
--- a/tests/Integration/Api/Client/ClientApiIntegrationTestCase.php
+++ b/tests/Integration/Api/Client/ClientApiIntegrationTestCase.php
@@ -11,9 +11,7 @@
use App\Models\Database;
use App\Models\Schedule;
use Illuminate\Support\Collection;
-use App\Models\Allocation;
use App\Models\DatabaseHost;
-use App\Tests\Integration\TestResponse;
use App\Tests\Integration\IntegrationTestCase;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use App\Transformers\Api\Client\BaseClientTransformer;
@@ -59,9 +57,6 @@ protected function link(mixed $model, ?string $append = null): string
case Task::class:
$link = "/api/client/servers/{$model->schedule->server->uuid}/schedules/{$model->schedule->id}/tasks/$model->id";
break;
- case Allocation::class:
- $link = "/api/client/servers/{$model->server->uuid}/network/allocations/$model->id";
- break;
case Backup::class:
$link = "/api/client/servers/{$model->server->uuid}/backups/$model->uuid";
break;
diff --git a/tests/Integration/Api/Client/ClientControllerTest.php b/tests/Integration/Api/Client/ClientControllerTest.php
index e4059f6947..0975e68a79 100644
--- a/tests/Integration/Api/Client/ClientControllerTest.php
+++ b/tests/Integration/Api/Client/ClientControllerTest.php
@@ -2,10 +2,10 @@
namespace App\Tests\Integration\Api\Client;
+use App\Models\Objects\Endpoint;
use App\Models\User;
use App\Models\Server;
use App\Models\Subuser;
-use App\Models\Allocation;
use App\Models\Permission;
use App\Models\Role;
@@ -96,49 +96,6 @@ public function testServersAreFilteredUsingNameAndUuidInformation(): void
->assertJsonPath('data.1.attributes.identifier', $servers[2]->uuid_short);
}
- /**
- * Test that using ?filter[*]=:25565 or ?filter[*]=192.168.1.1:25565 returns only those servers
- * with the same allocation for the given user.
- */
- public function testServersAreFilteredUsingAllocationInformation(): void
- {
- /** @var \App\Models\User $user */
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount();
- $server2 = $this->createServerModel(['user_id' => $user->id, 'node_id' => $server->node_id]);
-
- $allocation = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id, 'ip' => '192.168.1.1', 'port' => 25565]);
- $allocation2 = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server2->id, 'ip' => '192.168.1.1', 'port' => 25570]);
-
- $server->update(['allocation_id' => $allocation->id]);
- $server2->update(['allocation_id' => $allocation2->id]);
-
- $server->refresh();
- $server2->refresh();
-
- $this->actingAs($user)->getJson('/api/client?filter[*]=192.168.1.1')
- ->assertOk()
- ->assertJsonCount(2, 'data')
- ->assertJsonPath('data.0.attributes.identifier', $server->uuid_short)
- ->assertJsonPath('data.1.attributes.identifier', $server2->uuid_short);
-
- $this->actingAs($user)->getJson('/api/client?filter[*]=192.168.1.1:25565')
- ->assertOk()
- ->assertJsonCount(1, 'data')
- ->assertJsonPath('data.0.attributes.identifier', $server->uuid_short);
-
- $this->actingAs($user)->getJson('/api/client?filter[*]=:25570')
- ->assertOk()
- ->assertJsonCount(1, 'data')
- ->assertJsonPath('data.0.attributes.identifier', $server2->uuid_short);
-
- $this->actingAs($user)->getJson('/api/client?filter[*]=:255')
- ->assertOk()
- ->assertJsonCount(2, 'data')
- ->assertJsonPath('data.0.attributes.identifier', $server->uuid_short)
- ->assertJsonPath('data.1.attributes.identifier', $server2->uuid_short);
- }
-
/**
* Test that servers where the user is a subuser are returned by default in the API call.
*/
@@ -305,20 +262,16 @@ public function testNoServersAreReturnedIfAdminFilterIsPassedByRegularUser(strin
}
/**
- * Test that a subuser without the allocation.read permission is only able to see the primary
- * allocation for the server.
+ * Test that a subuser without the allocation.read permission cannot see any ports
*/
- public function testOnlyPrimaryAllocationIsReturnedToSubuser(): void
+ public function testNoPortsAreReturnedToSubuser(): void
{
/** @var \App\Models\Server $server */
[$user, $server] = $this->generateTestAccount([Permission::ACTION_WEBSOCKET_CONNECT]);
- $server->allocation->notes = 'Test notes';
- $server->allocation->save();
-
- Allocation::factory()->times(2)->create([
- 'node_id' => $server->node_id,
- 'server_id' => $server->id,
- ]);
+ $server->ports->add(new Endpoint(1234));
+ $server->ports->add(new Endpoint(2345, '1.2.3.4'));
+ $server->ports->add(new Endpoint(3456));
+ $server->save();
$server->refresh();
$response = $this->actingAs($user)->getJson('/api/client');
@@ -327,9 +280,7 @@ public function testOnlyPrimaryAllocationIsReturnedToSubuser(): void
$response->assertJsonCount(1, 'data');
$response->assertJsonPath('data.0.attributes.server_owner', false);
$response->assertJsonPath('data.0.attributes.uuid', $server->uuid);
- $response->assertJsonCount(1, 'data.0.attributes.relationships.allocations.data');
- $response->assertJsonPath('data.0.attributes.relationships.allocations.data.0.attributes.id', $server->allocation->id);
- $response->assertJsonPath('data.0.attributes.relationships.allocations.data.0.attributes.notes', null);
+ $response->assertJsonCount(0, 'data.0.attributes.ports');
}
public static function filterTypeDataProvider(): array
diff --git a/tests/Integration/Api/Client/Server/Allocation/AllocationAuthorizationTest.php b/tests/Integration/Api/Client/Server/Allocation/AllocationAuthorizationTest.php
deleted file mode 100644
index 6cd798e165..0000000000
--- a/tests/Integration/Api/Client/Server/Allocation/AllocationAuthorizationTest.php
+++ /dev/null
@@ -1,57 +0,0 @@
-generateTestAccount();
- // Will be a subuser of $server2.
- $server2 = $this->createServerModel();
- // And as no access to $server3.
- $server3 = $this->createServerModel();
-
- // Set the API $user as a subuser of server 2, but with no permissions
- // to do anything with the allocations for that server.
- Subuser::factory()->create(['server_id' => $server2->id, 'user_id' => $user->id]);
-
- $allocation1 = Allocation::factory()->create(['server_id' => $server1->id, 'node_id' => $server1->node_id]);
- $allocation2 = Allocation::factory()->create(['server_id' => $server2->id, 'node_id' => $server2->node_id]);
- $allocation3 = Allocation::factory()->create(['server_id' => $server3->id, 'node_id' => $server3->node_id]);
-
- // This is the only valid call for this test, accessing the allocation for the same
- // server that the API user is the owner of.
- $response = $this->actingAs($user)->json($method, $this->link($server1, '/network/allocations/' . $allocation1->id . $endpoint));
- $this->assertTrue($response->status() <= 204 || $response->status() === 400 || $response->status() === 422);
-
- // This request fails because the allocation is valid for that server but the user
- // making the request is not authorized to perform that action.
- $this->actingAs($user)->json($method, $this->link($server2, '/network/allocations/' . $allocation2->id . $endpoint))->assertForbidden();
-
- // Both of these should report a 404 error due to the allocations being linked to
- // servers that are not the same as the server in the request, or are assigned
- // to a server for which the user making the request has no access to.
- $this->actingAs($user)->json($method, $this->link($server1, '/network/allocations/' . $allocation2->id . $endpoint))->assertNotFound();
- $this->actingAs($user)->json($method, $this->link($server1, '/network/allocations/' . $allocation3->id . $endpoint))->assertNotFound();
- $this->actingAs($user)->json($method, $this->link($server2, '/network/allocations/' . $allocation3->id . $endpoint))->assertNotFound();
- $this->actingAs($user)->json($method, $this->link($server3, '/network/allocations/' . $allocation3->id . $endpoint))->assertNotFound();
- }
-
- public static function methodDataProvider(): array
- {
- return [
- ['POST', ''],
- ['DELETE', ''],
- ['POST', '/primary'],
- ];
- }
-}
diff --git a/tests/Integration/Api/Client/Server/Allocation/CreateNewAllocationTest.php b/tests/Integration/Api/Client/Server/Allocation/CreateNewAllocationTest.php
deleted file mode 100644
index 395e283a2d..0000000000
--- a/tests/Integration/Api/Client/Server/Allocation/CreateNewAllocationTest.php
+++ /dev/null
@@ -1,93 +0,0 @@
-set('panel.client_features.allocations.enabled', true);
- config()->set('panel.client_features.allocations.range_start', 5000);
- config()->set('panel.client_features.allocations.range_end', 5050);
- }
-
- /**
- * Tests that a new allocation can be properly assigned to a server.
- *
- * @dataProvider permissionDataProvider
- */
- public function testNewAllocationCanBeAssignedToServer(array $permission): void
- {
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount($permission);
- $server->update(['allocation_limit' => 2]);
-
- $response = $this->actingAs($user)->postJson($this->link($server, '/network/allocations'));
- $response->assertJsonPath('object', Allocation::RESOURCE_NAME);
-
- $matched = Allocation::query()->findOrFail($response->json('attributes.id'));
-
- $this->assertSame($server->id, $matched->server_id);
- $this->assertJsonTransformedWith($response->json('attributes'), $matched);
- }
-
- /**
- * Test that a user without the required permissions cannot create an allocation for
- * the server instance.
- */
- public function testAllocationCannotBeCreatedIfUserDoesNotHavePermission(): void
- {
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_UPDATE]);
- $server->update(['allocation_limit' => 2]);
-
- $this->actingAs($user)->postJson($this->link($server, '/network/allocations'))->assertForbidden();
- }
-
- /**
- * Test that an error is returned to the user if this feature is not enabled on the system.
- */
- public function testAllocationCannotBeCreatedIfNotEnabled(): void
- {
- config()->set('panel.client_features.allocations.enabled', false);
-
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount();
- $server->update(['allocation_limit' => 2]);
-
- $this->actingAs($user)->postJson($this->link($server, '/network/allocations'))
- ->assertStatus(Response::HTTP_BAD_REQUEST)
- ->assertJsonPath('errors.0.code', 'AutoAllocationNotEnabledException')
- ->assertJsonPath('errors.0.detail', 'Server auto-allocation is not enabled for this instance.');
- }
-
- /**
- * Test that an allocation cannot be created if the server has reached its allocation limit.
- */
- public function testAllocationCannotBeCreatedIfServerIsAtLimit(): void
- {
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount();
- $server->update(['allocation_limit' => 1]);
-
- $this->actingAs($user)->postJson($this->link($server, '/network/allocations'))
- ->assertStatus(Response::HTTP_BAD_REQUEST)
- ->assertJsonPath('errors.0.code', 'DisplayException')
- ->assertJsonPath('errors.0.detail', 'Cannot assign additional allocations to this server: limit has been reached.');
- }
-
- public static function permissionDataProvider(): array
- {
- return [[[Permission::ACTION_ALLOCATION_CREATE]], [[]]];
- }
-}
diff --git a/tests/Integration/Api/Client/Server/Allocation/DeleteAllocationTest.php b/tests/Integration/Api/Client/Server/Allocation/DeleteAllocationTest.php
deleted file mode 100644
index 07f101a62e..0000000000
--- a/tests/Integration/Api/Client/Server/Allocation/DeleteAllocationTest.php
+++ /dev/null
@@ -1,105 +0,0 @@
-generateTestAccount($permission);
- $server->update(['allocation_limit' => 2]);
-
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create([
- 'server_id' => $server->id,
- 'node_id' => $server->node_id,
- 'notes' => 'hodor',
- ]);
-
- $this->actingAs($user)->deleteJson($this->link($allocation))->assertStatus(Response::HTTP_NO_CONTENT);
-
- $this->assertDatabaseHas('allocations', ['id' => $allocation->id, 'server_id' => null, 'notes' => null]);
- }
-
- /**
- * Test that an error is returned if the user does not have permissiont to delete an allocation.
- */
- public function testErrorIsReturnedIfUserDoesNotHavePermission(): void
- {
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_CREATE]);
-
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create([
- 'server_id' => $server->id,
- 'node_id' => $server->node_id,
- 'notes' => 'hodor',
- ]);
-
- $this->actingAs($user)->deleteJson($this->link($allocation))->assertForbidden();
-
- $this->assertDatabaseHas('allocations', ['id' => $allocation->id, 'server_id' => $server->id]);
- }
-
- /**
- * Test that an allocation is not deleted if it is currently marked as the primary allocation
- * for the server.
- */
- public function testErrorIsReturnedIfAllocationIsPrimary(): void
- {
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount();
- $server->update(['allocation_limit' => 2]);
-
- $this->actingAs($user)->deleteJson($this->link($server->allocation))
- ->assertStatus(Response::HTTP_BAD_REQUEST)
- ->assertJsonPath('errors.0.code', 'DisplayException')
- ->assertJsonPath('errors.0.detail', 'You cannot delete the primary allocation for this server.');
- }
-
- public function testAllocationCannotBeDeletedIfServerLimitIsNotDefined(): void
- {
- [$user, $server] = $this->generateTestAccount();
-
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->forServer($server)->create(['notes' => 'Test notes']);
-
- $this->actingAs($user)->deleteJson($this->link($allocation))
- ->assertStatus(400)
- ->assertJsonPath('errors.0.detail', 'You cannot delete allocations for this server: no allocation limit is set.');
-
- $allocation->refresh();
- $this->assertNotNull($allocation->notes);
- $this->assertEquals($server->id, $allocation->server_id);
- }
-
- /**
- * Test that an allocation cannot be deleted if it does not belong to the server instance.
- */
- public function testErrorIsReturnedIfAllocationDoesNotBelongToServer(): void
- {
- /** @var \App\Models\Server $server */
- [$user, $server] = $this->generateTestAccount();
- [, $server2] = $this->generateTestAccount();
-
- $this->actingAs($user)->deleteJson($this->link($server2->allocation))->assertNotFound();
- $this->actingAs($user)->deleteJson($this->link($server, "/network/allocations/{$server2->allocation_id}"))->assertNotFound();
- }
-
- public static function permissionDataProvider(): array
- {
- return [[[Permission::ACTION_ALLOCATION_DELETE]], [[]]];
- }
-}
diff --git a/tests/Integration/Api/Client/Server/NetworkAllocationControllerTest.php b/tests/Integration/Api/Client/Server/NetworkAllocationControllerTest.php
deleted file mode 100644
index b1e7279eba..0000000000
--- a/tests/Integration/Api/Client/Server/NetworkAllocationControllerTest.php
+++ /dev/null
@@ -1,140 +0,0 @@
-generateTestAccount();
-
- $response = $this->actingAs($user)->getJson($this->link($server, '/network/allocations'));
-
- $response->assertOk();
- $response->assertJsonPath('object', 'list');
- $response->assertJsonCount(1, 'data');
-
- $this->assertJsonTransformedWith($response->json('data.0.attributes'), $server->allocation);
- }
-
- /**
- * Test that allocations cannot be returned without the required user permissions.
- */
- public function testServerAllocationsAreNotReturnedWithoutPermission(): void
- {
- [$user, $server] = $this->generateTestAccount();
- $user2 = User::factory()->create();
-
- $server->owner_id = $user2->id;
- $server->save();
-
- $this->actingAs($user)->getJson($this->link($server, '/network/allocations'))
- ->assertNotFound();
-
- [$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_CREATE]);
-
- $this->actingAs($user)->getJson($this->link($server, '/network/allocations'))
- ->assertForbidden();
- }
-
- /**
- * Tests that notes on an allocation can be set correctly.
- *
- * @dataProvider updatePermissionsDataProvider
- */
- public function testAllocationNotesCanBeUpdated(array $permissions): void
- {
- [$user, $server] = $this->generateTestAccount($permissions);
- $allocation = $server->allocation;
-
- $this->assertNull($allocation->notes);
-
- $this->actingAs($user)->postJson($this->link($allocation), [])
- ->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)
- ->assertJsonPath('errors.0.meta.rule', 'present');
-
- $this->actingAs($user)->postJson($this->link($allocation), ['notes' => 'Test notes'])
- ->assertOk()
- ->assertJsonPath('object', Allocation::RESOURCE_NAME)
- ->assertJsonPath('attributes.notes', 'Test notes');
-
- $allocation = $allocation->refresh();
-
- $this->assertSame('Test notes', $allocation->notes);
-
- $this->actingAs($user)->postJson($this->link($allocation), ['notes' => null])
- ->assertOk()
- ->assertJsonPath('object', Allocation::RESOURCE_NAME)
- ->assertJsonPath('attributes.notes', null);
-
- $allocation = $allocation->refresh();
-
- $this->assertNull($allocation->notes);
- }
-
- public function testAllocationNotesCannotBeUpdatedByInvalidUsers(): void
- {
- [$user, $server] = $this->generateTestAccount();
- $user2 = User::factory()->create();
-
- $server->owner_id = $user2->id;
- $server->save();
-
- $this->actingAs($user)->postJson($this->link($server->allocation))->assertNotFound();
-
- [$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_CREATE]);
-
- $this->actingAs($user)->postJson($this->link($server->allocation))->assertForbidden();
- }
-
- /**
- * @dataProvider updatePermissionsDataProvider
- */
- public function testPrimaryAllocationCanBeModified(array $permissions): void
- {
- [$user, $server] = $this->generateTestAccount($permissions);
- $allocation = $server->allocation;
- $allocation2 = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
-
- $server->allocation_id = $allocation->id;
- $server->save();
-
- $this->actingAs($user)->postJson($this->link($allocation2, '/primary'))
- ->assertOk();
-
- $server = $server->refresh();
-
- $this->assertSame($allocation2->id, $server->allocation_id);
- }
-
- public function testPrimaryAllocationCannotBeModifiedByInvalidUser(): void
- {
- [$user, $server] = $this->generateTestAccount();
- $user2 = User::factory()->create();
-
- $server->owner_id = $user2->id;
- $server->save();
-
- $this->actingAs($user)->postJson($this->link($server->allocation, '/primary'))
- ->assertNotFound();
-
- [$user, $server] = $this->generateTestAccount([Permission::ACTION_ALLOCATION_CREATE]);
-
- $this->actingAs($user)->postJson($this->link($server->allocation, '/primary'))
- ->assertForbidden();
- }
-
- public static function updatePermissionsDataProvider(): array
- {
- return [[[]], [[Permission::ACTION_ALLOCATION_UPDATE]]];
- }
-}
diff --git a/tests/Integration/Api/Client/Server/Startup/GetStartupAndVariablesTest.php b/tests/Integration/Api/Client/Server/Startup/GetStartupAndVariablesTest.php
index 88cc6ed6f2..25f5658d2a 100644
--- a/tests/Integration/Api/Client/Server/Startup/GetStartupAndVariablesTest.php
+++ b/tests/Integration/Api/Client/Server/Startup/GetStartupAndVariablesTest.php
@@ -40,7 +40,7 @@ public function testStartupVariablesAreReturnedForServer(array $permissions): vo
$response->assertJsonPath('meta.raw_startup_command', $server->startup);
$response->assertJsonPath('object', 'list');
- $response->assertJsonCount(1, 'data');
+ $response->assertJsonMissing(['env_variable' => 'BUNGEE_VERSION']);
$response->assertJsonPath('data.0.object', EggVariable::RESOURCE_NAME);
$this->assertJsonTransformedWith($response->json('data.0.attributes'), $egg->variables[1]);
}
diff --git a/tests/Integration/Services/Allocations/FindAssignableAllocationServiceTest.php b/tests/Integration/Services/Allocations/FindAssignableAllocationServiceTest.php
deleted file mode 100644
index 382703b036..0000000000
--- a/tests/Integration/Services/Allocations/FindAssignableAllocationServiceTest.php
+++ /dev/null
@@ -1,174 +0,0 @@
-set('panel.client_features.allocations.enabled', true);
- config()->set('panel.client_features.allocations.range_start', 0);
- config()->set('panel.client_features.allocations.range_end', 0);
- }
-
- /**
- * Test that an unassigned allocation is preferred rather than creating an entirely new
- * allocation for the server.
- */
- public function testExistingAllocationIsPreferred(): void
- {
- $server = $this->createServerModel();
-
- $created = Allocation::factory()->create([
- 'node_id' => $server->node_id,
- 'ip' => $server->allocation->ip,
- ]);
-
- $response = $this->getService()->handle($server);
-
- $this->assertSame($created->id, $response->id);
- $this->assertSame($server->allocation->ip, $response->ip);
- $this->assertSame($server->node_id, $response->node_id);
- $this->assertSame($server->id, $response->server_id);
- $this->assertNotSame($server->allocation_id, $response->id);
- }
-
- /**
- * Test that a new allocation is created if there is not a free one available.
- */
- public function testNewAllocationIsCreatedIfOneIsNotFound(): void
- {
- $server = $this->createServerModel();
- config()->set('panel.client_features.allocations.range_start', 5000);
- config()->set('panel.client_features.allocations.range_end', 5005);
-
- $response = $this->getService()->handle($server);
- $this->assertSame($server->id, $response->server_id);
- $this->assertSame($server->allocation->ip, $response->ip);
- $this->assertSame($server->node_id, $response->node_id);
- $this->assertNotSame($server->allocation_id, $response->id);
- $this->assertTrue($response->port >= 5000 && $response->port <= 5005);
- }
-
- /**
- * Test that a currently assigned port is never assigned to a server.
- */
- public function testOnlyPortNotInUseIsCreated(): void
- {
- $server = $this->createServerModel();
- $server2 = $this->createServerModel(['node_id' => $server->node_id]);
-
- config()->set('panel.client_features.allocations.range_start', 5000);
- config()->set('panel.client_features.allocations.range_end', 5001);
-
- Allocation::factory()->create([
- 'server_id' => $server2->id,
- 'node_id' => $server->node_id,
- 'ip' => $server->allocation->ip,
- 'port' => 5000,
- ]);
-
- $response = $this->getService()->handle($server);
- $this->assertSame(5001, $response->port);
- }
-
- public function testExceptionIsThrownIfNoMoreAllocationsCanBeCreatedInRange(): void
- {
- $server = $this->createServerModel();
- $server2 = $this->createServerModel(['node_id' => $server->node_id]);
- config()->set('panel.client_features.allocations.range_start', 5000);
- config()->set('panel.client_features.allocations.range_end', 5005);
-
- for ($i = 5000; $i <= 5005; $i++) {
- Allocation::factory()->create([
- 'ip' => $server->allocation->ip,
- 'port' => $i,
- 'node_id' => $server->node_id,
- 'server_id' => $server2->id,
- ]);
- }
-
- $this->expectException(NoAutoAllocationSpaceAvailableException::class);
- $this->expectExceptionMessage('Cannot assign additional allocation: no more space available on node.');
-
- $this->getService()->handle($server);
- }
-
- /**
- * Test that we only auto-allocate from the current server's IP address space, and not a random
- * IP address available on that node.
- */
- public function testExceptionIsThrownIfOnlyFreePortIsOnADifferentIp(): void
- {
- $server = $this->createServerModel();
-
- Allocation::factory()->times(5)->create(['node_id' => $server->node_id]);
-
- $this->expectException(NoAutoAllocationSpaceAvailableException::class);
- $this->expectExceptionMessage('Cannot assign additional allocation: no more space available on node.');
-
- $this->getService()->handle($server);
- }
-
- public function testExceptionIsThrownIfStartOrEndRangeIsNotDefined(): void
- {
- $server = $this->createServerModel();
-
- $this->expectException(NoAutoAllocationSpaceAvailableException::class);
- $this->expectExceptionMessage('Cannot assign additional allocation: no more space available on node.');
-
- $this->getService()->handle($server);
- }
-
- public function testExceptionIsThrownIfStartOrEndRangeIsNotNumeric(): void
- {
- $server = $this->createServerModel();
- config()->set('panel.client_features.allocations.range_start', 'hodor');
- config()->set('panel.client_features.allocations.range_end', 10);
-
- try {
- $this->getService()->handle($server);
- $this->fail('This assertion should not be reached.');
- } catch (\Exception $exception) {
- $this->assertInstanceOf(\InvalidArgumentException::class, $exception);
- $this->assertSame('Expected an integerish value. Got: string', $exception->getMessage());
- }
-
- config()->set('panel.client_features.allocations.range_start', 10);
- config()->set('panel.client_features.allocations.range_end', 'hodor');
-
- try {
- $this->getService()->handle($server);
- $this->fail('This assertion should not be reached.');
- } catch (\Exception $exception) {
- $this->assertInstanceOf(\InvalidArgumentException::class, $exception);
- $this->assertSame('Expected an integerish value. Got: string', $exception->getMessage());
- }
- }
-
- public function testExceptionIsThrownIfFeatureIsNotEnabled(): void
- {
- config()->set('panel.client_features.allocations.enabled', false);
- $server = $this->createServerModel();
-
- $this->expectException(AutoAllocationNotEnabledException::class);
-
- $this->getService()->handle($server);
- }
-
- private function getService(): FindAssignableAllocationService
- {
- return $this->app->make(FindAssignableAllocationService::class);
- }
-}
diff --git a/tests/Integration/Services/Servers/BuildModificationServiceTest.php b/tests/Integration/Services/Servers/BuildModificationServiceTest.php
index 152b11039f..7b269cac83 100644
--- a/tests/Integration/Services/Servers/BuildModificationServiceTest.php
+++ b/tests/Integration/Services/Servers/BuildModificationServiceTest.php
@@ -6,9 +6,7 @@
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use App\Models\Server;
-use App\Models\Allocation;
use GuzzleHttp\Exception\RequestException;
-use App\Exceptions\DisplayException;
use App\Tests\Integration\IntegrationTestCase;
use App\Repositories\Daemon\DaemonServerRepository;
use App\Services\Servers\BuildModificationService;
@@ -28,82 +26,12 @@ protected function setUp(): void
$this->daemonServerRepository = $this->mock(DaemonServerRepository::class);
}
- /**
- * Test that allocations can be added and removed from a server. Only the allocations on the
- * current node and belonging to this server should be modified.
- */
- public function testAllocationsCanBeModifiedForTheServer(): void
- {
- $server = $this->createServerModel();
- $server2 = $this->createServerModel();
-
- /** @var \App\Models\Allocation[] $allocations */
- $allocations = Allocation::factory()->times(4)->create(['node_id' => $server->node_id, 'notes' => 'Random notes']);
-
- $initialAllocationId = $server->allocation_id;
- $allocations[0]->update(['server_id' => $server->id, 'notes' => 'Test notes']);
-
- // Some additional test allocations for the other server, not the server we are attempting
- // to modify.
- $allocations[2]->update(['server_id' => $server2->id]);
- $allocations[3]->update(['server_id' => $server2->id]);
-
- $this->daemonServerRepository->expects('setServer->sync')->andReturnUndefined();
-
- $response = $this->getService()->handle($server, [
- // Attempt to add one new allocation, and an allocation assigned to another server. The
- // other server allocation should be ignored, and only the allocation for this server should
- // be used.
- 'add_allocations' => [$allocations[2]->id, $allocations[1]->id],
- // Remove the default server allocation, ensuring that the new allocation passed through
- // in the data becomes the default allocation.
- 'remove_allocations' => [$server->allocation_id, $allocations[0]->id, $allocations[3]->id],
- ]);
-
- $this->assertInstanceOf(Server::class, $response);
-
- // Only one allocation should exist for this server now.
- $this->assertCount(1, $response->allocations);
- $this->assertSame($allocations[1]->id, $response->allocation_id);
- $this->assertNull($response->allocation->notes);
-
- // These two allocations should not have been touched.
- $this->assertDatabaseHas('allocations', ['id' => $allocations[2]->id, 'server_id' => $server2->id]);
- $this->assertDatabaseHas('allocations', ['id' => $allocations[3]->id, 'server_id' => $server2->id]);
-
- // Both of these allocations should have been removed from the server, and have had their
- // notes properly reset.
- $this->assertDatabaseHas('allocations', ['id' => $initialAllocationId, 'server_id' => null, 'notes' => null]);
- $this->assertDatabaseHas('allocations', ['id' => $allocations[0]->id, 'server_id' => null, 'notes' => null]);
- }
-
- /**
- * Test that an exception is thrown if removing the default allocation without also assigning
- * new allocations to the server.
- */
- public function testExceptionIsThrownIfRemovingTheDefaultAllocation(): void
- {
- $server = $this->createServerModel();
- /** @var \App\Models\Allocation[] $allocations */
- $allocations = Allocation::factory()->times(4)->create(['node_id' => $server->node_id]);
-
- $allocations[0]->update(['server_id' => $server->id]);
-
- $this->expectException(DisplayException::class);
- $this->expectExceptionMessage('You are attempting to delete the default allocation for this server but there is no fallback allocation to use.');
-
- $this->getService()->handle($server, [
- 'add_allocations' => [],
- 'remove_allocations' => [$server->allocation_id, $allocations[0]->id],
- ]);
- }
-
/**
* Test that the build data for the server is properly passed along to the daemon instance so that
* the server data is updated in realtime. This test also ensures that only certain fields get updated
* for the server, and not just any arbitrary field.
*/
- public function testServerBuildDataIsProperlyUpdatedOndaemon(): void
+ public function testServerBuildDataIsProperlyUpdatedOnDaemon(): void
{
$server = $this->createServerModel();
@@ -164,91 +92,6 @@ public function testConnectionExceptionIsIgnoredWhenUpdatingServerSettings(): vo
$this->assertDatabaseHas('servers', ['id' => $response->id, 'memory' => 256, 'disk' => 10240]);
}
- /**
- * Test that no exception is thrown if we are only removing an allocation.
- */
- public function testNoExceptionIsThrownIfOnlyRemovingAllocation(): void
- {
- $server = $this->createServerModel();
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
-
- $this->daemonServerRepository->expects('setServer->sync')->andReturnUndefined();
-
- $this->getService()->handle($server, [
- 'remove_allocations' => [$allocation->id],
- ]);
-
- $this->assertDatabaseHas('allocations', ['id' => $allocation->id, 'server_id' => null]);
- }
-
- /**
- * Test that allocations in both the add and remove arrays are only added, and not removed.
- * This scenario wouldn't really happen in the UI, but it is possible to perform via the API,
- * so we want to make sure that the logic being used doesn't break if the allocation exists
- * in both arrays.
- *
- * We'll default to adding the allocation in this case.
- */
- public function testAllocationInBothAddAndRemoveIsAdded(): void
- {
- $server = $this->createServerModel();
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create(['node_id' => $server->node_id]);
-
- $this->daemonServerRepository->expects('setServer->sync')->andReturnUndefined();
-
- $this->getService()->handle($server, [
- 'add_allocations' => [$allocation->id],
- 'remove_allocations' => [$allocation->id],
- ]);
-
- $this->assertDatabaseHas('allocations', ['id' => $allocation->id, 'server_id' => $server->id]);
- }
-
- /**
- * Test that using the same allocation ID multiple times in the array does not cause an error.
- */
- public function testUsingSameAllocationIdMultipleTimesDoesNotError(): void
- {
- $server = $this->createServerModel();
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create(['node_id' => $server->node_id, 'server_id' => $server->id]);
- /** @var \App\Models\Allocation $allocation2 */
- $allocation2 = Allocation::factory()->create(['node_id' => $server->node_id]);
-
- $this->daemonServerRepository->expects('setServer->sync')->andReturnUndefined();
-
- $this->getService()->handle($server, [
- 'add_allocations' => [$allocation2->id, $allocation2->id],
- 'remove_allocations' => [$allocation->id, $allocation->id],
- ]);
-
- $this->assertDatabaseHas('allocations', ['id' => $allocation->id, 'server_id' => null]);
- $this->assertDatabaseHas('allocations', ['id' => $allocation2->id, 'server_id' => $server->id]);
- }
-
- /**
- * Test that any changes we made to the server or allocations are rolled back if there is an
- * exception while performing any action. This is different from the connection exception
- * test which should properly ignore connection issues. We want any other type of exception
- * to properly be thrown back to the caller.
- */
- public function testThatUpdatesAreRolledBackIfExceptionIsEncountered(): void
- {
- $server = $this->createServerModel();
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create(['node_id' => $server->node_id]);
-
- $this->daemonServerRepository->expects('setServer->sync')->andThrows(new DisplayException('Test'));
-
- $this->expectException(DisplayException::class);
-
- $this->getService()->handle($server, ['add_allocations' => [$allocation->id]]);
-
- $this->assertDatabaseHas('allocations', ['id' => $allocation->id, 'server_id' => null]);
- }
-
private function getService(): BuildModificationService
{
return $this->app->make(BuildModificationService::class);
diff --git a/tests/Integration/Services/Servers/ServerCreationServiceTest.php b/tests/Integration/Services/Servers/ServerCreationServiceTest.php
index c0b82a285d..7589dbe0a9 100644
--- a/tests/Integration/Services/Servers/ServerCreationServiceTest.php
+++ b/tests/Integration/Services/Servers/ServerCreationServiceTest.php
@@ -2,6 +2,7 @@
namespace App\Tests\Integration\Services\Servers;
+use App\Models\Objects\Endpoint;
use Mockery\MockInterface;
use App\Models\Egg;
use GuzzleHttp\Psr7\Request;
@@ -9,7 +10,6 @@
use App\Models\User;
use GuzzleHttp\Psr7\Response;
use App\Models\Server;
-use App\Models\Allocation;
use Illuminate\Foundation\Testing\WithFaker;
use GuzzleHttp\Exception\BadResponseException;
use Illuminate\Validation\ValidationException;
@@ -59,13 +59,8 @@ public function testServerIsCreatedWithDeploymentObject(): void
/** @var \App\Models\Node $node */
$node = Node::factory()->create();
- /** @var \App\Models\Allocation[]|\Illuminate\Database\Eloquent\Collection $allocations */
- $allocations = Allocation::factory()->times(5)->create([
- 'node_id' => $node->id,
- ]);
-
$deployment = (new DeploymentObject())->setDedicated(true)->setPorts([
- $allocations[0]->port,
+ 1234,
]);
$egg = $this->cloneEggAndVariables($this->bungeecord);
@@ -87,12 +82,12 @@ public function testServerIsCreatedWithDeploymentObject(): void
'startup' => 'java server2.jar',
'image' => 'java:8',
'egg_id' => $egg->id,
- 'allocation_additional' => [
- $allocations[4]->id,
- ],
+ 'ports' => [1234, 2345, 3456],
+ 'node_id' => $node->id,
'environment' => [
'BUNGEE_VERSION' => '123',
'SERVER_JARFILE' => 'server2.jar',
+ 'SERVER_PORT' => '1234',
],
'start_on_completion' => true,
];
@@ -104,13 +99,14 @@ public function testServerIsCreatedWithDeploymentObject(): void
'environment' => [
'BUNGEE_VERSION' => '',
'SERVER_JARFILE' => 'server2.jar',
+ 'SERVER_PORT' => '1234',
],
]), $deployment);
$this->fail('This execution pathway should not be reached.');
} catch (ValidationException $exception) {
- $this->assertCount(1, $exception->errors());
$this->assertArrayHasKey('environment.BUNGEE_VERSION', $exception->errors());
+ $this->assertArrayNotHasKey('environment.SERVER_JARFILE', $exception->errors());
$this->assertSame('The Bungeecord Version variable field is required.', $exception->errors()['environment.BUNGEE_VERSION'][0]);
}
@@ -120,23 +116,24 @@ public function testServerIsCreatedWithDeploymentObject(): void
$this->assertNotNull($response->uuid);
$this->assertSame($response->uuid_short, substr($response->uuid, 0, 8));
$this->assertSame($egg->id, $response->egg_id);
- $this->assertCount(2, $response->variables);
+ $this->assertCount(3, $response->variables);
$this->assertSame('123', $response->variables[0]->server_value);
$this->assertSame('server2.jar', $response->variables[1]->server_value);
foreach ($data as $key => $value) {
- if (in_array($key, ['allocation_additional', 'environment', 'start_on_completion'])) {
+ if (in_array($key, ['environment', 'start_on_completion'])) {
+ continue;
+ }
+
+ if ($key === 'ports') {
+ $this->assertSame($value, $response->ports->map(fn (Endpoint $endpoint) => $endpoint->port)->all());
+
continue;
}
$this->assertSame($value, $response->{$key}, "Failed asserting equality of '$key' in server response. Got: [{$response->{$key}}] Expected: [$value]");
}
- $this->assertCount(2, $response->allocations);
- $this->assertSame($response->allocation_id, $response->allocations[0]->id);
- $this->assertSame($allocations[0]->id, $response->allocations[0]->id);
- $this->assertSame($allocations[4]->id, $response->allocations[1]->id);
-
$this->assertFalse($response->isSuspended());
$this->assertFalse($response->oom_killer);
$this->assertSame(0, $response->database_limit);
@@ -156,17 +153,11 @@ public function testErrorEncounteredByDaemonCausesServerToBeDeleted(): void
/** @var \App\Models\Node $node */
$node = Node::factory()->create();
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create([
- 'node_id' => $node->id,
- ]);
-
$data = [
'name' => $this->faker->name(),
'description' => $this->faker->sentence(),
'owner_id' => $user->id,
- 'allocation_id' => $allocation->id,
- 'node_id' => $allocation->node_id,
+ 'node_id' => $node->id,
'memory' => 256,
'swap' => 128,
'disk' => 100,
@@ -178,6 +169,7 @@ public function testErrorEncounteredByDaemonCausesServerToBeDeleted(): void
'environment' => [
'BUNGEE_VERSION' => '123',
'SERVER_JARFILE' => 'server2.jar',
+ 'SERVER_PORT' => '1234',
],
];
diff --git a/tests/Integration/Services/Servers/StartupModificationServiceTest.php b/tests/Integration/Services/Servers/StartupModificationServiceTest.php
index f0d2726e1f..803a98486f 100644
--- a/tests/Integration/Services/Servers/StartupModificationServiceTest.php
+++ b/tests/Integration/Services/Servers/StartupModificationServiceTest.php
@@ -29,6 +29,7 @@ public function testNonAdminCanModifyServerVariables(): void
'environment' => [
'BUNGEE_VERSION' => '$$',
'SERVER_JARFILE' => 'server.jar',
+ 'SERVER_PORT' => '1234',
],
]);
@@ -54,11 +55,12 @@ public function testNonAdminCanModifyServerVariables(): void
'environment' => [
'BUNGEE_VERSION' => '1234',
'SERVER_JARFILE' => 'test.jar',
+ 'SERVER_PORT' => '1234',
],
]);
$this->assertInstanceOf(Server::class, $result);
- $this->assertCount(2, $result->variables);
+ $this->assertCount(3, $result->variables);
$this->assertSame($server->startup, $result->startup);
$this->assertSame('1234', $result->variables[0]->server_value);
$this->assertSame('test.jar', $result->variables[1]->server_value);
@@ -125,7 +127,7 @@ public function testEnvironmentVariablesCanBeUpdatedByAdmin(): void
],
]);
- $this->assertCount(2, $response->variables);
+ $this->assertCount(3, $response->variables);
$this->assertSame('EXIST', $response->variables[0]->server_value);
$this->assertSame('test.jar', $response->variables[1]->server_value);
@@ -135,12 +137,14 @@ public function testEnvironmentVariablesCanBeUpdatedByAdmin(): void
'environment' => [
'BUNGEE_VERSION' => '1234',
'SERVER_JARFILE' => 'test.jar',
+ 'SERVER_PORT' => '1111',
],
]);
- $this->assertCount(2, $response->variables);
+ $this->assertCount(3, $response->variables);
$this->assertSame('1234', $response->variables[0]->server_value);
$this->assertSame('test.jar', $response->variables[1]->server_value);
+ $this->assertSame('1111', $response->variables[2]->server_value);
}
/**
diff --git a/tests/Integration/Services/Servers/VariableValidatorServiceTest.php b/tests/Integration/Services/Servers/VariableValidatorServiceTest.php
index 6f49b97fb2..9f70f8b0d1 100644
--- a/tests/Integration/Services/Servers/VariableValidatorServiceTest.php
+++ b/tests/Integration/Services/Servers/VariableValidatorServiceTest.php
@@ -94,25 +94,28 @@ public function testEnvironmentVariablesCanBeUpdatedAsAdmin(): void
$this->getService()->setUserLevel(User::USER_LEVEL_ADMIN)->handle($egg->id, [
'BUNGEE_VERSION' => '1.2.3',
'SERVER_JARFILE' => 'server.jar',
+ 'SERVER_PORT' => '1234',
]);
$this->fail('This statement should not be reached.');
} catch (ValidationException $exception) {
- $this->assertCount(1, $exception->errors());
$this->assertArrayHasKey('environment.BUNGEE_VERSION', $exception->errors());
}
$response = $this->getService()->setUserLevel(User::USER_LEVEL_ADMIN)->handle($egg->id, [
'BUNGEE_VERSION' => '123',
'SERVER_JARFILE' => 'server.jar',
+ 'SERVER_PORT' => '1234',
]);
$this->assertInstanceOf(Collection::class, $response);
- $this->assertCount(2, $response);
+ $this->assertCount(3, $response);
$this->assertSame('BUNGEE_VERSION', $response->get(0)->key);
$this->assertSame('123', $response->get(0)->value);
$this->assertSame('SERVER_JARFILE', $response->get(1)->key);
$this->assertSame('server.jar', $response->get(1)->value);
+ $this->assertSame('SERVER_PORT', $response->get(2)->key);
+ $this->assertSame('1234', $response->get(2)->value);
}
public function testNullableEnvironmentVariablesCanBeUsedCorrectly(): void
diff --git a/tests/Traits/Integration/CreatesTestModels.php b/tests/Traits/Integration/CreatesTestModels.php
index 0e28cb40e7..f33fc63aa4 100644
--- a/tests/Traits/Integration/CreatesTestModels.php
+++ b/tests/Traits/Integration/CreatesTestModels.php
@@ -8,7 +8,6 @@
use App\Models\User;
use App\Models\Server;
use App\Models\Subuser;
-use App\Models\Allocation;
trait CreatesTestModels
{
@@ -37,12 +36,6 @@ public function createServerModel(array $attributes = []): Server
$attributes['node_id'] = $node->id;
}
- if (!isset($attributes['allocation_id'])) {
- /** @var \App\Models\Allocation $allocation */
- $allocation = Allocation::factory()->create(['node_id' => $attributes['node_id']]);
- $attributes['allocation_id'] = $allocation->id;
- }
-
if (empty($attributes['egg_id'])) {
$egg = $this->getBungeecordEgg();
@@ -54,10 +47,8 @@ public function createServerModel(array $attributes = []): Server
/** @var \App\Models\Server $server */
$server = Server::factory()->create($attributes);
- Allocation::query()->where('id', $server->allocation_id)->update(['server_id' => $server->id]);
-
return $server->fresh([
- 'user', 'node', 'allocation', 'egg',
+ 'user', 'node', 'egg',
]);
}