Improved database mechanics in admin CP for server view

This commit is contained in:
Dane Everitt 2017-03-05 16:37:38 -05:00
parent 16aaf531d6
commit 32dec97e46
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
6 changed files with 357 additions and 119 deletions

View file

@ -211,7 +211,10 @@ class ServersController extends Controller
{
$server = Models\Server::where('installed', 1)->with('databases.host')->findOrFail($id);
return view('admin.servers.view.build', ['server' => $server]);
return view('admin.servers.view.database', [
'hosts' => Models\DatabaseServer::all(),
'server' => $server
]);
}
/**
@ -503,29 +506,73 @@ class ServersController extends Controller
return redirect()->route('admin.servers.view.startup', $id);
}
//
// public function postDatabase(Request $request, $id)
// {
// try {
// $repo = new DatabaseRepository;
// $repo->create($id, $request->only([
// 'db_server', 'database', 'remote',
// ]));
// Alert::success('Added new database to this server.')->flash();
// } catch (DisplayValidationException $ex) {
// return redirect()->route('admin.servers.view', [
// 'id' => $id,
// 'tab' => 'tab_database',
// ])->withInput()->withErrors(json_decode($ex->getMessage()))->withInput();
// } catch (\Exception $ex) {
// Log::error($ex);
// Alert::danger('An exception occured while attempting to add a new database for this server.')->flash();
// }
//
// return redirect()->route('admin.servers.view', [
// 'id' => $id,
// 'tab' => 'tab_database',
// ])->withInput();
// }
// //
/**
* Creates a new database assigned to a specific server.
* @param Request $request
* @param int $id
* @return \Illuminate\Response\RedirectResponse
*/
public function newDatabase(Request $request, $id)
{
$repo = new DatabaseRepository;
try {
$repo->create($id, $request->only(['host', 'database', 'connection']));
Alert::success('A new database was assigned to this server successfully.')->flash();
} catch (DisplayValidationException $ex) {
return redirect()->route('admin.servers.view.database', $id)->withInput()->withErrors(json_decode($ex->getMessage()))->withInput();
} catch(DisplayException $ex) {
Alert::danger($ex->getMessage())->flash();
} catch (\Exception $ex) {
Log::error($ex);
Alert::danger('An exception occured while attempting to add a new database for this server. This error has been logged.')->flash();
}
return redirect()->route('admin.servers.view.database', $id)->withInput();
}
/**
* Resets the database password for a specific database on this server.
* @param Request $request
* @param int $id
* @return \Illuminate\Response\RedirectResponse
*/
public function resetDatabasePassword(Request $request, $id)
{
$database = Models\Database::where('server_id', $id)->findOrFail($request->input('database'));
$repo = new DatabaseRepository;
try {
$repo->password($database->id, str_random(20));
return response('', 204);
} catch (\Exception $ex) {
Log::error($ex);
return response()->json(['error' => 'A unhandled exception occurred while attempting to reset this password. This error has been logged.'], 503);
}
}
/**
* Deletes a database from a server.
* @param Request $request
* @param int $id
* @return \Illuminate\Response\RedirectResponse
*/
public function deleteDatabase(Request $request, $id, $database)
{
$database = Models\Database::where('server_id', $id)->findOrFail($database);
$repo = new DatabaseRepository;
try {
$repo->drop($database->id);
return response('', 204);
} catch (\Exception $ex) {
Log::error($ex);
return response()->json(['error' => 'A unhandled exception occurred while attempting to drop this database. This error has been logged.'], 503);
}
}
}

View file

@ -183,6 +183,19 @@ class AdminRoutes
'uses' => 'Admin\ServersController@viewDatabase',
]);
$router->post('/view/{id}/database', [
'uses' => 'Admin\ServersController@newDatabase',
]);
$router->patch('/view/{id}/database', [
'uses' => 'Admin\ServersController@resetDatabasePassword',
]);
$router->delete('/view/{id}/database/{database}/delete', [
'as' => 'admin.servers.view.database.delete',
'uses' => 'Admin\ServersController@deleteDatabase',
]);
$router->get('/view/{id}/manage', [
'as' => 'admin.servers.view.manage',
'uses' => 'Admin\ServersController@viewManage',

View file

@ -26,89 +26,98 @@ namespace Pterodactyl\Repositories;
use DB;
use Crypt;
use Config;
use Validator;
use Pterodactyl\Models;
use Pterodactyl\Exceptions\DisplayException;
use Illuminate\Database\Capsule\Manager as Capsule;
use Pterodactyl\Exceptions\DisplayValidationException;
class DatabaseRepository
{
/**
* Adds a new database to a given database server.
* Adds a new database to a specified database host server.
*
* @param int $server Id of the server to add a database for.
* @param array $options Array of options for creating that database.
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\DisplayValidationException
* @throws \Exception
* @return void
*/
public function create($server, $options)
public function create($server, $data)
{
$server = Models\Server::findOrFail($server);
$validator = Validator::make($options, [
'db_server' => 'required|exists:database_servers,id',
$validator = Validator::make($data, [
'host' => 'required|exists:database_servers,id',
'database' => 'required|regex:/^\w{1,100}$/',
'remote' => 'required|regex:/^[0-9%.]{1,15}$/',
'connection' => 'required|regex:/^[0-9%.]{1,15}$/',
]);
if ($validator->fails()) {
throw new DisplayValidationException($validator->errors());
}
$host = Models\DatabaseServer::findOrFail($data['host']);
DB::beginTransaction();
try {
$db = new Models\Database;
$db->fill([
$database = Models\Database::firstOrNew([
'server_id' => $server->id,
'db_server' => $options['db_server'],
'database' => "s{$server->id}_{$options['database']}",
'username' => $server->uuidShort . '_' . str_random(7),
'remote' => $options['remote'],
'password' => Crypt::encrypt(str_random(20)),
]);
$db->save();
// Contact Remote
$dbr = Models\DatabaseServer::findOrFail($options['db_server']);
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => $dbr->host,
'port' => $dbr->port,
'database' => 'mysql',
'username' => $dbr->username,
'password' => Crypt::decrypt($dbr->password),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
],
'db_server' => $data['host'],
'database' => sprintf('s%d_%s', $server->id, $data['database']),
]);
$capsule->setAsGlobal();
if ($database->exists) {
throw new DisplayException('A database with those details already exists in the system.');
}
$database->username = sprintf('s%d_%s', $server->id, str_random(10));
$database->remote = $data['connection'];
$database->password = Crypt::encrypt(str_random(20));
$database->save();
} catch (\Exception $ex) {
DB::rollBack();
throw new DisplayException('There was an error while connecting to the Database Host Server. Please check the error logs.', $ex);
throw $ex;
}
Config::set('database.connections.dynamic', [
'driver' => 'mysql',
'host' => $host->host,
'port' => $host->port,
'database' => 'mysql',
'username' => $host->username,
'password' => Crypt::decrypt($host->password),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
]);
try {
Capsule::statement('CREATE DATABASE `' . $db->database . '`');
Capsule::statement('CREATE USER `' . $db->username . '`@`' . $db->remote . '` IDENTIFIED BY \'' . Crypt::decrypt($db->password) . '\'');
Capsule::statement('GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX ON `' . $db->database . '`.* TO `' . $db->username . '`@`' . $db->remote . '`');
Capsule::statement('FLUSH PRIVILEGES');
DB::connection('dynamic')->statement(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database->database));
DB::connection('dynamic')->statement(sprintf(
'CREATE USER `%s`@`%s` IDENTIFIED BY \'%s\'',
$database->username, $database->remote, Crypt::decrypt($database->password)
));
DB::connection('dynamic')->statement(sprintf(
'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX ON `%s`.* TO `%s`@`%s`',
$database->database, $database->username, $database->remote
));
DB::connection('dynamic')->statement('FLUSH PRIVILEGES');
// Save Everything
DB::commit();
} catch (\Exception $ex) {
try {
Capsule::statement('DROP DATABASE `' . $db->database . '`');
Capsule::statement('DROP USER `' . $db->username . '`@`' . $db->remote . '`');
} catch (\Exception $exi) {
// ignore it, if it fails its probably
// because we failed to ever make the DB
// or the user on the system.
} finally {
DB::rollBack();
throw $ex;
}
DB::connection('dynamic')->statement(sprintf('DROP DATABASE IF EXISTS `%s`', $database->database));
DB::connection('dynamic')->statement(sprintf('DROP USER IF EXISTS `%s`@`%s`', $database->username, $database->remote));
DB::connection('dynamic')->statement('FLUSH PRIVILEGES');
} catch (\Exception $ex) {}
DB::rollBack();
throw $ex;
}
}
@ -118,7 +127,7 @@ class DatabaseRepository
* @param string $password The new password to use for the database.
* @return bool
*/
public function modifyPassword($id, $password)
public function password($id, $password)
{
$database = Models\Database::with('host')->findOrFail($id);
@ -127,33 +136,25 @@ class DatabaseRepository
$database->password = Crypt::encrypt($password);
$database->save();
$capsule = new Capsule;
$capsule->addConnection([
Config::set('database.connections.dynamic', [
'driver' => 'mysql',
'host' => $database->host->host,
'port' => $database->host->port,
'database' => 'mysql',
'username' => $database->host->username,
'password' => Crypt::decrypt($database->host->password),
'charset' => 'utf8',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
],
]);
$capsule->setAsGlobal();
Capsule::statement(sprintf(
DB::connection('dynamic')->statement(sprintf(
'SET PASSWORD FOR `%s`@`%s` = PASSWORD(\'%s\')',
$database->username,
$database->remote,
$password
$database->username, $database->remote, $password
));
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
DB::rollBack();
throw $ex;
}
}
@ -168,34 +169,25 @@ class DatabaseRepository
$database = Models\Database::with('host')->findOrFail($id);
DB::beginTransaction();
try {
$capsule = new Capsule;
$capsule->addConnection([
Config::set('database.connections.dynamic', [
'driver' => 'mysql',
'host' => $database->host->host,
'port' => $database->host->port,
'database' => 'mysql',
'username' => $database->host->username,
'password' => Crypt::decrypt($database->host->password),
'charset' => 'utf8',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
],
]);
$capsule->setAsGlobal();
Capsule::statement('DROP USER `' . $database->username . '`@`' . $database->remote . '`');
Capsule::statement('DROP DATABASE `' . $database->database . '`');
DB::connection('dynamic')->statement(sprintf('DROP DATABASE IF EXISTS `%s`', $database->database));
DB::connection('dynamic')->statement(sprintf('DROP USER IF EXISTS `%s`@`%s`', $database->username, $database->remote));
DB::connection('dynamic')->statement('FLUSH PRIVILEGES');
$database->delete();
DB::commit();
return true;
} catch (\Exception $ex) {
DB::rollback();
throw $ex;
@ -243,28 +235,20 @@ class DatabaseRepository
}
DB::beginTransaction();
try {
$capsule = new Capsule;
$capsule->addConnection([
Config::set('database.connections.dynamic', [
'driver' => 'mysql',
'host' => $data['host'],
'port' => $data['port'],
'database' => 'mysql',
'username' => $data['username'],
'password' => $data['password'],
'charset' => 'utf8',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'options' => [
\PDO::ATTR_TIMEOUT => 3,
],
]);
$capsule->setAsGlobal();
// Allows us to check that we can connect to things.
Capsule::select('SELECT 1 FROM dual');
DB::connection('dynamic')->select('SELECT 1 FROM dual');
Models\DatabaseServer::create([
'name' => $data['name'],

View file

@ -745,10 +745,12 @@ class ServerRepository
// Delete Databases
// This is the one un-recoverable point where
// transactions will not save us.
$repository = new DatabaseRepository;
foreach (Models\Database::select('id')->where('server_id', $server->id)->get() as &$database) {
$repository->drop($database->id);
}
//
// @TODO: move to post-deletion event as a queued task!
// $repository = new DatabaseRepository;
// foreach (Models\Database::select('id')->where('server_id', $server->id)->get() as &$database) {
// $repository->drop($database->id);
// }
$server->node->guzzleClient([
'X-Access-Token' => $server->node->daemonSecret,

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,192 @@
{{-- 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. --}}
@extends('layouts.admin')
@section('title')
Server {{ $server->name }}: Databases
@endsection
@section('content-header')
<h1>{{ $server->name }}<small>Manage server databases.</small></h1>
<ol class="breadcrumb">
<li><a href="{{ route('admin.index') }}">Admin</a></li>
<li><a href="{{ route('admin.servers') }}">Servers</a></li>
<li><a href="{{ route('admin.servers.view', $server->id) }}">{{ $server->name }}</a></li>
<li class="active">Databases</li>
</ol>
@endsection
@section('content')
<div class="row">
<div class="col-xs-12">
<div class="nav-tabs-custom nav-tabs-floating">
<ul class="nav nav-tabs">
<li><a href="{{ route('admin.servers.view', $server->id) }}">About</a></li>
@if(! $server->trashed() && $server->installed === 1)
<li><a href="{{ route('admin.servers.view.details', $server->id) }}">Details</a></li>
<li><a href="{{ route('admin.servers.view.build', $server->id) }}">Build Configuration</a></li>
<li><a href="{{ route('admin.servers.view.startup', $server->id) }}">Startup</a></li>
<li class="active"><a href="{{ route('admin.servers.view.database', $server->id) }}">Database</a></li>
@endif
@if(! $server->trashed())
<li><a href="{{ route('admin.servers.view.manage', $server->id) }}">Manage</a></li>
@endif
<li class="tab-danger"><a href="{{ route('admin.servers.view.delete', $server->id) }}">Delete</a></li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-7">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Active Databases</h3>
</div>
<div class="box-body table-responsible no-padding">
<table class="table table-hover">
<tr>
<th>Database</th>
<th>Username</th>
<th>Connections From</th>
<th>Host</th>
<th></th>
</tr>
@foreach($server->databases as $database)
<tr>
<td>{{ $database->database }}</td>
<td>{{ $database->username }}</td>
<td>{{ $database->remote }}</td>
<td><code>{{ $database->host->host }}:{{ $database->host->port }}</code></td>
<td class="text-center">
<button data-action="reset-password" data-id="{{ $database->id }}" class="btn btn-xs btn-primary"><i class="fa fa-refresh"></i></button>
<button data-action="remove" data-id="{{ $database->id }}" class="btn btn-xs btn-danger"><i class="fa fa-trash"></i></button>
</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
<div class="col-sm-5">
<div class="box box-success">
<div class="box-header with-border">
<h3 class="box-title">Create New Database</h3>
</div>
<form action="{{ route('admin.servers.view.database', $server->id) }}" method="POST">
<div class="box-body">
<div class="form-group">
<label for="pDatabaseHost" class="control-label">Database Host</label>
<select id="pDatabaseHost" name="host" class="form-control">
@foreach($hosts as $host)
<option value="{{ $host->id }}">{{ $host->name }}</option>
@endforeach
</select>
<p class="text-muted small">Select the host database server that this database should be created on.</p>
</div>
<div class="form-group">
<label for="pDatabaseName" class="control-label">Database</label>
<div class="input-group">
<span class="input-group-addon">s{{ $server->id }}_</span>
<input id="pDatabaseName" type="text" name="database" class="form-control" placeholder="database" />
</div>
</div>
<div class="form-group">
<label for="pConnections" class="control-label">Connections</label>
<input id="pConnections" type="text" name="connection" class="form-control" placeholder="%" value="%" />
<p class="text-muted small">This should reflect the IP address that connections are allowed from. Uses standard MySQL notation. If unsure leave as <code>%</code>.</p>
</div>
</div>
<div class="box-footer">
{!! csrf_field() !!}
<p class="text-muted small no-margin">A username and password for this database will be randomly generated after form submission.</p>
<input type="submit" class="btn btn-sm btn-success pull-right" value="Create Database" />
</div>
</form>
</div>
</div>
</div>
@endsection
@section('footer-scripts')
@parent
<script>
$('#pDatabaseHost').select2();
$('[data-action="remove"]').click(function (event) {
event.preventDefault();
var self = $(this);
swal({
title: '',
type: 'warning',
text: 'Are you sure that you want to delete this database? There is no going back, all data will immediately be removed.',
showCancelButton: true,
confirmButtonText: 'Delete',
confirmButtonColor: '#d9534f',
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function () {
$.ajax({
method: 'DELETE',
url: Router.route('admin.servers.view.database.delete', { id: '{{ $server->id }}', database: self.data('id') }),
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
}).done(function () {
self.parent().parent().slideUp();
swal.close();
}).fail(function (jqXHR) {
console.error(jqXHR);
swal({
type: 'error',
title: 'Whoops!',
text: (typeof jqXHR.responseJSON.error !== 'undefined') ? jqXHR.responseJSON.error : 'An error occured while processing this request.'
});
});
});
});
$('[data-action="reset-password"]').click(function (e) {
e.preventDefault();
var block = $(this);
$(this).addClass('disabled').find('i').addClass('fa-spin');
$.ajax({
type: 'PATCH',
url: Router.route('admin.servers.view.database', { id: '{{ $server->id }}' }),
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
data: { database: $(this).data('id') },
}).done(function (data) {
swal({
type: 'success',
title: '',
text: 'The password for this database has been reset.',
});
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR);
var error = 'An error occured while trying to process this request.';
if (typeof jqXHR.responseJSON !== 'undefined' && typeof jqXHR.responseJSON.error !== 'undefined') {
error = jqXHR.responseJSON.error;
}
swal({
type: 'error',
title: 'Whoops!',
text: error
});
}).always(function () {
block.removeClass('disabled').find('i').removeClass('fa-spin');
});
});
</script>
@endsection