diff --git a/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php b/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php new file mode 100644 index 000000000..75645e9af --- /dev/null +++ b/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php @@ -0,0 +1,24 @@ +fractal->item($request->getModel(Server::class)) + ->transformWith($this->getTransformer(StatsTransformer::class)) + ->toArray(); + } +} diff --git a/app/Transformers/Api/Client/StatsTransformer.php b/app/Transformers/Api/Client/StatsTransformer.php new file mode 100644 index 000000000..01d8e3f20 --- /dev/null +++ b/app/Transformers/Api/Client/StatsTransformer.php @@ -0,0 +1,88 @@ +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'; + } + } +} diff --git a/routes/api-client.php b/routes/api-client.php index b1f4c1b1b..23c79fd40 100644 --- a/routes/api-client.php +++ b/routes/api-client.php @@ -22,6 +22,9 @@ Route::get('/', 'ClientController@index')->name('api.client.index'); */ Route::group(['prefix' => '/servers/{server}', 'middleware' => [AuthenticateClientAccess::class]], function () { Route::get('/', 'Servers\ServerController@index')->name('api.client.servers.view'); + Route::get('/utilization', 'Servers\ResourceUtilizationController@index') + ->middleware(['throttle:15,1']) + ->name('api.client.servers.resources'); Route::post('/command', 'Servers\CommandController@index')->name('api.client.servers.command'); Route::post('/power', 'Servers\PowerController@index')->name('api.client.servers.power');