Refactor startup modification and environment variable services

Better setup, more flexibility, more tests.
This commit is contained in:
Dane Everitt 2017-10-26 23:49:54 -05:00
parent 7022ec788f
commit fa62a0982e
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
19 changed files with 660 additions and 563 deletions

View file

@ -69,12 +69,11 @@ interface ServerRepositoryInterface extends RepositoryInterface, SearchableInter
/**
* Return enough data to be used for the creation of a server via the daemon.
*
* @param int $id
* @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
* @param \Pterodactyl\Models\Server $server
* @param bool $refresh
* @return \Pterodactyl\Models\Server
*/
public function getDataForCreation($id);
public function getDataForCreation(Server $server, bool $refresh = false): Server;
/**
* Return a server as well as associated databases and their hosts.

View file

@ -11,6 +11,7 @@ namespace Pterodactyl\Http\Controllers\Admin;
use Javascript;
use Illuminate\Http\Request;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Exceptions\DisplayException;
@ -570,10 +571,8 @@ class ServersController extends Controller
*/
public function saveStartup(Request $request, Server $server)
{
$this->startupModificationService->isAdmin()->handle(
$server,
$request->except('_token')
);
$this->startupModificationService->setUserLevel(User::USER_LEVEL_ADMIN);
$this->startupModificationService->handle($server, $request->except('_token'));
$this->alert->success(trans('admin/server.alerts.startup_changed'))->flash();
return redirect()->route('admin.servers.view.startup', $server->id);

View file

@ -3,6 +3,7 @@
namespace Pterodactyl\Http\Controllers\Server\Settings;
use Illuminate\Http\Request;
use Pterodactyl\Models\User;
use Illuminate\Http\RedirectResponse;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Http\Controllers\Controller;
@ -84,6 +85,7 @@ class StartupController extends Controller
*/
public function update(UpdateStartupParametersFormRequest $request): RedirectResponse
{
$this->modificationService->setUserLevel(User::USER_LEVEL_USER);
$this->modificationService->handle($request->attributes->get('server'), $request->normalize());
$this->alert->success(trans('server.config.startup.edited'))->flash();

View file

@ -20,6 +20,8 @@ class Node extends Model implements CleansAttributes, ValidableContract
{
use Eloquence, Notifiable, Validable;
const DAEMON_SECRET_LENGTH = 36;
/**
* The table associated with the model.
*

View file

@ -32,6 +32,9 @@ class User extends Model implements
{
use Authenticatable, Authorizable, CanResetPassword, Eloquence, Notifiable, Validable;
const USER_LEVEL_USER = 0;
const USER_LEVEL_ADMIN = 1;
/**
* Level of servers to display when using access() on a user.
*

View file

@ -137,16 +137,21 @@ class ServerRepository extends EloquentRepository implements ServerRepositoryInt
}
/**
* {@inheritdoc}
* Return enough data to be used for the creation of a server via the daemon.
*
* @param \Pterodactyl\Models\Server $server
* @param bool $refresh
* @return \Pterodactyl\Models\Server
*/
public function getDataForCreation($id)
public function getDataForCreation(Server $server, bool $refresh = false): Server
{
$instance = $this->getBuilder()->with(['allocation', 'allocations', 'pack', 'egg'])->find($id, $this->getColumns());
if (! $instance) {
throw new RecordNotFoundException();
foreach (['allocation', 'allocations', 'pack', 'egg'] as $relation) {
if (! $server->relationLoaded($relation) || $refresh) {
$server->load($relation);
}
}
return $instance;
return $server;
}
/**

View file

@ -1,42 +1,37 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Services\Servers;
use Pterodactyl\Models\Server;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
class EnvironmentService
{
const ENVIRONMENT_CASTS = [
'STARTUP' => 'startup',
'P_SERVER_LOCATION' => 'location.short',
'P_SERVER_UUID' => 'uuid',
];
/**
* @var array
*/
protected $additional = [];
private $additional = [];
/**
* @var \Illuminate\Contracts\Config\Repository
*/
private $config;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
private $repository;
/**
* EnvironmentService constructor.
*
* @param \Illuminate\Contracts\Config\Repository $config
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository
*/
public function __construct(ServerRepositoryInterface $repository)
public function __construct(ConfigRepository $config, ServerRepositoryInterface $repository)
{
$this->config = $config;
$this->repository = $repository;
}
@ -46,42 +41,70 @@ class EnvironmentService
*
* @param string $key
* @param callable $closure
* @return $this
*/
public function setEnvironmentKey($key, callable $closure)
public function setEnvironmentKey(string $key, callable $closure)
{
$this->additional[] = [$key, $closure];
$this->additional[$key] = $closure;
}
return $this;
/**
* Return the dynamically added additional keys.
*
* @return array
*/
public function getEnvironmentKeys(): array
{
return $this->additional;
}
/**
* Take all of the environment variables configured for this server and return
* them in an easy to process format.
*
* @param int|\Pterodactyl\Models\Server $server
* @param \Pterodactyl\Models\Server $server
* @return array
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function process($server)
public function handle(Server $server): array
{
if (! $server instanceof Server) {
$server = $this->repository->find($server);
}
$variables = $this->repository->getVariablesWithValues($server->id);
// Process static environment variables defined in this file.
foreach (self::ENVIRONMENT_CASTS as $key => $object) {
// Process environment variables defined in this file. This is done first
// in order to allow run-time and config defined variables to take
// priority over built-in values.
foreach ($this->getEnvironmentMappings() as $key => $object) {
$variables[$key] = object_get($server, $object);
}
// Process variables set in the configuration file.
foreach ($this->config->get('pterodactyl.environment_mappings', []) as $key => $object) {
if (is_callable($object)) {
$variables[$key] = call_user_func($object, $server);
} else {
$variables[$key] = object_get($server, $object);
}
}
// Process dynamically included environment variables.
foreach ($this->additional as $item) {
$variables[$item[0]] = call_user_func($item[1], $server);
foreach ($this->additional as $key => $closure) {
$variables[$key] = call_user_func($closure, $server);
}
return $variables;
}
/**
* Return a mapping of Panel default environment variables.
*
* @return array
*/
final private function getEnvironmentMappings(): array
{
return [
'STARTUP' => 'startup',
'P_SERVER_LOCATION' => 'location.short',
'P_SERVER_UUID' => 'uuid',
];
}
}

View file

@ -19,12 +19,12 @@ class ServerConfigurationStructureService
/**
* @var \Pterodactyl\Services\Servers\EnvironmentService
*/
protected $environment;
private $environment;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
private $repository;
/**
* ServerConfigurationStructureService constructor.
@ -41,19 +41,21 @@ class ServerConfigurationStructureService
}
/**
* @param int|\Pterodactyl\Models\Server $server
* Return a configuration array for a specific server when passed a server model.
*
* @param \Pterodactyl\Models\Server $server
* @return array
*
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle($server): array
public function handle(Server $server): array
{
if (! $server instanceof Server || array_diff(self::REQUIRED_RELATIONS, $server->getRelations())) {
$server = $this->repository->getDataForCreation(is_digit($server) ? $server : $server->id);
if (array_diff(self::REQUIRED_RELATIONS, $server->getRelations())) {
$server = $this->repository->getDataForCreation($server);
}
return [
'uuid' => $server->uuid,
'user' => $server->username,
'build' => [
'default' => [
'ip' => $server->allocation->ip,
@ -62,7 +64,7 @@ class ServerConfigurationStructureService
'ports' => $server->allocations->groupBy('ip')->map(function ($item) {
return $item->pluck('port');
})->toArray(),
'env' => $this->environment->process($server),
'env' => $this->environment->handle($server),
'memory' => (int) $server->memory,
'swap' => (int) $server->swap,
'io' => (int) $server->io,
@ -70,7 +72,6 @@ class ServerConfigurationStructureService
'disk' => (int) $server->disk,
'image' => $server->image,
],
'keys' => [],
'service' => [
'egg' => $server->egg->uuid,
'pack' => object_get($server, 'pack.uuid'),

View file

@ -1,18 +1,12 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Services\Servers;
use Ramsey\Uuid\Uuid;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\User;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Services\Nodes\NodeCreationService;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
@ -26,47 +20,47 @@ class ServerCreationService
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface
*/
protected $allocationRepository;
private $allocationRepository;
/**
* @var \Pterodactyl\Services\Servers\ServerConfigurationStructureService
*/
protected $configurationStructureService;
private $configurationStructureService;
/**
* @var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
private $connection;
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface
*/
protected $daemonServerRepository;
private $daemonServerRepository;
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface
*/
protected $nodeRepository;
private $nodeRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface
*/
protected $serverVariableRepository;
private $serverVariableRepository;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $userRepository;
private $userRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
protected $validatorService;
private $validatorService;
/**
* CreationService constructor.
@ -116,33 +110,30 @@ class ServerCreationService
public function create(array $data)
{
// @todo auto-deployment
$validator = $this->validatorService->isAdmin()->setFields($data['environment'])->validate($data['egg_id']);
$uniqueShort = str_random(8);
$this->connection->beginTransaction();
$server = $this->repository->create([
'uuid' => Uuid::uuid4()->toString(),
'uuidShort' => $uniqueShort,
'node_id' => $data['node_id'],
'name' => $data['name'],
'description' => $data['description'],
'uuidShort' => str_random(8),
'node_id' => array_get($data, 'node_id'),
'name' => array_get($data, 'name'),
'description' => array_get($data, 'description'),
'skip_scripts' => isset($data['skip_scripts']),
'suspended' => false,
'owner_id' => $data['owner_id'],
'memory' => $data['memory'],
'swap' => $data['swap'],
'disk' => $data['disk'],
'io' => $data['io'],
'cpu' => $data['cpu'],
'owner_id' => array_get($data, 'owner_id'),
'memory' => array_get($data, 'memory'),
'swap' => array_get($data, 'swap'),
'disk' => array_get($data, 'disk'),
'io' => array_get($data, 'io'),
'cpu' => array_get($data, 'cpu'),
'oom_disabled' => isset($data['oom_disabled']),
'allocation_id' => $data['allocation_id'],
'nest_id' => $data['nest_id'],
'egg_id' => $data['egg_id'],
'allocation_id' => array_get($data, 'allocation_id'),
'nest_id' => array_get($data, 'nest_id'),
'egg_id' => array_get($data, 'egg_id'),
'pack_id' => (! isset($data['pack_id']) || $data['pack_id'] == 0) ? null : $data['pack_id'],
'startup' => $data['startup'],
'daemonSecret' => str_random(NodeCreationService::DAEMON_SECRET_LENGTH),
'image' => $data['docker_image'],
'startup' => array_get($data, 'startup'),
'daemonSecret' => str_random(Node::DAEMON_SECRET_LENGTH),
'image' => array_get($data, 'docker_image'),
]);
// Process allocations and assign them to the server in the database.
@ -154,17 +145,21 @@ class ServerCreationService
$this->allocationRepository->assignAllocationsToServer($server->id, $records);
// Process the passed variables and store them in the database.
$records = [];
foreach ($validator->getResults() as $result) {
$records[] = [
'server_id' => $server->id,
'variable_id' => $result['id'],
'variable_value' => $result['value'],
];
}
$this->validatorService->setUserLevel(User::USER_LEVEL_ADMIN);
$results = $this->validatorService->handle(array_get($data, 'egg_id'), array_get($data, 'environment', []));
$this->serverVariableRepository->insert($records);
$structure = $this->configurationStructureService->handle($server->id);
$records = $results->map(function ($result) use ($server) {
return [
'server_id' => $server->id,
'variable_id' => $result->id,
'variable_value' => $result->value,
];
})->toArray();
if (! empty($records)) {
$this->serverVariableRepository->insert($records);
}
$structure = $this->configurationStructureService->handle($server);
// Create the server on the daemon & commit it to the database.
try {

View file

@ -1,17 +1,12 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Pterodactyl\Services\Servers;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Traits\Services\HasUserLevels;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Exceptions\Http\Connection\DaemonConnectionException;
use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
@ -19,40 +14,37 @@ use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonS
class StartupModificationService
{
/**
* @var bool
*/
protected $admin = false;
use HasUserLevels;
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface
*/
protected $daemonServerRepository;
private $daemonServerRepository;
/**
* @var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
private $connection;
/**
* @var \Pterodactyl\Services\Servers\EnvironmentService
*/
protected $environmentService;
private $environmentService;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface
*/
protected $serverVariableRepository;
private $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
protected $validatorService;
private $validatorService;
/**
* StartupModificationService constructor.
@ -80,81 +72,39 @@ class StartupModificationService
$this->validatorService = $validatorService;
}
/**
* Determine if this function should run at an administrative level.
*
* @param bool $bool
* @return $this
*/
public function isAdmin($bool = true)
{
$this->admin = $bool;
return $this;
}
/**
* Process startup modification for a server.
*
* @param int|\Pterodactyl\Models\Server $server
* @param array $data
* @param \Pterodactyl\Models\Server $server
* @param array $data
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle($server, array $data)
public function handle(Server $server, array $data)
{
if (! $server instanceof Server) {
$server = $this->repository->find($server);
}
if (
$server->nest_id != array_get($data, 'nest_id', $server->nest_id) ||
$server->egg_id != array_get($data, 'egg_id', $server->egg_id) ||
$server->pack_id != array_get($data, 'pack_id', $server->pack_id)
) {
$hasServiceChanges = true;
}
$this->connection->beginTransaction();
if (! is_null(array_get($data, 'environment'))) {
$validator = $this->validatorService->isAdmin($this->admin)
->setFields(array_get($data, 'environment', []))
->validate(array_get($data, 'egg_id', $server->egg_id));
$this->validatorService->setUserLevel($this->getUserLevel());
$results = $this->validatorService->handle(array_get($data, 'egg_id', $server->egg_id), array_get($data, 'environment', []));
foreach ($validator->getResults() as $result) {
$results->each(function ($result) use ($server) {
$this->serverVariableRepository->withoutFresh()->updateOrCreate([
'server_id' => $server->id,
'variable_id' => $result['id'],
'variable_id' => $result->id,
], [
'variable_value' => $result['value'],
'variable_value' => $result->value,
]);
}
});
}
$daemonData = [
'build' => [
'env|overwrite' => $this->environmentService->process($server),
],
];
$daemonData = ['build' => [
'env|overwrite' => $this->environmentService->handle($server),
]];
if ($this->admin) {
$server = $this->repository->update($server->id, [
'installed' => 0,
'startup' => array_get($data, 'startup', $server->startup),
'nest_id' => array_get($data, 'nest_id', $server->nest_id),
'egg_id' => array_get($data, 'egg_id', $server->egg_id),
'pack_id' => array_get($data, 'pack_id', $server->pack_id) > 0 ? array_get($data, 'pack_id', $server->pack_id) : null,
'skip_scripts' => isset($data['skip_scripts']),
]);
if (isset($hasServiceChanges)) {
$daemonData['service'] = array_merge(
$this->repository->withColumns(['id', 'egg_id', 'pack_id'])->getDaemonServiceData($server->id),
['skip_scripts' => isset($data['skip_scripts'])]
);
}
if ($this->isUserLevel(User::USER_LEVEL_ADMIN)) {
$this->updateAdministrativeSettings($data, $server, $daemonData);
}
try {
@ -166,4 +116,37 @@ class StartupModificationService
$this->connection->commit();
}
/**
* Update certain administrative settings for a server in the DB.
*
* @param array $data
* @param \Pterodactyl\Models\Server $server
* @param array $daemonData
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
private function updateAdministrativeSettings(array $data, Server &$server, array &$daemonData)
{
$server = $this->repository->update($server->id, [
'installed' => 0,
'startup' => array_get($data, 'startup', $server->startup),
'nest_id' => array_get($data, 'nest_id', $server->nest_id),
'egg_id' => array_get($data, 'egg_id', $server->egg_id),
'pack_id' => array_get($data, 'pack_id', $server->pack_id) > 0 ? array_get($data, 'pack_id', $server->pack_id) : null,
'skip_scripts' => isset($data['skip_scripts']),
]);
if (
$server->nest_id != array_get($data, 'nest_id', $server->nest_id) ||
$server->egg_id != array_get($data, 'egg_id', $server->egg_id) ||
$server->pack_id != array_get($data, 'pack_id', $server->pack_id)
) {
$daemonData['service'] = array_merge(
$this->repository->withColumns(['id', 'egg_id', 'pack_id'])->getDaemonServiceData($server->id),
['skip_scripts' => isset($data['skip_scripts'])]
);
}
}
}

View file

@ -9,6 +9,9 @@
namespace Pterodactyl\Services\Servers;
use Pterodactyl\Models\User;
use Illuminate\Support\Collection;
use Pterodactyl\Traits\Services\HasUserLevels;
use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
@ -17,20 +20,7 @@ use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
class VariableValidatorService
{
/**
* @var bool
*/
protected $isAdmin = false;
/**
* @var array
*/
protected $fields = [];
/**
* @var array
*/
protected $results = [];
use HasUserLevels;
/**
* @var \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface
@ -72,56 +62,26 @@ class VariableValidatorService
$this->validator = $validator;
}
/**
* Set the fields with populated data to validate.
*
* @param array $fields
* @return $this
*/
public function setFields(array $fields)
{
$this->fields = $fields;
return $this;
}
/**
* Set this function to be running at the administrative level.
*
* @param bool $bool
* @return $this
*/
public function isAdmin($bool = true)
{
$this->isAdmin = $bool;
return $this;
}
/**
* Validate all of the passed data aganist the given service option variables.
*
* @param int $option
* @return $this
* @param int $egg
* @param array $fields
* @return \Illuminate\Support\Collection
*/
public function validate($option)
public function handle(int $egg, array $fields = []): Collection
{
$variables = $this->optionVariableRepository->findWhere([['egg_id', '=', $option]]);
if (count($variables) === 0) {
$this->results = [];
$variables = $this->optionVariableRepository->findWhere([['egg_id', '=', $egg]]);
return $this;
}
$variables->each(function ($item) {
// Skip doing anything if user is not an admin and variable is not user viewable
// or editable.
if (! $this->isAdmin && (! $item->user_editable || ! $item->user_viewable)) {
return;
return $variables->map(function ($item) use ($fields) {
// Skip doing anything if user is not an admin and
// variable is not user viewable or editable.
if (! $this->isUserLevel(User::USER_LEVEL_ADMIN) && (! $item->user_editable || ! $item->user_viewable)) {
return false;
}
$validator = $this->validator->make([
'variable_value' => array_key_exists($item->env_variable, $this->fields) ? $this->fields[$item->env_variable] : null,
'variable_value' => array_get($fields, $item->env_variable),
], [
'variable_value' => $item->rules,
]);
@ -136,23 +96,13 @@ class VariableValidatorService
));
}
$this->results[] = [
return (object) [
'id' => $item->id,
'key' => $item->env_variable,
'value' => $this->fields[$item->env_variable],
'value' => array_get($fields, $item->env_variable),
];
})->filter(function ($item) {
return is_object($item);
});
return $this;
}
/**
* Return the final results after everything has been validated.
*
* @return array
*/
public function getResults()
{
return $this->results;
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace Pterodactyl\Traits\Services;
use Pterodactyl\Models\User;
trait HasUserLevels
{
/**
* @var int
*/
private $userLevel = User::USER_LEVEL_USER;
/**
* Set the access level for running this function.
*
* @param int $level
*/
public function setUserLevel(int $level)
{
$this->userLevel = $level;
}
/**
* Determine which level this function is running at.
*
* @return int
*/
public function getUserLevel(): int
{
return $this->userLevel;
}
/**
* Determine if the current user level is set to a specific level.
*
* @param int $level
* @return bool
*/
public function isUserLevel(int $level): bool
{
return $this->getUserLevel() === $level;
}
}