Merge branch 'develop' into feature/api-integration-testing

This commit is contained in:
Dane Everitt 2018-03-21 22:25:16 -05:00
commit bde4d4187f
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
61 changed files with 1017 additions and 453 deletions

View file

@ -0,0 +1,28 @@
<?php
namespace Pterodactyl\Console\Commands\Overrides;
use Illuminate\Foundation\Console\KeyGenerateCommand as BaseKeyGenerateCommand;
class KeyGenerateCommand extends BaseKeyGenerateCommand
{
/**
* Override the default Laravel key generation command to throw a warning to the user
* if it appears that they have already generated an application encryption key.
*/
public function handle()
{
if (! empty(config('app.key')) && $this->input->isInteractive()) {
$this->output->warning(trans('command/messages.key.warning'));
if (! $this->confirm(trans('command/messages.key.confirm'))) {
return;
}
if (! $this->confirm(trans('command/messages.key.final_confirm'))) {
return;
}
}
parent::handle();
}
}

View file

@ -2,9 +2,11 @@
namespace Pterodactyl\Exceptions;
use Log;
use Exception;
use Throwable;
use Psr\Log\LoggerInterface;
use Illuminate\Http\Response;
use Illuminate\Container\Container;
use Prologue\Alerts\AlertsMessageBag;
class DisplayException extends PterodactylException
@ -31,10 +33,6 @@ class DisplayException extends PterodactylException
{
parent::__construct($message, $code, $previous);
if (! is_null($previous)) {
Log::{$level}($previous);
}
$this->level = $level;
}
@ -70,8 +68,31 @@ class DisplayException extends PterodactylException
]), method_exists($this, 'getStatusCode') ? $this->getStatusCode() : Response::HTTP_BAD_REQUEST);
}
app()->make(AlertsMessageBag::class)->danger($this->getMessage())->flash();
Container::getInstance()->make(AlertsMessageBag::class)->danger($this->getMessage())->flash();
return redirect()->back()->withInput();
}
/**
* Log the exception to the logs using the defined error level only if the previous
* exception is set.
*
* @return mixed
*
* @throws \Exception
*/
public function report()
{
if (! $this->getPrevious() instanceof Exception || ! Handler::isReportable($this->getPrevious())) {
return null;
}
try {
$logger = Container::getInstance()->make(LoggerInterface::class);
} catch (Exception $ex) {
throw $this->getPrevious();
}
return $logger->{$this->getErrorLevel()}($this->getPrevious());
}
}

View file

@ -5,6 +5,7 @@ namespace Pterodactyl\Exceptions;
use Exception;
use PDOException;
use Psr\Log\LoggerInterface;
use Illuminate\Container\Container;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
@ -31,7 +32,6 @@ class Handler extends ExceptionHandler
protected $dontReport = [
AuthenticationException::class,
AuthorizationException::class,
DisplayException::class,
HttpException::class,
ModelNotFoundException::class,
RecordNotFoundException::class,
@ -210,6 +210,17 @@ class Handler extends ExceptionHandler
return ['errors' => [array_merge($error, $override)]];
}
/**
* Return an array of exceptions that should not be reported.
*
* @param \Exception $exception
* @return bool
*/
public static function isReportable(Exception $exception): bool
{
return (new static(Container::getInstance()))->shouldReport($exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*

View file

@ -0,0 +1,16 @@
<?php
namespace Pterodactyl\Exceptions\Service\Allocation;
use Pterodactyl\Exceptions\DisplayException;
class CidrOutOfRangeException extends DisplayException
{
/**
* CidrOutOfRangeException constructor.
*/
public function __construct()
{
parent::__construct(trans('exceptions.allocations.cidr_out_of_range'));
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Pterodactyl\Exceptions\Service\Allocation;
use Pterodactyl\Exceptions\DisplayException;
class InvalidPortMappingException extends DisplayException
{
/**
* InvalidPortMappingException constructor.
*
* @param mixed $port
*/
public function __construct($port)
{
parent::__construct(trans('exceptions.allocations.invalid_mapping', ['port' => $port]));
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Pterodactyl\Exceptions\Service\Allocation;
use Pterodactyl\Exceptions\DisplayException;
class PortOutOfRangeException extends DisplayException
{
/**
* PortOutOfRangeException constructor.
*/
public function __construct()
{
parent::__construct(trans('exceptions.allocations.port_out_of_range'));
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Pterodactyl\Exceptions\Service\Allocation;
use Pterodactyl\Exceptions\DisplayException;
class TooManyPortsInRangeException extends DisplayException
{
/**
* TooManyPortsInRangeException constructor.
*/
public function __construct()
{
parent::__construct(trans('exceptions.allocations.too_many_ports'));
}
}

View file

@ -0,0 +1,9 @@
<?php
namespace Pterodactyl\Exceptions\Service\Egg\Variable;
use Pterodactyl\Exceptions\DisplayException;
class BadValidationRuleException extends DisplayException
{
}

View file

@ -331,7 +331,10 @@ class NodesController extends Controller
* @param int|\Pterodactyl\Models\Node $node
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Service\Allocation\CidrOutOfRangeException
* @throws \Pterodactyl\Exceptions\Service\Allocation\InvalidPortMappingException
* @throws \Pterodactyl\Exceptions\Service\Allocation\PortOutOfRangeException
* @throws \Pterodactyl\Exceptions\Service\Allocation\TooManyPortsInRangeException
*/
public function createAllocation(AllocationFormRequest $request, Node $node)
{

View file

@ -73,7 +73,10 @@ class AllocationController extends ApplicationApiController
* @param \Pterodactyl\Http\Requests\Api\Application\Allocations\StoreAllocationRequest $request
* @return array
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Service\Allocation\CidrOutOfRangeException
* @throws \Pterodactyl\Exceptions\Service\Allocation\InvalidPortMappingException
* @throws \Pterodactyl\Exceptions\Service\Allocation\PortOutOfRangeException
* @throws \Pterodactyl\Exceptions\Service\Allocation\TooManyPortsInRangeException
*/
public function store(StoreAllocationRequest $request): array
{

View file

@ -0,0 +1,24 @@
<?php
namespace Pterodactyl\Http\Controllers\Api\Client\Servers;
use Pterodactyl\Models\Server;
use Pterodactyl\Transformers\Api\Client\StatsTransformer;
use Pterodactyl\Http\Controllers\Api\Client\ClientApiController;
use Pterodactyl\Http\Requests\Api\Client\Servers\GetServerRequest;
class ResourceUtilizationController extends ClientApiController
{
/**
* Return the current resource utilization for a server.
*
* @param \Pterodactyl\Http\Requests\Api\Client\Servers\GetServerRequest $request
* @return array
*/
public function index(GetServerRequest $request): array
{
return $this->fractal->item($request->getModel(Server::class))
->transformWith($this->getTransformer(StatsTransformer::class))
->toArray();
}
}

View file

@ -4,6 +4,8 @@ namespace Pterodactyl\Http\Controllers\Base;
use Illuminate\Http\Request;
use Pterodactyl\Models\User;
use Illuminate\Http\Response;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Pterodactyl\Http\Controllers\Controller;
use Symfony\Component\HttpKernel\Exception\HttpException;
@ -81,6 +83,8 @@ class IndexController extends Controller
try {
$response = $this->daemonRepository->setServer($server)->setToken($token)->details();
} catch (ConnectException $exception) {
throw new HttpException(Response::HTTP_GATEWAY_TIMEOUT, $exception->getMessage());
} catch (RequestException $exception) {
throw new HttpException(500, $exception->getMessage());
}

View file

@ -0,0 +1,59 @@
<?php
namespace Pterodactyl\Http\Controllers\Server\Settings;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Traits\Controllers\JavascriptInjection;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Http\Requests\Server\Settings\ChangeServerNameRequest;
class NameController extends Controller
{
use JavascriptInjection;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
private $repository;
/**
* NameController constructor.
*
* @param \Pterodactyl\Contracts\Repository\ServerRepositoryInterface $repository
*/
public function __construct(ServerRepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function index(Request $request)
{
$this->authorize('view-name', $request->attributes->get('server'));
$this->setRequest($request)->injectJavascript();
return view('server.settings.name');
}
/**
* Update the stored name for a specific server.
*
* @param \Pterodactyl\Http\Requests\Server\Settings\ChangeServerNameRequest $request
* @return \Illuminate\Http\RedirectResponse
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function update(ChangeServerNameRequest $request): RedirectResponse
{
$this->repository->update($request->getServer()->id, $request->validated());
return redirect()->route('server.settings.name', $request->getServer()->uuidShort);
}
}

View file

@ -16,9 +16,12 @@ class SftpController extends Controller
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\View\View
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function index(Request $request): View
{
$this->authorize('access-sftp', $request->attributes->get('server'));
$this->setRequest($request)->injectJavascript();
return view('server.settings.sftp');

View file

@ -41,7 +41,7 @@ class SetSessionDriver
*/
public function handle(Request $request, Closure $next)
{
if ($this->app->environment() !== 'production') {
if ($this->config->get('app.debug')) {
$this->app->make(LaravelDebugbar::class)->disable();
}

View file

@ -0,0 +1,31 @@
<?php
namespace Pterodactyl\Http\Requests\Server\Settings;
use Pterodactyl\Models\Server;
use Pterodactyl\Http\Requests\Server\ServerFormRequest;
class ChangeServerNameRequest extends ServerFormRequest
{
/**
* Permission to use when checking if a user can access this resource.
*
* @return string
*/
protected function permission(): string
{
return 'edit-name';
}
/**
* Rules to use when validating the submitted data.
*
* @return array
*/
public function rules()
{
return [
'name' => Server::getCreateRules()['name'],
];
}
}

View file

@ -113,7 +113,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getCopyScriptInstallAttribute()
{
return (is_null($this->copy_script_from)) ? $this->script_install : $this->scriptFrom->script_install;
if (! is_null($this->script_install) || is_null($this->copy_script_from)) {
return $this->script_install;
}
return $this->scriptFrom->script_install;
}
/**
@ -124,7 +128,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getCopyScriptEntryAttribute()
{
return (is_null($this->copy_script_from)) ? $this->script_entry : $this->scriptFrom->script_entry;
if (! is_null($this->script_entry) || is_null($this->copy_script_from)) {
return $this->script_entry;
}
return $this->scriptFrom->script_entry;
}
/**
@ -135,7 +143,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getCopyScriptContainerAttribute()
{
return (is_null($this->copy_script_from)) ? $this->script_container : $this->scriptFrom->script_container;
if (! is_null($this->script_container) || is_null($this->copy_script_from)) {
return $this->script_container;
}
return $this->scriptFrom->script_container;
}
/**
@ -145,7 +157,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getInheritConfigFilesAttribute()
{
return is_null($this->config_from) ? $this->config_files : $this->configFrom->config_files;
if (! is_null($this->config_files) || is_null($this->config_from)) {
return $this->config_files;
}
return $this->configFrom->config_files;
}
/**
@ -155,7 +171,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getInheritConfigStartupAttribute()
{
return is_null($this->config_from) ? $this->config_startup : $this->configFrom->config_startup;
if (! is_null($this->config_startup) || is_null($this->config_from)) {
return $this->config_startup;
}
return $this->configFrom->config_startup;
}
/**
@ -165,7 +185,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getInheritConfigLogsAttribute()
{
return is_null($this->config_from) ? $this->config_logs : $this->configFrom->config_logs;
if (! is_null($this->config_logs) || is_null($this->config_from)) {
return $this->config_logs;
}
return $this->configFrom->config_logs;
}
/**
@ -175,7 +199,11 @@ class Egg extends Model implements CleansAttributes, ValidableContract
*/
public function getInheritConfigStopAttribute()
{
return is_null($this->config_from) ? $this->config_stop : $this->configFrom->config_stop;
if (! is_null($this->config_stop) || is_null($this->config_from)) {
return $this->config_stop;
}
return $this->configFrom->config_stop;
}
/**

View file

@ -164,7 +164,7 @@ class Node extends Model implements CleansAttributes, ValidableContract
'enabled' => true,
'kill_at_count' => 5,
'decay' => 10,
'bytes' => 30720,
'lines' => 1000,
'check_interval_ms' => 100,
],
],

View file

@ -1,26 +1,24 @@
<?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\Allocations;
use IPTools\Network;
use Pterodactyl\Models\Node;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Exceptions\Service\Allocation\CidrOutOfRangeException;
use Pterodactyl\Exceptions\Service\Allocation\PortOutOfRangeException;
use Pterodactyl\Exceptions\Service\Allocation\InvalidPortMappingException;
use Pterodactyl\Exceptions\Service\Allocation\TooManyPortsInRangeException;
class AssignmentService
{
const CIDR_MAX_BITS = 27;
const CIDR_MIN_BITS = 32;
const PORT_FLOOR = 1024;
const PORT_CEIL = 65535;
const PORT_RANGE_LIMIT = 1000;
const PORT_RANGE_REGEX = '/^(\d{1,5})-(\d{1,5})$/';
const PORT_RANGE_REGEX = '/^(\d{4,5})-(\d{4,5})$/';
/**
* @var \Illuminate\Database\ConnectionInterface
@ -38,10 +36,8 @@ class AssignmentService
* @param \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface $repository
* @param \Illuminate\Database\ConnectionInterface $connection
*/
public function __construct(
AllocationRepositoryInterface $repository,
ConnectionInterface $connection
) {
public function __construct(AllocationRepositoryInterface $repository, ConnectionInterface $connection)
{
$this->connection = $connection;
$this->repository = $repository;
}
@ -49,21 +45,20 @@ class AssignmentService
/**
* Insert allocations into the database and link them to a specific node.
*
* @param int|\Pterodactyl\Models\Node $node
* @param array $data
* @param \Pterodactyl\Models\Node $node
* @param array $data
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Service\Allocation\CidrOutOfRangeException
* @throws \Pterodactyl\Exceptions\Service\Allocation\PortOutOfRangeException
* @throws \Pterodactyl\Exceptions\Service\Allocation\InvalidPortMappingException
* @throws \Pterodactyl\Exceptions\Service\Allocation\TooManyPortsInRangeException
*/
public function handle($node, array $data)
public function handle(Node $node, array $data)
{
if ($node instanceof Node) {
$node = $node->id;
}
$explode = explode('/', $data['allocation_ip']);
if (count($explode) !== 1) {
if (! ctype_digit($explode[1]) || ($explode[1] > self::CIDR_MIN_BITS || $explode[1] < self::CIDR_MAX_BITS)) {
throw new DisplayException(trans('exceptions.allocations.cidr_out_of_range'));
throw new CidrOutOfRangeException;
}
}
@ -71,7 +66,7 @@ class AssignmentService
foreach (Network::parse(gethostbyname($data['allocation_ip'])) as $ip) {
foreach ($data['allocation_ports'] as $port) {
if (! is_digit($port) && ! preg_match(self::PORT_RANGE_REGEX, $port)) {
throw new DisplayException(trans('exceptions.allocations.invalid_mapping', ['port' => $port]));
throw new InvalidPortMappingException($port);
}
$insertData = [];
@ -79,12 +74,16 @@ class AssignmentService
$block = range($matches[1], $matches[2]);
if (count($block) > self::PORT_RANGE_LIMIT) {
throw new DisplayException(trans('exceptions.allocations.too_many_ports'));
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,
'node_id' => $node->id,
'ip' => $ip->__toString(),
'port' => (int) $unit,
'ip_alias' => array_get($data, 'allocation_alias'),
@ -92,8 +91,12 @@ class AssignmentService
];
}
} else {
if ((int) $port <= self::PORT_FLOOR || (int) $port > self::PORT_CEIL) {
throw new PortOutOfRangeException;
}
$insertData[] = [
'node_id' => $node,
'node_id' => $node->id,
'ip' => $ip->__toString(),
'port' => (int) $port,
'ip_alias' => array_get($data, 'allocation_alias'),

View file

@ -3,24 +3,46 @@
namespace Pterodactyl\Services\Eggs\Variables;
use Pterodactyl\Models\EggVariable;
use Illuminate\Contracts\Validation\Factory;
use Pterodactyl\Traits\Services\ValidatesValidationRules;
use Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface;
use Pterodactyl\Exceptions\Service\Egg\Variable\ReservedVariableNameException;
class VariableCreationService
{
use ValidatesValidationRules;
/**
* @var \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface
*/
protected $repository;
private $repository;
/**
* @var \Illuminate\Contracts\Validation\Factory
*/
private $validator;
/**
* VariableCreationService constructor.
*
* @param \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface $repository
* @param \Illuminate\Contracts\Validation\Factory $validator
*/
public function __construct(EggVariableRepositoryInterface $repository)
public function __construct(EggVariableRepositoryInterface $repository, Factory $validator)
{
$this->repository = $repository;
$this->validator = $validator;
}
/**
* Return the validation factory instance to be used by rule validation
* checking in the trait.
*
* @return \Illuminate\Contracts\Validation\Factory
*/
protected function getValidator(): Factory
{
return $this->validator;
}
/**
@ -31,6 +53,7 @@ class VariableCreationService
* @return \Pterodactyl\Models\EggVariable
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Service\Egg\Variable\BadValidationRuleException
* @throws \Pterodactyl\Exceptions\Service\Egg\Variable\ReservedVariableNameException
*/
public function handle(int $egg, array $data): EggVariable
@ -42,6 +65,10 @@ class VariableCreationService
));
}
if (! empty($data['rules'] ?? '')) {
$this->validateRules($data['rules']);
}
$options = array_get($data, 'options') ?? [];
return $this->repository->create([

View file

@ -3,25 +3,47 @@
namespace Pterodactyl\Services\Eggs\Variables;
use Pterodactyl\Models\EggVariable;
use Illuminate\Contracts\Validation\Factory;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Traits\Services\ValidatesValidationRules;
use Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface;
use Pterodactyl\Exceptions\Service\Egg\Variable\ReservedVariableNameException;
class VariableUpdateService
{
use ValidatesValidationRules;
/**
* @var \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface
*/
protected $repository;
private $repository;
/**
* @var \Illuminate\Contracts\Validation\Factory
*/
private $validator;
/**
* VariableUpdateService constructor.
*
* @param \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface $repository
* @param \Illuminate\Contracts\Validation\Factory $validator
*/
public function __construct(EggVariableRepositoryInterface $repository)
public function __construct(EggVariableRepositoryInterface $repository, Factory $validator)
{
$this->repository = $repository;
$this->validator = $validator;
}
/**
* Return the validation factory instance to be used by rule validation
* checking in the trait.
*
* @return \Illuminate\Contracts\Validation\Factory
*/
protected function getValidator(): Factory
{
return $this->validator;
}
/**
@ -58,6 +80,10 @@ class VariableUpdateService
}
}
if (! empty($data['rules'] ?? '')) {
$this->validateRules($data['rules']);
}
$options = array_get($data, 'options') ?? [];
return $this->repository->withoutFreshModel()->update($variable->id, [

View file

@ -105,7 +105,7 @@ class StartupModificationService
'server_id' => $server->id,
'variable_id' => $result->id,
], [
'variable_value' => $result->value,
'variable_value' => $result->value ?? '',
]);
});
}

View file

@ -0,0 +1,40 @@
<?php
namespace Pterodactyl\Traits\Services;
use BadMethodCallException;
use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Factory;
use Pterodactyl\Exceptions\Service\Egg\Variable\BadValidationRuleException;
trait ValidatesValidationRules
{
/**
* @return \Illuminate\Contracts\Validation\Factory
*/
abstract protected function getValidator(): Factory;
/**
* Validate that the rules being provided are valid for Laravel and can
* be resolved.
*
* @param array|string $rules
*
* @throws \Pterodactyl\Exceptions\Service\Egg\Variable\BadValidationRuleException
*/
public function validateRules($rules)
{
try {
$this->getValidator()->make(['__TEST' => 'test'], ['__TEST' => $rules])->fails();
} catch (BadMethodCallException $exception) {
$matches = [];
if (preg_match('/Method \[(.+)\] does not exist\./', $exception->getMessage(), $matches)) {
throw new BadValidationRuleException(trans('exceptions.nest.variables.bad_validation_rule', [
'rule' => Str::snake(str_replace('validate', '', array_get($matches, 1, 'unknownRule'))),
]), $exception);
}
throw $exception;
}
}
}

View file

@ -0,0 +1,88 @@
<?php
namespace Pterodactyl\Transformers\Api\Client;
use Pterodactyl\Models\Server;
use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface;
class StatsTransformer extends BaseClientTransformer
{
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface
*/
private $repository;
/**
* Perform dependency injection.
*
* @param \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface $repository
*/
public function handle(ServerRepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* @return string
*/
public function getResourceName(): string
{
return 'stats';
}
/**
* Transform stats from the daemon into a result set that can be used in
* the client API.
*
* @param \Pterodactyl\Models\Server $model
* @return array
*/
public function transform(Server $model)
{
try {
$stats = $this->repository->setServer($model)->details();
} catch (RequestException $exception) {
throw new DaemonConnectionException($exception);
}
$object = json_decode($stats->getBody()->getContents());
return [
'state' => $this->transformState(object_get($object, 'status', 0)),
'memory' => [
'current' => round(object_get($object, 'proc.memory.total', 0) / 1024 / 1024),
'limit' => floatval($model->memory),
],
'cpu' => [
'current' => object_get($object, 'proc.cpu.total', 0),
'cores' => object_get($object, 'proc.cpu.cores', []),
'limit' => floatval($model->cpu),
],
'disk' => [
'current' => round(object_get($object, 'proc.disk.used', 0)),
'limit' => floatval($model->disk),
],
];
}
/**
* Transform the state returned by the daemon into a human readable string.
*
* @param int $state
* @return string
*/
private function transformState(int $state): string
{
switch ($state) {
case 1:
return 'on';
case 2:
return 'starting';
case 3:
return 'stopping';
case 0:
default:
return 'off';
}
}
}