From 00b3560517e47ab4ea33298fffa208fc8576189f Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 25 May 2024 10:30:16 +0800 Subject: [PATCH 01/22] =?UTF-8?q?=E2=9C=A8=20=E5=8A=A0=E5=85=A5Keepalive?= =?UTF-8?q?=E9=87=8D=E8=AF=95=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/socketio.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/inc/socketio.php b/inc/socketio.php index e6358a9..7308d5b 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -75,8 +75,15 @@ public function connect() { }); } elseif (isset($jsondata[0][1]) && $jsondata[0][1] == "0"){ - mlog("[socket.io]节点已掉线"); - exits(); + if($this->rekeepalive < 3){ + mlog("Keep-Alive失败,正在重试({$this->rekeepalive}/3)"); + global $kadata; + $this->ack("keep-alive",$kadata); + $this->rekeepalive++; + } + else{ + exits(); + } } elseif (isset($jsondata[0][1]) && $this->IsTime($jsondata[0][1])){ global $kadata; From 50b21c2d81e20cf259dac5bac15a9e3eb5f30e97 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 25 May 2024 11:23:42 +0800 Subject: [PATCH 02/22] =?UTF-8?q?=E2=9C=A8=20=E6=9B=B4=E6=94=B9get?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E7=9A=84=E8=8E=B7=E5=8F=96=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/server.php | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/inc/server.php b/inc/server.php index eb96a03..5a3f98c 100644 --- a/inc/server.php +++ b/inc/server.php @@ -20,12 +20,11 @@ public function __construct($host,$port,$cert,$key,$secret) { } public function startserver() { - $this->server = $server = new Server($this->host, $this->port, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL); + $this->server = $server = new Server($this->host, $this->port, true); $server->set([ 'ssl_cert_file' => './cert/'.$this->cert, 'ssl_key_file' => './cert/'.$this->key, - 'open_http2_protocol' => true, - 'max_connection' => 10000, + 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 ]); $server->handle('/', function ($request, $response) { $code = 404; @@ -43,9 +42,8 @@ public function startserver() { $server->handle('/download', function ($request, $response) { $downloadhash = str_replace('/download/', '', $request->server['request_uri']); if(isset($request->server['query_string'])){ - parse_str($request->server['query_string'], $allurl); $filepath = $this->dir.'/'.substr($downloadhash, 0, 2).'/'.$downloadhash; - if ($this->check_sign($downloadhash, $this->secret, $allurl['s'], $allurl['e'])){ + if ($this->check_sign($downloadhash, $this->secret, $request->get['s'], $request->get['e'])){ if (!file_exists($filepath)) { $download = new download(); $download->downloadnopoen($downloadhash); @@ -68,7 +66,7 @@ public function startserver() { $code = 206; $response->header('Content-Type', 'application/octet-stream'); if(isset($request->header['name'])){ - $response->header('Content-Disposition', 'attachment; filename='.$allurl['name']); + $response->header('Content-Disposition', 'attachment; filename='.$request->get['name']); } $response->header('x-bmclapi-hash', $downloadhash); $response->sendfile($filepath,$start_byte,$length); @@ -83,7 +81,7 @@ public function startserver() { $code = 200; $response->header('Content-Type', 'application/octet-stream'); if(isset($request->header['name'])){ - $response->header('Content-Disposition', 'attachment; filename='.$allurl['name']); + $response->header('Content-Disposition', 'attachment; filename='.$request->get['name']); } $response->header('x-bmclapi-hash', $downloadhash); $response->sendfile($filepath); @@ -119,8 +117,7 @@ public function startserver() { } if(isset($request->server['query_string'])){ if(is_numeric($measuresize)){ - parse_str($request->server['query_string'], $allurl); - if ($this->check_sign($request->server['request_uri'], $this->secret, $allurl['s'], $allurl['e'])){ + if ($this->check_sign($request->server['request_uri'], $this->secret, $request->get['s'], $request->get['e'])){ if (!file_exists($this->dir.'/measure/'.$measuresize)) { $file = fopen($this->dir.'/measure/'.$measuresize, 'w+'); $bytesToWrite = $measuresize * 1048576; From 200dd5fba4217fc5f0ea7e8eb632d12dc73ac3e8 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 25 May 2024 11:25:55 +0800 Subject: [PATCH 03/22] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20=E5=8A=A0=E4=B8=AA?= =?UTF-8?q?=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/socketio.php | 1 + 1 file changed, 1 insertion(+) diff --git a/inc/socketio.php b/inc/socketio.php index 7308d5b..ef45aa9 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -8,6 +8,7 @@ class socketio { private $data; private $certdata; private $kattl; + private $rekeepalive; private $Connected = false; public function __construct($url,$token,$kattl) { $this->url = $url; From d1190b4aa7985a6eb933a9435c929acd835942b4 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 25 May 2024 11:27:09 +0800 Subject: [PATCH 04/22] =?UTF-8?q?=F0=9F=90=9B=20=E9=87=8D=E8=AF=95?= =?UTF-8?q?=E6=AC=A1=E6=95=B0=E4=B8=8D=E4=BC=9A=E9=87=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/socketio.php | 1 + 1 file changed, 1 insertion(+) diff --git a/inc/socketio.php b/inc/socketio.php index ef45aa9..372f5fb 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -87,6 +87,7 @@ public function connect() { } } elseif (isset($jsondata[0][1]) && $this->IsTime($jsondata[0][1])){ + $this->rekeepalive = 0; global $kadata; mlog(" Keep-alive success: hits={$kadata['hits']} bytes={$kadata['bytes']} Time={$jsondata[0][1]}"); } From c006de8f8569411233491bbcd175ca6c1fc97032 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 25 May 2024 12:13:16 +0800 Subject: [PATCH 05/22] =?UTF-8?q?=E2=9C=A8=20=E6=B7=BB=E5=8A=A0log?= =?UTF-8?q?=E5=86=99=E5=85=A5=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/cluster.php | 9 +++--- inc/mlog.class.php | 73 +++++++++++++++++++++++++++++++--------------- inc/server.php | 2 +- inc/socketio.php | 8 ++--- inc/token.php | 2 +- main.php | 6 ++-- 6 files changed, 62 insertions(+), 38 deletions(-) diff --git a/inc/cluster.php b/inc/cluster.php index d4fd156..e03ecd2 100644 --- a/inc/cluster.php +++ b/inc/cluster.php @@ -95,15 +95,14 @@ public function getFileList() { 'Accept' => '*', 'Authorization' => "Bearer {$this->token}" ]); - mlog("Start FileList Download"); - if (!$client->download('/openbmclapi/files',$DOWNLOAD_DIR.'/filecache/filelist.zstd')) { - mlog("FileList Download Failed",2); + mlog("Starting to download fileList"); + if (!$client->get('/openbmclapi/files')) { + mlog("Failed to download fileList",2); $client->close(); } else{ - mlog("FileList Download Success"); + $this->compressedData = zstd_uncompress($client->body); $client->close(); - $this->compressedData = file_get_contents("compress.zstd://".$DOWNLOAD_DIR."/filecache/filelist.zstd"); } $parser = new ParseFileList($this->compressedData); $files = $parser->parse(); diff --git a/inc/mlog.class.php b/inc/mlog.class.php index 3ebff5f..e402faf 100644 --- a/inc/mlog.class.php +++ b/inc/mlog.class.php @@ -1,24 +1,51 @@ 'INFO', + 1 => 'DEBUG', + 2 => 'ERROR' + ]; + + if (!isset($logTypes[$type])) { + trigger_error("Type {$type} not found", E_USER_ERROR); + return; + } + + $logDir = 'logs/'; + if (!file_exists($logDir)) { + mkdir($logDir, 0755, true); + } + + $timePrefix = !$minimalFormat ? '[' . date('Y.n.j-H:i:s') . ']' : ''; + $levelPrefix = !$minimalFormat ? '[' . strtoupper($logTypes[$type]) . ']' : ''; + $logEntry = $timePrefix . $levelPrefix . $content . PHP_EOL; + + // 写入日志文件 + if ($type !== 1 || (isset($GLOBALS['config']['advanced']['Debug']) && $GLOBALS['config']['advanced']['Debug'])) { + $logFile = $logDir . date('Y-n-j') . '.log'; + file_put_contents($logFile, $logEntry, FILE_APPEND); + } + + // 输出到控制台 + switch ($type) { + case 0: // INFO + echo $logEntry; + break; + case 1: // DEBUG + if (isDebugMode()) { + echo $logEntry; + } + break; + case 2: // ERROR + echo $logEntry; + break; + } +} + +function isDebugMode() +{ + global $config; + return isset($config['advanced']['Debug']) && $config['advanced']['Debug']; +} \ No newline at end of file diff --git a/inc/server.php b/inc/server.php index 5a3f98c..5e719be 100644 --- a/inc/server.php +++ b/inc/server.php @@ -159,7 +159,7 @@ public function startserver() { $server->start(); } public function stopserver() { - mlog("Stop Http Server"); + mlog("Stop Http Server",1); $this->server->shutdown(); } //你问我这段函数为什么要放在server里面? 因为只有server需要check_sign( diff --git a/inc/socketio.php b/inc/socketio.php index 372f5fb..74bf246 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -43,7 +43,7 @@ public function connect() { } if ($code[0] == '42'){ $data = substr($data, strlen($code[0])); - mlog("[socket.io]Got data {$data}"); + mlog("[socket.io]{$data}"); } if ($code[0] == '2'){ $client->push('3'); @@ -92,9 +92,9 @@ public function connect() { mlog(" Keep-alive success: hits={$kadata['hits']} bytes={$kadata['bytes']} Time={$jsondata[0][1]}"); } elseif (isset($jsondata[0][0]["message"])){ - mlog("[socket.io]Got data {$jsondata[0][0]["message"]}"); + mlog("[socket.io]{$jsondata[0][0]["message"]}"); if (strpos($jsondata[0][0]["message"], "Error") !== false) { - mlog("[socket.io]节点启用失败"); + mlog("节点启用失败",2); exits(); } } @@ -200,7 +200,7 @@ public function disable() { $this->ack("disable"); Coroutine::sleep(2); } - mlog("[socket.io]Close Connection"); + mlog("[socket.io]Close Connection",1); $this->client->close(); } } \ No newline at end of file diff --git a/inc/token.php b/inc/token.php index fccc81b..28db766 100644 --- a/inc/token.php +++ b/inc/token.php @@ -16,7 +16,7 @@ public function gettoken() { 'User-Agent' => 'openbmclapi-cluster/'.$this->version, 'Content-Type' => 'application/json; charset=utf-8', ]); - $client->set(['timeout' => 1]); + $client->set(['timeout' => 20]); $client->get('/openbmclapi-agent/challenge?clusterId='.$this->clusterId); $client->close(); $challenge = json_decode($client->body, true); diff --git a/main.php b/main.php index e348ff6..6ccfe82 100644 --- a/main.php +++ b/main.php @@ -2,7 +2,6 @@ use Swoole\Coroutine; use function Swoole\Coroutine\run; use function Swoole\Timer; -declare(ticks=1) date_default_timezone_set('Asia/Shanghai'); require './config.php'; const PHPOBAVERSION = '1.6.0'; @@ -15,11 +14,9 @@ foreach ($list as $file) { require $file; } -global $pid; -$pid = getmypid(); global $enable; $enable = false; -echo"OpenBmclApionPHP v". PHPOBAVERSION . "-" . VERSION . PHP_EOL; +mlog("OpenBmclApi on PHP v". PHPOBAVERSION . "-" . VERSION,0,true); run(function()use ($config){ //注册信号处理器、 function exits() { @@ -31,6 +28,7 @@ function exits() { mlog("正在退出..."); } function registerSigintHandler() { + global $shouldExit; $shouldExit = false; // 初始化为false Swoole\Process::signal(SIGINT, function ($signo){ exits(); From 9e2d51a96ca39edad157b833d1d91c777fede72a Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sun, 26 May 2024 17:08:29 +0800 Subject: [PATCH 06/22] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20=E6=8A=8A=E5=A4=A7?= =?UTF-8?q?=E9=83=A8=E5=88=86=E7=9A=84global=E5=8F=98=E9=87=8F=E7=A7=BB?= =?UTF-8?q?=E5=88=B0class=E9=87=8C=E9=9D=A2=E4=BA=86,=E6=96=B9=E4=BE=BF?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E5=92=8Capi=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/api.php | 26 ++++++++++++++++++++++++++ inc/cluster.php | 42 +++++++++++++++++++++--------------------- inc/mlog.class.php | 3 +-- inc/server.php | 38 +++++++++++++++++++++++++++++++++----- inc/socketio.php | 14 +++++++------- inc/webapi.php | 6 ++++++ main.php | 19 +++++++++---------- 7 files changed, 103 insertions(+), 45 deletions(-) create mode 100644 inc/api.php create mode 100644 inc/webapi.php diff --git a/inc/api.php b/inc/api.php new file mode 100644 index 0000000..0ef3b85 --- /dev/null +++ b/inc/api.php @@ -0,0 +1,26 @@ +false,'isSynchronized'=>true]; + private static $server; + + public static function getconfig($newConfig = null) { + if (!is_null($newConfig)) { + self::$config = $newConfig; + } + return self::$config; + } + + public static function getinfo($newinfo = null) { + if (!is_null($newinfo)) { + self::$info = $newinfo; + } + return self::$info; + } + public static function getserver($newserver = null) { + if (!is_null($newserver)) { + self::$server = $newserver; + } + return self::$server; + } +} \ No newline at end of file diff --git a/inc/cluster.php b/inc/cluster.php index e03ecd2..fb3b7bd 100644 --- a/inc/cluster.php +++ b/inc/cluster.php @@ -83,9 +83,9 @@ public function __construct($token,$version){ $this->version = $version; } public function getFileList() { - global $DOWNLOAD_DIR; - if (!file_exists($DOWNLOAD_DIR."/filecache")) { - mkdir($DOWNLOAD_DIR."/filecache",0777,true); + $download_dir = api::getconfig()['file']['cache_dir']; + if (!file_exists($download_dir."/filecache")) { + mkdir($download_dir."/filecache",0777,true); } $client = new Client(OPENBMCLAPIURL,443,true); $client->set(['timeout' => -1]); @@ -122,14 +122,14 @@ public function __construct($filesList = [], $maxConcurrent = 1) { } private function downloader(Swoole\Coroutine\Http\Client $client, $file,$bar) { - global $DOWNLOAD_DIR; - $filePath = $DOWNLOAD_DIR . '/' . substr($file->hash, 0, 2) . '/'; + $download_dir = api::getconfig()['file']['cache_dir']; + $filePath = $download_dir . '/' . substr($file->hash, 0, 2) . '/'; if (!file_exists($filePath)) { mkdir($filePath, 0777, true); } $savePath = $filePath . $file->hash; $file->path = str_replace(' ', '%20', $file->path); - $downloader = $client->download($file->path,$DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash); + $downloader = $client->download($file->path,$download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash); if (!$downloader) { mlog("Error connecting to the main control:{$client->errMsg}",2); return false; @@ -151,7 +151,7 @@ private function downloader(Swoole\Coroutine\Http\Client $client, $file,$bar) { 'User-Agent' => USERAGENT, 'Accept' => '*/*', ]); - $downloader = $client->download($location_url['path'].'?'.($location_url['query']??''),$DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash); + $downloader = $client->download($location_url['path'].'?'.($location_url['query']??''),$download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash); if (in_array($client->statusCode, [301, 302])) { while(in_array($client->statusCode, [301, 302])){ $location_url = parse_url($client->getHeaders()['location']); @@ -168,7 +168,7 @@ private function downloader(Swoole\Coroutine\Http\Client $client, $file,$bar) { 'User-Agent' => USERAGENT, 'Accept' => '*/*', ]); - $downloader = $client->download($location_url['path'].'?'.($location_url['query']??''),$DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash); + $downloader = $client->download($location_url['path'].'?'.($location_url['query']??''),$download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash); } if (!$downloader) { echo PHP_EOL; @@ -191,7 +191,7 @@ private function downloader(Swoole\Coroutine\Http\Client $client, $file,$bar) { } elseif($client->statusCode >= 400){ echo PHP_EOL; - mlog("Download Failed:{$client->statusCode} | {$file->path} | {$location_url['host']}:{$location_url['port']}",2); + mlog("{$file->path} Download Failed: {$client->statusCode} | {$location_url['host']}:{$location_url['port']}",2); $bar->progress(); return false; } @@ -211,7 +211,7 @@ private function downloader(Swoole\Coroutine\Http\Client $client, $file,$bar) { public function downloadFiles() { $bar = new CliProgressBar(count($this->filesList)); - $bar->setDetails("[Downloader]"); + $bar->setDetails("[Downloader][线程数:{$this->maxConcurrent}]"); $bar->display(); foreach ($this->filesList as $file) { global $shouldExit; @@ -246,9 +246,9 @@ public function downloadFiles() { } public function downloadnopoen($hash) { - global $DOWNLOAD_DIR; + $download_dir = api::getconfig()['file']['cache_dir']; global $tokendata; - $filePath = $DOWNLOAD_DIR . '/' . substr($hash, 0, 2) . '/'; + $filePath = $download_dir . '/' . substr($hash, 0, 2) . '/'; if (!file_exists($filePath)) { mkdir($filePath, 0777, true); } @@ -263,7 +263,7 @@ public function downloadnopoen($hash) { 'Accept' => '*/*', 'Authorization' => "Bearer {$tokendata['token']}" ]); - $downloader = $client->download($filepath,$DOWNLOAD_DIR.'/'.substr($hash, 0, 2).'/'.$hash); + $downloader = $client->download($filepath,$download_dir.'/'.substr($hash, 0, 2).'/'.$hash); if (!$downloader) { mlog("Error download to the main control:{$client->errMsg}",2); return false; @@ -290,14 +290,14 @@ public function FilesCheckerhash() { $bar = new CliProgressBar(count($this->filesList)); $bar->setDetails("[FileCheck]"); $bar->display(); + $download_dir = api::getconfig()['file']['cache_dir']; foreach ($this->filesList as $file) { global $shouldExit; - global $DOWNLOAD_DIR; if ($shouldExit) { return; break; } - if (!file_exists($DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash)){ + if (!file_exists($download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash)){ $this->Missfile[] = new BMCLAPIFile( $file->path, $file->hash, @@ -306,7 +306,7 @@ public function FilesCheckerhash() { ); } else{ - if (hash_file('sha1',$DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash) != $file->hash) { + if (hash_file('sha1',$download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash) != $file->hash) { $this->Missfile[] = new BMCLAPIFile( $file->path, $file->hash, @@ -327,14 +327,14 @@ public function FilesCheckersize() { $bar = new CliProgressBar(count($this->filesList)); $bar->setDetails("[FileCheck]"); $bar->display(); + $download_dir = api::getconfig()['file']['cache_dir']; foreach ($this->filesList as $file) { global $shouldExit; - global $DOWNLOAD_DIR; if ($shouldExit) { return; break; } - if (!file_exists($DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash)){ + if (!file_exists($download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash)){ $this->Missfile[] = new BMCLAPIFile( $file->path, $file->hash, @@ -343,7 +343,7 @@ public function FilesCheckersize() { ); } else{ - if (filesize($DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash) != $file->size) { + if (filesize($download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash) != $file->size) { $this->Missfile[] = new BMCLAPIFile( $file->path, $file->hash, @@ -364,14 +364,14 @@ public function FilesCheckerexists() { $bar = new CliProgressBar(count($this->filesList)); $bar->setDetails("[FileCheck]"); $bar->display(); + $download_dir = api::getconfig()['file']['cache_dir']; foreach ($this->filesList as $file) { global $shouldExit; - global $DOWNLOAD_DIR; if ($shouldExit) { return; break; } - if (!file_exists($DOWNLOAD_DIR.'/'.substr($file->hash, 0, 2).'/'.$file->hash)){ + if (!file_exists($download_dir.'/'.substr($file->hash, 0, 2).'/'.$file->hash)){ $this->Missfile[] = new BMCLAPIFile( $file->path, $file->hash, diff --git a/inc/mlog.class.php b/inc/mlog.class.php index e402faf..9b8f203 100644 --- a/inc/mlog.class.php +++ b/inc/mlog.class.php @@ -46,6 +46,5 @@ function mlog($content, $type = 0, $minimalFormat = false) function isDebugMode() { - global $config; - return isset($config['advanced']['Debug']) && $config['advanced']['Debug']; + return isset(api::getconfig()['advanced']['Debug']) && api::getconfig()['advanced']['Debug']; } \ No newline at end of file diff --git a/inc/server.php b/inc/server.php index 5e719be..5a6a5a8 100644 --- a/inc/server.php +++ b/inc/server.php @@ -10,12 +10,11 @@ class fileserver { private $dir; private $secret; public function __construct($host,$port,$cert,$key,$secret) { - global $DOWNLOAD_DIR; $this->host = $host; $this->port = $port; $this->cert = $cert; $this->key = $key; - $this->dir = $DOWNLOAD_DIR; + $this->dir = api::getconfig()['file']['cache_dir']; $this->secret = $secret; } @@ -57,8 +56,7 @@ public function startserver() { } $length = $end_byte - $start_byte + 1; $fileSize = filesize($filepath); - global $enable; - if ($enable){ + if (api::getinfo()['enable']){ global $kacounters; $kacounters->incr('1','hits'); $kacounters->incr('1','bytes',$length); @@ -72,7 +70,7 @@ public function startserver() { $response->sendfile($filepath,$start_byte,$length); } else{ - global $enable; + $enable = api::getinfo()['enable']; if ($enable){ global $kacounters; $kacounters->incr('1','hits'); @@ -155,6 +153,36 @@ public function startserver() { } mlog(" Serve {$code} | {$request->server['remote_addr']} | {$request->server['server_protocol']} | {$url} | {$request->header['user-agent']};") ; }); + + $server->handle('/api/cluster', function ($request, $response) { + $type = $request->server['request_uri'] ? substr($request->server['request_uri'], strlen('/api/cluster') + 1) : ''; + if($type === "type"){ + $code = 200; + $response->header('Content-Type: application/json; charset=utf-8'); + + $response->end("hello"); + } + elseif($type === "status"){ + + } + elseif($type === "info"){ + + } + else{ + $code = 403; + $response->status($code); + $response->header('Content-Type', 'text/html; charset=utf-8'); + $response->end("Error
Forbidden
"); + } + if(!isset($request->server['query_string'])){ + $url = $request->server['request_uri']; + } + else{ + $url = $request->server['request_uri']."?".$request->server['query_string']; + } + mlog(" Serve {$code} | {$request->server['remote_addr']} | {$request->server['server_protocol']} | {$url} | {$request->header['user-agent']};") ; + }); + mlog("Start Http Server on {$this->host}:{$this->port}"); $server->start(); } diff --git a/inc/socketio.php b/inc/socketio.php index 74bf246..957cc91 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -8,7 +8,7 @@ class socketio { private $data; private $certdata; private $kattl; - private $rekeepalive; + private $rekeepalive = 1; private $Connected = false; public function __construct($url,$token,$kattl) { $this->url = $url; @@ -61,7 +61,7 @@ public function connect() { $this->certdata = $jsondata; } elseif (isset($jsondata[0][1]) && $jsondata[0][1] == "1"){ - global $enable; + $enable = api::getinfo()['enable']; $enable = true; mlog("节点已启用 Let's Goooooo!"); global $kacounters; @@ -76,7 +76,7 @@ public function connect() { }); } elseif (isset($jsondata[0][1]) && $jsondata[0][1] == "0"){ - if($this->rekeepalive < 3){ + if($this->rekeepalive <= 3){ mlog("Keep-Alive失败,正在重试({$this->rekeepalive}/3)"); global $kadata; $this->ack("keep-alive",$kadata); @@ -87,7 +87,7 @@ public function connect() { } } elseif (isset($jsondata[0][1]) && $this->IsTime($jsondata[0][1])){ - $this->rekeepalive = 0; + $this->rekeepalive = 1; global $kadata; mlog(" Keep-alive success: hits={$kadata['hits']} bytes={$kadata['bytes']} Time={$jsondata[0][1]}"); } @@ -115,9 +115,9 @@ public function connect() { //var_dump($data); } global $shouldExit; - global $httpserver; + $httpserver = api::getserver(); if ($shouldExit) { - global $enable; + $enable = api::getinfo()['enable']; if($enable){ Swoole\Timer::clear($katimeid); } @@ -195,7 +195,7 @@ public function IsTime($inputString) { } public function disable() { - global $enable; + $enable = api::getinfo()['enable']; if ($enable){ $this->ack("disable"); Coroutine::sleep(2); diff --git a/inc/webapi.php b/inc/webapi.php new file mode 100644 index 0000000..41ef0df --- /dev/null +++ b/inc/webapi.php @@ -0,0 +1,6 @@ +startserver(); }); + api::getserver($httpserver); //下载文件列表 $cluster = new cluster($tokendata['token'],VERSION); From 660cd1c3adb1f50d70355e553f0ad9f271b82823 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sun, 26 May 2024 17:52:55 +0800 Subject: [PATCH 07/22] =?UTF-8?q?=E2=9C=A8=20=E5=88=9D=E6=AD=A5=E6=8E=A5?= =?UTF-8?q?=E5=85=A5api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/api.php | 9 +-------- inc/server.php | 11 +++++++---- inc/socketio.php | 11 ++++------- inc/webapi.php | 25 +++++++++++++++++++++++-- main.php | 16 ++++++++++++---- 5 files changed, 47 insertions(+), 25 deletions(-) diff --git a/inc/api.php b/inc/api.php index 0ef3b85..f29da21 100644 --- a/inc/api.php +++ b/inc/api.php @@ -1,8 +1,7 @@ false,'isSynchronized'=>true]; - private static $server; + private static $info = ['enable'=>false,'isSynchronized'=>false,'uptime'=>0]; public static function getconfig($newConfig = null) { if (!is_null($newConfig)) { @@ -17,10 +16,4 @@ public static function getinfo($newinfo = null) { } return self::$info; } - public static function getserver($newserver = null) { - if (!is_null($newserver)) { - self::$server = $newserver; - } - return self::$server; - } } \ No newline at end of file diff --git a/inc/server.php b/inc/server.php index 5a6a5a8..104f78d 100644 --- a/inc/server.php +++ b/inc/server.php @@ -158,12 +158,15 @@ public function startserver() { $type = $request->server['request_uri'] ? substr($request->server['request_uri'], strlen('/api/cluster') + 1) : ''; if($type === "type"){ $code = 200; - $response->header('Content-Type: application/json; charset=utf-8'); - - $response->end("hello"); + $response->header('Content-Type', 'application/json; charset=utf-8'); + $type = new webapi(); + $response->end($type->gettype()); } elseif($type === "status"){ - + $code = 200; + $response->header('Content-Type', 'application/json; charset=utf-8'); + $type = new webapi(); + $response->end($type->getstatus()); } elseif($type === "info"){ diff --git a/inc/socketio.php b/inc/socketio.php index 957cc91..6413c22 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -61,8 +61,9 @@ public function connect() { $this->certdata = $jsondata; } elseif (isset($jsondata[0][1]) && $jsondata[0][1] == "1"){ - $enable = api::getinfo()['enable']; - $enable = true; + $enable = api::getinfo(); + $enable['enable'] = true; + api::getinfo($enable); mlog("节点已启用 Let's Goooooo!"); global $kacounters; $kacounters = new Swoole\Table(1024); @@ -115,12 +116,8 @@ public function connect() { //var_dump($data); } global $shouldExit; - $httpserver = api::getserver(); + global $httpserver; if ($shouldExit) { - $enable = api::getinfo()['enable']; - if($enable){ - Swoole\Timer::clear($katimeid); - } $this->disable(); $httpserver->stopserver(); return; diff --git a/inc/webapi.php b/inc/webapi.php index 41ef0df..17dbfd3 100644 --- a/inc/webapi.php +++ b/inc/webapi.php @@ -1,6 +1,27 @@ 200, + 'msg' => 'success', + 'type' => 'php-openbmclapi', + 'version'=> PHPOBAVERSION . "-" . VERSION + ]; + $type = json_encode($array); + return $type; + } + public function getstatus() { + $array = [ + 'code' => 200, + 'msg' => 'success', + 'data' => [ + "isEnabled" => api::getinfo()['enable'], + "isSynchronized" => api::getinfo()['isSynchronized'], + "isTrusted" => true, + "uptime" => api::getinfo()['uptime'] + ] + ]; + $type = json_encode($array); + return $type; } } \ No newline at end of file diff --git a/main.php b/main.php index df4f3ec..322dbc1 100644 --- a/main.php +++ b/main.php @@ -12,7 +12,7 @@ const PHPOBAVERSION = '1.6.0'; const VERSION = '1.10.6'; $download_dir = api::getconfig()['file']['cache_dir']; -const USERAGENT = 'openbmclapi-cluster/' . VERSION . ' ' . 'PHP-OpenBmclApi/'.PHPOBAVERSION; +const USERAGENT = 'openbmclapi-cluster/' . VERSION . ' ' . 'php-openbmclapi/'.PHPOBAVERSION; const OPENBMCLAPIURL = 'openbmclapi.staging.bangbang93.com'; mlog("OpenBmclApi on PHP v". PHPOBAVERSION . "-" . VERSION,0,true); run(function(){ @@ -20,9 +20,8 @@ //注册信号处理器、 function exits() { global $shouldExit; - global $tokentimerid; $shouldExit = true; // 设置退出标志 - Swoole\Timer::clear($tokentimerid); + Swoole\Timer::clearAll(); echo PHP_EOL; mlog("正在退出..."); } @@ -83,11 +82,14 @@ function registerSigintHandler() { fclose($cert); } //启动http服务器 + global $httpserver; $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],$config['cluster']['CLUSTER_ID'].'.crt',$config['cluster']['CLUSTER_ID'].'.key',$config['cluster']['CLUSTER_SECRET']); Coroutine::create(function () use ($config,$httpserver){ $httpserver->startserver(); }); - api::getserver($httpserver); + $uptime = api::getinfo(); + $uptime['uptime'] = time(); + api::getinfo($uptime); //下载文件列表 $cluster = new cluster($tokendata['token'],VERSION); @@ -122,6 +124,9 @@ function registerSigintHandler() { //mlog("缺失/损坏".count($Missfile)."个文件"); } else{ + $isSynchronized = api::getinfo(); + $isSynchronized['isSynchronized'] = true; + api::getinfo($isSynchronized); mlog("检查文件完毕,没有缺失/损坏"); } } @@ -129,6 +134,9 @@ function registerSigintHandler() { else{ global $shouldExit; if (!$shouldExit){ + $isSynchronized = api::getinfo(); + $isSynchronized['isSynchronized'] = true; + api::getinfo($isSynchronized); mlog("检查文件完毕,没有缺失/损坏"); } } From a800adc1da0b409cc6058c7b4296a4d7f16b5ca1 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 1 Jun 2024 16:36:16 +0800 Subject: [PATCH 08/22] =?UTF-8?q?=F0=9F=90=9B=20=E7=BB=88=E4=BA=8E?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=81=87=E6=AD=BB=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/socketio.php | 58 +++++++++++++++++++++++++----------------------- main.php | 11 ++++++++- 2 files changed, 40 insertions(+), 29 deletions(-) diff --git a/inc/socketio.php b/inc/socketio.php index 6413c22..b01975d 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -10,7 +10,7 @@ class socketio { private $kattl; private $rekeepalive = 1; private $Connected = false; - public function __construct($url,$token,$kattl) { + public function __construct($url=null,$token=null,$kattl=null) { $this->url = $url; $this->token = $token; $this->kattl = $kattl; @@ -25,9 +25,13 @@ public function connect() { if ($ret) { $client->push('40'.json_encode($auth)); } - while(true) { - $alldata = $client->recv(1); + $alldata = $client->recv(); + if (empty($alldata)) { + $client->close(); + mlog("与主控的连接断开"); + break; + } if (!is_bool($alldata)){ $this->data = $data = $alldata->data; preg_match('/^\d+/', $data, $code); @@ -51,9 +55,9 @@ public function connect() { } if ($code[0] == '41'){ mlog("[socket.io]Close Connection"); - exits(); $client->close(); - return; + exits(); + break; } if ($code[0] == '430'){ $jsondata = json_decode(substr($data, strlen($code[0])),true); @@ -62,19 +66,27 @@ public function connect() { } elseif (isset($jsondata[0][1]) && $jsondata[0][1] == "1"){ $enable = api::getinfo(); - $enable['enable'] = true; - api::getinfo($enable); - mlog("节点已启用 Let's Goooooo!"); - global $kacounters; - $kacounters = new Swoole\Table(1024); - $kacounters->column('hits', Swoole\Table::TYPE_FLOAT); - $kacounters->column('bytes', Swoole\Table::TYPE_FLOAT); - $kacounters->create(); - $kacounters->set('1', ['hits' => 0, 'bytes' => 0]); - global $katimeid; - $katimeid = Swoole\Timer::tick($this->kattl*1000, function () use ($kacounters) { - $this->keepalive($kacounters); - }); + if(!$enable['enable']){ + $enable = api::getinfo(); + $enable['enable'] = true; + api::getinfo($enable); + mlog("节点已启用 Let's Goooooo!"); + global $kacounters; + $kacounters = new Swoole\Table(1024); + $kacounters->column('hits', Swoole\Table::TYPE_FLOAT); + $kacounters->column('bytes', Swoole\Table::TYPE_FLOAT); + $kacounters->create(); + $kacounters->set('1', ['hits' => 0, 'bytes' => 0]); + global $katimeid; + $katimeid = Swoole\Timer::tick($this->kattl*1000, function () use ($kacounters) { + $this->keepalive($kacounters); + }); + } + else{ + $client->close(); + break; + mlog("[socket.io]Close Connection"); + } } elseif (isset($jsondata[0][1]) && $jsondata[0][1] == "0"){ if($this->rekeepalive <= 3){ @@ -115,13 +127,6 @@ public function connect() { } //var_dump($data); } - global $shouldExit; - global $httpserver; - if ($shouldExit) { - $this->disable(); - $httpserver->stopserver(); - return; - } } } public function Getcert() { @@ -195,9 +200,6 @@ public function disable() { $enable = api::getinfo()['enable']; if ($enable){ $this->ack("disable"); - Coroutine::sleep(2); } - mlog("[socket.io]Close Connection",1); - $this->client->close(); } } \ No newline at end of file diff --git a/main.php b/main.php index 322dbc1..f4f6137 100644 --- a/main.php +++ b/main.php @@ -22,6 +22,14 @@ function exits() { global $shouldExit; $shouldExit = true; // 设置退出标志 Swoole\Timer::clearAll(); + global $socketio; + if (is_object($socketio)) { + $socketio->disable(); + } + global $httpserver; + if (is_object($httpserver)) { + $httpserver->stopserver(); + } echo PHP_EOL; mlog("正在退出..."); } @@ -46,9 +54,10 @@ function registerSigintHandler() { registerSigintHandler(); mlog("Timer start on ID{$tokentimerid}",1); //建立socketio连接主控 + global $socketio; $socketio = new socketio(OPENBMCLAPIURL,$tokendata['token'],$config['advanced']['keepalive']); mlog("正在连接主控"); - Coroutine::create(function () use ($socketio){ + Coroutine::create(function () use (&$socketio){ $socketio->connect(); }); Coroutine::sleep(1); From 7f41afa4b6c93295cdd1f79ba407bd6f3cdc73b2 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 1 Jun 2024 17:07:36 +0800 Subject: [PATCH 09/22] =?UTF-8?q?=E2=9C=A8=20=E5=AE=8C=E6=95=B4=E7=9A=84?= =?UTF-8?q?=20Status=20=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/server.php | 2 ++ inc/socketio.php | 10 ++++++++-- inc/webapi.php | 15 ++++++++------- main.php | 2 +- 4 files changed, 19 insertions(+), 10 deletions(-) diff --git a/inc/server.php b/inc/server.php index 104f78d..336f98e 100644 --- a/inc/server.php +++ b/inc/server.php @@ -177,12 +177,14 @@ public function startserver() { $response->header('Content-Type', 'text/html; charset=utf-8'); $response->end("Error
Forbidden
"); } + if(!isset($request->server['query_string'])){ $url = $request->server['request_uri']; } else{ $url = $request->server['request_uri']."?".$request->server['query_string']; } + mlog(" Serve {$code} | {$request->server['remote_addr']} | {$request->server['server_protocol']} | {$url} | {$request->header['user-agent']};") ; }); diff --git a/inc/socketio.php b/inc/socketio.php index b01975d..94f7ae1 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -47,7 +47,13 @@ public function connect() { } if ($code[0] == '42'){ $data = substr($data, strlen($code[0])); - mlog("[socket.io]{$data}"); + $jsondata = json_decode($data); + if(isset($jsondata[0])){ + mlog("{$jsondata[1]}"); + } + else{ + mlog("[socket.io]{$data}"); + } } if ($code[0] == '2'){ $client->push('3'); @@ -112,7 +118,7 @@ public function connect() { } } else { - mlog("[socket.io]Got data {$data}"); + mlog("[socket.io]Got data {$data}"); }; //mlog("[socket.io]Got MESSAGE {$data}",1); } diff --git a/inc/webapi.php b/inc/webapi.php index 17dbfd3..3a71618 100644 --- a/inc/webapi.php +++ b/inc/webapi.php @@ -2,23 +2,24 @@ class webapi{ public function gettype() { $array = [ - 'code' => 200, - 'msg' => 'success', 'type' => 'php-openbmclapi', - 'version'=> PHPOBAVERSION . "-" . VERSION + 'openbmclapiVersion' => VERSION, + 'version'=> 'v' . PHPOBAVERSION ]; $type = json_encode($array); return $type; } public function getstatus() { $array = [ - 'code' => 200, - 'msg' => 'success', - 'data' => [ + 'clusterStatus' => [ "isEnabled" => api::getinfo()['enable'], "isSynchronized" => api::getinfo()['isSynchronized'], "isTrusted" => true, - "uptime" => api::getinfo()['uptime'] + "uptime" => api::getinfo()['uptime'], + "systemOccupancy" =>[ + "memoryUsage" => memory_get_usage(), + "loadAverage" => sys_getloadavg()[0] + ] ] ]; $type = json_encode($array); diff --git a/main.php b/main.php index f4f6137..084c711 100644 --- a/main.php +++ b/main.php @@ -13,7 +13,7 @@ const VERSION = '1.10.6'; $download_dir = api::getconfig()['file']['cache_dir']; const USERAGENT = 'openbmclapi-cluster/' . VERSION . ' ' . 'php-openbmclapi/'.PHPOBAVERSION; -const OPENBMCLAPIURL = 'openbmclapi.staging.bangbang93.com'; +const OPENBMCLAPIURL = 'openbmclapi.bangbang93.com'; mlog("OpenBmclApi on PHP v". PHPOBAVERSION . "-" . VERSION,0,true); run(function(){ $config = api::getconfig(); From f67148f1e9a0cf1a9ae86ef28dc83d81871ca11c Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Mon, 10 Jun 2024 15:19:20 +0800 Subject: [PATCH 10/22] =?UTF-8?q?=E2=9C=A8=20=E5=AE=8C=E5=85=A8=E6=94=AF?= =?UTF-8?q?=E6=8C=81API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.php | 1 + inc/database.php | 136 +++++++++++++++++++++++++++++++++++++++++++++++ inc/server.php | 29 +++++----- inc/socketio.php | 17 ++++++ inc/webapi.php | 75 ++++++++++++++++++++++++++ main.php | 7 ++- 6 files changed, 250 insertions(+), 15 deletions(-) create mode 100644 inc/database.php diff --git a/config.php b/config.php index adf6ec8..c653467 100644 --- a/config.php +++ b/config.php @@ -12,6 +12,7 @@ "file"=> [ "cache_dir"=> "./cache",//缓存文件夹 "check"=> "size",//检查文件策略(hash:检查文件hash size:检查文件大小 exists:检查文件是否存在) + "database_dir"=> "./database",//访问数据数据库目录 ], "advanced"=> [ "keepalive"=> 60,//keepalive时间,秒为单位(不建议调整) diff --git a/inc/database.php b/inc/database.php new file mode 100644 index 0000000..0114a9c --- /dev/null +++ b/inc/database.php @@ -0,0 +1,136 @@ +dirPath) { + $base_dir = api::getconfig(); + $this->dirPath = $base_dir['file']['database_dir']; + } + } + + public function initializeDatabase() { + $filename = $this->dirPath . '/' . date('Ymd'); + if (!is_dir($this->dirPath)) { + mkdir($this->dirPath, 0777, true); + } + if (!file_exists($filename)) { + $initialData = []; + for ($hour = 0; $hour < 24; ++$hour) { + $timeKey = date('Ymd') . str_pad($hour, 2, '0', STR_PAD_LEFT); + $initialData[$timeKey] = ['hits' => 0, 'bytes' => 0]; + } + file_put_contents($filename, json_encode($initialData, JSON_PRETTY_PRINT)); + } + } + + public function writeDatabase($hits, $bytes) { + $filename = $this->dirPath . '/' . date('Ymd'); + if (!file_exists($filename)) { + $this->initializeDatabase(); + } + $data = json_decode(Swoole\Coroutine\System::readFile($filename), true); + $timeKey = date('Ymd') . str_pad(date('G'), 2, '0', STR_PAD_LEFT); + if (!isset($data[$timeKey])) { + $data[$timeKey] = ['hits' => 0, 'bytes' => 0]; + } + $data[$timeKey]['hits'] += $hits; + $data[$timeKey]['bytes'] += $bytes; + $w = Swoole\Coroutine\System::writeFile($filename, json_encode($data, JSON_PRETTY_PRINT)); + } + + public function getDaysData(): array { + $dailyTraffic = []; + $endDate = date('Ymd'); + $startDate = date('Ymd', strtotime('-14 days')); + + for ($i = 0; $i <= 14; ++$i) { + $date = date('Ymd', strtotime("-$i days", strtotime($endDate))); + $filename = $this->dirPath . '/' . $date; + $dailySummary = ['hits' => 0, 'bytes' => 0]; + if (file_exists($filename)) { + $data = json_decode(Swoole\Coroutine\System::readFile($filename), true); + foreach ($data as $hourlyRecord) { + if (isset($hourlyRecord['hits']) && isset($hourlyRecord['bytes'])) { + $dailySummary['hits'] += $hourlyRecord['hits']; + $dailySummary['bytes'] += $hourlyRecord['bytes']; + } + } + } + $dailyTraffic[$date] = $dailySummary; + } + ksort($dailyTraffic); + return $dailyTraffic; + } + + public function getMonthsData(): array { + $monthlyTraffic = []; + $endDate = new DateTime(); // 获取当前日期 + $startDate = clone $endDate; + $startDate->modify('-11 months'); // 回溯11个月,以包含完整的12个月数据 + + while ($startDate <= $endDate) { + $monthStr = $startDate->format('Ym'); // 格式化为YYYYMM格式 + $monthlySummary = ['hits' => 0, 'bytes' => 0]; + + for ($day = 1; $day <= $startDate->format('t'); ++$day) { // 遍历当月的所有天 + $dateStr = $startDate->format('Ymd'); + $filename = $this->dirPath . '/' . $dateStr; + + if (file_exists($filename)) { + $data = json_decode(file_get_contents($filename), true); // 使用file_get_contents以兼容更多环境 + + foreach ($data as $hourlyRecord) { + if (isset($hourlyRecord['hits']) && isset($hourlyRecord['bytes'])) { + $monthlySummary['hits'] += $hourlyRecord['hits']; + $monthlySummary['bytes'] += $hourlyRecord['bytes']; + } + } + } + $startDate->modify('+1 day'); // 移动到下一天 + } + + // 累加完一个月的数据后存入结果数组 + $monthlyTraffic[$monthStr] = $monthlySummary; + } + + return $monthlyTraffic; + } + + public function getYearsData(): array { + $annualTraffic = []; + $currentYear = (int)date('Y'); + $startYear = $currentYear - 5; + + for ($year = $startYear; $year <= $currentYear; ++$year) { + $yearHits = 0; + $yearBytes = 0; + + for ($month = 1; $month <= 12; ++$month) { + for ($day = 1; $day <= 31; ++$day) { // 假定每月最多31天,实际应用需按月份调整 + $date = sprintf('%04d%02d%02d', $year, $month, $day); + $filename = $this->dirPath . '/' . $date; + + if (file_exists($filename)) { + $data = json_decode(Swoole\Coroutine\System::readFile($filename), true); + foreach ($data as $hourlyRecord) { + if (isset($hourlyRecord['hits']) && isset($hourlyRecord['bytes'])) { + $yearHits += $hourlyRecord['hits']; + $yearBytes += $hourlyRecord['bytes']; + } + } + } + } + } + + // 累计完一年的数据后存入结果数组 + $annualTraffic[$year] = [ + 'hits' => $yearHits, + 'bytes' => $yearBytes + ]; + } + + return $annualTraffic; + } +} \ No newline at end of file diff --git a/inc/server.php b/inc/server.php index 336f98e..529dc2f 100644 --- a/inc/server.php +++ b/inc/server.php @@ -55,12 +55,6 @@ public function startserver() { $end_byte = filesize($filepath) - 1; } $length = $end_byte - $start_byte + 1; - $fileSize = filesize($filepath); - if (api::getinfo()['enable']){ - global $kacounters; - $kacounters->incr('1','hits'); - $kacounters->incr('1','bytes',$length); - } $code = 206; $response->header('Content-Type', 'application/octet-stream'); if(isset($request->header['name'])){ @@ -70,12 +64,7 @@ public function startserver() { $response->sendfile($filepath,$start_byte,$length); } else{ - $enable = api::getinfo()['enable']; - if ($enable){ - global $kacounters; - $kacounters->incr('1','hits'); - $kacounters->incr('1','bytes',filesize($filepath)); - } + $length = filesize($filepath); $code = 200; $response->header('Content-Type', 'application/octet-stream'); if(isset($request->header['name'])){ @@ -84,6 +73,15 @@ public function startserver() { $response->header('x-bmclapi-hash', $downloadhash); $response->sendfile($filepath); } + if (api::getinfo()['enable']){ + global $kacounters; + $kacounters->incr('1','hits'); + $kacounters->incr('1','bytes',$length); + + global $dbcounters; + $dbcounters->incr('1','hits'); + $dbcounters->incr('1','bytes',$length); + } } else{ $code = 403; @@ -169,7 +167,10 @@ public function startserver() { $response->end($type->getstatus()); } elseif($type === "info"){ - + $code = 200; + $response->header('Content-Type', 'application/json; charset=utf-8'); + $type = new webapi(); + $response->end($type->getinfo()); } else{ $code = 403; @@ -196,7 +197,7 @@ public function stopserver() { $this->server->shutdown(); } //你问我这段函数为什么要放在server里面? 因为只有server需要check_sign( - public function check_sign(string $hash, string $secret, string $s, string $e): bool { + public function check_sign(string $hash, string $secret, string $s=null, string $e=null): bool { try { $t = intval($e, 36); } catch (\Exception $ex) { diff --git a/inc/socketio.php b/inc/socketio.php index 94f7ae1..29f4334 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -87,6 +87,16 @@ public function connect() { $katimeid = Swoole\Timer::tick($this->kattl*1000, function () use ($kacounters) { $this->keepalive($kacounters); }); + + global $dbcounters; + $dbcounters = new Swoole\Table(1024); + $dbcounters->column('hits', Swoole\Table::TYPE_FLOAT); + $dbcounters->column('bytes', Swoole\Table::TYPE_FLOAT); + $dbcounters->create(); + $dbcounters->set('1', ['hits' => 0, 'bytes' => 0]); + $dbtimeid = Swoole\Timer::tick(3000, function () use ($dbcounters) { + $this->updatedatabase($dbcounters); + }); } else{ $client->close(); @@ -197,6 +207,11 @@ public function keepalive($kacounters) { $kacounters->set('1', ['hits' => 0, 'bytes' => 0]); } + public function updatedatabase($dbcounters) { + $database = new database(); + $database->writeDatabase($dbcounters->get('1','hits'),$dbcounters->get('1','bytes')); + $dbcounters->set('1', ['hits' => 0, 'bytes' => 0]); + } public function IsTime($inputString) { $pattern = '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/'; return preg_match($pattern, $inputString) === 1; @@ -207,5 +222,7 @@ public function disable() { if ($enable){ $this->ack("disable"); } + $this->client->close(); + $this->Connected = false; } } \ No newline at end of file diff --git a/inc/webapi.php b/inc/webapi.php index 3a71618..21dd7b2 100644 --- a/inc/webapi.php +++ b/inc/webapi.php @@ -1,4 +1,5 @@ [ + "hours" => $this->DataTohours(), + "days" => $this->DataTodays(), + "months" => $this->DataTomonths() + ] + ]; + $type = json_encode($array); + return $type; + } + + public function DataTohours() { + $base_dir = api::getconfig(); + $dirPath = $base_dir['file']['database_dir']; + $data = file_get_contents($dirPath . '/' . date('Ymd')); // 读取文件内容 + $dataArray = json_decode($data, true); // 解码JSON数据为关联数组 + + if (json_last_error() !== JSON_ERROR_NONE) { + echo "Error decoding JSON: " . json_last_error_msg(); + return []; + } + + $formattedData = []; + $currentHourTimestamp = strtotime(date('Y-m-d H:00:00', time())); // 当前小时的时间戳 + $twelveHoursAgoTimestamp = $currentHourTimestamp - (12 * 3600); // 12小时前的时间戳 + foreach ($dataArray as $key => $value) { + // 提取日期时间字符串的前8位为日期(如20240610),后两位为小时 + $dateStr = substr($key, 0, 8); + $hour = intval(substr($key, 8)); + // 假设日期格式为YYYYMMDD,转换为Unix时间戳(这里未考虑时区,实际应用中可能需要调整) + $timestamp = mktime(0, 0, 0, substr($dateStr, 4, 2), substr($dateStr, 6, 2), substr($dateStr, 0, 4)) + ($hour * 3600); + if ($timestamp >= $twelveHoursAgoTimestamp && $timestamp < $currentHourTimestamp){ + $formattedData[] = [ + 'timestamp' => $timestamp, + 'hits' => $value['hits'], + 'bytes' => $value['bytes'] + ]; + } + } + return $formattedData; + } + + public function DataTodays() { + $database = new Database(); + $data = $database->getDaysData(); + $formattedData = []; + foreach ($data as $date => $stats) { + $timestamp = strtotime($date); + $formattedData[] = [ + 'timestamp' => $timestamp, + 'hits' => $stats['hits'], + 'bytes' => $stats['bytes'] + ]; + } + + return $formattedData; + } + + public function DataTomonths() { + $database = new Database(); + $data = $database->getMonthsData(); + $formattedData = []; + foreach ($data as $date => $stats) { + $timestamp = strtotime($date . 00); + $formattedData[] = [ + 'timestamp' => $timestamp, + 'hits' => $stats['hits'], + 'bytes' => $stats['bytes'] + ]; + } + return $formattedData; + } } \ No newline at end of file diff --git a/main.php b/main.php index 084c711..07c873f 100644 --- a/main.php +++ b/main.php @@ -10,7 +10,7 @@ } api::getconfig($config); const PHPOBAVERSION = '1.6.0'; -const VERSION = '1.10.6'; +const VERSION = '1.10.9'; $download_dir = api::getconfig()['file']['cache_dir']; const USERAGENT = 'openbmclapi-cluster/' . VERSION . ' ' . 'php-openbmclapi/'.PHPOBAVERSION; const OPENBMCLAPIURL = 'openbmclapi.bangbang93.com'; @@ -40,6 +40,11 @@ function registerSigintHandler() { exits(); }); } + + //创建数据库 + $database = new database(); + $database->initializedatabase(); + //获取初次Token $token = new token($config['cluster']['CLUSTER_ID'],$config['cluster']['CLUSTER_SECRET'],VERSION); $tokendata = $token->gettoken(); From 606d10d9cf63f23541d75b39c63c0fc3d7786ed6 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Mon, 10 Jun 2024 16:35:48 +0800 Subject: [PATCH 11/22] =?UTF-8?q?=E2=9C=A8=20=E6=94=AF=E6=8C=81=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- inc/PluginInfoInterface.php | 7 +++++++ inc/pluginsmanager.php | 42 +++++++++++++++++++++++++++++++++++++ inc/server.php | 9 ++++++-- main.php | 12 +++++++++-- 5 files changed, 69 insertions(+), 7 deletions(-) create mode 100644 inc/PluginInfoInterface.php create mode 100644 inc/pluginsmanager.php diff --git a/README.md b/README.md index 06bf8ae..3f88d4b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ PHP 版本 >= 8.0.0 - [Swoole](https://www.swoole.com/) 版本 >= 5.1. + [Swoole](https://www.swoole.com/) 版本 >= 5.1.0 以及对应版本的 [Zstd](https://github.com/kjdev/php-ext-zstd) @@ -81,12 +81,12 @@ $config=[ ``` ## 📍 Todo -- [ ] Web仪表盘(主要) - [ ] 支持WebDAV - [ ] 打包二进制文件 -- [ ] 完善Log系统 - [ ] 添加注释 - [x] 可以正常上线使用 +- [x] 插件系统 +- [x] 完善Log系统 ## ❓ FAQ diff --git a/inc/PluginInfoInterface.php b/inc/PluginInfoInterface.php new file mode 100644 index 0000000..f2606cd --- /dev/null +++ b/inc/PluginInfoInterface.php @@ -0,0 +1,7 @@ +pluginsPath)) { + mkdir($this->pluginsPath, 0777, true); + } + } + + public function loadPlugins(&$server) { + $pluginsInfo = []; + $files = scandir($this->pluginsPath); + + foreach ($files as $file) { + if ($file == '.' || $file == '..' || pathinfo($file, PATHINFO_EXTENSION) != 'php') { + continue; + } + + $className = "Plugin\\" . basename($file, '.plugin.php'); // 确保类名包含命名空间 + require_once $this->pluginsPath . '/' . $file; + if (class_exists($className) && in_array('Plugin\PluginInfoInterface', class_implements($className))) { + try { + $pluginInstance = new $className(); + $pluginsInfo[$className] = $pluginInstance->getInfo(); + mlog("已加载插件: " . $pluginsInfo[$className]['Name'] . ", 作者: " . $pluginsInfo[$className]['Author'] . ", 版本: " . $pluginsInfo[$className]['Version']); + if($pluginsInfo[$className]['ServerSupport']){ + $pluginInstance->main($server); + } + else{ + $pluginInstance->main(); + } + } catch (Exception $e) { + error_log("Error instantiating plugin class {$className}: " . $e->getMessage()); + } + } + } + + return $pluginsInfo; + } + +} \ No newline at end of file diff --git a/inc/server.php b/inc/server.php index 529dc2f..f177490 100644 --- a/inc/server.php +++ b/inc/server.php @@ -9,6 +9,7 @@ class fileserver { private $server; private $dir; private $secret; + private $lock; public function __construct($host,$port,$cert,$key,$secret) { $this->host = $host; $this->port = $port; @@ -16,9 +17,10 @@ public function __construct($host,$port,$cert,$key,$secret) { $this->key = $key; $this->dir = api::getconfig()['file']['cache_dir']; $this->secret = $secret; + $this->lock = new Swoole\Lock(SWOOLE_RWLOCK); } - public function startserver() { + public function setupserver() { $this->server = $server = new Server($this->host, $this->port, true); $server->set([ 'ssl_cert_file' => './cert/'.$this->cert, @@ -188,9 +190,12 @@ public function startserver() { mlog(" Serve {$code} | {$request->server['remote_addr']} | {$request->server['server_protocol']} | {$url} | {$request->header['user-agent']};") ; }); + return $server; + } + public function startserver() { mlog("Start Http Server on {$this->host}:{$this->port}"); - $server->start(); + $this->server->start(); } public function stopserver() { mlog("Stop Http Server",1); diff --git a/main.php b/main.php index 07c873f..4113bd8 100644 --- a/main.php +++ b/main.php @@ -13,7 +13,7 @@ const VERSION = '1.10.9'; $download_dir = api::getconfig()['file']['cache_dir']; const USERAGENT = 'openbmclapi-cluster/' . VERSION . ' ' . 'php-openbmclapi/'.PHPOBAVERSION; -const OPENBMCLAPIURL = 'openbmclapi.bangbang93.com'; +const OPENBMCLAPIURL = 'openbmclapi.staging.bangbang93.com'; mlog("OpenBmclApi on PHP v". PHPOBAVERSION . "-" . VERSION,0,true); run(function(){ $config = api::getconfig(); @@ -58,6 +58,7 @@ function registerSigintHandler() { }); registerSigintHandler(); mlog("Timer start on ID{$tokentimerid}",1); + //建立socketio连接主控 global $socketio; $socketio = new socketio(OPENBMCLAPIURL,$tokendata['token'],$config['advanced']['keepalive']); @@ -95,9 +96,16 @@ function registerSigintHandler() { $Writtencert = fwrite($cert, $allcert['0']['1']['key']); fclose($cert); } - //启动http服务器 + //设置http服务器 global $httpserver; $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],$config['cluster']['CLUSTER_ID'].'.crt',$config['cluster']['CLUSTER_ID'].'.key',$config['cluster']['CLUSTER_SECRET']); + $server = $httpserver->setupserver(); + + //开始加载插件 + $pluginsManager = new PluginsManager(); + $pluginsManager->loadPlugins($server); + + //启动http服务器 Coroutine::create(function () use ($config,$httpserver){ $httpserver->startserver(); }); From 9148de725910e2aa528c270e503a86f14e678e01 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Mon, 10 Jun 2024 17:28:15 +0800 Subject: [PATCH 12/22] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8DAPI?= =?UTF-8?q?=E4=B8=80=E7=9B=B4=E5=90=8C=E6=AD=A5=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/main.php b/main.php index 4113bd8..b5e410c 100644 --- a/main.php +++ b/main.php @@ -126,6 +126,9 @@ function registerSigintHandler() { elseif($config['file']['check'] == "exists"){ $Missfile = $FilesCheck->FilesCheckerexists(); } + $isSynchronized = api::getinfo(); + $isSynchronized['isSynchronized'] = true; + api::getinfo($isSynchronized); //循环到没有Missfile这个变量 if (is_array($Missfile)){ mlog("缺失/损坏".count($Missfile)."个文件"); @@ -147,7 +150,7 @@ function registerSigintHandler() { } else{ $isSynchronized = api::getinfo(); - $isSynchronized['isSynchronized'] = true; + $isSynchronized['isSynchronized'] = false; api::getinfo($isSynchronized); mlog("检查文件完毕,没有缺失/损坏"); } @@ -157,7 +160,7 @@ function registerSigintHandler() { global $shouldExit; if (!$shouldExit){ $isSynchronized = api::getinfo(); - $isSynchronized['isSynchronized'] = true; + $isSynchronized['isSynchronized'] = false; api::getinfo($isSynchronized); mlog("检查文件完毕,没有缺失/损坏"); } From 0a5472d23e918365dd3b45307ede678b809703f7 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sun, 16 Jun 2024 15:16:23 +0800 Subject: [PATCH 13/22] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8Dapi?= =?UTF-8?q?=E5=9C=A8=E5=87=8C=E6=99=A8=E4=B8=8D=E8=BF=94=E5=9B=9E=E5=AE=8C?= =?UTF-8?q?=E6=95=B4=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/webapi.php | 68 +++++++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 26 deletions(-) diff --git a/inc/webapi.php b/inc/webapi.php index 21dd7b2..7839992 100644 --- a/inc/webapi.php +++ b/inc/webapi.php @@ -39,35 +39,51 @@ public function getinfo() { return $type; } - public function DataTohours() { - $base_dir = api::getconfig(); - $dirPath = $base_dir['file']['database_dir']; - $data = file_get_contents($dirPath . '/' . date('Ymd')); // 读取文件内容 - $dataArray = json_decode($data, true); // 解码JSON数据为关联数组 + public function dataToHours() { + $base_dir = api::getconfig(); + $dirPath = $base_dir['file']['database_dir']; + $currentHourTimestamp = strtotime(date('Y-m-d H:00:00')); + $twelveHoursAgoTimestamp = $currentHourTimestamp - (12 * 3600); + $formattedData = []; - if (json_last_error() !== JSON_ERROR_NONE) { - echo "Error decoding JSON: " . json_last_error_msg(); - return []; - } + // 处理今天的数据 + $todayData = @file_get_contents($dirPath . '/' . date('Ymd')); + $dataArrayToday = json_decode($todayData, true); + if (json_last_error() !== JSON_ERROR_NONE) { + echo "Error decoding today's JSON: " . json_last_error_msg(); + return []; + } + + // 如果需要包含昨天的数据 + $yesterdayKey = date('Ymd', strtotime('-1 day')); + if (strtotime(date('Y-m-d')) !== strtotime($yesterdayKey)) { // 确保昨天的日期正确 + echo $yesterdayKey; + $yesterdayData = @file_get_contents($dirPath . '/' . $yesterdayKey); + $dataArrayYesterday = json_decode($yesterdayData, true); + if (json_last_error() !== JSON_ERROR_NONE) { + echo "Error decoding yesterday's JSON: " . json_last_error_msg(); + return []; + } + $dataArray = array_replace($dataArrayYesterday, $dataArrayToday); + } else { + $dataArray = $dataArrayToday; + } - $formattedData = []; - $currentHourTimestamp = strtotime(date('Y-m-d H:00:00', time())); // 当前小时的时间戳 - $twelveHoursAgoTimestamp = $currentHourTimestamp - (12 * 3600); // 12小时前的时间戳 - foreach ($dataArray as $key => $value) { - // 提取日期时间字符串的前8位为日期(如20240610),后两位为小时 - $dateStr = substr($key, 0, 8); - $hour = intval(substr($key, 8)); - // 假设日期格式为YYYYMMDD,转换为Unix时间戳(这里未考虑时区,实际应用中可能需要调整) - $timestamp = mktime(0, 0, 0, substr($dateStr, 4, 2), substr($dateStr, 6, 2), substr($dateStr, 0, 4)) + ($hour * 3600); - if ($timestamp >= $twelveHoursAgoTimestamp && $timestamp < $currentHourTimestamp){ - $formattedData[] = [ - 'timestamp' => $timestamp, - 'hits' => $value['hits'], - 'bytes' => $value['bytes'] - ]; + // 统一处理数据 + foreach ($dataArray as $key => $value) { + $dateStr = substr($key, 0, 8); + $hour = intval(substr($key, 8)); + $timestamp = mktime(0, 0, 0, substr($dateStr, 4, 2), substr($dateStr, 6, 2), substr($dateStr, 0, 4)) + ($hour * 3600); + if ($timestamp >= $twelveHoursAgoTimestamp && $timestamp < $currentHourTimestamp) { + $formattedData[] = [ + 'timestamp' => $timestamp, + 'hits' => $value['hits'], + 'bytes' => $value['bytes'] + ]; + } } - } - return $formattedData; + + return $formattedData; } public function DataTodays() { From 9515e42d3a0d4bd5653b1fcc67df6f6b4d28f5b1 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Thu, 11 Jul 2024 11:13:04 +0800 Subject: [PATCH 14/22] =?UTF-8?q?=E2=9C=A8=20Add=20CenterUrl=20(Support=20?= =?UTF-8?q?93@home)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.php | 1 + inc/cluster.php | 3 +-- inc/socketio.php | 8 ++++++-- inc/token.php | 4 ++-- main.php | 10 +++++++++- 5 files changed, 19 insertions(+), 7 deletions(-) diff --git a/config.php b/config.php index c653467..cd6e44a 100644 --- a/config.php +++ b/config.php @@ -15,6 +15,7 @@ "database_dir"=> "./database",//访问数据数据库目录 ], "advanced"=> [ + "CenterUrl"=> "https://openbmclapi.staging.bangbang93.com",//主控链接(不建议调整) "keepalive"=> 60,//keepalive时间,秒为单位(不建议调整) "MaxConcurrent"=> 30,//下载使用的线程 "Debug"=> false,//Debug开关 diff --git a/inc/cluster.php b/inc/cluster.php index fb3b7bd..285f2f2 100644 --- a/inc/cluster.php +++ b/inc/cluster.php @@ -87,10 +87,9 @@ public function getFileList() { if (!file_exists($download_dir."/filecache")) { mkdir($download_dir."/filecache",0777,true); } - $client = new Client(OPENBMCLAPIURL,443,true); + $client = new Client(OPENBMCLAPIURL['host'],OPENBMCLAPIURL['port'],OPENBMCLAPIURL['ssl']); $client->set(['timeout' => -1]); $client->setHeaders([ - 'Host' => OPENBMCLAPIURL, 'User-Agent' => 'openbmclapi-cluster/'.$this->version, 'Accept' => '*', 'Authorization' => "Bearer {$this->token}" diff --git a/inc/socketio.php b/inc/socketio.php index 29f4334..94f3e10 100644 --- a/inc/socketio.php +++ b/inc/socketio.php @@ -3,6 +3,8 @@ use Swoole\Coroutine\Http\Client; class socketio { private $url; + private $port; + private $ssl; private $token; private $client; private $data; @@ -11,13 +13,15 @@ class socketio { private $rekeepalive = 1; private $Connected = false; public function __construct($url=null,$token=null,$kattl=null) { - $this->url = $url; + $this->url = $url['host']; + $this->port = $url['port']; + $this->ssl = $url['ssl']; $this->token = $token; $this->kattl = $kattl; $katimeid = 0; } public function connect() { - $this->client = $client = new Client($this->url, 443, true); + $this->client = $client = new Client($this->url, $this->port, $this->ssl); $ret = $client->upgrade('/socket.io/?EIO=4&transport=websocket'); $auth = [ 'token' => $this->token diff --git a/inc/token.php b/inc/token.php index 28db766..47edd93 100644 --- a/inc/token.php +++ b/inc/token.php @@ -11,7 +11,7 @@ public function __construct($clusterId,$clusterSecret,$version){ } public function gettoken() { //获取challenge - $client = new Client(OPENBMCLAPIURL,443,true); + $client = new Client(OPENBMCLAPIURL['host'],OPENBMCLAPIURL['port'],OPENBMCLAPIURL['ssl']); $client->setHeaders([ 'User-Agent' => 'openbmclapi-cluster/'.$this->version, 'Content-Type' => 'application/json; charset=utf-8', @@ -22,7 +22,7 @@ public function gettoken() { $challenge = json_decode($client->body, true); $signature = hash_hmac('sha256', $challenge['challenge'], $this->clusterSecret); //获取token和ttl - $client = new Client(OPENBMCLAPIURL,443,true); + $client = new Client(OPENBMCLAPIURL['host'],OPENBMCLAPIURL['port'],OPENBMCLAPIURL['ssl']); $client->post( '/openbmclapi-agent/token', array( diff --git a/main.php b/main.php index b5e410c..44d173b 100644 --- a/main.php +++ b/main.php @@ -13,8 +13,16 @@ const VERSION = '1.10.9'; $download_dir = api::getconfig()['file']['cache_dir']; const USERAGENT = 'openbmclapi-cluster/' . VERSION . ' ' . 'php-openbmclapi/'.PHPOBAVERSION; -const OPENBMCLAPIURL = 'openbmclapi.staging.bangbang93.com'; mlog("OpenBmclApi on PHP v". PHPOBAVERSION . "-" . VERSION,0,true); + +//预处理主控链接 +$parsed = parse_url(api::getconfig()['advanced']['CenterUrl']); +$scheme = isset($parsed['scheme']) ? $parsed['scheme'] : ''; +$host = isset($parsed['host']) ? $parsed['host'] : ''; +$port = isset($parsed['port']) ? $parsed['port'] : ($scheme === 'https' ? 443 : 80); +$ssl = $scheme === 'https' ? true : false;//https支持 +define('OPENBMCLAPIURL', ['host' => $host, 'port' => $port, 'ssl' => $ssl]); + run(function(){ $config = api::getconfig(); //注册信号处理器、 From 3ca12529045065408601cb8916ab5970fbb326f5 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Thu, 11 Jul 2024 13:57:52 +0800 Subject: [PATCH 15/22] =?UTF-8?q?=F0=9F=92=84=20=E6=9B=B4=E6=94=B9=20Cente?= =?UTF-8?q?rurl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.php | 2 +- main.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/config.php b/config.php index cd6e44a..0a2cd1b 100644 --- a/config.php +++ b/config.php @@ -15,7 +15,7 @@ "database_dir"=> "./database",//访问数据数据库目录 ], "advanced"=> [ - "CenterUrl"=> "https://openbmclapi.staging.bangbang93.com",//主控链接(不建议调整) + "Centerurl"=> "https://openbmclapi.staging.bangbang93.com",//主控链接(不建议调整) "keepalive"=> 60,//keepalive时间,秒为单位(不建议调整) "MaxConcurrent"=> 30,//下载使用的线程 "Debug"=> false,//Debug开关 diff --git a/main.php b/main.php index 44d173b..cd3af5b 100644 --- a/main.php +++ b/main.php @@ -16,7 +16,7 @@ mlog("OpenBmclApi on PHP v". PHPOBAVERSION . "-" . VERSION,0,true); //预处理主控链接 -$parsed = parse_url(api::getconfig()['advanced']['CenterUrl']); +$parsed = parse_url(api::getconfig()['advanced']['Centerurl']); $scheme = isset($parsed['scheme']) ? $parsed['scheme'] : ''; $host = isset($parsed['host']) ? $parsed['host'] : ''; $port = isset($parsed['port']) ? $parsed['port'] : ($scheme === 'https' ? 443 : 80); From 6fef2f9fb4f29062e24ffcd9338527a35673f32b Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 13 Jul 2024 18:25:58 +0800 Subject: [PATCH 16/22] =?UTF-8?q?=E2=9C=A8=20=E5=AE=8C=E5=96=84=20byoc=20?= =?UTF-8?q?=E5=8F=8A=E8=87=AA=E5=AE=9A=E4=B9=89=E8=AF=81=E4=B9=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.php | 7 +++++- inc/server.php | 24 ++++++++++++------ main.php | 68 +++++++++++++++++++++++++++++--------------------- 3 files changed, 63 insertions(+), 36 deletions(-) diff --git a/config.php b/config.php index 0a2cd1b..2d333f0 100644 --- a/config.php +++ b/config.php @@ -7,7 +7,12 @@ "public_port"=> 4000,//服务端口 "CLUSTER_ID"=> "", "CLUSTER_SECRET"=> "", - "byoc"=>false, + "byoc"=> false, + "certificates"=>[ //如果 byoc 关闭,以下设置默认禁用 + "use-cert"=> false, //是否使用自己的证书 + "cert"=> "/path/to/cert.crt", + "key"=> "/path/to/key.key", + ], ], "file"=> [ "cache_dir"=> "./cache",//缓存文件夹 diff --git a/inc/server.php b/inc/server.php index f177490..ffc2e85 100644 --- a/inc/server.php +++ b/inc/server.php @@ -9,24 +9,34 @@ class fileserver { private $server; private $dir; private $secret; + private $ssl; private $lock; - public function __construct($host,$port,$cert,$key,$secret) { + public function __construct($host,$port,$cert,$key,$secret,$ssl) { $this->host = $host; $this->port = $port; $this->cert = $cert; $this->key = $key; + $this->ssl = $ssl; $this->dir = api::getconfig()['file']['cache_dir']; $this->secret = $secret; $this->lock = new Swoole\Lock(SWOOLE_RWLOCK); } public function setupserver() { - $this->server = $server = new Server($this->host, $this->port, true); - $server->set([ - 'ssl_cert_file' => './cert/'.$this->cert, - 'ssl_key_file' => './cert/'.$this->key, - 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 - ]); + if($this->ssl){ + $this->server = $server = new Server($this->host, $this->port, true); + $server->set([ + 'ssl_cert_file' => $this->cert, + 'ssl_key_file' => $this->key, + 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 + ]); + } + else{ + $this->server = $server = new Server($this->host, $this->port); + $server->set([ + 'heartbeat_check_interval' => 60, // 表示每60秒遍历一次 + ]); + } $server->handle('/', function ($request, $response) { $code = 404; $response->status($code); diff --git a/main.php b/main.php index cd3af5b..ddc2390 100644 --- a/main.php +++ b/main.php @@ -75,38 +75,50 @@ function registerSigintHandler() { $socketio->connect(); }); Coroutine::sleep(1); - //获取证书 - $socketio->ack("request-cert"); - Coroutine::sleep(1); - $allcert = $socketio->Getcert(); - //写入证书并且是否损坏 - if (!file_exists('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt') && !file_exists('./cert/'.$config['cluster']['CLUSTER_ID'].'.key')) { - mlog("正在获取证书"); - if (!file_exists("./cert")) { - mkdir("./cert",0777,true); + if (!$config['cluster']['byoc']){ + $socketio->ack("request-cert"); + Coroutine::sleep(1); + $allcert = $socketio->Getcert(); + //写入证书并且是否损坏 + if (!file_exists('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt') && !file_exists('./cert/'.$config['cluster']['CLUSTER_ID'].'.key')) { + mlog("正在获取证书"); + if (!file_exists("./cert")) { + mkdir("./cert",0777,true); + } + mlog("已获取证书,到期时间{$allcert['0']['1']['expires']}"); + $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt', 'w'); + $Writtencert = fwrite($cert, $allcert['0']['1']['cert']); + fclose($cert); + $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.key', 'w'); + $Writtencert = fwrite($cert, $allcert['0']['1']['key']); + fclose($cert); + } + $crt = file_get_contents('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt'); + if ($crt!== $allcert['0']['1']['cert']) { + mlog("证书损坏/过期"); + mlog("已获取新的证书,到期时间{$allcert['0']['1']['expires']}"); + $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt', 'w'); + $Writtencert = fwrite($cert, $allcert['0']['1']['cert']); + fclose($cert); + $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.key', 'w'); + $Writtencert = fwrite($cert, $allcert['0']['1']['key']); + fclose($cert); + global $httpserver; + $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],'./cert/'.$config['cluster']['CLUSTER_ID'].'.crt','./cert/'.$config['cluster']['CLUSTER_ID'].'.key',$config['cluster']['CLUSTER_SECRET'],true); } - mlog("已获取证书,到期时间{$allcert['0']['1']['expires']}"); - $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt', 'w'); - $Writtencert = fwrite($cert, $allcert['0']['1']['cert']); - fclose($cert); - $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.key', 'w'); - $Writtencert = fwrite($cert, $allcert['0']['1']['key']); - fclose($cert); } - $crt = file_get_contents('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt'); - if ($crt!== $allcert['0']['1']['cert']) { - mlog("证书损坏/过期"); - mlog("已获取新的证书,到期时间{$allcert['0']['1']['expires']}"); - $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.crt', 'w'); - $Writtencert = fwrite($cert, $allcert['0']['1']['cert']); - fclose($cert); - $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.key', 'w'); - $Writtencert = fwrite($cert, $allcert['0']['1']['key']); - fclose($cert); + else{ + if(!$config['cluster']['certificates']['use-cert']){ + global $httpserver; + $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],null,null,$config['cluster']['CLUSTER_SECRET'],false); + mlog("检测到 byoc 开启并且 use-cert 关闭,请自备反代!"); + } + global $httpserver; + $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],$config['cluster']['certificates']['cert'],$config['cluster']['certificates']['key'],$config['cluster']['CLUSTER_SECRET'],true); } + + //获取证书 //设置http服务器 - global $httpserver; - $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],$config['cluster']['CLUSTER_ID'].'.crt',$config['cluster']['CLUSTER_ID'].'.key',$config['cluster']['CLUSTER_SECRET']); $server = $httpserver->setupserver(); //开始加载插件 From eb27f6f65121006ea5ae011d4aba189e862a82c8 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 13 Jul 2024 18:35:37 +0800 Subject: [PATCH 17/22] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E4=B8=8D=E5=88=B0=20$httpserver=20=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.php b/main.php index ddc2390..9882ede 100644 --- a/main.php +++ b/main.php @@ -103,9 +103,9 @@ function registerSigintHandler() { $cert = fopen('./cert/'.$config['cluster']['CLUSTER_ID'].'.key', 'w'); $Writtencert = fwrite($cert, $allcert['0']['1']['key']); fclose($cert); - global $httpserver; - $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],'./cert/'.$config['cluster']['CLUSTER_ID'].'.crt','./cert/'.$config['cluster']['CLUSTER_ID'].'.key',$config['cluster']['CLUSTER_SECRET'],true); } + global $httpserver; + $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],'./cert/'.$config['cluster']['CLUSTER_ID'].'.crt','./cert/'.$config['cluster']['CLUSTER_ID'].'.key',$config['cluster']['CLUSTER_SECRET'],true); } else{ if(!$config['cluster']['certificates']['use-cert']){ From 9cc5a980274ae5558caf5b1dbf5c571ddf8cf330 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 13 Jul 2024 18:39:13 +0800 Subject: [PATCH 18/22] =?UTF-8?q?=F0=9F=90=9B=20=E8=AE=A9=E4=B8=8B?= =?UTF-8?q?=E8=BD=BD=E6=96=87=E4=BB=B6=E5=9C=B0=E5=9D=80=E8=B7=9F=E4=B8=BB?= =?UTF-8?q?=E6=8E=A7=E5=9C=B0=E5=9D=80=E8=B5=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/cluster.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/inc/cluster.php b/inc/cluster.php index 285f2f2..b5bf2c1 100644 --- a/inc/cluster.php +++ b/inc/cluster.php @@ -219,12 +219,11 @@ public function downloadFiles() { } $this->semaphore->push(true); go(function () use ($file,$bar) { - $client = new Swoole\Coroutine\Http\Client('openbmclapi.bangbang93.com', 443, true); + $client = new Swoole\Coroutine\Http\Client(OPENBMCLAPIURL['host'],OPENBMCLAPIURL['port'],OPENBMCLAPIURL['ssl']); $client->set([ 'timeout' => -1 ]); $client->setHeaders([ - 'Host' => 'openbmclapi.bangbang93.com', 'User-Agent' => USERAGENT, 'Accept' => '*/*', ]); From c8defc88e49cf60018a03878aa9cd201cb997c5b Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sat, 13 Jul 2024 18:45:20 +0800 Subject: [PATCH 19/22] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8D=20use-c?= =?UTF-8?q?ert=20=E5=85=B3=E9=97=AD=E8=BF=98=E6=98=AF=E5=BC=80=E5=90=AF=20?= =?UTF-8?q?https?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/main.php b/main.php index 9882ede..80f7ed0 100644 --- a/main.php +++ b/main.php @@ -113,8 +113,10 @@ function registerSigintHandler() { $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],null,null,$config['cluster']['CLUSTER_SECRET'],false); mlog("检测到 byoc 开启并且 use-cert 关闭,请自备反代!"); } - global $httpserver; - $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],$config['cluster']['certificates']['cert'],$config['cluster']['certificates']['key'],$config['cluster']['CLUSTER_SECRET'],true); + else{ + global $httpserver; + $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],$config['cluster']['certificates']['cert'],$config['cluster']['certificates']['key'],$config['cluster']['CLUSTER_SECRET'],true); + } } //获取证书 From 895b70d5783895dd330b2e5027b595a628db71c8 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sun, 14 Jul 2024 11:36:31 +0800 Subject: [PATCH 20/22] =?UTF-8?q?=E2=9C=A8=20=E6=94=AF=E6=8C=81=20refreshT?= =?UTF-8?q?oken=20=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inc/api.php | 2 +- inc/cluster.php | 7 +++---- inc/token.php | 18 ++++++++++++++++++ main.php | 12 +++++++++--- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/inc/api.php b/inc/api.php index f29da21..8d82cc6 100644 --- a/inc/api.php +++ b/inc/api.php @@ -1,7 +1,7 @@ false,'isSynchronized'=>false,'uptime'=>0]; + private static $info = ['enable'=>false,'isSynchronized'=>false,'uptime'=>0,'token'=>null]; public static function getconfig($newConfig = null) { if (!is_null($newConfig)) { diff --git a/inc/cluster.php b/inc/cluster.php index b5bf2c1..8c17b7c 100644 --- a/inc/cluster.php +++ b/inc/cluster.php @@ -245,21 +245,20 @@ public function downloadFiles() { public function downloadnopoen($hash) { $download_dir = api::getconfig()['file']['cache_dir']; - global $tokendata; + $tokenapi = api::getinfo(); $filePath = $download_dir . '/' . substr($hash, 0, 2) . '/'; if (!file_exists($filePath)) { mkdir($filePath, 0777, true); } $filepath = "/openbmclapi/download/{$hash}?noopen=1"; - $client = new Swoole\Coroutine\Http\Client('openbmclapi.bangbang93.com', 443, true); + $client = new Swoole\Coroutine\Http\Client(OPENBMCLAPIURL['host'],OPENBMCLAPIURL['port'],OPENBMCLAPIURL['ssl']); $client->set([ 'timeout' => -1 ]); $client->setHeaders([ - 'Host' => 'openbmclapi.bangbang93.com', 'User-Agent' => USERAGENT, 'Accept' => '*/*', - 'Authorization' => "Bearer {$tokendata['token']}" + 'Authorization' => "Bearer {$tokenapi['token']}" ]); $downloader = $client->download($filepath,$download_dir.'/'.substr($hash, 0, 2).'/'.$hash); if (!$downloader) { diff --git a/inc/token.php b/inc/token.php index 47edd93..e4a8b2d 100644 --- a/inc/token.php +++ b/inc/token.php @@ -38,4 +38,22 @@ public function gettoken() { 'upttl' => $responseData['ttl'] - 600000,//前十分钟更新 ); } + + public function refreshToken($token) { + //刷新token + $client = new Client(OPENBMCLAPIURL['host'],OPENBMCLAPIURL['port'],OPENBMCLAPIURL['ssl']); + $client->post( + '/openbmclapi-agent/token', + array( + 'clusterId' => $this->clusterId, + 'token' => $token, + ) + ); + $client->close(); + $responseData = json_decode($client->body, true); + return array( + 'token' => $responseData["token"], + 'upttl' => $responseData['ttl'] - 600000,//前十分钟更新 + ); + } } \ No newline at end of file diff --git a/main.php b/main.php index 80f7ed0..ace9910 100644 --- a/main.php +++ b/main.php @@ -20,7 +20,7 @@ $scheme = isset($parsed['scheme']) ? $parsed['scheme'] : ''; $host = isset($parsed['host']) ? $parsed['host'] : ''; $port = isset($parsed['port']) ? $parsed['port'] : ($scheme === 'https' ? 443 : 80); -$ssl = $scheme === 'https' ? true : false;//https支持 +$ssl = $scheme === 'https' ? true : false; //https支持 define('OPENBMCLAPIURL', ['host' => $host, 'port' => $port, 'ssl' => $ssl]); run(function(){ @@ -58,10 +58,16 @@ function registerSigintHandler() { $tokendata = $token->gettoken(); mlog("GetToken:".$tokendata['token'],1); mlog("TokenTTL:".$tokendata['upttl'],1); + $tokenapi = api::getinfo(); + $tokenapi['token'] = $tokendata['token']; + api::getinfo($tokenapi); + //启动更新TokenTimer - global $tokentimerid; $tokentimerid = Swoole\Timer::tick($tokendata['upttl'], function () use ($token) { - $tokendata = $token->gettoken(); + $tokenapi = api::getinfo(); + $tokendata = $token->refreshToken($tokenapi['token']); + $tokenapi['token'] = $tokendata['token']; + api::getinfo($tokenapi); mlog("GetNewToken:".$tokendata['token'],1); }); registerSigintHandler(); From df3227283408d450e4d3f3e891bee932e21f31c4 Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sun, 14 Jul 2024 11:38:03 +0800 Subject: [PATCH 21/22] =?UTF-8?q?=F0=9F=8E=A8=20=E6=9B=B4=E6=94=B9?= =?UTF-8?q?=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.php b/main.php index ace9910..dd26a4e 100644 --- a/main.php +++ b/main.php @@ -117,7 +117,7 @@ function registerSigintHandler() { if(!$config['cluster']['certificates']['use-cert']){ global $httpserver; $httpserver = new fileserver($config['cluster']['host'],$config['cluster']['port'],null,null,$config['cluster']['CLUSTER_SECRET'],false); - mlog("检测到 byoc 开启并且 use-cert 关闭,请自备反代!"); + mlog("byoc 已开启并且 use-cert 已关闭,请自备反代!"); } else{ global $httpserver; From a6996be4fce021c0d4b7e4c6352cb476cb01470c Mon Sep 17 00:00:00 2001 From: Mxmilu Date: Sun, 14 Jul 2024 11:40:57 +0800 Subject: [PATCH 22/22] =?UTF-8?q?=F0=9F=8E=A8=20=E5=8A=A0=E4=B8=AA=20TODO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3f88d4b..9470505 100644 --- a/README.md +++ b/README.md @@ -66,13 +66,20 @@ $config=[ "public_port"=> 4000,//服务端口 "CLUSTER_ID"=> "", "CLUSTER_SECRET"=> "", - "byoc"=>false, + "byoc"=> false, + "certificates"=>[ //如果 byoc 关闭,以下设置默认禁用 + "use-cert"=> false, //是否使用自己的证书 + "cert"=> "/path/to/cert.crt", + "key"=> "/path/to/key.key", + ], ], "file"=> [ "cache_dir"=> "./cache",//缓存文件夹 "check"=> "size",//检查文件策略(hash:检查文件hash size:检查文件大小 exists:检查文件是否存在) + "database_dir"=> "./database",//访问数据数据库目录 ], "advanced"=> [ + "Centerurl"=> "https://openbmclapi.bangbang93.com",//主控链接(不建议调整) "keepalive"=> 60,//keepalive时间,秒为单位(不建议调整) "MaxConcurrent"=> 30,//下载使用的线程 "Debug"=> false,//Debug开关 @@ -81,12 +88,13 @@ $config=[ ``` ## 📍 Todo +- [ ] 支持上报错误 url(主要) - [ ] 支持WebDAV -- [ ] 打包二进制文件 - [ ] 添加注释 - [x] 可以正常上线使用 - [x] 插件系统 - [x] 完善Log系统 +- [ ] 打包二进制文件 (延期:[原因](https://github.com/crazywhalecc/static-php-cli/issues/479)) ## ❓ FAQ