- minor code/performance improvements

This commit is contained in:
Mark Friedrich
2019-02-09 16:33:31 +01:00
parent e28fea9081
commit 8abd5cba6e
7 changed files with 137 additions and 92 deletions

View File

@@ -10,6 +10,7 @@ namespace Controller;
use Controller\Api as Api;
use Exception\PathfinderException;
use lib\api\CcpClient;
use lib\Config;
use lib\Resource;
use lib\Monolog;
@@ -542,72 +543,86 @@ class Controller {
*/
public function getEveServerStatus(\Base $f3){
$esiStatusVersion = 'latest';
$cacheKey = 'eve_server_status';
$return = (object) [];
$return->error = [];
if( !$f3->exists($cacheKey, $return) ){
$return = (object) [];
$return->error = [];
if($client = $f3->ccpClient()){
$return->server = [
'name' => strtoupper( self::getEnvironmentData('CCP_ESI_DATASOURCE') ),
'status' => 'offline',
'statusColor' => 'red',
];
$return->api = [
'name' => 'ESI API',
'status' => 'offline',
'statusColor' => 'red',
'url' => $client->getUrl(),
'timeout' => $client->getTimeout(),
'connectTimeout' => $client->getConnectTimeout(),
'readTimeout' => $client->getReadTimeout(),
'proxy' => ($proxy = $client->getProxy()) ? : 'false',
'verify' => $client->getVerify(),
'debug' => $client->getDebugRequests(),
'dataSource' => $client->getDataSource(),
'statusVersion' => $esiStatusVersion,
'routes' => []
];
/**
* @var $client CcpClient
*/
if($client = $f3->ccpClient()){
$return->server = [
'name' => strtoupper(self::getEnvironmentData('CCP_ESI_DATASOURCE')),
'status' => 'offline',
'statusColor' => 'red',
];
$return->api = [
'name' => 'ESI API',
'status' => 'offline',
'statusColor' => 'red',
'url' => $client->getUrl(),
'timeout' => $client->getTimeout(),
'connectTimeout' => $client->getConnectTimeout(),
'readTimeout' => $client->getReadTimeout(),
'proxy' => ($proxy = $client->getProxy()) ? : 'false',
'verify' => $client->getVerify(),
'debug' => $client->getDebugRequests(),
'dataSource' => $client->getDataSource(),
'statusVersion' => $esiStatusVersion,
'routes' => []
];
$serverStatus = $client->getServerStatus();
if( !isset($serverStatus['error']) ){
$statusData = $serverStatus['status'];
// calculate time diff since last server restart
$timezone = $f3->get('getTimeZone')();
$dateNow = new \DateTime('now', $timezone);
$dateServerStart = new \DateTime($statusData['startTime']);
$interval = $dateNow->diff($dateServerStart);
$startTimestampFormat = $interval->format('%hh %im');
if($interval->days > 0){
$startTimestampFormat = $interval->days . 'd ' . $startTimestampFormat;
$serverStatus = $client->getServerStatus();
if( !isset($serverStatus['error']) ){
$statusData = $serverStatus['status'];
// calculate time diff since last server restart
$timezone = $f3->get('getTimeZone')();
$dateNow = new \DateTime('now', $timezone);
$dateServerStart = new \DateTime($statusData['startTime']);
$interval = $dateNow->diff($dateServerStart);
$startTimestampFormat = $interval->format('%hh %im');
if($interval->days > 0){
$startTimestampFormat = $interval->days . 'd ' . $startTimestampFormat;
}
$statusData['name'] = $return->server['name'];
$statusData['status'] = 'online';
$statusData['statusColor'] = 'green';
$statusData['startTime'] = $startTimestampFormat;
$return->server = $statusData;
}else{
$return->error[] = (new PathfinderException($serverStatus['error'], 500))->getError();
}
$statusData['name'] = $return->server['name'];
$statusData['status'] = 'online';
$statusData['statusColor'] = 'green';
$statusData['startTime'] = $startTimestampFormat;
$return->server = $statusData;
}
$apiStatus = $client->getStatusForRoutes('latest');
if( !isset($apiStatus['error']) ){
// find top status
$status = 'OK';
$color = 'green';
foreach($apiStatus['status'] as $statusData){
if('red' == $statusData['status']){
$status = 'unstable';
$color = $statusData['status'];
break;
}
if('yellow' == $statusData['status']){
$status = 'degraded';
$color = $statusData['status'];
}
}
$apiStatus = $client->getStatusForRoutes('latest');
if( !isset($apiStatus['error']) ){
// find top status
$status = 'OK';
$color = 'green';
foreach($apiStatus['status'] as $statusData){
if('red' == $statusData['status']){
$status = 'unstable';
$color = $statusData['status'];
break;
}
if('yellow' == $statusData['status']){
$status = 'degraded';
$color = $statusData['status'];
}
$return->api['status'] = $status;
$return->api['statusColor'] = $color;
$return->api['routes'] = $apiStatus['status'];
}else{
$return->error[] = (new PathfinderException($apiStatus['error'], 500))->getError();
}
$return->api['status'] = $status;
$return->api['statusColor'] = $color;
$return->api['routes'] = $apiStatus['status'];
if(empty($return->error)){
$f3->set($cacheKey, $return, 15);
}
}
}

View File

@@ -162,9 +162,9 @@ class LogController extends \Prefab {
/**
* get Logger instance
* @param string $type
* @return \Log|null
* @return \Log
*/
public static function getLogger($type){
public static function getLogger(string $type) : \Log {
$logFiles = Config::getPathfinderData('logfiles');
$logFileName = empty($logFiles[$type]) ? 'error' : $logFiles[$type];

View File

@@ -1408,12 +1408,13 @@ class Setup extends Controller {
return $this->databases;
}
/** check MySQL params
/**
* check MySQL params
* @param \Base $f3
* @param $db
* @param SQL $db
* @return array
*/
protected function checkDBConfig(\Base $f3, $db){
protected function checkDBConfig(\Base $f3, SQL $db){
// some db like "Maria DB" have some strange version strings....
$dbVersionString = $db->version();
@@ -1436,19 +1437,13 @@ class Setup extends Controller {
]
];
// get specific MySQL config Value
$getDBConfigValue = function($db, $param){
$result = $db->exec([
//"USE " . $db->name(),
"SHOW VARIABLES LIKE '" . strtolower($param) . "'"
]);
$tmpResult = reset($result);
return !empty($result)? end($tmpResult) : 'unknown';
};
$mySQLConfigParams = $f3->get('REQUIREMENTS.MYSQL.VARS');
$mySQLConfigParams = (array)$f3->get('REQUIREMENTS.MYSQL.VARS');
foreach($mySQLConfigParams as $param => $requiredValue){
$value = $getDBConfigValue($db, $param);
// get current MySQL config value for $param
$result = $db->exec("SHOW VARIABLES LIKE '" . strtolower($param) . "'");
$tmpResult = reset($result);
$value = !empty($result)? end($tmpResult) : 'unknown';
$dbConfig[] = [
'label' => strtolower($param),
'required' => $requiredValue,

View File

@@ -7,6 +7,8 @@
*/
namespace DB;
use controller\LogController;
use lib\Config;
@@ -29,7 +31,7 @@ class Database extends \Prefab {
* @param string $dbKey
* @return SQL|null
*/
public function connectToServer(string $dbKey = 'PF'){
public function connectToServer(string $dbKey = 'PF') : ?SQL {
$dbConfig = Config::getDatabaseConfig($dbKey);
$dbConfig['DNS'] = str_replace(';dbname=', '', $dbConfig['DNS'] );
$dbConfig['NAME'] = '';
@@ -42,7 +44,7 @@ class Database extends \Prefab {
* @param string $dbKey
* @return SQL|null
*/
public function createDB(string $dbKey = 'PF'){
public function createDB(string $dbKey = 'PF') : ?SQL {
$db = null;
$dbConfig = Config::getDatabaseConfig($dbKey);
// remove database from $dsn (we want to crate it)
@@ -51,6 +53,9 @@ class Database extends \Prefab {
$dbConfig['NAME'] = '';
$dbConfig['DNS'] = str_replace(';dbname=', '', $dbConfig['DNS'] );
/**
* @var $db SQL|null
*/
$db = call_user_func_array([$this, 'connect'], $dbConfig);
if(!is_null($db)){
@@ -83,12 +88,15 @@ class Database extends \Prefab {
* @param string $dbKey
* @return SQL|null
*/
public function getDB(string $dbKey = 'PF'){
public function getDB(string $dbKey = 'PF') : ?SQL {
$f3 = \Base::instance();
// "Hive" Key for DB object cache
$dbHiveKey = $this->getDbHiveKey($dbKey);
if( !$f3->exists($dbHiveKey, $db) ){
$dbConfig = Config::getDatabaseConfig($dbKey);
/**
* @var $db SQL|null
*/
$db = call_user_func_array([$this, 'connect'], $dbConfig);
if(!is_null($db)){
self::prepareDBConnection($db);
@@ -104,7 +112,7 @@ class Database extends \Prefab {
* @param $dbKey
* @return string
*/
protected function getDbHiveKey($dbKey){
protected function getDbHiveKey(string $dbKey) : string {
return 'DB_' . $dbKey;
}
@@ -117,7 +125,7 @@ class Database extends \Prefab {
* @param string $alias
* @return SQL|null
*/
protected function connect($dns, $name, $user, $password, $alias){
protected function connect(string $dns, string $name, string $user, string $password, string $alias) : ?SQL {
$db = null;
$f3 = \Base::instance();
@@ -155,18 +163,18 @@ class Database extends \Prefab {
* @param string $dbKey
* @return array|bool
*/
public function getTables($dbKey = 'PF'){
public function getTables(string $dbKey = 'PF'){
$schema = new SQL\Schema( $this->getDB($dbKey) );
return $schema->getTables();
}
/**
* checks whether a table exists on a DB or not
* @param $table
* @param string $table
* @param string $dbKey
* @return bool
*/
public function tableExists($table, $dbKey = 'PF'){
public function tableExists(string $table, string $dbKey = 'PF') : bool {
$tableNames = $this->getTables($dbKey);
return in_array($table, $tableNames);
}
@@ -174,11 +182,11 @@ class Database extends \Prefab {
/**
* get current row (data) count for an existing table
* -> returns 0 if table not exists or empty
* @param $table
* @param string $table
* @param string $dbKey
* @return int
*/
public function getRowCount($table, $dbKey = 'PF') {
public function getRowCount(string $table, string $dbKey = 'PF') : int {
$count = 0;
if( $this->tableExists($table, $dbKey) ){
$db = $this->getDB($dbKey);
@@ -193,7 +201,7 @@ class Database extends \Prefab {
/**
* @return bool
*/
public function isSilent() : bool{
public function isSilent() : bool {
return $this->silent;
}
@@ -251,11 +259,15 @@ class Database extends \Prefab {
*/
public static function prepareDBConnection(SQL &$db){
// set DB timezone to UTC +00:00 (eve server time)
$db->exec('SET @@session.time_zone = "+00:00";');
// set default storage engine
$db->exec('SET @@session.default_storage_engine = "' .
self::getRequiredMySqlVariables('DEFAULT_STORAGE_ENGINE') . '"');
$db->exec([
'SET @@session.time_zone = :time_zone',
'SET @@session.default_storage_engine = :storage_engine'
], [
[':time_zone' => '+00:00'],
[':storage_engine' => self::getRequiredMySqlVariables('DEFAULT_STORAGE_ENGINE')]
]
);
}
/**
@@ -277,7 +289,7 @@ class Database extends \Prefab {
* @param string $key
* @return string|null
*/
public static function getRequiredMySqlVariables(string $key){
public static function getRequiredMySqlVariables(string $key) : ?string {
\Base::instance()->exists('REQUIREMENTS[MYSQL][VARS][' . $key . ']', $data);
return $data;
}
@@ -286,7 +298,7 @@ class Database extends \Prefab {
* get logger for DB logging
* @return \Log
*/
static function getLogger(){
static function getLogger() : \Log {
return LogController::getLogger('ERROR');
}
}

View File

@@ -22,6 +22,19 @@ use Exodus4D\ESI\Client\ApiInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\RequestInterface;
/**
* Class AbstractClient
* @package lib\api
*
* @method ApiInterface getUrl()
* @method ApiInterface getTimeout()
* @method ApiInterface getConnectTimeout()
* @method ApiInterface getReadTimeout()
* @method ApiInterface getProxy()
* @method ApiInterface getVerify()
* @method ApiInterface getDebugRequests()
* @method ApiInterface getDataSource()
*/
abstract class AbstractClient extends \Prefab {
const ERROR_CLIENT_INVALID = "HTTP API client not found → Check installed Composer packages";

View File

@@ -11,7 +11,16 @@ namespace lib\api;
use lib\Config;
use Exodus4D\ESI\Client\ESI as Client;
use Exodus4D\ESI\Client\ApiInterface;
use Exodus4D\ESI\Client\EsiInterface;
/**
* Class CcpClient
* @package lib\api
*
* @method EsiInterface getServerStatus()
* @method EsiInterface getStatusForRoutes(string $version)
*/
class CcpClient extends AbstractClient {
/**

View File

@@ -69,6 +69,7 @@ CHARACTER_SET_CONNECTION = utf8
COLLATION_DATABASE = utf8_general_ci
COLLATION_CONNECTION = utf8_general_ci
FOREIGN_KEY_CHECKS = ON
INNODB_FILE_PER_TABLE = ON
[REQUIREMENTS.REDIS]
VERSION = 3.0