Move server creation over to new service/repository setup.

Moves tons of functions around, but the basic implementation is working again.

Some features are still missing, and the service never actually commits the server to the database right now.

This push is mostly just to get the code into Github and backed up.
This commit is contained in:
Dane Everitt 2017-07-19 20:49:41 -05:00
parent 736a323eff
commit 0c513f24d5
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
35 changed files with 1398 additions and 44 deletions

View file

@ -37,6 +37,7 @@ class UuidService
* @param string $field
* @param int $type
* @return string
* @deprecated
*/
public function generate($table = 'users', $field = 'uuid', $type = 4)
{
@ -58,6 +59,7 @@ class UuidService
* @param string $field
* @param null|string $attachedUuid
* @return string
* @deprecated
*/
public function generateShort($table = 'servers', $field = 'uuidShort', $attachedUuid = null)
{

View file

@ -0,0 +1,106 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Services\Servers;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Models\Server;
class EnvironmentService
{
const ENVIRONMENT_CASTS = [
'STARTUP' => 'startup',
'P_SERVER_LOCATION' => 'location.short',
'P_SERVER_UUID' => 'uuid',
];
/**
* @var array
*/
protected $additional = [];
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
/**
* EnvironmentService constructor.
*
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository
*/
public function __construct(ServerRepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* Dynamically configure additional environment variables to be assigned
* with a specific server.
*
* @param string $key
* @param callable $closure
* @return $this
*/
public function setEnvironmentKey($key, callable $closure)
{
$this->additional[] = [$key, $closure];
return $this;
}
/**
* 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
* @return array
*/
public function process($server)
{
if (! $server instanceof Server) {
if (! is_numeric($server)) {
throw new \InvalidArgumentException(
'First argument passed to process() must be an instance of \\Pterodactyl\\Models\\Server or numeric.'
);
}
$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) {
$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);
}
return $variables;
}
}

View file

@ -0,0 +1,149 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Services\Servers;
use Ramsey\Uuid\Uuid;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface;
class ServerService
{
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface
*/
protected $allocationRepository;
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface
*/
protected $nodeRepository;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $userRepository;
protected $database;
protected $repository;
protected $usernameService;
protected $serverVariableRepository;
protected $daemonServerRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
protected $validatorService;
public function __construct(
AllocationRepositoryInterface $allocationRepository,
ConnectionInterface $database,
ServerRepositoryInterface $repository,
DaemonServerRepositoryInterface $daemonServerRepository,
ServerVariableRepositoryInterface $serverVariableRepository,
NodeRepositoryInterface $nodeRepository,
UsernameGenerationService $usernameService,
UserRepositoryInterface $userRepository,
VariableValidatorService $validatorService
) {
$this->allocationRepository = $allocationRepository;
$this->database = $database;
$this->repository = $repository;
$this->nodeRepository = $nodeRepository;
$this->userRepository = $userRepository;
$this->usernameService = $usernameService;
$this->validatorService = $validatorService;
$this->serverVariableRepository = $serverVariableRepository;
$this->daemonServerRepository = $daemonServerRepository;
}
public function create(array $data)
{
// @todo auto-deployment and packs
$data['user_id'] = 1;
$node = $this->nodeRepository->find($data['node_id']);
$validator = $this->validatorService->setAdmin()->setFields($data['environment'])->validate($data['option_id']);
$uniqueShort = bin2hex(random_bytes(4));
$this->database->beginTransaction();
$server = $this->repository->create([
'uuid' => Uuid::uuid4()->toString(),
'uuidShort' => bin2hex(random_bytes(4)),
'node_id' => $data['node_id'],
'name' => $data['name'],
'description' => $data['description'],
'skip_scripts' => isset($data['skip_scripts']),
'suspended' => false,
'owner_id' => $data['user_id'],
'memory' => $data['memory'],
'swap' => $data['swap'],
'disk' => $data['disk'],
'io' => $data['io'],
'cpu' => $data['cpu'],
'oom_disabled' => isset($data['oom_disabled']),
'allocation_id' => $data['allocation_id'],
'service_id' => $data['service_id'],
'option_id' => $data['option_id'],
'pack_id' => ($data['pack_id'] == 0) ? null : $data['pack_id'],
'startup' => $data['startup'],
'daemonSecret' => bin2hex(random_bytes(18)),
'image' => $data['docker_image'],
'username' => $this->usernameService->generate($data['name'], $uniqueShort),
'sftp_password' => null,
]);
// Process allocations and assign them to the server in the database.
$records = [$data['allocation_id']];
if (isset($data['allocation_additional']) && is_array($data['allocation_additional'])) {
$records = array_merge($records, $data['allocation_additional']);
}
$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->serverVariableRepository->insert($records);
// Create the server on the daemon & commit it to the database.
$this->daemonServerRepository->setNode($server->node_id)->setAccessToken($node->daemonSecret)->create($server->id);
$this->database->rollBack();
return $server;
}
}

View file

@ -0,0 +1,55 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Services\Servers;
class UsernameGenerationService
{
/**
* Generate a unique username to be used for SFTP connections and identification
* of the server docker container on the host system.
*
* @param string $name
* @param null $identifier
* @return string
*/
public function generate($name, $identifier = null)
{
if (is_null($identifier) || ! ctype_alnum($identifier)) {
$unique = bin2hex(random_bytes(4));
} else {
if (strlen($identifier) < 8) {
$unique = $identifier . str_random((8 - strlen($identifier)));
} else {
$unique = substr($identifier, 0, 8);
}
}
// Filter the Server Name
$name = trim(preg_replace('/[^\w]+/', '', $name), '_');
$name = (strlen($name) < 1) ? str_random(6) : $name;
return strtolower(substr($name, 0, 6) . '_' . $unique);
}
}

View file

@ -0,0 +1,173 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Services\Servers;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
use Pterodactyl\Exceptions\DisplayValidationException;
use Illuminate\Validation\Factory as ValidationFactory;
use Pterodactyl\Contracts\Repository\OptionVariableRepositoryInterface;
use Pterodactyl\Exceptions\Services\Servers\RequiredVariableMissingException;
class VariableValidatorService
{
/**
* @var bool
*/
protected $isAdmin = false;
/**
* @var array
*/
protected $fields = [];
/**
* @var array
*/
protected $results = [];
/**
* @var \Pterodactyl\Contracts\Repository\OptionVariableRepositoryInterface
*/
protected $optionVariableRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $serverRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface
*/
protected $serverVariableRepository;
/**
* @var \Illuminate\Validation\Factory
*/
protected $validator;
public function __construct(
OptionVariableRepositoryInterface $optionVariableRepository,
ServerRepositoryInterface $serverRepository,
ServerVariableRepositoryInterface $serverVariableRepository,
ValidationFactory $validator
) {
$this->optionVariableRepository = $optionVariableRepository;
$this->serverRepository = $serverRepository;
$this->serverVariableRepository = $serverVariableRepository;
$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.
*
* @return $this
*/
public function setAdmin()
{
$this->isAdmin = true;
return $this;
}
/**
* Validate all of the passed data aganist the given service option variables.
*
* @param int $option
* @return $this
*/
public function validate($option)
{
$variables = $this->optionVariableRepository->findWhere([['option_id', '=', $option]]);
if (count($variables) === 0) {
$this->results = [];
return $this;
}
$variables->each(function ($item) {
if (! isset($this->fields[$item->env_variable]) && $item->required) {
if ($item->required) {
throw new RequiredVariableMissingException(
sprintf('Required service option variable %s was missing from this request.', $item->env_variable)
);
}
}
// 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;
}
$validator = $this->validator->make([
'variable_value' => array_key_exists($item->env_variable, $this->fields) ? $this->fields[$item->env_variable] : null,
], [
'variable_value' => $item->rules,
]);
if ($validator->fails()) {
throw new DisplayValidationException(json_encode(
collect([
'notice' => [
sprintf('There was a validation error with the %s variable.', $item->name),
],
])->merge($validator->errors()->toArray())
));
}
$this->results[] = [
'id' => $item->id,
'key' => $item->env_variable,
'value' => $this->fields[$item->env_variable],
];
});
return $this;
}
/**
* Return the final results after everything has been validated.
*
* @return array
*/
public function getResults()
{
return $this->results;
}
}