feat: 增加主机节点表结构代码

This commit is contained in:
augushong
2025-08-23 22:44:47 +08:00
parent 46722e5a66
commit b1a6b37ee0
12 changed files with 282 additions and 15 deletions

View File

@@ -1,4 +1,3 @@
<?php
namespace base\common\service;
@@ -9,7 +8,7 @@ use think\facade\Log;
/**
* 主机(节点)服务 - 基础类
* 用于注册、上报主机心跳及性能指标
* 用于注册、上报主机心跳及性能指标.
*/
class HostServiceBase
{
@@ -36,7 +35,7 @@ class HostServiceBase
// 2. 如果文件不存在或为空生成新的唯一ID
// 格式: hostname-8位随机字符串
$hostname = gethostname() ?: 'unknown_host';
$uniqueSuffix = substr(md5(uniqid((string)mt_rand(), true)), 0, 8);
$uniqueSuffix = substr(md5(uniqid((string) mt_rand(), true)), 0, 8);
$newHostId = "{$hostname}-{$uniqueSuffix}";
// 3. 将新ID写入文件以便下次启动时使用
@@ -58,6 +57,7 @@ class HostServiceBase
$hostId = self::getHostId();
if (empty($hostId)) {
Log::error('无法获取当前主机ID心跳更新失败');
return;
}
@@ -84,7 +84,7 @@ class HostServiceBase
}
/**
* 收集主机的动态性能指标 (不依赖任何外部系统命令)
* 收集主机的动态性能指标 (不依赖任何外部系统命令).
* @return array
*/
public static function collectHostMetrics(): array
@@ -93,29 +93,29 @@ class HostServiceBase
$cpuLoad = null;
if (function_exists('sys_getloadavg')) {
$load = sys_getloadavg();
$cpuLoad = is_array($load) ? implode(',', array_map(fn($l) => round($l, 2), $load)) : null;
$cpuLoad = is_array($load) ? implode(',', array_map(fn ($l) => round($l, 2), $load)) : null;
}
return [
'status' => 1,
'last_heartbeat_at' => date('Y-m-d H:i:s'),
'ip_address' => gethostbyname(gethostname()),
'cpu_load' => $cpuLoad,
'memory_usage' => memory_get_usage(), // false: 获取脚本自身内存占用
'disk_free' => disk_free_space(App::getRootPath()),
'disk_total' => disk_total_space(App::getRootPath()),
'status' => 1,
'last_heartbeat_at' => date('Y-m-d H:i:s'),
'ip_address' => gethostbyname(gethostname()),
'cpu_load' => $cpuLoad,
'memory_usage' => memory_get_usage(), // false: 获取脚本自身内存占用
'disk_free' => disk_free_space(App::getRootPath()),
'disk_total' => disk_total_space(App::getRootPath()),
];
}
/**
* 收集主机的静态信息 (仅在首次注册时调用)
* 收集主机的静态信息 (仅在首次注册时调用).
* @return array
*/
public static function collectStaticInfo(): array
{
return [
'os_info' => php_uname(),
'php_version' => PHP_VERSION,
'os_info' => php_uname(),
'php_version' => PHP_VERSION,
];
}
}