Files

434 lines
14 KiB
PHP
Raw Permalink Normal View History

2015-12-06 13:58:49 -05:00
<?php
2016-12-07 22:46:38 +00:00
2026-10-05 18:10:18 -04:00
declare(strict_types=1);
2015-12-06 13:58:49 -05:00
namespace Pterodactyl\Models;
2026-10-05 18:10:18 -04:00
use Database\Factories\ServerFactory;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
2026-10-12 00:21:31 -04:00
use Illuminate\Database\Eloquent\Collection;
2024-10-21 19:18:20 -06:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2026-10-05 18:10:18 -04:00
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
2022-10-14 10:59:20 -06:00
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
2026-10-05 18:10:18 -04:00
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Notifications\Notifiable;
use Pterodactyl\Contracts\Models\Identifiable;
use Pterodactyl\Exceptions\Http\Server\ServerStateConflictException;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
2026-10-12 00:21:31 -04:00
use UnexpectedValueException;
2015-12-06 13:58:49 -05:00
/**
2026-10-11 22:55:07 -04:00
* @property int|null $database_limit Larastan's schema dump parser misses that this column is nullable
* @property-read Node $node
* @property-read User $user
*/
#[Attributes\Identifiable('serv')]
2026-10-05 18:10:18 -04:00
#[Guarded(['id', self::CREATED_AT, self::UPDATED_AT, 'deleted_at', 'installed_at'])]
class Server extends Model implements Identifiable
2015-12-06 13:58:49 -05:00
{
2026-10-05 18:10:18 -04:00
/** @use HasFactory<ServerFactory> */
2024-10-21 19:18:20 -06:00
use HasFactory;
2026-10-05 18:10:18 -04:00
use HasRealtimeIdentifier;
2026-10-05 18:10:18 -04:00
use Notifiable;
2016-10-27 20:05:29 -04:00
2026-10-05 18:10:18 -04:00
public const string RESOURCE_NAME = 'server';
2020-04-03 13:46:45 -07:00
2026-10-05 18:10:18 -04:00
public const string STATUS_INSTALLING = 'installing';
public const string STATUS_INSTALL_FAILED = 'install_failed';
public const string STATUS_REINSTALL_FAILED = 'reinstall_failed';
public const string STATUS_SUSPENDED = 'suspended';
public const string STATUS_RESTORING_BACKUP = 'restoring_backup';
private const string ADMIN_ROUTE_BINDING_FIELD = 'admin_identifier';
2015-12-06 13:58:49 -05:00
/**
2026-10-11 22:55:07 -04:00
* New servers have the OOM killer disabled unless the request says otherwise.
*/
protected $attributes = [
'status' => self::STATUS_INSTALLING,
'oom_disabled' => true,
'installed_at' => null,
];
protected $with = ['allocation'];
2015-12-15 15:08:41 -05:00
/**
2026-10-05 18:10:18 -04:00
* @return array<string, string>
*/
2026-10-05 18:10:18 -04:00
protected function casts(): array
{
return [
'node_id' => 'integer',
'skip_scripts' => 'boolean',
'owner_id' => 'integer',
'memory' => 'integer',
'swap' => 'integer',
'disk' => 'integer',
'io' => 'integer',
'cpu' => 'integer',
'oom_disabled' => 'boolean',
'allocation_id' => 'integer',
'egg_id' => 'integer',
'database_limit' => 'integer',
'allocation_limit' => 'integer',
'backup_limit' => 'integer',
'deleted_at' => 'datetime',
'installed_at' => 'datetime',
];
}
2016-01-26 22:17:51 -05:00
/**
* Returns the format for server allocations when communicating with the Daemon.
2026-10-05 18:10:18 -04:00
*
* @return array<string, list<int>> ports keyed by the allocation IP
*/
public function getAllocationMappings(): array
{
2026-10-05 18:10:18 -04:00
$mappings = [];
foreach ($this->allocations as $allocation) {
if ($allocation->node_id === $this->node_id) {
$mappings[$allocation->ip] ??= [];
$mappings[$allocation->ip][] = $allocation->port;
}
}
return $mappings;
}
2018-08-25 15:07:42 -07:00
public function isInstalled(): bool
{
return $this->status !== self::STATUS_INSTALLING && $this->status !== self::STATUS_INSTALL_FAILED;
}
public function isSuspended(): bool
{
return $this->status === self::STATUS_SUSPENDED;
2018-08-25 15:07:42 -07:00
}
2026-10-05 18:10:18 -04:00
/**
* Whether a reinstall would run the egg's install script. A server that skips its install
* script can still be reinstalled while its install is unfinished or has failed.
*/
public function canBeReinstalled(): bool
{
return ! $this->skip_scripts || in_array($this->status, [
self::STATUS_INSTALLING,
self::STATUS_INSTALL_FAILED,
self::STATUS_REINSTALL_FAILED,
], true);
}
public function resolveRouteBinding($value, $field = null): ?\Illuminate\Database\Eloquent\Model
{
if ($field !== self::ADMIN_ROUTE_BINDING_FIELD) {
return parent::resolveRouteBinding($value, $field);
}
if (! is_int($value) && ! is_string($value)) {
return null;
}
$routeValue = (string) $value;
if (ctype_digit($routeValue)) {
$server = self::query()->whereKey($routeValue)->first();
if (($server) !== null) {
return $server;
}
}
return self::query()->whereUuidOrShort($routeValue)->first();
}
/**
2026-10-05 18:10:18 -04:00
* @return BelongsTo<User, $this>
*/
2022-10-14 10:59:20 -06:00
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id');
}
2017-02-09 19:38:54 -05:00
/**
2026-10-05 18:10:18 -04:00
* @return HasMany<Subuser, $this>
2017-02-09 19:38:54 -05:00
*/
2022-10-14 10:59:20 -06:00
public function subusers(): HasMany
2017-02-09 19:38:54 -05:00
{
2019-12-28 11:39:44 -08:00
return $this->hasMany(Subuser::class, 'server_id', 'id');
2017-02-09 19:38:54 -05:00
}
/**
* Gets the default allocation for a server.
*
2026-10-05 18:10:18 -04:00
* @return HasOne<Allocation, $this>
*/
2022-10-14 10:59:20 -06:00
public function allocation(): HasOne
{
2026-10-05 18:10:18 -04:00
return $this->hasOne(Allocation::class, 'id', 'allocation_id')->chaperone('server');
}
/**
2026-10-05 18:10:18 -04:00
* @return HasMany<Allocation, $this>
*/
2022-10-14 10:59:20 -06:00
public function allocations(): HasMany
{
2026-10-05 18:10:18 -04:00
return $this->hasMany(Allocation::class, 'server_id')->chaperone('server');
}
/**
2026-10-05 18:10:18 -04:00
* @return HasOne<Egg, $this>
*/
2026-10-05 18:10:18 -04:00
public function egg(): HasOne
{
2026-10-05 18:10:18 -04:00
return $this->hasOne(Egg::class, 'id', 'egg_id');
}
/**
2026-10-05 18:10:18 -04:00
* The tag slugs that describe this server's game, taken from its egg. These are
* what feature gating matches on, replacing the nest a server used to carry.
*
2026-10-05 18:10:18 -04:00
* @return string[]
*/
2026-10-05 18:10:18 -04:00
public function tagSlugs(): array
{
2026-10-05 18:10:18 -04:00
$this->loadMissing('egg.tags');
2026-10-11 16:47:03 -04:00
return $this->egg === null ? [] : $this->egg->tags->map(fn (Tag $tag): string => $tag->slug)->all();
2026-10-05 18:10:18 -04:00
}
public function hasTag(string $slug): bool
{
return in_array($slug, $this->tagSlugs(), true);
}
/**
2026-10-05 18:10:18 -04:00
* @return HasMany<EggVariable, $this>
*/
2022-10-14 10:59:20 -06:00
public function variables(): HasMany
{
2026-10-05 18:10:18 -04:00
// WARNING: lazy/instance use only. The join below captures $this->id, and an
// eager load (with()/load()/loadMissing()) rebuilds the relation on a blank
// model, degrading the join to "server_id is null" and nulling server_value.
return $this->hasMany(EggVariable::class, 'egg_id', 'egg_id')
->select(['egg_variables.*', 'server_variables.variable_value as server_value'])
2026-10-05 18:10:18 -04:00
->leftJoin('server_variables', function (JoinClause $join): void {
// Don't forget to join against the server ID as well since the way we're using this relationship
2022-10-14 10:59:20 -06:00
// would actually return all the variables and their values for _all_ servers using that egg,
// rather than only the server for this model.
//
// @see https://github.com/pterodactyl/panel/issues/2250
$join->on('server_variables.variable_id', 'egg_variables.id')
->where('server_variables.server_id', $this->id);
});
}
2026-10-05 18:10:18 -04:00
/**
* Gets the environment variable overrides stored specifically for this server.
*
* @return HasMany<ServerVariable, $this>
*/
public function serverVariables(): HasMany
{
return $this->hasMany(ServerVariable::class);
}
2026-10-12 00:21:31 -04:00
/**
* The egg's variables with this server's values as server_value. When a list has eager
* loaded egg.variables and serverVariables this runs no query for each server.
*
* @return Collection<int, EggVariable>
*/
public function resolvedVariables(): Collection
{
if (! $this->relationLoaded('egg')
|| ! $this->egg?->relationLoaded('variables')
|| ! $this->relationLoaded('serverVariables')
) {
return $this->variables()->get();
}
$overrides = $this->serverVariables->pluck('variable_value', 'variable_id');
return $this->egg->variables->map(function (EggVariable $variable) use ($overrides): EggVariable {
$resolved = clone $variable;
$resolved->setAttribute('server_value', $overrides->get($variable->id));
return $resolved;
});
}
/**
* The startup command with its variables filled in. A variable the user cannot view, or
* every variable when $hideAllValues is set, shows as "[hidden]".
*/
public function startupCommand(bool $hideAllValues = false): string
{
$this->loadMissing('allocation');
$allocation = $this->allocation ?? throw new UnexpectedValueException('The server does not have a primary allocation.');
$find = ['{{SERVER_MEMORY}}', '{{SERVER_IP}}', '{{SERVER_PORT}}'];
$replace = [(string) $this->memory, $allocation->ip, (string) $allocation->port];
foreach ($this->resolvedVariables() as $variable) {
$find[] = '{{'.$variable->env_variable.'}}';
$replace[] = (string) (($variable->user_viewable && ! $hideAllValues) ? ($variable->server_value ?? $variable->default_value) : '[hidden]');
}
return str_replace($find, $replace, $this->startup);
}
/**
2026-10-05 18:10:18 -04:00
* @return BelongsTo<Node, $this>
*/
2022-10-14 10:59:20 -06:00
public function node(): BelongsTo
{
return $this->belongsTo(Node::class);
}
/**
2026-10-05 18:10:18 -04:00
* @return HasMany<Schedule, $this>
*/
2022-10-14 10:59:20 -06:00
public function schedules(): HasMany
{
return $this->hasMany(Schedule::class);
}
/**
2026-10-05 18:10:18 -04:00
* @return HasMany<Database, $this>
*/
2022-10-14 10:59:20 -06:00
public function databases(): HasMany
{
2026-10-13 21:07:43 -04:00
return $this->hasMany(Database::class)->chaperone('server')->orderBy('id');
}
/**
2026-10-05 18:10:18 -04:00
* The server's location is whatever its node belongs to, so this resolves
* through the node with local keys - the same native emulation of an inverse
* through-relation used elsewhere in this codebase.
*
2026-10-05 18:10:18 -04:00
* @return HasOneThrough<Location, Node, $this>
*/
2026-10-05 18:10:18 -04:00
public function location(): HasOneThrough
{
2026-10-05 18:10:18 -04:00
return $this->hasOneThrough(Location::class, Node::class, 'id', 'id', 'node_id', 'location_id');
}
/**
2026-10-05 18:10:18 -04:00
* @return HasOne<ServerTransfer, $this>
*/
2022-10-14 10:59:20 -06:00
public function transfer(): HasOne
{
return $this->hasOne(ServerTransfer::class)->whereNull('successful')->orderByDesc('id');
}
/**
2026-10-05 18:10:18 -04:00
* @return HasMany<Backup, $this>
*/
2022-10-14 10:59:20 -06:00
public function backups(): HasMany
{
return $this->hasMany(Backup::class);
}
/**
2026-10-05 18:10:18 -04:00
* @return HasManyThrough<Mount, MountServer, $this>
*/
2022-10-14 10:59:20 -06:00
public function mounts(): HasManyThrough
{
return $this->hasManyThrough(Mount::class, MountServer::class, 'server_id', 'id', 'id', 'mount_id');
}
2021-01-17 10:49:36 -08:00
/**
* Returns all of the activity log entries where the server is the subject.
*
2026-10-05 18:10:18 -04:00
* @return MorphToMany<ActivityLog, $this>
2021-01-17 10:49:36 -08:00
*/
public function activity(): MorphToMany
2021-01-17 10:49:36 -08:00
{
return $this->morphToMany(ActivityLog::class, 'subject', 'activity_log_subjects');
2021-01-17 10:49:36 -08:00
}
2026-10-12 00:30:02 -04:00
/**
* The server's activity without disabled events. With activity.hide_admin_activity set,
* entries by root admins who are neither the owner nor a subuser are left out.
*
2026-10-12 00:57:27 -04:00
* @return MorphToMany<ActivityLog, $this>
2026-10-12 00:30:02 -04:00
*/
2026-10-12 00:57:27 -04:00
public function visibleActivity(): MorphToMany
2026-10-12 00:30:02 -04:00
{
2026-10-12 00:57:27 -04:00
$query = $this->activity()->select('activity_logs.*')->withoutDisabledEvents();
2026-10-12 00:30:02 -04:00
if (config('activity.hide_admin_activity')) {
$subusers = $this->subusers()->pluck('user_id')->merge([$this->owner_id]);
$query->leftJoin('users', function (JoinClause $join): void {
$join->on('users.id', 'activity_logs.actor_id')
->where('activity_logs.actor_type', (new User)->getMorphClass());
})->where(function (Builder $builder) use ($subusers): void {
$builder->whereNull('users.id')
->orWhere('users.root_admin', 0)
->orWhereIn('users.id', $subusers);
});
}
return $query;
}
/**
* Checks if the server is currently in a user-accessible state. If not, an
* exception is raised. This should be called whenever something needs to make
* sure the server is not in a weird state that should block user access.
*
2024-10-21 19:18:20 -06:00
* @throws ServerStateConflictException
*/
2026-10-05 18:10:18 -04:00
public function validateCurrentState(): void
{
2026-10-05 18:10:18 -04:00
throw_if($this->isSuspended()
|| $this->node->isUnderMaintenance()
|| ! $this->isInstalled()
|| $this->status === self::STATUS_RESTORING_BACKUP
|| ($this->transfer) !== null, ServerStateConflictException::class, $this);
}
/**
* Checks if the server is currently in a transferable state. If not, an
* exception is raised. This should be called whenever something needs to make
* sure the server is able to be transferred and is not currently being transferred
* or installed.
*/
2026-10-05 18:10:18 -04:00
public function validateTransferState(): void
{
2026-10-05 18:10:18 -04:00
throw_if(! $this->isInstalled()
|| $this->status === self::STATUS_RESTORING_BACKUP
|| ($this->transfer) !== null, ServerStateConflictException::class, $this);
}
/**
* @return Attribute<int, never>
*/
protected function adminIdentifier(): Attribute
{
return Attribute::make(get: fn (): int => $this->id);
}
/**
* Match a server by its full uuid or its eight-character short uuid.
*
* @param Builder<self> $query
*/
#[Scope]
protected function whereUuidOrShort(Builder $query, string $uuid): void
{
$query->where(fn (Builder $inner) => $inner->where('uuidShort', $uuid)->orWhere('uuid', $uuid));
}
2015-12-06 13:58:49 -05:00
}