Added Automatic Allocations

Known issues:
- Port range to auto create is hard coded
- React interface is still a WIP.
This commit is contained in:
Caleb 2020-09-28 11:50:34 -04:00
parent bcbd2c4996
commit 8f8bd0be83
8 changed files with 186 additions and 4 deletions

41
.env.bkup Normal file
View file

@ -0,0 +1,41 @@
APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:TdNqOn+57eXjhYF9xaM4WZZ0JAAyeGcHF/5dcclZhhk=
APP_THEME=pterodactyl
APP_TIMEZONE=America/Los_Angeles
APP_CLEAR_TASKLOG=720
APP_DELETE_MINUTES=10
APP_ENVIRONMENT_ONLY=false
LOG_CHANNEL=daily
APP_LOCALE=en
DB_HOST=127.0.0.1
DB_PORT=33060
DB_DATABASE=panel
DB_USERNAME=pterodactyl
DB_PASSWORD=pterodactyl
HASHIDS_SALT=g9nStpee2fwL2bUsfQqy
HASHIDS_LENGTH=8
MAIL_DRIVER=smtp
MAIL_HOST=host.pterodactyl.test
MAIL_PORT=1025
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM="outgoing@example.com"
QUEUE_HIGH=high
QUEUE_STANDARD=standard
QUEUE_LOW=low
APP_SERVICE_AUTHOR="you@example.com"
APP_URL="http://pterodactyl.test"
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
REDIS_HOST=host.pterodactyl.test
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_FROM_NAME="Pterodactyl Panel"

View file

@ -13,7 +13,10 @@ use Pterodactyl\Http\Controllers\Api\Client\ClientApiController;
use Pterodactyl\Http\Requests\Api\Client\Servers\Network\GetNetworkRequest;
use Pterodactyl\Http\Requests\Api\Client\Servers\Network\DeleteAllocationRequest;
use Pterodactyl\Http\Requests\Api\Client\Servers\Network\UpdateAllocationRequest;
use Pterodactyl\Http\Requests\Api\Client\Servers\Network\NewAllocationRequest;
use Pterodactyl\Http\Requests\Api\Client\Servers\Network\SetPrimaryAllocationRequest;
use Pterodactyl\Services\Allocations\AssignmentService;
use Illuminate\Support\Facades\Log;
class NetworkAllocationController extends ClientApiController
{
@ -27,20 +30,28 @@ class NetworkAllocationController extends ClientApiController
*/
private $serverRepository;
/**
* @var \Pterodactyl\Services\Allocations\AssignmentService
*/
protected $assignmentService;
/**
* NetworkController constructor.
*
* @param \Pterodactyl\Repositories\Eloquent\AllocationRepository $repository
* @param \Pterodactyl\Repositories\Eloquent\ServerRepository $serverRepository
* @param \Pterodactyl\Services\Allocations\AssignmentService $assignmentService
*/
public function __construct(
AllocationRepository $repository,
ServerRepository $serverRepository
ServerRepository $serverRepository,
AssignmentService $assignmentService
) {
parent::__construct();
$this->repository = $repository;
$this->serverRepository = $serverRepository;
$this->assignmentService = $assignmentService;
}
/**
@ -100,6 +111,66 @@ class NetworkAllocationController extends ClientApiController
->toArray();
}
/**
* Set the notes for the allocation for a server.
*s
* @param \Pterodactyl\Http\Requests\Api\Client\Servers\Network\NewAllocationRequest $request
* @param \Pterodactyl\Models\Server $server
* @param \Pterodactyl\Models\Allocation $allocation
* @return array
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function addNew(NewAllocationRequest $request, Server $server): array
{
Log::info('addNew()');
$topRange = 25700;
$bottomRange = 25565;
if($server->allocation_limit <= $server->allocations->count()) {
Log::error('You have created the maximum number of allocations!');
throw new DisplayException(
'You have created the maximum number of allocations!'
);
}
$allocation = $server->node->allocations()->where('ip',$server->allocation->ip)->whereNull('server_id')->first();
if(!$allocation) {
if($server->node->allocations()->where('ip',$server->allocation->ip)->count() >= $topRange-$bottomRange) {
Log::error('No allocations available!');
throw new DisplayException(
'No more allocations available!'
);
}
Log::info('Creating new allocation...');
$allPorts = $server->node->allocations()->select(['port'])->where('ip',$server->allocation->ip)->get()->pluck('port')->toArray();
do {
$port = rand($bottomRange, $topRange);
Log::info('Picking port....');
// TODO ADD ITERATOR THAT TIMES OUT AFTER SEARCHING FOR SO MUCH TIME?
} while(array_search($port, $allPorts));
$this->assignmentService->handle($server->node,[
'allocation_ip'=>$server->allocation->ip,
'allocation_ports'=>[$port],
'server_id'=>$server->id
]);
$allocation = $server->node->allocations()->where('ip',$server->allocation->ip)->where('port', $port)->first();
}
$allocation->update(['server_id' => $server->id]);
return $this->fractal->item($allocation)
->transformWith($this->getTransformer(AllocationTransformer::class))
->toArray();
}
/**
* Delete an allocation from a server.
*

View file

@ -0,0 +1,20 @@
<?php
namespace Pterodactyl\Http\Requests\Api\Client\Servers\Network;
use Illuminate\Support\Collection;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Permission;
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
class NewAllocationRequest extends ClientApiRequest
{
/**
* @return string
*/
public function permission(): string
{
return Permission::ACTION_ALLOCATION_CREATE;
}
}

View file

@ -0,0 +1,11 @@
import { Allocation } from '@/api/server/getServer';
import http from '@/api/http';
import { rawDataToServerAllocation } from '@/api/transformers';
export default (uuid: string): Promise<Allocation> => {
return new Promise((resolve, reject) => {
http.get(`/api/client/servers/${uuid}/network/allocations/new`)
.then(({ data }) => resolve(rawDataToServerAllocation(data)))
.catch(reject);
});
};

View file

@ -42,7 +42,7 @@ const AllocationRow = ({ allocation, onSetPrimary, onNotesChanged }: Props) => {
return (
<GreyRowBox
$hoverable={false}
// css={index > 0 ? tw`mt-2 overflow-x-auto` : tw`overflow-x-auto`}
css={tw`mt-2 overflow-x-auto`}
>
<div css={tw`hidden md:block pl-4 pr-6 text-neutral-400`}>
<FontAwesomeIcon icon={faNetworkWired}/>

View file

@ -1,4 +1,4 @@
import React, { useCallback, useEffect } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import useSWR from 'swr';
import getServerAllocations from '@/api/server/network/getServerAllocations';
import { Allocation } from '@/api/server/getServer';
@ -9,10 +9,15 @@ import { ServerContext } from '@/state/server';
import { useDeepMemoize } from '@/plugins/useDeepMemoize';
import AllocationRow from '@/components/server/network/AllocationRow';
import setPrimaryServerAllocation from '@/api/server/network/setPrimaryServerAllocation';
import Button from '@/components/elements/Button';
import newServerAllocation from '@/api/server/network/newServerAllocation';
import tw from 'twin.macro';
import GreyRowBox from '@/components/elements/GreyRowBox';
const NetworkContainer = () => {
const uuid = ServerContext.useStoreState(state => state.server.data!.uuid);
const allocations = useDeepMemoize(ServerContext.useStoreState(state => state.server.data!.allocations));
const [ addingAllocation, setAddingAllocation ] = useState(false);
const { clearFlashes, clearAndAddHttpError } = useFlash();
const { data, error, mutate } = useSWR<Allocation[]>(uuid, key => getServerAllocations(key), {
@ -39,6 +44,22 @@ const NetworkContainer = () => {
});
}, []);
const getNewAllocation = () => {
clearFlashes('server:network');
setAddingAllocation(true);
newServerAllocation(uuid)
.then(allocation => {
mutate(data => ({ ...data, items: data.concat(allocation) }), false);
setAddingAllocation(false);
})
.catch(error => {
clearAndAddHttpError({ key: 'server:network', error });
mutate(data, false);
setAddingAllocation(false);
});
};
const onNotesAdded = useCallback((id: number, notes: string) => {
mutate(data?.map(a => a.id === id ? { ...a, notes } : a), false);
}, []);
@ -57,6 +78,23 @@ const NetworkContainer = () => {
/>
))
}
<GreyRowBox
$hoverable={false}
css={tw`mt-2 overflow-x-auto flex items-center justify-center`}
>
{addingAllocation ?
<Spinner size={'base'} centered/>
:
<Button
color={'primary'}
isSecondary
onClick={() => getNewAllocation() }
css={tw`my-2`}
>
Add New Allocation
</Button>
}
</GreyRowBox>
</ServerContentBlock>
);
};

View file

@ -83,6 +83,7 @@ Route::group(['prefix' => '/servers/{server}', 'middleware' => [AuthenticateServ
Route::get('/allocations', 'Servers\NetworkAllocationController@index');
Route::post('/allocations/{allocation}', 'Servers\NetworkAllocationController@update');
Route::post('/allocations/{allocation}/primary', 'Servers\NetworkAllocationController@setPrimary');
Route::get('/allocations/new', 'Servers\NetworkAllocationController@addNew');
Route::delete('/allocations/{allocation}', 'Servers\NetworkAllocationController@delete');
});

View file

@ -112,7 +112,7 @@ module.exports = {
contentBase: path.join(__dirname, '/public'),
publicPath: (process.env.PUBLIC_PATH || '') + '/assets/',
allowedHosts: [
'.pterodactyl.test',
'pterodactyl.test',
],
headers: {
'Access-Control-Allow-Origin': '*',