2026-10-05 18:10:18 -04:00
<? php
declare ( strict_types = 1 );
namespace Pterodactyl\Actions\Servers ;
2026-10-12 00:09:41 -04:00
use Illuminate\Database\Eloquent\Builder ;
2026-10-05 18:10:18 -04:00
use Illuminate\Support\Collection ;
use Illuminate\Support\Facades\DB ;
use Illuminate\Support\Facades\Event ;
2026-10-11 08:45:00 -04:00
use Illuminate\Support\Facades\Validator ;
2026-10-11 23:18:58 -04:00
use Illuminate\Support\ValidatedInput ;
2026-10-11 08:45:00 -04:00
use Illuminate\Validation\Rule ;
use Pterodactyl\Actions\Allocations\CreateAllocations ;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Contracts\Servers\CreatesServers ;
use Pterodactyl\Contracts\Servers\DeletesServers ;
use Pterodactyl\Data\ValidatedEggVariable ;
use Pterodactyl\Events\Server\OperationCompleted ;
2026-10-12 01:07:41 -04:00
use Pterodactyl\Exceptions\DisplayException ;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException ;
2026-10-12 00:09:41 -04:00
use Pterodactyl\Exceptions\Service\Deployment\NoViableAllocationException ;
use Pterodactyl\Exceptions\Service\Deployment\NoViableNodeException ;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Facades\Daemon ;
use Pterodactyl\Models\Allocation ;
use Pterodactyl\Models\Egg ;
2026-10-12 00:09:41 -04:00
use Pterodactyl\Models\Node ;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Models\Objects\DeploymentObject ;
use Pterodactyl\Models\Server ;
use Pterodactyl\Models\ServerVariable ;
use Pterodactyl\Models\User ;
2026-10-09 06:26:45 +01:00
use Pterodactyl\Services\Extensions\ExtensionFields ;
use Pterodactyl\Services\Extensions\ValidatedExtensionValues ;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Services\Servers\VariableValidatorService ;
use Ramsey\Uuid\Uuid ;
2026-10-11 20:11:13 -04:00
use UnexpectedValueException ;
2026-10-05 18:10:18 -04:00
final readonly class CreateServer implements CreatesServers
{
public function __construct (
private DeletesServers $deleteServer ,
private VariableValidatorService $validatorService ,
2026-10-09 06:26:45 +01:00
private ExtensionFields $extensions ,
2026-10-05 18:10:18 -04:00
) {}
/**
2026-10-11 23:50:53 -04:00
* Memory, disk, CPU and the feature limits take 0 for unlimited, and swap takes -1. The CPU
* threads are a pattern of cores such as "0-1,3", which a bare number also matches. Pass a
* server being updated so its own external id is not taken for a duplicate.
2026-10-11 08:45:00 -04:00
*
* @return NormalizedValidationRules
*/
2026-10-11 09:04:02 -04:00
public static function rules ( ? Server $ignore = null ) : array
2026-10-11 08:45:00 -04:00
{
return [
2026-10-11 09:04:02 -04:00
'external_id' => [ 'sometimes' , 'nullable' , 'string' , 'between:1,191' , Rule :: unique ( 'servers' , 'external_id' ) -> ignore ( $ignore )],
2026-10-11 08:45:00 -04:00
'name' => [ 'required' , 'string' , 'min:1' , 'max:191' ],
'description' => [ 'nullable' , 'string' ],
'owner_id' => [ 'required' , 'integer' , 'exists:users,id' ],
'egg_id' => [ 'required' , 'integer' , 'exists:eggs,id' ],
'image' => [ 'required' , 'string' , 'max:191' , 'regex:/^~?[\w\.\/\-:@ ]*$/' ],
'startup' => [ 'required' , 'string' ],
'environment' => [ 'sometimes' , 'array' ],
'skip_scripts' => [ 'sometimes' , 'boolean' ],
'oom_disabled' => [ 'sometimes' , 'nullable' , 'boolean' ],
'memory' => [ 'required' , 'integer' , 'min:0' ],
'swap' => [ 'required' , 'integer' , 'min:-1' ],
'disk' => [ 'required' , 'integer' , 'min:0' ],
'io' => [ 'required' , 'integer' , 'between:10,1000' ],
'threads' => [ 'nullable' , 'regex:/^[0-9-,]+$/' ],
'cpu' => [ 'required' , 'integer' , 'min:0' ],
'database_limit' => [ 'sometimes' , 'nullable' , 'integer' , 'min:0' ],
'allocation_limit' => [ 'sometimes' , 'nullable' , 'integer' , 'min:0' ],
'backup_limit' => [ 'sometimes' , 'nullable' , 'integer' , 'min:0' ],
'allocation_id' => [ 'required' , 'integer' , 'bail' , CreateAllocations :: unassigned ()],
'allocation_additional' => [ 'sometimes' , 'nullable' , 'array' , 'list' ],
'allocation_additional.*' => [ 'integer' , CreateAllocations :: unassigned ()],
'start_on_completion' => [ 'sometimes' , 'boolean' ],
];
}
2026-10-11 23:18:58 -04:00
public function create ( array $input , ? DeploymentObject $deployment = null ) : Server
2026-10-11 08:45:00 -04:00
{
$rules = self :: rules ();
2026-10-11 23:18:58 -04:00
// A deployment picks the default allocation, so none is read from the input.
2026-10-11 08:45:00 -04:00
if ( $deployment instanceof DeploymentObject ) {
unset ( $rules [ 'allocation_id' ]);
}
2026-10-11 23:18:58 -04:00
$validated = Validator :: make ( $input , $rules ) -> safe ();
2026-10-11 08:45:00 -04:00
// Laravel's typed accessors would turn every value into one type, but the egg's
// variable rules have to see each value as it was sent.
2026-10-11 20:11:13 -04:00
$environment = [];
2026-10-11 23:18:58 -04:00
foreach ( $validated -> array ( 'environment' ) as $key => $value ) {
2026-10-11 20:11:13 -04:00
throw_unless ( is_string ( $key ) && ( $value === null || is_scalar ( $value )), UnexpectedValueException :: class , 'Server environment variables must map names to scalar values.' );
$environment [ $key ] = $value ;
}
2026-10-11 08:45:00 -04:00
$extensions = ValidatedExtensionValues :: of ( $input [ 'extensions' ] ?? null );
2026-10-05 18:10:18 -04:00
2026-10-11 23:18:58 -04:00
$egg = Egg :: query () -> with ( 'tags' ) -> findOrFail ( $validated -> integer ( 'egg_id' ));
2026-10-05 18:10:18 -04:00
// Resolve the egg first because its tags constrain which nodes are viable.
2026-10-11 08:45:00 -04:00
$allocation = $deployment instanceof DeploymentObject
2026-10-11 23:18:58 -04:00
? $this -> configureDeployment ( $validated , $deployment , $egg )
: Allocation :: query () -> findOrFail ( $validated -> integer ( 'allocation_id' ));
2026-10-05 18:10:18 -04:00
2026-10-12 00:21:31 -04:00
$eggVariableData = $this -> validatorService -> validate ( $egg , $environment , User :: USER_LEVEL_ADMIN );
2026-10-05 18:10:18 -04:00
// Wings requires the server to exist in the Panel before it can start creation.
2026-10-11 23:18:58 -04:00
$server = DB :: transaction ( function () use ( $validated , $allocation , $eggVariableData , $extensions ) : Server {
$server = $this -> createModel ( $validated , $allocation );
Allocation :: query () -> whereIn ( 'id' , [ $allocation -> id , ... $validated -> array ( 'allocation_additional' )]) -> update ([ 'server_id' => $server -> id ]);
2026-10-05 18:10:18 -04:00
$this -> storeEggVariables ( $server , $eggVariableData );
2026-10-11 08:45:00 -04:00
$this -> extensions -> save ( $server , $extensions );
2026-10-05 18:10:18 -04:00
return $server ;
}, 5 );
try {
2026-10-11 23:18:58 -04:00
Daemon :: server ( $server ) -> create ( $validated -> boolean ( 'start_on_completion' ));
2026-10-05 18:10:18 -04:00
} catch ( DaemonConnectionException $daemonConnectionException ) {
// Remove the persisted record even when Wings could not be reached.
$this -> deleteServer -> withForce () -> delete ( $server );
throw $daemonConnectionException ;
}
Event :: dispatch ( new OperationCompleted ( $server -> uuid , 'provision' , true , $server -> uuid ));
return $server ;
}
2026-10-11 23:18:58 -04:00
private function configureDeployment ( ValidatedInput $validated , DeploymentObject $deployment , Egg $egg ) : Allocation
2026-10-05 18:10:18 -04:00
{
2026-10-12 00:09:41 -04:00
$nodes = Node :: query ()
-> viableFor ( $validated -> integer ( 'memory' ), $validated -> integer ( 'disk' ))
-> inLocations ( $deployment -> getLocations ())
-> forEggTags ( $egg -> tagSlugs ())
-> forDeployTags ( $deployment -> getTags ())
-> get ()
-> map ( fn ( Node $node ) : int => $node -> id )
-> all ();
throw_if ( $nodes === [], NoViableNodeException :: class , trans ( 'exceptions.deployment.no_viable_nodes' ));
2026-10-12 01:07:41 -04:00
[ $ports , $ranges ] = $this -> parsePorts ( $deployment -> getPorts ());
2026-10-12 00:09:41 -04:00
return Allocation :: query ()
-> unassigned ()
-> onNodes ( $nodes )
2026-10-12 01:07:41 -04:00
-> onPorts ( $ports , $ranges )
2026-10-12 00:09:41 -04:00
-> when ( $deployment -> isDedicated (), fn ( Builder $query ) => $query -> onDedicatedIp ( $nodes ))
-> inRandomOrder ()
-> first () ?? throw new NoViableAllocationException ( trans ( 'exceptions.deployment.no_viable_allocations' ));
2026-10-05 18:10:18 -04:00
}
2026-10-12 01:07:41 -04:00
/**
* Splits deployment ports into single ports and [start, end] ranges. Entries that are
* neither are ignored.
*
* @param list<int|string> $ports
* @return array{list<int>, list<array{int, int}>}
*
* @throws DisplayException
*/
private function parsePorts ( array $ports ) : array
{
$single = [];
$ranges = [];
foreach ( $ports as $port ) {
if ( ctype_digit (( string ) $port )) {
$single [] = ( int ) $port ;
}
if ( preg_match ( CreateAllocations :: PORT_RANGE_REGEX , ( string ) $port , $matches )) {
throw_if ( abs ( $matches [ 2 ] - $matches [ 1 ]) > CreateAllocations :: PORT_RANGE_LIMIT , DisplayException :: class , trans ( 'exceptions.allocations.too_many_ports' ));
$ranges [] = [( int ) $matches [ 1 ], ( int ) $matches [ 2 ]];
}
}
return [ $single , $ranges ];
}
2026-10-11 23:18:58 -04:00
/**
* A server given no description gets an empty one, and a feature limit given as null or
* left out is 0. A server given no OOM flag, or null, has the OOM killer disabled.
*/
private function createModel ( ValidatedInput $validated , Allocation $allocation ) : Server
2026-10-05 18:10:18 -04:00
{
$uuid = $this -> generateUniqueUuidCombo ();
return Server :: query () -> create ([
2026-10-11 23:18:58 -04:00
'external_id' => $validated -> filled ( 'external_id' ) ? $validated [ 'external_id' ] : null ,
2026-10-05 18:10:18 -04:00
'uuid' => $uuid ,
'uuidShort' => mb_substr ( $uuid , 0 , 8 ),
2026-10-11 08:45:00 -04:00
'node_id' => $allocation -> node_id ,
2026-10-11 23:18:58 -04:00
'name' => $validated [ 'name' ],
'description' => $validated [ 'description' ] ?? '' ,
2026-10-05 18:10:18 -04:00
'status' => Server :: STATUS_INSTALLING ,
2026-10-11 23:18:58 -04:00
'skip_scripts' => $validated [ 'skip_scripts' ] ?? false ,
'owner_id' => $validated [ 'owner_id' ],
'memory' => $validated [ 'memory' ],
'swap' => $validated [ 'swap' ],
'disk' => $validated [ 'disk' ],
'io' => $validated [ 'io' ],
'cpu' => $validated [ 'cpu' ],
'threads' => $validated -> filled ( 'threads' ) ? $validated [ 'threads' ] : null ,
'oom_disabled' => $validated -> filled ( 'oom_disabled' ) ? $validated [ 'oom_disabled' ] : true ,
2026-10-11 08:45:00 -04:00
'allocation_id' => $allocation -> id ,
2026-10-11 23:18:58 -04:00
'egg_id' => $validated [ 'egg_id' ],
'startup' => $validated [ 'startup' ],
'image' => $validated [ 'image' ],
'database_limit' => $validated [ 'database_limit' ] ?? 0 ,
'allocation_limit' => $validated [ 'allocation_limit' ] ?? 0 ,
'backup_limit' => $validated [ 'backup_limit' ] ?? 0 ,
2026-10-05 18:10:18 -04:00
]) -> refresh ();
}
/** @param Collection<int, ValidatedEggVariable> $variables */
private function storeEggVariables ( Server $server , Collection $variables ) : void
{
$records = [];
foreach ( $variables as $result ) {
$records [] = [ 'server_id' => $server -> id , 'variable_id' => $result -> id , 'variable_value' => $result -> value ?? '' ];
}
if ( $records !== []) {
ServerVariable :: query () -> insert ( $records );
}
}
private function generateUniqueUuidCombo () : string
{
$uuid = Uuid :: uuid4 () -> toString ();
if ( Server :: query () -> where ( 'uuid' , $uuid ) -> orWhere ( 'uuidShort' , mb_substr ( $uuid , 0 , 8 )) -> exists ()) {
return $this -> generateUniqueUuidCombo ();
}
return $uuid ;
}
}