Compare commits

..
6 Commits
Author SHA1 Message Date
MasonLiu 9e85e64345 更改验证 2026-08-25 00:07:26 +08:00
MasonLiu 00617621f9 BUG修复:添加分离式刷新按钮 2026-06-30 23:56:57 +08:00
MasonLiu ec5c2db848 添加异常处理 2026-06-30 21:07:26 +08:00
MasonLiu 8cb285866f 添加对阿里云的支持(ecs未测试) 2026-06-30 01:24:49 +08:00
MasonLiu cbd886bd0a 添加腾讯云源(暂不支持开关机) 2026-06-23 00:02:34 +08:00
MasonLiu 88f7fc7141 bug修复 2026-05-30 15:06:24 +08:00
17 changed files with 3572 additions and 473 deletions

No files matched your search

+28 -6
View File
@@ -110,16 +110,19 @@
## 💻 技术栈 ## 💻 技术栈
### 后端 ### 后端
- **PHP 7.4+**:Web服务器端逻辑 - **PHP 7.4+**:Web服务器端逻辑
- **Python 3.6+**:后台监控服务 - **Python 3.6+**:后台监控服务
- **SQLite 3**:轻量级数据库 - **SQLite 3**:轻量级数据库
### 前端 ### 前端
- **HTML5/CSS3**:页面结构和样式 - **HTML5/CSS3**:页面结构和样式
- **JavaScript**:交互逻辑 - **JavaScript**:交互逻辑
- **响应式设计**:支持移动端访问 - **响应式设计**:支持移动端访问
### 依赖库 ### 依赖库
- **PHP**: cURL, PDO-SQLite - **PHP**: cURL, PDO-SQLite
- **Python**: requests, schedule, sqlite3 - **Python**: requests, schedule, sqlite3
@@ -164,13 +167,15 @@ chmod 755 app/install.sh
首次访问会自动跳转到配置页面,添加第一个VPS平台配置。 首次访问会自动跳转到配置页面,添加第一个VPS平台配置。
设置访问密码后,进入 `index.php` 或 `config_add.php` 时需先输入访问密码(POST 方式验证),验证成功后建立 PHP 会话(有效期 30 分钟,操作自动续期)。
--- ---
## ⚙️ 配置说明 ## ⚙️ 配置说明
### 添加VPS平台配置 ### 添加VPS平台配置
1. 访问 `config_add.php?pass=YOUR_API_PASS` 1. 访问 `config_add.php`,首次访问需先设置访问密码
2. 填写配置信息: 2. 填写配置信息:
- **API标识**:自定义名称(唯一) - **API标识**:自定义名称(唯一)
- **网站类型**:选择平台(目前支持魔方平台) - **网站类型**:选择平台(目前支持魔方平台)
@@ -184,6 +189,7 @@ chmod 755 app/install.sh
### 配置示例 ### 配置示例
**魔方平台配置**: **魔方平台配置**:
``` ```
API标识: 核云IDC API标识: 核云IDC
网站类型: 魔方平台 网站类型: 魔方平台
@@ -196,6 +202,7 @@ API密钥: your_api_key
![API_KEY](./src/api.png) ![API_KEY](./src/api.png)
⚠️ **重要提示**: ⚠️ **重要提示**:
- 网站链接只填写根域名,不要包含 `/v1` 或 `/api` 等路径 - 网站链接只填写根域名,不要包含 `/v1` 或 `/api` 等路径
- API标识必须唯一,不能重复 - API标识必须唯一,不能重复
- 确保账户和密码正确 - 确保账户和密码正确
@@ -208,14 +215,18 @@ API密钥: your_api_key
#### 查看VPS列表 #### 查看VPS列表
访问 `index.php?pass=YOUR_API_PASS`,可以看到: 访问 `index.php`,输入访问密码登录后即可看到:
- 按配置分组的VPS列表 - 按配置分组的VPS列表
- 每个VPS的状态、IP、配置信息 - 每个VPS的状态、IP、配置信息
- 实时统计数据 - 实时统计数据
> 登录会话有效期 30 分钟(滑动过期),每次请求新数据会自动续期;超过 30 分钟无操作需重新登录。
#### 操作VPS #### 操作VPS
每个VPS卡片提供三个操作按钮: 每个VPS卡片提供三个操作按钮:
- **⚡ 开机**:启动VPS - **⚡ 开机**:启动VPS
- **🔴 关机**:关闭VPS - **🔴 关机**:关闭VPS
- **🔄 硬重启**:强制重启VPS - **🔄 硬重启**:强制重启VPS
@@ -225,6 +236,7 @@ API密钥: your_api_key
#### 刷新VPS列表 #### 刷新VPS列表
点击顶部工具栏的 "🔄 手动刷新VPS列表" 按钮: 点击顶部工具栏的 "🔄 手动刷新VPS列表" 按钮:
1. 从API获取最新的VPS列表 1. 从API获取最新的VPS列表
2. 更新数据库中的VPS信息 2. 更新数据库中的VPS信息
3. 获取每个VPS的详细配置(CPU、内存、磁盘、带宽、系统) 3. 获取每个VPS的详细配置(CPU、内存、磁盘、带宽、系统)
@@ -243,7 +255,6 @@ sudo systemctl start idc_monitor
sudo systemctl status idc_monitor sudo systemctl status idc_monitor
``` ```
#### 停止监控 #### 停止监控
```bash ```bash
@@ -285,7 +296,7 @@ sudo systemctl restart idc_monitor
### 数据库文件 ### 数据库文件
| 文件名 | 用途 | 主要表 | | 文件名 | 用途 | 主要表 |
|--------|------|--------| | ------------ | ------------ | ---------------------------- |
| `vps.db` | 存储平台配置 | `configs` | | `vps.db` | 存储平台配置 | `configs` |
| `vpslist.db` | 存储VPS列表 | `vps_list` | | `vpslist.db` | 存储VPS列表 | `vps_list` |
| `status.db` | 存储监控记录 | `ping_status`, `vps_summary` | | `status.db` | 存储监控记录 | `ping_status`, `vps_summary` |
@@ -421,7 +432,8 @@ WantedBy=multi-user.target
### 访问控制 ### 访问控制
- **API密码保护**:所有页面都需要通过 `?pass=API_PASS` 验证 - **会话密码保护**:所有页面通过前端输入访问密码(POST 方式)验证,验证成功后建立 PHP 会话
- **会话有效期**:单次会话 30 分钟,用户请求新数据后自动刷新会话有效期(滑动过期)
- **密码文件**:存储在 `app/pass.php`,权限设置为 600 - **密码文件**:存储在 `app/pass.php`,权限设置为 600
- **数据库保护**:Nginx配置禁止直接访问 `.db` 文件,或者限制访问app路径需要basic认证 - **数据库保护**:Nginx配置禁止直接访问 `.db` 文件,或者限制访问app路径需要basic认证
@@ -446,6 +458,7 @@ WantedBy=multi-user.target
### Q1: 页面显示"0台VPS"怎么办? ### Q1: 页面显示"0台VPS"怎么办?
**A**: **A**:
1. 点击"手动刷新VPS列表"按钮 1. 点击"手动刷新VPS列表"按钮
2. 检查配置是否正确(特别是site_url不要包含路径) 2. 检查配置是否正确(特别是site_url不要包含路径)
3. 查看PHP错误日志:`tail -f /var/log/php/error.log` 3. 查看PHP错误日志:`tail -f /var/log/php/error.log`
@@ -455,6 +468,7 @@ WantedBy=multi-user.target
### Q2: 监控服务无法启动? ### Q2: 监控服务无法启动?
**A**: **A**:
```bash ```bash
# 检查服务状态 # 检查服务状态
sudo systemctl status idc_monitor sudo systemctl status idc_monitor
@@ -474,6 +488,7 @@ journalctl -u idc_monitor -n 50
**A**: **A**:
系统已经做了兼容处理: 系统已经做了兼容处理:
- 如果exec被禁用,会显示友好提示 - 如果exec被禁用,会显示友好提示
- 需要手动执行安装脚本:`sudo bash app/install.sh` - 需要手动执行安装脚本:`sudo bash app/install.sh`
- 监控服务仍然可以正常运行 - 监控服务仍然可以正常运行
@@ -484,11 +499,13 @@ journalctl -u idc_monitor -n 50
**A**: **A**:
可能原因: 可能原因:
1. 数据库中还没有该VPS的记录 1. 数据库中还没有该VPS的记录
2. 多次调用导致状态被覆盖(已修复) 2. 多次调用导致状态被覆盖(已修复)
3. API返回异常 3. API返回异常
解决方法: 解决方法:
- 手动刷新VPS列表 - 手动刷新VPS列表
- 检查日志确认API调用是否正常 - 检查日志确认API调用是否正常
- 等待下一次监控循环 - 等待下一次监控循环
@@ -498,12 +515,14 @@ journalctl -u idc_monitor -n 50
### Q5: 如何添加新的VPS平台? ### Q5: 如何添加新的VPS平台?
**A**: **A**:
1. 在 `app/monitor.py` 中创建新的适配器类 1. 在 `app/monitor.py` 中创建新的适配器类
2. 继承 `PlatformAdapter` 基类 2. 继承 `PlatformAdapter` 基类
3. 实现必要的方法(login, get_vps_list, get_vps_status等) 3. 实现必要的方法(login, get_vps_list, get_vps_status等)
4. 在 `load_configs_and_create_adapters()` 中添加判断逻辑 4. 在 `load_configs_and_create_adapters()` 中添加判断逻辑
示例: 示例:
```python ```python
class AliyunAdapter(PlatformAdapter): class AliyunAdapter(PlatformAdapter):
def login(self): def login(self):
@@ -520,11 +539,13 @@ class AliyunAdapter(PlatformAdapter):
### Q6: 数据库文件在哪里? ### Q6: 数据库文件在哪里?
**A**: **A**:
- `app/db/vps.db` - 配置数据库 - `app/db/vps.db` - 配置数据库
- `app/db/vpslist.db` - VPS列表数据库 - `app/db/vpslist.db` - VPS列表数据库
- `app/db/status.db` - 监控状态数据库 - `app/db/status.db` - 监控状态数据库
可以使用SQLite工具查看: 可以使用SQLite工具查看:
```bash ```bash
sqlite3 app/db/vpslist.db sqlite3 app/db/vpslist.db
.tables .tables
@@ -536,6 +557,7 @@ SELECT * FROM vps_list;
### Q7: 如何备份数据? ### Q7: 如何备份数据?
**A**: **A**:
```bash ```bash
# 备份所有数据库 # 备份所有数据库
cp app/db/*.db backup/$(date +%Y%m%d)/ cp app/db/*.db backup/$(date +%Y%m%d)/
@@ -552,7 +574,6 @@ sqlite3 app/db/vpslist.db ".dump" > backup/vpslist.sql
--- ---
## 📧 联系方式 ## 📧 联系方式
- **项目地址**: [https://git.masonliu.com/MasonLiu/VPSHUB](https://git.masonliu.com/MasonLiu/VPSHUB) - **项目地址**: [https://git.masonliu.com/MasonLiu/VPSHUB](https://git.masonliu.com/MasonLiu/VPSHUB)
@@ -564,6 +585,7 @@ sqlite3 app/db/vpslist.db ".dump" > backup/vpslist.sql
## 🙏 致谢 ## 🙏 致谢
感谢以下开源项目: 感谢以下开源项目:
- [PHP](https://www.php.net/) - [PHP](https://www.php.net/)
- [Python](https://www.python.org/) - [Python](https://www.python.org/)
- [SQLite](https://www.sqlite.org/) - [SQLite](https://www.sqlite.org/)
+938
View File
@@ -0,0 +1,938 @@
<?php
require_once __DIR__ . '/app/db_helper.php';
require_once __DIR__ . '/app/logger.php';
/**
* 阿里云ECS和轻量应用服务器API适配器
* 支持ECS云服务器和轻量应用服务器(SWAS)的查询和管理
*/
/**
* URL编码函数(RFC3986规范)
*/
function aliyunEncode($str) {
$res = urlencode($str);
$res = preg_replace('/\+/', '%20', $res);
$res = preg_replace('/\*/', '%2A', $res);
$res = preg_replace('/%7E/', '~', $res);
return $res;
}
/**
* 生成阿里云API签名 (HMAC-SHA1)
*/
function generateAliyunSignature($method, $params, $secretKey) {
// 按参数名排序
ksort($params);
// 构建规范化请求字符串
$canonicalizedQueryString = '';
foreach ($params as $key => $value) {
if ($canonicalizedQueryString !== '') {
$canonicalizedQueryString .= '&';
}
$canonicalizedQueryString .= aliyunEncode($key) . '=' . aliyunEncode($value);
}
// 构造待签名字符串
$stringToSign = $method . '&%2F&' . aliyunEncode($canonicalizedQueryString);
// 计算HMAC-SHA1签名
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $secretKey . '&', true));
return $signature;
}
/**
* 发送阿里云API请求
* @param string $configId 配置ID
* @param string $action API动作
* @param array $params 请求参数
* @param string $region 区域
* @param string $serviceType 服务类型: ecs 或 swas
* @return array|null
*/
function aliyunApiRequest($configId, $action, $params = [], $region = 'cn-hangzhou', $serviceType = 'ecs') {
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config) {
Logger::error("配置ID {$configId} 不存在", 'aliyunApiRequest');
return null;
}
$accessKeyId = $config['account'];
$accessKeySecret = $config['api_key'];
Logger::debug("[aliyunApiRequest] Config ID: {$configId}, AccessKeyId: " . substr($accessKeyId, 0, 8) . "***", 'aliyunApiRequest');
// 确定API域名
if (!$region || empty($region)) {
Logger::error("Region参数为空,无法构建API域名", 'aliyunApiRequest');
return ['status' => 400, 'error' => 'Region参数为空'];
}
if ($serviceType === 'swas') {
$host = 'swas.' . $region . '.aliyuncs.com';
} else {
$host = 'ecs.' . $region . '.aliyuncs.com';
}
// 公共参数
$commonParams = [
'Action' => $action,
'Version' => ($serviceType === 'swas') ? '2020-06-01' : '2014-05-26',
'Format' => 'JSON',
'AccessKeyId' => $accessKeyId,
'SignatureMethod' => 'HMAC-SHA1',
'SignatureVersion' => '1.0',
'SignatureNonce' => uniqid(),
'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
'RegionId' => $region,
];
// 合并参数
$allParams = array_merge($commonParams, $params);
// 生成签名
$signature = generateAliyunSignature(
'GET',
$allParams,
$accessKeySecret
);
$allParams['Signature'] = $signature;
// 构建URL
$url = 'https://' . $host . '/?' . http_build_query($allParams);
Logger::debug("[aliyunApiRequest] URL: {$url}", 'aliyunApiRequest');
Logger::debug("[aliyunApiRequest] Action: {$action}, Region: {$region}, ServiceType: {$serviceType}", 'aliyunApiRequest');
// 发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
Logger::error("cURL错误: {$curlError}", 'aliyunApiRequest');
return ['status' => 0, 'error' => $curlError];
}
if ($httpCode !== 200) {
Logger::error("HTTP请求失败: {$httpCode}, 响应: {$response}", 'aliyunApiRequest');
// 尝试解析错误响应
$errorResult = json_decode($response, true);
if ($errorResult && isset($errorResult['Message'])) {
return ['status' => $httpCode, 'error' => $errorResult['Message'], 'code' => $errorResult['Code'] ?? 'Unknown'];
}
return ['status' => $httpCode, 'error' => 'HTTP请求失败 (' . $httpCode . ')'];
}
$result = json_decode($response, true);
if (!$result) {
Logger::error("JSON解析失败", 'aliyunApiRequest');
return ['status' => 500, 'error' => '响应解析失败'];
}
// 检查响应
if (isset($result['Code'])) {
Logger::error("API错误: {$result['Code']} - {$result['Message']}", 'aliyunApiRequest');
return ['status' => 400, 'error' => $result['Message'], 'code' => $result['Code']];
}
return ['status' => 200, 'data' => $result, 'region' => $region, 'service_type' => $serviceType];
}
/**
* 获取所有可用区域列表(ECS)
*/
function getAliyunRegions($configId) {
return [
'cn-qingdao', // 华北1(青岛)
'cn-beijing', // 华北2(北京)
'cn-zhangjiakou', // 华北3(张家口)
'cn-huhehaote', // 华北5(呼和浩特)
'cn-wulanchabu', // 华北6(乌兰察布)
'cn-hangzhou', // 华东1(杭州)
'cn-shanghai', // 华东2(上海)
'cn-nanjing', // 华东5(南京)
'cn-fuzhou', // 华东6(福州)
'cn-shenzhen', // 华南1(深圳)
'cn-heyuan', // 华南2(河源)
'cn-guangzhou', // 华南3(广州)
'cn-chengdu', // 西南1(成都)
'cn-hongkong', // 中国香港
'ap-southeast-1', // 新加坡
'ap-southeast-5', // 印度尼西亚(雅加达)
'ap-northeast-1', // 日本(东京)
'ap-northeast-2', // 韩国(首尔)
'ap-southeast-3', // 马来西亚(吉隆坡)
'ap-southeast-6', // 菲律宾(马尼拉)
'ap-southeast-7', // 泰国(曼谷)
'us-west-1', // 美国(硅谷)
'us-east-1', // 美国(弗吉尼亚)
'eu-central-1', // 德国(法兰克福)
'eu-west-1', // 英国(伦敦)
'me-east-1', // 阿联酋(迪拜)
'me-central-1', // 沙特(利雅得)
];
}
/**
* 获取轻量应用服务器可用区域列表
*/
function getAliyunSwasRegions($configId) {
return [
'cn-qingdao', // 华北1(青岛)
'cn-beijing', // 华北2(北京)
'cn-zhangjiakou', // 华北3(张家口)
'cn-huhehaote', // 华北5(呼和浩特)
'cn-wulanchabu', // 华北6(乌兰察布)
'cn-hangzhou', // 华东1(杭州)
'cn-shanghai', // 华东2(上海)
'cn-nanjing', // 华东5(南京)
'cn-fuzhou', // 华东6(福州)
'cn-shenzhen', // 华南1(深圳)
'cn-heyuan', // 华南2(河源)
'cn-guangzhou', // 华南3(广州)
'cn-chengdu', // 西南1(成都)
'cn-hongkong', // 中国香港
'ap-southeast-1', // 新加坡
'ap-northeast-1', // 日本(东京)
'us-west-1', // 美国(硅谷)
'eu-central-1', // 德国(法兰克福)
];
}
/**
* 获取ECS实例列表(单个区域)
*/
function aliyunGetEcsList($configId, $region, $maxResults = 100, $nextToken = null) {
$params = [
'MaxResults' => $maxResults,
];
if ($nextToken) {
$params['NextToken'] = $nextToken;
}
return aliyunApiRequest($configId, 'DescribeInstances', $params, $region, 'ecs');
}
/**
* 获取轻量应用服务器实例列表(单个区域)
*/
function aliyunGetSwasList($configId, $region, $pageNumber = 1, $pageSize = 100) {
$params = [
'PageNumber' => $pageNumber,
'PageSize' => $pageSize,
];
return aliyunApiRequest($configId, 'ListInstances', $params, $region, 'swas');
}
/**
* 获取ECS实例详细信息
*/
function aliyunGetEcsDetails($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceIds' => json_encode([$instanceId]),
];
$result = aliyunApiRequest($configId, 'DescribeInstances', $params, $region, 'ecs');
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['Instances']['Instance'] ?? [];
if (!empty($instances)) {
updateAliyunEcsToDatabase($configId, $instances[0]);
}
}
return $result;
}
/**
* 获取轻量应用服务器实例详细信息
*/
function aliyunGetSwasDetails($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceIds' => json_encode([$instanceId]),
];
$result = aliyunApiRequest($configId, 'ListInstances', $params, $region, 'swas');
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['Instances'] ?? [];
if (!empty($instances)) {
updateAliyunSwasToDatabase($configId, $instances[0]);
}
}
return $result;
}
/**
* 获取ECS实例状态
*/
function aliyunGetEcsStatus($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceId.1' => $instanceId,
];
$result = aliyunApiRequest($configId, 'DescribeInstanceStatus', $params, $region, 'ecs');
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instanceStatusSet = $result['data']['InstanceStatuses']['InstanceStatus'] ?? [];
if (!empty($instanceStatusSet)) {
$statusInfo = $instanceStatusSet[0];
$rawStatus = $statusInfo['Status'] ?? 'UNKNOWN';
// 状态映射
$statusMap = [
'Pending' => 'process',
'Running' => 'on',
'Starting' => 'process',
'Stopping' => 'process',
'Stopped' => 'off',
'Rebooting' => 'process',
'Unknown' => 'unknown'
];
$status = $statusMap[$rawStatus] ?? 'unknown';
updateVpsStatusInDatabaseAliyun($configId, $instanceId, $status);
}
}
return $result;
}
/**
* 获取轻量应用服务器实例状态
*/
function aliyunGetSwasStatus($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceIds' => json_encode([$instanceId]),
];
$result = aliyunApiRequest($configId, 'ListInstanceStatus', $params, $region, 'swas');
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instanceStatusSet = $result['data']['InstanceStatuses'] ?? [];
if (!empty($instanceStatusSet)) {
$statusInfo = $instanceStatusSet[0];
$rawStatus = $statusInfo['Status'] ?? 'UNKNOWN';
// 状态映射
$statusMap = [
'Pending' => 'process',
'Starting' => 'process',
'Running' => 'on',
'Stopping' => 'process',
'Stopped' => 'off',
'Resetting' => 'process',
'Upgrading' => 'process',
'Disabled' => 'off',
'Unknown' => 'unknown'
];
$status = $statusMap[$rawStatus] ?? 'unknown';
updateVpsStatusInDatabaseAliyun($configId, $instanceId, $status);
}
}
return $result;
}
/**
* 启动ECS实例
*/
function aliyunPowerOn($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
Logger::info("[aliyunPowerOn] 从数据库获取到 region: {$region}", 'aliyunPowerOn');
} else {
Logger::error("[aliyunPowerOn] 无法从数据库获取 region,config_id: {$configId}, instance_id: {$instanceId}", 'aliyunPowerOn');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceId' => $instanceId,
];
$result = aliyunApiRequest($configId, 'StartInstance', $params, $region, 'ecs');
// 开机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
aliyunGetEcsStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 启动轻量应用服务器
*/
function aliyunSwasPowerOn($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
Logger::info("[aliyunSwasPowerOn] 从数据库获取到 region: {$region}", 'aliyunSwasPowerOn');
} else {
Logger::error("[aliyunSwasPowerOn] 无法从数据库获取 region,config_id: {$configId}, instance_id: {$instanceId}", 'aliyunSwasPowerOn');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceId' => $instanceId,
];
$result = aliyunApiRequest($configId, 'StartInstance', $params, $region, 'swas');
// 开机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
aliyunGetSwasStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 停止ECS实例
*/
function aliyunPowerOff($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[aliyunPowerOff] 无法从数据库获取 region", 'aliyunPowerOff');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceId' => $instanceId,
];
$result = aliyunApiRequest($configId, 'StopInstance', $params, $region, 'ecs');
// 关机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
aliyunGetEcsStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 停止轻量应用服务器
*/
function aliyunSwasPowerOff($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[aliyunSwasPowerOff] 无法从数据库获取 region", 'aliyunSwasPowerOff');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceId' => $instanceId,
];
$result = aliyunApiRequest($configId, 'StopInstance', $params, $region, 'swas');
// 关机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
aliyunGetSwasStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 重启ECS实例
*/
function aliyunReboot($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[aliyunReboot] 无法从数据库获取 region", 'aliyunReboot');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceId' => $instanceId,
];
$result = aliyunApiRequest($configId, 'RebootInstance', $params, $region, 'ecs');
// 重启操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(3);
aliyunGetEcsStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 重启轻量应用服务器
*/
function aliyunSwasReboot($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[aliyunSwasReboot] 无法从数据库获取 region", 'aliyunSwasReboot');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceId' => $instanceId,
];
$result = aliyunApiRequest($configId, 'RebootInstance', $params, $region, 'swas');
// 重启操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(3);
aliyunGetSwasStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 将ECS信息更新到数据库
*/
function updateAliyunEcsToDatabase($configId, $instance) {
$listDb = getVpsListDB();
$vpsId = $instance['InstanceId'];
$region = $instance['RegionId'] ?? '';
$zoneId = $instance['ZoneId'] ?? '';
// 提取CPU和内存信息
$cpuCores = $instance['Cpu'] ?? null;
// 注意:阿里云API返回的Memory单位是MB,需要转换为GB
$memorySize = isset($instance['Memory']) ? round($instance['Memory'] / 1024, 2) . 'G' : null;
// 提取系统盘信息
$diskSize = null;
if (isset($instance['SystemDisk']) && isset($instance['SystemDisk']['Size'])) {
$diskSize = $instance['SystemDisk']['Size'] . 'G';
}
// 提取带宽信息
$bandwidth = null;
if (isset($instance['InternetMaxBandwidthOut'])) {
$bandwidth = $instance['InternetMaxBandwidthOut'] . 'Mbps';
}
// 提取操作系统信息
$osType = $instance['OSName'] ?? ($instance['ImageId'] ?? null);
// 提取IP地址
$ipAddress = null;
if (isset($instance['PublicIpAddress']) && !empty($instance['PublicIpAddress']['IpAddress'])) {
$ipAddress = $instance['PublicIpAddress']['IpAddress'][0];
} elseif (isset($instance['EipAddress']) && isset($instance['EipAddress']['IpAddress'])) {
$ipAddress = $instance['EipAddress']['IpAddress'];
}
// 提取实例名称
$productName = $instance['InstanceName'] ?? null;
// 提取到期时间
$nextduedate = null;
if (isset($instance['ExpiredTime'])) {
$expiredTime = $instance['ExpiredTime'];
if ($expiredTime !== '' && $expiredTime !== null) {
$nextduedate = strtotime($expiredTime);
}
}
// 检查记录是否存在
$existing = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId]
);
if ($existing) {
// 更新现有记录
$listDb->execute(
'UPDATE vps_list SET domain = ?, ip_address = ?, product_name = ?, cpu_cores = ?, memory_size = ?, disk_size = ?, bandwidth = ?, os_type = ?, nextduedate = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[
$zoneId,
$ipAddress,
$productName,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$nextduedate,
$existing['id']
]
);
Logger::info("[updateAliyunEcsToDatabase] ECS {$vpsId} 详细信息已更新", 'updateAliyunEcsToDatabase');
} else {
// 插入新记录
$listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, status, nextduedate, last_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, CURRENT_TIMESTAMP)',
[
$configId,
$vpsId,
$zoneId,
$ipAddress,
$productName,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$nextduedate
]
);
Logger::info("[updateAliyunEcsToDatabase] ECS {$vpsId} 新记录已插入", 'updateAliyunEcsToDatabase');
}
}
/**
* 将轻量应用服务器信息更新到数据库
*/
function updateAliyunSwasToDatabase($configId, $instance) {
$listDb = getVpsListDB();
$vpsId = $instance['InstanceId'];
$region = $instance['RegionId'] ?? '';
// 提取CPU和内存信息(从ResourceSpec中获取)
$cpuCores = isset($instance['ResourceSpec']) ? $instance['ResourceSpec']['Cpu'] : null;
$memorySize = isset($instance['ResourceSpec']) ? $instance['ResourceSpec']['Memory'] . 'G' : null;
// 提取磁盘信息
$diskSize = isset($instance['ResourceSpec']) ? $instance['ResourceSpec']['DiskSize'] . 'G' : null;
// 提取带宽信息
$bandwidth = isset($instance['ResourceSpec']) ? $instance['ResourceSpec']['Bandwidth'] . 'Mbps' : null;
// 提取操作系统信息
$osType = null;
if (isset($instance['Image'])) {
$osType = $instance['Image']['OsType'] ?? null;
}
// 提取IP地址
$ipAddress = $instance['PublicIpAddress'] ?? null;
// 提取实例名称
$productName = $instance['InstanceName'] ?? null;
// 提取到期时间
$nextduedate = null;
if (isset($instance['ExpiredTime'])) {
$expiredTime = $instance['ExpiredTime'];
if ($expiredTime !== '' && $expiredTime !== null) {
$nextduedate = strtotime($expiredTime);
}
}
// 检查记录是否存在
$existing = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId]
);
if ($existing) {
// 更新现有记录
$listDb->execute(
'UPDATE vps_list SET domain = ?, ip_address = ?, product_name = ?, cpu_cores = ?, memory_size = ?, disk_size = ?, bandwidth = ?, os_type = ?, nextduedate = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[
$region,
$ipAddress,
$productName,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$nextduedate,
$existing['id']
]
);
Logger::info("[updateAliyunSwasToDatabase] SWAS {$vpsId} 详细信息已更新", 'updateAliyunSwasToDatabase');
} else {
// 插入新记录
$listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, status, nextduedate, last_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, CURRENT_TIMESTAMP)',
[
$configId,
$vpsId,
$region,
$ipAddress,
$productName,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$nextduedate
]
);
Logger::info("[updateAliyunSwasToDatabase] SWAS {$vpsId} 新记录已插入", 'updateAliyunSwasToDatabase');
}
}
/**
* 更新VPS状态到数据库
*/
function updateVpsStatusInDatabaseAliyun($configId, $vpsId, $status) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId]
);
if ($vpsInfo) {
$listDb->execute(
'UPDATE vps_list SET status = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[$status, $vpsInfo['id']]
);
Logger::info("[updateVpsStatusInDatabaseAliyun] VPS {$vpsId} 状态已更新为: {$status}", 'updateVpsStatusInDatabaseAliyun');
} else {
$listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, status, last_check) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
[$configId, $vpsId, $status]
);
Logger::info("[updateVpsStatusInDatabaseAliyun] VPS {$vpsId} 新记录已插入,状态: {$status}", 'updateVpsStatusInDatabaseAliyun');
}
}
/**
* 刷新指定配置的ECS列表(遍历所有区域)
*/
function refreshAliyunEcsListForConfig($configId) {
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config || $config['site_type'] !== 'aliyun') {
return false;
}
// 先获取区域列表
$regions = getAliyunRegions($configId);
$totalInstances = 0;
Logger::info("[refreshAliyunEcsListForConfig] 开始遍历所有区域获取ECS列表", 'refreshAliyunEcsListForConfig');
foreach ($regions as $region) {
try {
$nextToken = null;
do {
$result = aliyunGetEcsList($configId, $region, 100, $nextToken);
if ($result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['Instances']['Instance'] ?? [];
if (!empty($instances)) {
Logger::info("[refreshAliyunEcsListForConfig] 区域 {$region} 找到 " . count($instances) . " 台ECS", 'refreshAliyunEcsListForConfig');
foreach ($instances as $instance) {
updateAliyunEcsToDatabase($configId, $instance);
// 获取状态
aliyunGetEcsStatus($configId, $instance['InstanceId'], $region, true);
$totalInstances++;
// 避免频繁请求
usleep(300000); // 300毫秒
}
}
// 检查是否有下一页
$nextToken = $result['data']['NextToken'] ?? null;
} else {
Logger::warning("[refreshAliyunEcsListForConfig] 区域 {$region} 获取失败: " . ($result['msg'] ?? '未知错误'), 'refreshAliyunEcsListForConfig');
break;
}
} while ($nextToken);
} catch (Exception $e) {
Logger::error("[refreshAliyunEcsListForConfig] 区域 {$region} 异常: " . $e->getMessage(), 'refreshAliyunEcsListForConfig');
}
// 区域之间稍作延迟
usleep(500000); // 500毫秒
}
Logger::info("[refreshAliyunEcsListForConfig] ECS列表刷新完成,共获取 {$totalInstances} 台实例", 'refreshAliyunEcsListForConfig');
return true;
}
/**
* 刷新指定配置的轻量应用服务器列表(遍历所有区域)
*/
function refreshAliyunSwasListForConfig($configId) {
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config || $config['site_type'] !== 'aliyun_swas') {
return false;
}
// 先获取区域列表
$regions = getAliyunSwasRegions($configId);
$totalInstances = 0;
Logger::info("[refreshAliyunSwasListForConfig] 开始遍历所有区域获取轻量应用服务器列表", 'refreshAliyunSwasListForConfig');
foreach ($regions as $region) {
try {
$pageNumber = 1;
do {
$result = aliyunGetSwasList($configId, $region, $pageNumber, 100);
if ($result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['Instances'] ?? [];
$totalCount = $result['data']['TotalCount'] ?? 0;
$pageSize = $result['data']['PageSize'] ?? 10;
if (!empty($instances)) {
Logger::info("[refreshAliyunSwasListForConfig] 区域 {$region} 找到 " . count($instances) . " 台轻量服务器", 'refreshAliyunSwasListForConfig');
foreach ($instances as $instance) {
updateAliyunSwasToDatabase($configId, $instance);
// 获取状态
aliyunGetSwasStatus($configId, $instance['InstanceId'], $region, true);
$totalInstances++;
// 避免频繁请求
usleep(300000); // 300毫秒
}
}
// 检查是否有下一页
$totalPages = ceil($totalCount / $pageSize);
$pageNumber++;
if ($pageNumber > $totalPages) {
break;
}
} else {
Logger::warning("[refreshAliyunSwasListForConfig] 区域 {$region} 获取失败: " . ($result['msg'] ?? '未知错误'), 'refreshAliyunSwasListForConfig');
break;
}
} while (true);
} catch (Exception $e) {
Logger::error("[refreshAliyunSwasListForConfig] 区域 {$region} 异常: " . $e->getMessage(), 'refreshAliyunSwasListForConfig');
}
// 区域之间稍作延迟
usleep(500000); // 500毫秒
}
Logger::info("[refreshAliyunSwasListForConfig] 轻量应用服务器列表刷新完成,共获取 {$totalInstances} 台实例", 'refreshAliyunSwasListForConfig');
return true;
}
/**
* 刷新所有阿里云配置的实例列表(ECS + SWAS)
*/
function refreshAllAliyunVpsLists() {
$db = getVpsDB();
$configs = $db->query('SELECT * FROM configs WHERE site_type IN (?, ?)', ['aliyun', 'aliyun_swas']);
$successCount = 0;
foreach ($configs as $config) {
if ($config['site_type'] === 'aliyun') {
// 刷新ECS列表
if (refreshAliyunEcsListForConfig($config['id'])) {
$successCount++;
}
} elseif ($config['site_type'] === 'aliyun_swas') {
// 刷新轻量应用服务器列表
if (refreshAliyunSwasListForConfig($config['id'])) {
$successCount++;
}
}
}
return $successCount;
}
?>
+86
View File
@@ -0,0 +1,86 @@
// 腾讯云API签名v3实现示例
// 本代码基于腾讯云API签名v3文档实现: https://cloud.tencent.com/document/product/213/30654
// 请严格按照文档说明使用,不建议随意修改签名相关代码
<?php
function sign($key, $msg) {
return hash_hmac("sha256", $msg, $key, true);
}
// 密钥信息从环境变量读取,需要提前在环境变量中设置 TENCENTCLOUD_SECRET_ID 和 TENCENTCLOUD_SECRET_KEY
// 使用环境变量方式可以避免密钥硬编码在代码中,提高安全性
// 生产环境建议使用更安全的密钥管理方案,如密钥管理系统(KMS)、容器密钥注入等
// 请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
$secret_id = getenv("TENCENTCLOUD_SECRET_ID");
$secret_key = getenv("TENCENTCLOUD_SECRET_KEY");
$token = "";
$service = "lighthouse";
$host = "lighthouse.tencentcloudapi.com";
$req_region = "ap-guangzhou";
$version = "2020-03-24";
$action = "RebootInstances";
$payload = "{}";
$params = json_decode($payload);
$endpoint = "https://lighthouse.tencentcloudapi.com";
$algorithm = "TC3-HMAC-SHA256";
$timestamp = time();
$date = gmdate("Y-m-d", $timestamp);
// ************* 步骤 1:拼接规范请求串 *************
$http_request_method = "POST";
$canonical_uri = "/";
$canonical_querystring = "";
$ct = "application/json; charset=utf-8";
$canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
$signed_headers = "content-type;host;x-tc-action";
$hashed_request_payload = hash("sha256", $payload);
$canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";
// ************* 步骤 2:拼接待签名字符串 *************
$credential_scope = "$date/$service/tc3_request";
$hashed_canonical_request = hash("sha256", $canonical_request);
$string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";
// ************* 步骤 3:计算签名 *************
$secret_date = sign("TC3".$secret_key, $date);
$secret_service = sign($secret_date, $service);
$secret_signing = sign($secret_service, "tc3_request");
$signature = hash_hmac("sha256", $string_to_sign, $secret_signing);
// ************* 步骤 4:拼接 Authorization *************
$authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";
// ************* 步骤 5:构造并发起请求 *************
$headers = [
"Authorization" => $authorization,
"Content-Type" => "application/json; charset=utf-8",
"Host" => $host,
"X-TC-Action" => $action,
"X-TC-Timestamp" => $timestamp,
"X-TC-Version" => $version
];
if ($req_region) {
$headers["X-TC-Region"] = $req_region;
}
if ($token) {
$headers["X-TC-Token"] = $token;
}
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
} catch (Exception $err) {
echo $err->getMessage();
}
?>
+86
View File
@@ -0,0 +1,86 @@
// 腾讯云API签名v3实现示例
// 本代码基于腾讯云API签名v3文档实现: https://cloud.tencent.com/document/product/213/30654
// 请严格按照文档说明使用,不建议随意修改签名相关代码
<?php
function sign($key, $msg) {
return hash_hmac("sha256", $msg, $key, true);
}
// 密钥信息从环境变量读取,需要提前在环境变量中设置 TENCENTCLOUD_SECRET_ID 和 TENCENTCLOUD_SECRET_KEY
// 使用环境变量方式可以避免密钥硬编码在代码中,提高安全性
// 生产环境建议使用更安全的密钥管理方案,如密钥管理系统(KMS)、容器密钥注入等
// 请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
$secret_id = getenv("TENCENTCLOUD_SECRET_ID");
$secret_key = getenv("TENCENTCLOUD_SECRET_KEY");
$token = "";
$service = "lighthouse";
$host = "lighthouse.tencentcloudapi.com";
$req_region = "ap-guangzhou";
$version = "2020-03-24";
$action = "StopInstances";
$payload = "{}";
$params = json_decode($payload);
$endpoint = "https://lighthouse.tencentcloudapi.com";
$algorithm = "TC3-HMAC-SHA256";
$timestamp = time();
$date = gmdate("Y-m-d", $timestamp);
// ************* 步骤 1:拼接规范请求串 *************
$http_request_method = "POST";
$canonical_uri = "/";
$canonical_querystring = "";
$ct = "application/json; charset=utf-8";
$canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
$signed_headers = "content-type;host;x-tc-action";
$hashed_request_payload = hash("sha256", $payload);
$canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";
// ************* 步骤 2:拼接待签名字符串 *************
$credential_scope = "$date/$service/tc3_request";
$hashed_canonical_request = hash("sha256", $canonical_request);
$string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";
// ************* 步骤 3:计算签名 *************
$secret_date = sign("TC3".$secret_key, $date);
$secret_service = sign($secret_date, $service);
$secret_signing = sign($secret_service, "tc3_request");
$signature = hash_hmac("sha256", $string_to_sign, $secret_signing);
// ************* 步骤 4:拼接 Authorization *************
$authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";
// ************* 步骤 5:构造并发起请求 *************
$headers = [
"Authorization" => $authorization,
"Content-Type" => "application/json; charset=utf-8",
"Host" => $host,
"X-TC-Action" => $action,
"X-TC-Timestamp" => $timestamp,
"X-TC-Version" => $version
];
if ($req_region) {
$headers["X-TC-Region"] = $req_region;
}
if ($token) {
$headers["X-TC-Token"] = $token;
}
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
} catch (Exception $err) {
echo $err->getMessage();
}
?>
+86
View File
@@ -0,0 +1,86 @@
// 腾讯云API签名v3实现示例
// 本代码基于腾讯云API签名v3文档实现: https://cloud.tencent.com/document/product/213/30654
// 请严格按照文档说明使用,不建议随意修改签名相关代码
<?php
function sign($key, $msg) {
return hash_hmac("sha256", $msg, $key, true);
}
// 密钥信息从环境变量读取,需要提前在环境变量中设置 TENCENTCLOUD_SECRET_ID 和 TENCENTCLOUD_SECRET_KEY
// 使用环境变量方式可以避免密钥硬编码在代码中,提高安全性
// 生产环境建议使用更安全的密钥管理方案,如密钥管理系统(KMS)、容器密钥注入等
// 请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
$secret_id = getenv("TENCENTCLOUD_SECRET_ID");
$secret_key = getenv("TENCENTCLOUD_SECRET_KEY");
$token = "";
$service = "lighthouse";
$host = "lighthouse.tencentcloudapi.com";
$req_region = "ap-guangzhou";
$version = "2020-03-24";
$action = "StartInstances";
$payload = "{\"InstanceIds\":[\"lhins-celb8v9d\"]}";
$params = json_decode($payload);
$endpoint = "https://lighthouse.tencentcloudapi.com";
$algorithm = "TC3-HMAC-SHA256";
$timestamp = time();
$date = gmdate("Y-m-d", $timestamp);
// ************* 步骤 1:拼接规范请求串 *************
$http_request_method = "POST";
$canonical_uri = "/";
$canonical_querystring = "";
$ct = "application/json; charset=utf-8";
$canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
$signed_headers = "content-type;host;x-tc-action";
$hashed_request_payload = hash("sha256", $payload);
$canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";
// ************* 步骤 2:拼接待签名字符串 *************
$credential_scope = "$date/$service/tc3_request";
$hashed_canonical_request = hash("sha256", $canonical_request);
$string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";
// ************* 步骤 3:计算签名 *************
$secret_date = sign("TC3".$secret_key, $date);
$secret_service = sign($secret_date, $service);
$secret_signing = sign($secret_service, "tc3_request");
$signature = hash_hmac("sha256", $string_to_sign, $secret_signing);
// ************* 步骤 4:拼接 Authorization *************
$authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";
// ************* 步骤 5:构造并发起请求 *************
$headers = [
"Authorization" => $authorization,
"Content-Type" => "application/json; charset=utf-8",
"Host" => $host,
"X-TC-Action" => $action,
"X-TC-Timestamp" => $timestamp,
"X-TC-Version" => $version
];
if ($req_region) {
$headers["X-TC-Region"] = $req_region;
}
if ($token) {
$headers["X-TC-Token"] = $token;
}
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
} catch (Exception $err) {
echo $err->getMessage();
}
?>
+175
View File
@@ -0,0 +1,175 @@
<?php
/**
* VPS Hub 统一会话认证模块
*
* 功能:
* - 前端输入访问密码(POST)验证后建立 PHP 会话
* - 单次会话有效期 30 分钟(滑动过期)
* - 用户每次发起有效请求后自动刷新会话有效期
*
* 用法:
* require_once __DIR__ . '/app/auth.php';
* requireAuth(); // 未登录则展示登录页并终止脚本
* isLoggedIn(); // 返回当前会话是否有效
* attemptLogin($password); // 验证密码并建立会话
* logout(); // 手动退出登录
*/
// 会话有效期:30 分钟(秒)
if (!defined('SESSION_LIFETIME')) {
define('SESSION_LIFETIME', 1800);
}
// 会话垃圾回收最大存活时间(需在 session_start 之前设置)
ini_set('session.gc_maxlifetime', SESSION_LIFETIME);
// 启动会话
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
/**
* 判断当前会话是否已通过认证
* 已登录且未超过 30 分钟无操作时,刷新会话有效期(滑动过期)
*
* @return bool 是否有效登录态
*/
function isLoggedIn() {
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
return false;
}
// 滑动过期判断:超过 30 分钟无任何请求则会话失效
if (!isset($_SESSION['last_activity']) || (time() - intval($_SESSION['last_activity'])) > SESSION_LIFETIME) {
// 销毁过期会话
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
if (session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
}
return false;
}
// 用户请求了新数据,刷新会话有效期
$_SESSION['last_activity'] = time();
return true;
}
/**
* 验证访问密码并建立登录会话
* 使用 hash_equals 进行时序安全比对,防止时序攻击
*
* @param string $password 用户提交的访问密码
* @return bool 是否登录成功
*/
function attemptLogin($password) {
if (!defined('API_PASS')) {
return false;
}
if (hash_equals(API_PASS, (string)$password)) {
// 会话固定攻击防护:重新生成会话ID
session_regenerate_id(true);
$_SESSION['admin_logged_in'] = true;
$_SESSION['last_activity'] = time();
return true;
}
return false;
}
/**
* 强制要求登录认证
* 未认证时输出登录页面并终止当前脚本
* 已认证时直接返回,不影响后续流程
*
* @param string $redirect 登录成功后跳转的站内地址(可选,默认回到当前页面)
*/
function requireAuth($redirect = '') {
if (isLoggedIn()) {
return;
}
// 处理登录表单提交(POST 携带 auth_password)
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['auth_password'])) {
if (attemptLogin($_POST['auth_password'])) {
// 登录成功,跳转回目标页面
$target = !empty($_POST['redirect']) ? trim($_POST['redirect']) : $redirect;
// 仅允许站内跳转,防止开放重定向
if ($target && strpos($target, '://') === false && strpos($target, '\\') === false) {
header('Location: ' . $target);
} else {
header('Location: ' . $_SERVER['PHP_SELF']);
}
exit;
}
$error = '访问密码错误,请重试!';
}
// 构造登录成功后返回的地址(默认当前请求地址)
$currentPage = $_SERVER['PHP_SELF'];
$queryString = $_SERVER['QUERY_STRING'] ?? '';
$redirectTarget = !empty($redirect)
? $redirect
: ($queryString ? $currentPage . '?' . $queryString : $currentPage);
// 输出登录页面
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="./static/favicon.ico" type="image/x-icon">
<link href="./static/initial.css" rel="stylesheet" type="text/css">
<title>访问验证 - VPS Hub</title>
</head>
<body>
<div class="config-container">
<div class="config-header">
<h1>🔐 VPS Hub</h1>
<p>请输入访问密码以进入管理面板</p>
</div>
<?php if ($error): ?>
<div class="error-message">❌ <?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>
<form method="POST" action="<?php echo htmlspecialchars($currentPage); ?>">
<input type="hidden" name="redirect" value="<?php echo htmlspecialchars($redirectTarget); ?>">
<div class="form-group">
<label for="auth_password">访问密码</label>
<input type="password" id="auth_password" name="auth_password" required
placeholder="请输入访问密码" autofocus autocomplete="current-password">
</div>
<button type="submit" class="btn-submit">🔓 登录</button>
</form>
<div class="info-box" style="margin-top: 20px;">
💡 登录会话有效期 30 分钟,期间操作会自动续期;超过 30 分钟无操作需重新登录。
</div>
</div>
</body>
</html>
<?php
exit;
}
/**
* 退出登录并销毁会话
*/
function logout() {
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
if (session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
}
}
+61 -42
View File
@@ -1,21 +1,13 @@
<?php <?php
/** require_once __DIR__ . '/logger.php';
* VPS Hub 数据库辅助类
* 提供SQLite数据库的统一访问接口
*/
class DBHelper { class DBHelper {
private $db; private $db;
private $dbPath; private $dbPath;
/**
* 构造函数
* @param string $dbPath 数据库文件路径
*/
public function __construct($dbPath) { public function __construct($dbPath) {
$this->dbPath = $dbPath; $this->dbPath = $dbPath;
// 确保目录存在
$dir = dirname($dbPath); $dir = dirname($dbPath);
if (!is_dir($dir)) { if (!is_dir($dir)) {
mkdir($dir, 0755, true); mkdir($dir, 0755, true);
@@ -32,9 +24,6 @@ class DBHelper {
/** /**
* 执行查询并返回所有结果 * 执行查询并返回所有结果
* @param string $sql SQL语句
* @param array $params 参数数组
* @return array 结果数组
*/ */
public function query($sql, $params = []) { public function query($sql, $params = []) {
try { try {
@@ -42,16 +31,13 @@ class DBHelper {
$stmt->execute($params); $stmt->execute($params);
return $stmt->fetchAll(); return $stmt->fetchAll();
} catch (PDOException $e) { } catch (PDOException $e) {
error_log("数据库查询错误: " . $e->getMessage() . " | SQL: " . $sql); Logger::error("数据库查询错误: " . $e->getMessage() . " | SQL: " . $sql, 'DBHelper::query');
return []; return [];
} }
} }
/** /**
* 执行查询并返回单条结果 * 执行查询并返回单条结果
* @param string $sql SQL语句
* @param array $params 参数数组
* @return array|false 结果数组或false
*/ */
public function queryOne($sql, $params = []) { public function queryOne($sql, $params = []) {
try { try {
@@ -59,32 +45,26 @@ class DBHelper {
$stmt->execute($params); $stmt->execute($params);
return $stmt->fetch(); return $stmt->fetch();
} catch (PDOException $e) { } catch (PDOException $e) {
error_log("数据库查询错误: " . $e->getMessage() . " | SQL: " . $sql); Logger::error("数据库查询错误: " . $e->getMessage() . " | SQL: " . $sql, 'DBHelper::queryOne');
return false; return false;
} }
} }
/** /**
* 执行插入、更新、删除操作 * 执行插入、更新、删除操作
* @param string $sql SQL语句
* @param array $params 参数数组
* @return bool 是否成功
*/ */
public function execute($sql, $params = []) { public function execute($sql, $params = []) {
try { try {
$stmt = $this->db->prepare($sql); $stmt = $this->db->prepare($sql);
return $stmt->execute($params); return $stmt->execute($params);
} catch (PDOException $e) { } catch (PDOException $e) {
error_log("数据库执行错误: " . $e->getMessage() . " | SQL: " . $sql); Logger::error("数据库执行错误: " . $e->getMessage() . " | SQL: " . $sql, 'DBHelper::execute');
return false; return false;
} }
} }
/** /**
* 插入数据并返回最后插入的ID * 插入数据并返回最后插入的ID
* @param string $sql SQL语句
* @param array $params 参数数组
* @return int|false 最后插入的ID或false
*/ */
public function insert($sql, $params = []) { public function insert($sql, $params = []) {
try { try {
@@ -92,36 +72,23 @@ class DBHelper {
$stmt->execute($params); $stmt->execute($params);
return $this->db->lastInsertId(); return $this->db->lastInsertId();
} catch (PDOException $e) { } catch (PDOException $e) {
error_log("数据库插入错误: " . $e->getMessage() . " | SQL: " . $sql); Logger::error("数据库插入错误: " . $e->getMessage() . " | SQL: " . $sql, 'DBHelper::insert');
return false; return false;
} }
} }
/**
* 开始事务
*/
public function beginTransaction() { public function beginTransaction() {
return $this->db->beginTransaction(); return $this->db->beginTransaction();
} }
/**
* 提交事务
*/
public function commit() { public function commit() {
return $this->db->commit(); return $this->db->commit();
} }
/**
* 回滚事务
*/
public function rollBack() { public function rollBack() {
return $this->db->rollBack(); return $this->db->rollBack();
} }
/**
* 获取数据库连接对象(用于高级操作)
* @return PDO
*/
public function getConnection() { public function getConnection() {
return $this->db; return $this->db;
} }
@@ -133,7 +100,6 @@ function getVpsDB() {
if ($db === null) { if ($db === null) {
$dbPath = __DIR__ . '/db/vps.db'; $dbPath = __DIR__ . '/db/vps.db';
$db = new DBHelper($dbPath); $db = new DBHelper($dbPath);
// 初始化表结构
initVpsTables($db); initVpsTables($db);
} }
return $db; return $db;
@@ -156,7 +122,6 @@ function getStatusDB() {
if ($db === null) { if ($db === null) {
$dbPath = __DIR__ . '/db/status.db'; $dbPath = __DIR__ . '/db/status.db';
$db = new DBHelper($dbPath); $db = new DBHelper($dbPath);
// 初始化表结构
initStatusTables($db); initStatusTables($db);
} }
return $db; return $db;
@@ -179,6 +144,58 @@ function initVpsTables($db) {
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) )
"); ");
// 迁移:如果存在旧的UNIQUE约束,需要重建表
migrateConfigsTable($db);
}
/**
* 迁移configs表,删除UNIQUE(site_url, account)约束
* 允许同一个源添加多个不同的AccessKey
*/
function migrateConfigsTable($db) {
try {
// 检查是否存在旧的唯一约束
$result = $db->query("PRAGMA index_list(configs)");
$hasOldConstraint = false;
foreach ($result as $index) {
if (isset($index['name']) && strpos($index['name'], 'site_url') !== false) {
$hasOldConstraint = true;
break;
}
}
if ($hasOldConstraint) {
// 需要迁移:创建新表 -> 复制数据 -> 删除旧表 -> 重命名
$db->execute("ALTER TABLE configs RENAME TO configs_old");
$db->execute("
CREATE TABLE configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
api_label TEXT NOT NULL UNIQUE,
site_type TEXT NOT NULL,
site_url TEXT,
account TEXT NOT NULL,
api_key TEXT NOT NULL,
auto_monitor BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
$db->execute("
INSERT INTO configs (id, api_label, site_type, site_url, account, api_key, auto_monitor, created_at, updated_at)
SELECT id, api_label, site_type, site_url, account, api_key, auto_monitor, created_at, updated_at
FROM configs_old
");
$db->execute("DROP TABLE configs_old");
}
} catch (Exception $e) {
// 迁移失败不影响正常使用,记录日志即可
error_log("[迁移警告] configs表迁移失败: " . $e->getMessage());
}
} }
/** /**
@@ -199,15 +216,17 @@ function initVpsListTables($db) {
bandwidth TEXT, bandwidth TEXT,
os_type TEXT, os_type TEXT,
status TEXT, status TEXT,
amount TEXT,
nextduedate INTEGER,
section BOOLEAN DEFAULT 0, section BOOLEAN DEFAULT 0,
last_check TIMESTAMP, last_check TIMESTAMP,
FOREIGN KEY (config_id) REFERENCES configs(id), FOREIGN KEY (config_id) REFERENCES configs(id)
UNIQUE(config_id, vps_id)
) )
"); ");
$db->execute('CREATE INDEX IF NOT EXISTS idx_vps_config ON vps_list(config_id)'); $db->execute('CREATE INDEX IF NOT EXISTS idx_vps_config ON vps_list(config_id)');
$db->execute('CREATE INDEX IF NOT EXISTS idx_vps_vps_id ON vps_list(vps_id)'); $db->execute('CREATE INDEX IF NOT EXISTS idx_vps_vps_id ON vps_list(vps_id)');
$db->execute('CREATE INDEX IF NOT EXISTS idx_vps_unique ON vps_list(vps_id, ip_address)');
} }
/** /**
+226 -199
View File
@@ -1,9 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """VPS Hub 数据库管理模块"""
VPS Hub 数据库管理模块
负责初始化和管理三个SQLite数据库: vps.db, vpslist.db, status.db
"""
import os import os
import sqlite3 import sqlite3
@@ -14,38 +11,25 @@ class DatabaseManager:
"""数据库管理器""" """数据库管理器"""
def __init__(self, db_dir=None): def __init__(self, db_dir=None):
"""初始化数据库管理器
Args:
db_dir: 数据库文件目录,默认为app/db/
"""
if db_dir is None: if db_dir is None:
db_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'db') db_dir = os.path.join(os.path.dirname(
os.path.abspath(__file__)), 'db')
self.db_dir = db_dir self.db_dir = db_dir
os.makedirs(db_dir, exist_ok=True) os.makedirs(db_dir, exist_ok=True)
# 数据库文件路径
self.vps_db = os.path.join(db_dir, 'vps.db') self.vps_db = os.path.join(db_dir, 'vps.db')
self.vpslist_db = os.path.join(db_dir, 'vpslist.db') self.vpslist_db = os.path.join(db_dir, 'vpslist.db')
self.status_db = os.path.join(db_dir, 'status.db') self.status_db = os.path.join(db_dir, 'status.db')
# 初始化所有数据库
self.init_vps_db() self.init_vps_db()
self.init_vpslist_db() self.init_vpslist_db()
self.init_status_db() self.init_status_db()
def get_connection(self, db_path): def get_connection(self, db_path):
"""获取数据库连接 """获取数据库连接"""
Args:
db_path: 数据库文件路径
Returns:
SQLite连接对象
"""
conn = sqlite3.connect(db_path) conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row # 使结果可以通过列名访问 conn.row_factory = sqlite3.Row
return conn return conn
def init_vps_db(self): def init_vps_db(self):
@@ -89,16 +73,20 @@ class DatabaseManager:
bandwidth TEXT, bandwidth TEXT,
os_type TEXT, os_type TEXT,
status TEXT, status TEXT,
amount TEXT,
nextduedate INTEGER,
section BOOLEAN DEFAULT 0, section BOOLEAN DEFAULT 0,
last_check TIMESTAMP, last_check TIMESTAMP,
FOREIGN KEY (config_id) REFERENCES configs(id), FOREIGN KEY (config_id) REFERENCES configs(id)
UNIQUE(config_id, vps_id)
) )
''') ''')
# 创建索引以提高查询性能 cursor.execute(
cursor.execute('CREATE INDEX IF NOT EXISTS idx_vps_config ON vps_list(config_id)') 'CREATE INDEX IF NOT EXISTS idx_vps_config ON vps_list(config_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_vps_vps_id ON vps_list(vps_id)') cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_vps_vps_id ON vps_list(vps_id)')
cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_vps_unique ON vps_list(vps_id, ip_address)')
conn.commit() conn.commit()
conn.close() conn.close()
@@ -108,7 +96,6 @@ class DatabaseManager:
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
# Ping状态记录表
cursor.execute(''' cursor.execute('''
CREATE TABLE IF NOT EXISTS ping_status ( CREATE TABLE IF NOT EXISTS ping_status (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -120,7 +107,6 @@ class DatabaseManager:
) )
''') ''')
# VPS摘要统计表
cursor.execute(''' cursor.execute('''
CREATE TABLE IF NOT EXISTS vps_summary ( CREATE TABLE IF NOT EXISTS vps_summary (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -138,11 +124,14 @@ class DatabaseManager:
) )
''') ''')
# 创建索引 cursor.execute(
cursor.execute('CREATE INDEX IF NOT EXISTS idx_ping_vps ON ping_status(vps_id)') 'CREATE INDEX IF NOT EXISTS idx_ping_vps ON ping_status(vps_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_ping_time ON ping_status(check_time)') cursor.execute(
cursor.execute('CREATE INDEX IF NOT EXISTS idx_summary_vps ON vps_summary(vps_id)') 'CREATE INDEX IF NOT EXISTS idx_ping_time ON ping_status(check_time)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_summary_date ON vps_summary(date)') cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_summary_vps ON vps_summary(vps_id)')
cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_summary_date ON vps_summary(date)')
conn.commit() conn.commit()
conn.close() conn.close()
@@ -150,23 +139,19 @@ class DatabaseManager:
# ==================== vps.db 操作 ==================== # ==================== vps.db 操作 ====================
def add_config(self, api_label, site_type, account, api_key, site_url=None, auto_monitor=True): def add_config(self, api_label, site_type, account, api_key, site_url=None, auto_monitor=True):
"""添加VPS配置 """添加VPS配置,基于site_url和account去重"""
Args:
api_label: API标识(必填,唯一)
site_type: 网站类型 (mofang/aliyun/tencent)
account: 账户
api_key: API密钥
site_url: 网站链接
auto_monitor: 是否开启自动监控
Returns:
新配置的ID
"""
conn = self.get_connection(self.vps_db) conn = self.get_connection(self.vps_db)
cursor = conn.cursor() cursor = conn.cursor()
try: try:
existing = cursor.execute(
'SELECT id FROM configs WHERE site_url = ? AND account = ?',
(site_url, account)
).fetchone()
if existing:
return existing['id']
cursor.execute(''' cursor.execute('''
INSERT INTO configs (api_label, site_type, site_url, account, api_key, auto_monitor) INSERT INTO configs (api_label, site_type, site_url, account, api_key, auto_monitor)
VALUES (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
@@ -182,11 +167,7 @@ class DatabaseManager:
conn.close() conn.close()
def get_all_configs(self): def get_all_configs(self):
"""获取所有配置 """获取所有配置"""
Returns:
配置列表
"""
conn = self.get_connection(self.vps_db) conn = self.get_connection(self.vps_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -197,14 +178,7 @@ class DatabaseManager:
return configs return configs
def get_config_by_id(self, config_id): def get_config_by_id(self, config_id):
"""根据ID获取配置 """根据ID获取配置"""
Args:
config_id: 配置ID
Returns:
配置字典或None
"""
conn = self.get_connection(self.vps_db) conn = self.get_connection(self.vps_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -215,27 +189,19 @@ class DatabaseManager:
return dict(row) if row else None return dict(row) if row else None
def update_config(self, config_id, **kwargs): def update_config(self, config_id, **kwargs):
"""更新配置 """更新配置"""
Args:
config_id: 配置ID
**kwargs: 要更新的字段
Returns:
是否成功
"""
if not kwargs: if not kwargs:
return False return False
conn = self.get_connection(self.vps_db) conn = self.get_connection(self.vps_db)
cursor = conn.cursor() cursor = conn.cursor()
# 构建UPDATE语句
fields = ', '.join([f"{key} = ?" for key in kwargs.keys()]) fields = ', '.join([f"{key} = ?" for key in kwargs.keys()])
values = list(kwargs.values()) values = list(kwargs.values())
values.append(config_id) values.append(config_id)
cursor.execute(f'UPDATE configs SET {fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?', values) cursor.execute(
f'UPDATE configs SET {fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?', values)
affected = cursor.rowcount affected = cursor.rowcount
conn.commit() conn.commit()
@@ -244,14 +210,7 @@ class DatabaseManager:
return affected > 0 return affected > 0
def delete_config(self, config_id): def delete_config(self, config_id):
"""删除配置 """删除配置"""
Args:
config_id: 配置ID
Returns:
是否成功
"""
conn = self.get_connection(self.vps_db) conn = self.get_connection(self.vps_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -263,26 +222,84 @@ class DatabaseManager:
return affected > 0 return affected > 0
def reset_config_ids(self):
"""重置configs表的ID序列,从1开始连续编号"""
conn = self.get_connection(self.vps_db)
cursor = conn.cursor()
try:
cursor.execute('SELECT * FROM configs ORDER BY id')
configs = [dict(row) for row in cursor.fetchall()]
if not configs:
return True
cursor.execute('DROP TABLE IF EXISTS configs_backup')
cursor.execute('''
CREATE TABLE configs_backup AS SELECT * FROM configs
''')
cursor.execute('DELETE FROM configs')
cursor.execute("DELETE FROM sqlite_sequence WHERE name='configs'")
for config in configs:
cursor.execute('''
INSERT INTO configs (api_label, site_type, site_url, account, api_key, auto_monitor, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
config['api_label'],
config['site_type'],
config['site_url'],
config['account'],
config['api_key'],
config['auto_monitor'],
config['created_at'],
config['updated_at']
))
cursor.execute('DROP TABLE IF EXISTS configs_backup')
conn.commit()
return True
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
# ==================== vpslist.db 操作 ==================== # ==================== vpslist.db 操作 ====================
def add_vps(self, config_id, vps_id, domain=None, ip_address=None, def get_next_available_id(self):
product_name=None, section=False): """获取下一个可用的ID(填补空缺)"""
"""添加VPS到列表
Args:
config_id: 配置ID
vps_id: VPS在平台的ID
domain: 域名
ip_address: IP地址
product_name: 产品名称
section: 是否标记为需要监控
Returns:
新记录的ID
"""
conn = self.get_connection(self.vpslist_db) conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT id FROM vps_list ORDER BY id')
ids = [row['id'] for row in cursor.fetchall()]
conn.close()
if not ids:
return 1
for i in range(1, max(ids) + 1):
if i not in ids:
return i
return None
def add_vps(self, config_id, vps_id, domain=None, ip_address=None, product_name=None, section=False, custom_id=None):
"""添加VPS到列表,支持指定ID以填补空缺"""
conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor()
if custom_id is None:
custom_id = self.get_next_available_id()
if custom_id:
cursor.execute('''
INSERT INTO vps_list (id, config_id, vps_id, domain, ip_address, product_name, section, last_check)
VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
''', (custom_id, config_id, vps_id, domain, ip_address, product_name, section))
else:
cursor.execute(''' cursor.execute('''
INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, section, last_check) INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, section, last_check)
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
@@ -295,19 +312,47 @@ class DatabaseManager:
return record_id return record_id
def batch_add_vps(self, vps_list): def batch_add_vps(self, vps_list):
"""批量添加VPS """批量添加VPS,基于vps_id和ip_address去重"""
Args:
vps_list: VPS信息列表,每个元素是字典
"""
conn = self.get_connection(self.vpslist_db) conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor() cursor = conn.cursor()
for vps in vps_list: for vps in vps_list:
existing = cursor.execute(
'SELECT id FROM vps_list WHERE vps_id = ? AND ip_address = ?',
(vps['vps_id'], vps.get('ip_address'))
).fetchone()
if existing:
continue
custom_id = self.get_next_available_id()
if custom_id:
cursor.execute(''' cursor.execute('''
INSERT OR REPLACE INTO vps_list INSERT INTO vps_list
(config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, section, last_check) (id, config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, amount, nextduedate, section, last_check)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
''', (
custom_id,
vps['config_id'],
vps['vps_id'],
vps.get('domain'),
vps.get('ip_address'),
vps.get('product_name'),
vps.get('cpu_cores'),
vps.get('memory_size'),
vps.get('disk_size'),
vps.get('bandwidth'),
vps.get('os_type'),
vps.get('amount'),
vps.get('nextduedate'),
vps.get('section', False)
))
else:
cursor.execute('''
INSERT INTO vps_list
(config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, amount, nextduedate, section, last_check)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
''', ( ''', (
vps['config_id'], vps['config_id'],
vps['vps_id'], vps['vps_id'],
@@ -319,6 +364,8 @@ class DatabaseManager:
vps.get('disk_size'), vps.get('disk_size'),
vps.get('bandwidth'), vps.get('bandwidth'),
vps.get('os_type'), vps.get('os_type'),
vps.get('amount'),
vps.get('nextduedate'),
vps.get('section', False) vps.get('section', False)
)) ))
@@ -326,11 +373,7 @@ class DatabaseManager:
conn.close() conn.close()
def get_all_vps(self): def get_all_vps(self):
"""获取所有VPS """获取所有VPS"""
Returns:
VPS列表
"""
conn = self.get_connection(self.vpslist_db) conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -341,33 +384,19 @@ class DatabaseManager:
return vps_list return vps_list
def get_vps_by_config(self, config_id): def get_vps_by_config(self, config_id):
"""根据配置ID获取VPS列表 """根据配置ID获取VPS列表"""
Args:
config_id: 配置ID
Returns:
VPS列表
"""
conn = self.get_connection(self.vpslist_db) conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT * FROM vps_list WHERE config_id = ? ORDER BY vps_id', (config_id,)) cursor.execute(
'SELECT * FROM vps_list WHERE config_id = ? ORDER BY vps_id', (config_id,))
vps_list = [dict(row) for row in cursor.fetchall()] vps_list = [dict(row) for row in cursor.fetchall()]
conn.close() conn.close()
return vps_list return vps_list
def update_vps_details(self, vps_id, **kwargs): def update_vps_details(self, vps_id, **kwargs):
"""更新VPS详细信息 """更新VPS详细信息"""
Args:
vps_id: VPS ID
**kwargs: 要更新的字段
Returns:
是否成功
"""
if not kwargs: if not kwargs:
return False return False
@@ -378,7 +407,8 @@ class DatabaseManager:
values = list(kwargs.values()) values = list(kwargs.values())
values.append(vps_id) values.append(vps_id)
cursor.execute(f'UPDATE vps_list SET {fields}, last_check = CURRENT_TIMESTAMP WHERE vps_id = ?', values) cursor.execute(
f'UPDATE vps_list SET {fields}, last_check = CURRENT_TIMESTAMP WHERE vps_id = ?', values)
affected = cursor.rowcount affected = cursor.rowcount
conn.commit() conn.commit()
@@ -387,43 +417,76 @@ class DatabaseManager:
return affected > 0 return affected > 0
def update_vps_status(self, vps_id, status): def update_vps_status(self, vps_id, status):
"""更新VPS状态 """更新VPS状态"""
Args:
vps_id: VPS ID
status: 状态 (on/off/unknown)
Returns:
是否成功
"""
return self.update_vps_details(vps_id, status=status) return self.update_vps_details(vps_id, status=status)
def get_monitored_vps(self): def get_monitored_vps(self):
"""获取所有标记为需要监控的VPS """获取所有标记为需要监控的VPS"""
Returns:
VPS列表
"""
conn = self.get_connection(self.vpslist_db) conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT * FROM vps_list WHERE section = 1 ORDER BY config_id, vps_id') cursor.execute(
'SELECT * FROM vps_list WHERE section = 1 ORDER BY config_id, vps_id')
vps_list = [dict(row) for row in cursor.fetchall()] vps_list = [dict(row) for row in cursor.fetchall()]
conn.close() conn.close()
return vps_list return vps_list
def reset_vps_list_ids(self):
"""重置vps_list表的ID序列,从1开始连续编号"""
conn = self.get_connection(self.vpslist_db)
cursor = conn.cursor()
try:
cursor.execute('SELECT * FROM vps_list ORDER BY id')
vps_items = [dict(row) for row in cursor.fetchall()]
if not vps_items:
return True
cursor.execute('DROP TABLE IF EXISTS vps_list_backup')
cursor.execute('''
CREATE TABLE vps_list_backup AS SELECT * FROM vps_list
''')
cursor.execute('DELETE FROM vps_list')
cursor.execute("DELETE FROM sqlite_sequence WHERE name='vps_list'")
for vps in vps_items:
cursor.execute('''
INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, amount, nextduedate, status, section, last_check)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
vps['config_id'],
vps['vps_id'],
vps.get('domain'),
vps.get('ip_address'),
vps.get('product_name'),
vps.get('cpu_cores'),
vps.get('memory_size'),
vps.get('disk_size'),
vps.get('bandwidth'),
vps.get('os_type'),
vps.get('amount'),
vps.get('nextduedate'),
vps.get('status'),
vps.get('section', 0),
vps.get('last_check')
))
cursor.execute('DROP TABLE IF EXISTS vps_list_backup')
conn.commit()
return True
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
# ==================== status.db 操作 ==================== # ==================== status.db 操作 ====================
def save_ping_status(self, vps_id, target, status, latency_ms=None): def save_ping_status(self, vps_id, target, status, latency_ms=None):
"""保存Ping状态记录 """保存Ping状态记录"""
Args:
vps_id: VPS ID
target: 目标(IP或域名)
status: 状态 (normal/abnormal)
latency_ms: 延迟(ms)
"""
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -436,15 +499,7 @@ class DatabaseManager:
conn.close() conn.close()
def get_ping_records(self, vps_id, date=None): def get_ping_records(self, vps_id, date=None):
"""获取Ping记录 """获取Ping记录"""
Args:
vps_id: VPS ID
date: 日期 (YYYY-MM-DD),为空则获取所有记录
Returns:
Ping记录列表
"""
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -467,18 +522,16 @@ class DatabaseManager:
return records return records
def cleanup_old_ping_records(self, days=30): def cleanup_old_ping_records(self, days=30):
"""清理旧的Ping记录 """清理旧的Ping记录"""
Args:
days: 保留天数,默认30天
"""
from datetime import timedelta from datetime import timedelta
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
cutoff_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d %H:%M:%S') cutoff_date = (datetime.now() - timedelta(days=days)
cursor.execute('DELETE FROM ping_status WHERE check_time < ?', (cutoff_date,)) ).strftime('%Y-%m-%d %H:%M:%S')
cursor.execute(
'DELETE FROM ping_status WHERE check_time < ?', (cutoff_date,))
deleted = cursor.rowcount deleted = cursor.rowcount
conn.commit() conn.commit()
@@ -489,20 +542,7 @@ class DatabaseManager:
def save_vps_summary(self, vps_id, date, avg_latency, max_latency, min_latency, def save_vps_summary(self, vps_id, date, avg_latency, max_latency, min_latency,
count_under_100, count_100_to_300, count_300_to_500, count_under_100, count_100_to_300, count_300_to_500,
count_abnormal, availability): count_abnormal, availability):
"""保存VPS摘要统计 """保存VPS摘要统计"""
Args:
vps_id: VPS ID
date: 日期 (YYYY-MM-DD)
avg_latency: 平均延迟
max_latency: 最大延迟
min_latency: 最小延迟
count_under_100: <100ms次数
count_100_to_300: 100-300ms次数
count_300_to_500: 300-500ms次数
count_abnormal: 异常次数
availability: 可用性评分
"""
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
@@ -519,22 +559,16 @@ class DatabaseManager:
conn.close() conn.close()
def get_vps_summary(self, vps_id, date=None): def get_vps_summary(self, vps_id, date=None):
"""获取VPS摘要统计 """获取VPS摘要统计"""
Args:
vps_id: VPS ID
date: 日期,为空则获取最新一条
Returns:
摘要统计字典或None
"""
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
if date: if date:
cursor.execute('SELECT * FROM vps_summary WHERE vps_id = ? AND date = ?', (vps_id, date)) cursor.execute(
'SELECT * FROM vps_summary WHERE vps_id = ? AND date = ?', (vps_id, date))
else: else:
cursor.execute('SELECT * FROM vps_summary WHERE vps_id = ? ORDER BY date DESC LIMIT 1', (vps_id,)) cursor.execute(
'SELECT * FROM vps_summary WHERE vps_id = ? ORDER BY date DESC LIMIT 1', (vps_id,))
row = cursor.fetchone() row = cursor.fetchone()
conn.close() conn.close()
@@ -542,21 +576,14 @@ class DatabaseManager:
return dict(row) if row else None return dict(row) if row else None
def get_all_summaries(self, date=None): def get_all_summaries(self, date=None):
"""获取所有VPS的摘要统计 """获取所有VPS的摘要统计"""
Args:
date: 日期,为空则获取最新
Returns:
摘要统计列表
"""
conn = self.get_connection(self.status_db) conn = self.get_connection(self.status_db)
cursor = conn.cursor() cursor = conn.cursor()
if date: if date:
cursor.execute('SELECT * FROM vps_summary WHERE date = ? ORDER BY vps_id', (date,)) cursor.execute(
'SELECT * FROM vps_summary WHERE date = ? ORDER BY vps_id', (date,))
else: else:
# 获取每个VPS的最新摘要
cursor.execute(''' cursor.execute('''
SELECT vs.* FROM vps_summary vs SELECT vs.* FROM vps_summary vs
INNER JOIN ( INNER JOIN (
+102
View File
@@ -0,0 +1,102 @@
<?php
/**
* PHP日志管理类
* 统一处理所有PHP文件的日志记录
*/
class Logger {
private static $logFile = __DIR__ . '/logs/php.log';
private static $initialized = false;
/**
* 初始化日志系统
*/
public static function init() {
if (self::$initialized) {
return;
}
// 确保日志目录存在
$logDir = dirname(self::$logFile);
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// 创建日志文件(如果不存在)
if (!file_exists(self::$logFile)) {
touch(self::$logFile);
chmod(self::$logFile, 0666);
}
// 设置PHP错误日志路径
ini_set('error_log', self::$logFile);
ini_set('log_errors', 1);
ini_set('display_errors', 0); // 生产环境不显示错误
self::$initialized = true;
}
/**
* 记录日志
* @param string $message 日志消息
* @param string $level 日志级别 (INFO, WARNING, ERROR, DEBUG)
* @param string $source 来源文件/函数
*/
public static function log($message, $level = 'INFO', $source = '') {
self::init();
$timestamp = date('Y-m-d H:i:s');
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$caller = $source ?: (isset($backtrace[1]) ? basename($backtrace[1]['file']) . ':' . $backtrace[1]['line'] : 'unknown');
$logEntry = "[{$timestamp}] [{$level}] [{$caller}] {$message}" . PHP_EOL;
file_put_contents(self::$logFile, $logEntry, FILE_APPEND | LOCK_EX);
}
/**
* 记录信息日志
*/
public static function info($message, $source = '') {
self::log($message, 'INFO', $source);
}
/**
* 记录警告日志
*/
public static function warning($message, $source = '') {
self::log($message, 'WARNING', $source);
}
/**
* 记录错误日志
*/
public static function error($message, $source = '') {
self::log($message, 'ERROR', $source);
}
/**
* 记录调试日志
*/
public static function debug($message, $source = '') {
self::log($message, 'DEBUG', $source);
}
/**
* 获取日志文件路径
*/
public static function getLogFile() {
return self::$logFile;
}
/**
* 清空日志文件
*/
public static function clear() {
file_put_contents(self::$logFile, '');
}
}
// 自动初始化
Logger::init();
?>
View File
Whitespace-only changes.
+5 -37
View File
@@ -1,9 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """VPS Hub 多平台监控程序"""
VPS Hub 多平台监控程序
功能:支持多平台(魔方/阿里云/腾讯云)的VPS监控、自动开机和可用性统计
"""
import os import os
import sys import sys
@@ -16,7 +13,6 @@ import schedule
from datetime import datetime, timedelta from datetime import datetime, timedelta
from pathlib import Path from pathlib import Path
# 导入数据库管理器
from db_manager import DatabaseManager from db_manager import DatabaseManager
@@ -29,41 +25,12 @@ class PlatformAdapter:
self.api_key = api_key self.api_key = api_key
self.jwt_token = None self.jwt_token = None
def login(self):
"""登录获取Token - 需要子类实现"""
raise NotImplementedError
def get_vps_list(self):
"""获取VPS列表 - 需要子类实现"""
raise NotImplementedError
def get_vps_status(self, vps_id):
"""获取VPS状态 - 需要子类实现"""
raise NotImplementedError
def get_vps_details(self, vps_id):
"""获取VPS详细信息 - 需要子类实现"""
raise NotImplementedError
def power_on(self, vps_id):
"""开机 - 需要子类实现"""
raise NotImplementedError
def power_off(self, vps_id):
"""关机 - 需要子类实现"""
raise NotImplementedError
def hard_reboot(self, vps_id):
"""硬重启 - 需要子类实现"""
raise NotImplementedError
class MofangAdapter(PlatformAdapter): class MofangAdapter(PlatformAdapter):
"""魔方平台适配器(核云IDC等使用此适配器)""" """魔方平台适配器"""
def __init__(self, site_url, account, api_key): def __init__(self, site_url, account, api_key):
super().__init__(site_url, account, api_key) super().__init__(site_url, account, api_key)
# 魔方平台的API路径统一为 /v1
if not self.site_url: if not self.site_url:
raise ValueError("魔方平台必须提供网站链接(API地址)") raise ValueError("魔方平台必须提供网站链接(API地址)")
@@ -79,7 +46,6 @@ class MofangAdapter(PlatformAdapter):
def login(self): def login(self):
try: try:
# 魔方平台API统一在 /v1 路径下
url = f"{self.site_url}/v1/login_api" url = f"{self.site_url}/v1/login_api"
data = { data = {
'account': self.account, 'account': self.account,
@@ -729,7 +695,9 @@ class MonitorService:
'disk_size': disk_size, 'disk_size': disk_size,
'bandwidth': bandwidth, 'bandwidth': bandwidth,
'os_type': os_type, 'os_type': os_type,
'section': config['auto_monitor'] # 根据配置的auto_monitor设置 'amount': host.get('amount'),
'nextduedate': host.get('nextduedate'),
'section': config['auto_monitor']
}) })
# 批量添加到数据库 # 批量添加到数据库
+193 -23
View File
@@ -5,6 +5,7 @@
*/ */
require_once __DIR__ . '/app/db_helper.php'; require_once __DIR__ . '/app/db_helper.php';
require_once __DIR__ . '/app/auth.php';
require_once __DIR__ . '/mofangidc.php'; require_once __DIR__ . '/mofangidc.php';
// Token文件路径(存储API_PASS) // Token文件路径(存储API_PASS)
@@ -33,7 +34,10 @@ if ($needSetup && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['setup_p
if (file_put_contents($tokenFile, $content)) { if (file_put_contents($tokenFile, $content)) {
chmod($tokenFile, 0600); chmod($tokenFile, 0600);
header('Location: config_add.php?pass=' . urlencode($apiPass)); // 密码刚由本人设置,直接建立登录会话并跳转
include $tokenFile;
attemptLogin($apiPass);
header('Location: config_add.php');
exit; exit;
} else { } else {
$setupError = '保存失败,请检查目录权限!'; $setupError = '保存失败,请检查目录权限!';
@@ -114,14 +118,8 @@ if (file_exists($tokenFile)) {
include $tokenFile; include $tokenFile;
} }
// 验证pass参数 // 会话认证:前端输入密码验证后建立会话,30分钟滑动过期
$pass = isset($_GET['pass']) ? $_GET['pass'] : ''; requireAuth();
if (!defined('API_PASS') || $pass !== API_PASS) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 403, 'msg' => '访问密码错误'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
// 处理添加配置 // 处理添加配置
$message = ''; $message = '';
@@ -134,6 +132,107 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$apiKey = trim($_POST['api_key']); $apiKey = trim($_POST['api_key']);
$autoMonitor = isset($_POST['auto_monitor']) ? 1 : 0; $autoMonitor = isset($_POST['auto_monitor']) ? 1 : 0;
// 将前端类型转换为数据库类型
$dbSiteType = $siteType;
if ($siteType === 'tencent_cvm' || $siteType === 'tencent_lh') {
$dbSiteType = 'tencent';
} elseif ($siteType === 'aliyun_swas') {
$dbSiteType = 'aliyun_swas';
}
// 验证必填字段(腾讯云和阿里云需要siteUrl)
if ($siteType === 'tencent_cvm' || $siteType === 'tencent_lh' || $siteType === 'aliyun' || $siteType === 'aliyun_swas') {
// 腾讯云/阿里云:siteUrl必填(API域名)
if (empty($apiLabel) || empty($siteType) || empty($siteUrl) || empty($account) || empty($apiKey)) {
$message = '<div class="error-message">❌ API标识、网站类型、API地址、AccessKey ID和AccessKey Secret不能为空!</div>';
} else {
$db = getVpsDB();
// 检查API标识是否已存在
$existingConfig = $db->queryOne('SELECT id FROM configs WHERE api_label = ?', [$apiLabel]);
if ($existingConfig) {
$message = '<div class="error-message">❌ API标识 "' . htmlspecialchars($apiLabel) . '" 已存在,请使用其他标识!</div>';
} else {
$configId = $db->insert(
'INSERT INTO configs (api_label, site_type, site_url, account, api_key, auto_monitor) VALUES (?, ?, ?, ?, ?, ?)',
[$apiLabel, $dbSiteType, $siteUrl, $account, $apiKey, $autoMonitor]
);
if ($configId) {
if ($siteType === 'aliyun') {
$message = '<div class="success-message">✅ 阿里云ECS配置添加成功!ID: ' . $configId . '</div>';
} elseif ($siteType === 'aliyun_swas') {
$message = '<div class="success-message">✅ 阿里云轻量应用服务器配置添加成功!ID: ' . $configId . '</div>';
} else {
$typeName = ($siteType === 'tencent_cvm') ? 'CVM云服务器' : '轻量应用服务器';
$message = '<div class="success-message">✅ 腾讯云' . $typeName . '配置添加成功!ID: ' . $configId . '</div>';
}
// 如果是首次添加配置,提示运行install.sh
$configCount = $db->queryOne('SELECT COUNT(*) as count FROM configs')['count'];
if ($configCount == 1) {
$message .= '<div class="info-box">💡 这是第一个配置,请运行 <code>app/install.sh</code> 安装监控服务</div>';
// 尝试自动执行install.sh(需要PHP有执行权限)
$installScript = __DIR__ . '/app/install.sh';
if (file_exists($installScript)) {
// 检查exec函数是否可用
if (!function_exists('exec')) {
$message .= '<div class="warning-message">⚠️ exec函数被禁用,无法自动安装监控服务。请手动执行: sudo bash app/install.sh</div>';
} else {
// 先设置可执行权限
chmod($installScript, 0755);
// 执行安装脚本
$output = [];
$returnVar = 0;
exec("bash {$installScript} 2>&1", $output, $returnVar);
if ($returnVar === 0) {
$message .= '<div class="success-message">✅ 监控服务已自动安装并启动</div>';
} else {
$message .= '<div class="error-message">⚠️ 自动安装失败,请手动执行: sudo bash app/install.sh</div>';
// 输出错误信息以便调试
if (!empty($output)) {
$message .= '<details><summary>查看错误详情</summary><pre>' . htmlspecialchars(implode("\n", $output)) . '</pre></details>';
}
}
}
}
}
// 自动刷新VPS列表
if ($dbSiteType === 'mofang') {
refreshVpsListForConfig($configId);
$message .= '<div class="info-box">✅ 已自动获取VPS列表</div>';
} elseif ($dbSiteType === 'tencent') {
// 腾讯云需要区分CVM和轻量服务器
require_once __DIR__ . '/tencentcloud.php';
if ($siteType === 'tencent_cvm') {
refreshTencentCvmListForConfig($configId);
} else {
refreshTencentLighthouseListForConfig($configId);
}
$message .= '<div class="info-box">✅ 已自动获取实例列表(遍历所有区域)</div>';
} elseif ($dbSiteType === 'aliyun') {
// 阿里云ECS
require_once __DIR__ . '/aliyun.php';
refreshAliyunEcsListForConfig($configId);
$message .= '<div class="info-box">✅ 已自动获取ECS实例列表(遍历所有区域)</div>';
} elseif ($dbSiteType === 'aliyun_swas') {
// 阿里云轻量应用服务器
require_once __DIR__ . '/aliyun.php';
refreshAliyunSwasListForConfig($configId);
$message .= '<div class="info-box">✅ 已自动获取轻量应用服务器列表(遍历所有区域)</div>';
}
} else {
$message = '<div class="error-message">❌ 配置添加失败,请重试</div>';
}
}
}
} else {
// 其他平台:siteUrl必填
if (empty($apiLabel) || empty($siteType) || empty($siteUrl) || empty($account) || empty($apiKey)) { if (empty($apiLabel) || empty($siteType) || empty($siteUrl) || empty($account) || empty($apiKey)) {
$message = '<div class="error-message">❌ API标识、网站类型、网站链接、账户和密钥不能为空!</div>'; $message = '<div class="error-message">❌ API标识、网站类型、网站链接、账户和密钥不能为空!</div>';
} else { } else {
@@ -198,7 +297,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$message .= '<div class="info-box">✅ 已自动获取VPS列表</div>'; $message .= '<div class="info-box">✅ 已自动获取VPS列表</div>';
} }
} else { } else {
$message = '<div class="error-message">❌ 配置添加失败!</div>'; $message = '<div class="error-message">❌ 配置添加失败,请重试</div>';
}
} }
} }
} }
@@ -281,7 +381,10 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
<div class="header"> <div class="header">
<h1>⚙️ VPS配置管理</h1> <h1>⚙️ VPS配置管理</h1>
<p>添加和管理多平台VPS配置</p> <p>添加和管理多平台VPS配置</p>
<a href="index.php?pass=<?php echo urlencode($pass); ?>" class="btn" style="float: right; margin-top: -60px;">返回首页</a> <div style="float: right; margin-top: -60px; display: flex; gap: 10px; align-items: center;">
<a href="index.php" class="btn">返回首页</a>
<a href="index.php?logout=1" class="btn" style="background: #6c757d; color: white;" onclick="return confirm('确认退出登录?')">🚪 退出登录</a>
</div>
</div> </div>
<div class="content"> <div class="content">
@@ -303,8 +406,10 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
<label>网站类型 *</label> <label>网站类型 *</label>
<select name="site_type" required onchange="toggleSiteUrl(this.value)"> <select name="site_type" required onchange="toggleSiteUrl(this.value)">
<option value="mofang">魔方平台</option> <option value="mofang">魔方平台</option>
<option value="aliyun">阿里云(暂不支持)</option> <option value="aliyun">阿里云 - ECS云服务器</option>
<option value="tencent">腾讯云(暂不支持)</option> <option value="aliyun_swas">阿里云 - 轻量应用服务器</option>
<option value="tencent_cvm">腾讯云 - CVM云服务器</option>
<option value="tencent_lh">腾讯云 - 轻量应用服务器</option>
</select> </select>
</div> </div>
@@ -317,13 +422,13 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
<div class="form-row"> <div class="form-row">
<div class="form-group-inline"> <div class="form-group-inline">
<label>账户 * <small>(邮箱或手机号)</small></label> <label>SecretId * <small>(腾讯云API密钥ID)</small></label>
<input type="text" name="account" required placeholder="输入账户"> <input type="text" name="account" required placeholder="输入SecretId" id="account_input">
</div> </div>
<div class="form-group-inline"> <div class="form-group-inline">
<label>API密钥 *</label> <label>SecretKey *</label>
<input type="password" name="api_key" required placeholder="输入API密钥"> <input type="password" name="api_key" required placeholder="输入SecretKey" id="api_key_input">
</div> </div>
</div> </div>
@@ -331,6 +436,7 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
<div class="checkbox-group"> <div class="checkbox-group">
<input type="checkbox" name="auto_monitor" id="auto_monitor" checked> <input type="checkbox" name="auto_monitor" id="auto_monitor" checked>
<label for="auto_monitor">开启自动开机监控</label> <label for="auto_monitor">开启自动开机监控</label>
<span id="monitor_hint" style="color: #dc3545; margin-left: 10px; display: none;">⚠️ 不支持监控此源</span>
</div> </div>
</div> </div>
@@ -350,7 +456,6 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
<table class="config-table"> <table class="config-table">
<thead> <thead>
<tr> <tr>
<th>序号</th>
<th>API标识</th> <th>API标识</th>
<th>网站类型</th> <th>网站类型</th>
<th>网站链接</th> <th>网站链接</th>
@@ -363,13 +468,13 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
<tbody> <tbody>
<?php foreach ($configs as $config): ?> <?php foreach ($configs as $config): ?>
<tr> <tr>
<td><?php echo $config['id']; ?></td>
<td><strong><?php echo htmlspecialchars($config['api_label']); ?></strong></td> <td><strong><?php echo htmlspecialchars($config['api_label']); ?></strong></td>
<td> <td>
<?php <?php
$typeMap = [ $typeMap = [
'mofang' => '魔方', 'mofang' => '魔方',
'aliyun' => '阿里云', 'aliyun' => '阿里云ECS',
'aliyun_swas' => '阿里云轻量',
'tencent' => '腾讯云' 'tencent' => '腾讯云'
]; ];
echo $typeMap[$config['site_type']] ?? $config['site_type']; echo $typeMap[$config['site_type']] ?? $config['site_type'];
@@ -408,17 +513,82 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
function toggleSiteUrl(siteType) { function toggleSiteUrl(siteType) {
const urlGroup = document.getElementById('site_url_group'); const urlGroup = document.getElementById('site_url_group');
const urlInput = document.getElementById('site_url_input'); const urlInput = document.getElementById('site_url_input');
const accountLabel = document.querySelector('label[for="account_input"]') || document.querySelector('input[name="account"]').previousElementSibling;
const keyLabel = document.querySelector('label[for="api_key_input"]') || document.querySelector('input[name="api_key"]').previousElementSibling;
const autoMonitorCheckbox = document.getElementById('auto_monitor');
const monitorHint = document.getElementById('monitor_hint');
// 判断是否为魔方平台
const isMofang = (siteType === 'mofang');
if (isMofang) {
// 魔方平台:启用监控选项
autoMonitorCheckbox.disabled = false;
autoMonitorCheckbox.checked = true;
monitorHint.style.display = 'none';
} else {
// 非魔方平台:禁用监控选项
autoMonitorCheckbox.disabled = true;
autoMonitorCheckbox.checked = false;
monitorHint.style.display = 'inline';
}
if (siteType === 'mofang') { if (siteType === 'mofang') {
// 魔方平台
urlGroup.style.display = 'block';
urlInput.placeholder = '例如: https://www.heyunidc.cn'; urlInput.placeholder = '例如: https://www.heyunidc.cn';
urlInput.required = true;
accountLabel.innerHTML = '账户 * <small>(邮箱或手机号)</small>';
keyLabel.textContent = 'API密钥 *';
} else if (siteType === 'aliyun') { } else if (siteType === 'aliyun') {
urlInput.placeholder = '例如: https://ecs.aliyuncs.com'; // 阿里云ECS
} else if (siteType === 'tencent') { urlGroup.style.display = 'block';
urlInput.placeholder = '例如: https://cvm.tencentcloudapi.com'; urlInput.value = 'https://ecs.aliyuncs.com';
urlInput.placeholder = 'https://ecs.aliyuncs.com';
urlInput.required = true;
accountLabel.innerHTML = 'AccessKey ID * <small>(阿里云访问密钥ID)</small>';
keyLabel.textContent = 'AccessKey Secret *';
} else if (siteType === 'aliyun_swas') {
// 阿里云轻量应用服务器
urlGroup.style.display = 'block';
urlInput.value = 'https://swas.aliyuncs.com';
urlInput.placeholder = 'https://swas.aliyuncs.com';
urlInput.required = true;
accountLabel.innerHTML = 'AccessKey ID * <small>(阿里云访问密钥ID)</small>';
keyLabel.textContent = 'AccessKey Secret *';
} else if (siteType === 'tencent_cvm') {
// CVM云服务器
urlGroup.style.display = 'block';
urlInput.value = 'https://cvm.tencentcloudapi.com';
urlInput.placeholder = 'https://cvm.tencentcloudapi.com';
urlInput.required = true;
accountLabel.innerHTML = 'SecretId * <small>(腾讯云API密钥ID)</small>';
keyLabel.textContent = 'SecretKey *';
} else if (siteType === 'tencent_lh') {
// 轻量应用服务器
urlGroup.style.display = 'block';
urlInput.value = 'https://lighthouse.tencentcloudapi.com';
urlInput.placeholder = 'https://lighthouse.tencentcloudapi.com';
urlInput.required = true;
accountLabel.innerHTML = 'SecretId * <small>(腾讯云API密钥ID)</small>';
keyLabel.textContent = 'SecretKey *';
} else { } else {
// 其他类型
urlGroup.style.display = 'block';
urlInput.placeholder = '例如: https://www.example.com'; urlInput.placeholder = '例如: https://www.example.com';
urlInput.required = true;
accountLabel.innerHTML = '账户 *';
keyLabel.textContent = 'API密钥 *';
} }
} }
// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
const siteTypeSelect = document.querySelector('select[name="site_type"]');
if (siteTypeSelect) {
toggleSiteUrl(siteTypeSelect.value);
}
});
</script> </script>
</body> </body>
</html> </html>
+250 -68
View File
@@ -1,6 +1,10 @@
<?php <?php
require_once __DIR__ . '/app/db_helper.php'; require_once __DIR__ . '/app/db_helper.php';
require_once __DIR__ . '/app/logger.php';
require_once __DIR__ . '/app/auth.php';
require_once __DIR__ . '/mofangidc.php'; require_once __DIR__ . '/mofangidc.php';
require_once __DIR__ . '/tencentcloud.php';
require_once __DIR__ . '/aliyun.php';
// 存储API_PASS // 存储API_PASS
$tokenFile = __DIR__ . '/app/pass.php'; $tokenFile = __DIR__ . '/app/pass.php';
@@ -14,25 +18,34 @@ if (!file_exists($tokenFile)) {
// 加载API_PASS // 加载API_PASS
include $tokenFile; include $tokenFile;
// 验证pass参数 // 处理退出登录(需在会话认证之前,保证已登录用户也能退出)
$pass = isset($_GET['pass']) ? $_GET['pass'] : ''; if (isset($_GET['logout'])) {
logout();
if (!defined('API_PASS') || $pass !== API_PASS) { header('Location: ' . $_SERVER['PHP_SELF']);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 403, 'msg' => '访问密码错误或者未输入密码,请拼接?pass=API_PASS后再尝试访问'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit; exit;
} }
// 会话认证:前端输入密码验证后建立会话,30分钟滑动过期
requireAuth();
// 处理操作请求 // 处理操作请求
$message = ''; $message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? ''; $action = $_POST['action'] ?? '';
$hostId = intval($_POST['host_id'] ?? 0); $hostId = $_POST['host_id'] ?? '';
$configId = intval($_POST['config_id'] ?? 0); $configId = intval($_POST['config_id'] ?? 0);
if ($action && $hostId > 0 && $configId > 0) { if ($action && !empty($hostId) && $configId > 0) {
$result = null; $result = null;
Logger::info("[操作请求] action={$action}, host_id={$hostId}, config_id={$configId}", 'index.php');
// 获取配置信息以确定平台类型
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if ($config) {
if ($config['site_type'] === 'mofang') {
if ($action === 'reboot') { if ($action === 'reboot') {
$result = mofangHardReboot($configId, $hostId); $result = mofangHardReboot($configId, $hostId);
} elseif ($action === 'on') { } elseif ($action === 'on') {
@@ -40,16 +53,102 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} elseif ($action === 'off') { } elseif ($action === 'off') {
$result = mofangPowerOff($configId, $hostId); $result = mofangPowerOff($configId, $hostId);
} }
} elseif ($config['site_type'] === 'tencent') {
// 腾讯云智能操作(自动识别CVM或轻量服务器)
if ($action === 'reboot') {
$result = tencentSmartReboot($configId, $hostId);
} elseif ($action === 'on') {
$result = tencentSmartPowerOn($configId, $hostId);
} elseif ($action === 'off') {
$result = tencentSmartPowerOff($configId, $hostId);
}
} elseif ($config['site_type'] === 'aliyun') {
// 阿里云ECS操作
if ($action === 'reboot') {
$result = aliyunReboot($configId, $hostId);
} elseif ($action === 'on') {
$result = aliyunPowerOn($configId, $hostId);
} elseif ($action === 'off') {
$result = aliyunPowerOff($configId, $hostId);
}
} elseif ($config['site_type'] === 'aliyun_swas') {
// 阿里云轻量应用服务器操作
if ($action === 'reboot') {
$result = aliyunSwasReboot($configId, $hostId);
} elseif ($action === 'on') {
$result = aliyunSwasPowerOn($configId, $hostId);
} elseif ($action === 'off') {
$result = aliyunSwasPowerOff($configId, $hostId);
}
}
}
if ($result && isset($result['status']) && $result['status'] === 200) { if ($result && isset($result['status']) && $result['status'] === 200) {
$message = '<div class="success-message"><h3>✅ 操作成功</h3><p>VPS #' . $hostId . ' 已成功执行操作</p></div>'; $message = '<div class="success-message"><h3>✅ 操作成功</h3><p>VPS #' . $hostId . ' 已成功执行操作</p></div>';
} else { } else {
$errorMsg = $result['msg'] ?? '未知错误'; $errorMsg = $result['error'] ?? $result['msg'] ?? '未知错误';
$message = '<div class="error-message"><h3>❌ 操作失败</h3><p>' . htmlspecialchars($errorMsg) . '</p></div>'; $message = '<div class="error-message"><h3>❌ 操作失败</h3><p>' . htmlspecialchars($errorMsg) . '</p></div>';
} }
} elseif ($action === 'refresh_single_config') {
// 单独刷新某个配置
$configId = intval($_POST['config_id'] ?? 0);
if ($configId > 0) {
$configDb = getVpsDB();
$config = $configDb->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if ($config) {
$success = false;
$typeName = '';
if ($config['site_type'] === 'mofang') {
require_once __DIR__ . '/mofangidc.php';
$success = refreshVpsListForConfig($configId);
$typeName = '魔方平台';
} elseif ($config['site_type'] === 'tencent') {
require_once __DIR__ . '/tencentcloud.php';
// 同时刷新CVM和轻量
$cvmSuccess = refreshTencentCvmListForConfig($configId);
$lhSuccess = refreshTencentLighthouseListForConfig($configId);
$success = $cvmSuccess || $lhSuccess;
$typeName = '腾讯云';
} elseif ($config['site_type'] === 'aliyun') {
require_once __DIR__ . '/aliyun.php';
$success = refreshAliyunEcsListForConfig($configId);
$typeName = '阿里云ECS';
} elseif ($config['site_type'] === 'aliyun_swas') {
require_once __DIR__ . '/aliyun.php';
$success = refreshAliyunSwasListForConfig($configId);
$typeName = '阿里云轻量';
}
if ($success) {
$message = '<div class="success-message"><h3>✅ 刷新成功</h3><p>已刷新配置「' . htmlspecialchars($config['api_label']) . '」(' . $typeName . ')的VPS列表</p></div>';
} else {
$message = '<div class="error-message"><h3>❌ 刷新失败</h3><p>配置「' . htmlspecialchars($config['api_label']) . '」刷新失败,请检查API凭证和网络连接</p></div>';
}
} else {
$message = '<div class="error-message">❌ 配置不存在</div>';
}
} else {
$message = '<div class="error-message">❌ 无效的配置ID</div>';
}
} elseif ($action === 'refresh_vps_list') { } elseif ($action === 'refresh_vps_list') {
// 手动刷新VPS列表 // 手动刷新VPS列表(全部)
$count = refreshAllVpsLists(); $count = 0;
// 刷新魔方平台的VPS列表
$mofangCount = refreshAllVpsLists();
$count += $mofangCount;
// 刷新腾讯云的CVM和轻量应用服务器列表
$tencentCount = refreshAllTencentVpsLists();
$count += $tencentCount;
// 刷新阿里云的ECS列表
$aliyunCount = refreshAllAliyunVpsLists();
$count += $aliyunCount;
$message = '<div class="success-message"><h3>✅ 刷新完成</h3><p>已成功刷新 ' . $count . ' 个配置的VPS列表</p></div>'; $message = '<div class="success-message"><h3>✅ 刷新完成</h3><p>已成功刷新 ' . $count . ' 个配置的VPS列表</p></div>';
// 获取每个VPS的详细信息并更新数据库 // 获取每个VPS的详细信息并更新数据库
@@ -58,10 +157,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$configs = $configDb->query('SELECT * FROM configs'); $configs = $configDb->query('SELECT * FROM configs');
foreach ($configs as $config) { foreach ($configs as $config) {
if ($config['site_type'] !== 'mofang') { if ($config['site_type'] === 'mofang') {
continue; // 目前只支持魔方平台
}
// 获取该配置下的所有VPS // 获取该配置下的所有VPS
$vpsItems = $listDb->query('SELECT vps_id FROM vps_list WHERE config_id = ?', [$config['id']]); $vpsItems = $listDb->query('SELECT vps_id FROM vps_list WHERE config_id = ?', [$config['id']]);
@@ -81,14 +177,13 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($host['config_option']) && is_array($host['config_option'])) { if (isset($host['config_option']) && is_array($host['config_option'])) {
foreach ($host['config_option'] as $option) { foreach ($host['config_option'] as $option) {
if ($option['key'] === 'cpu' && isset($option['value'])) { if ($option['key'] === 'cpu' && isset($option['value'])) {
// 提取数字,例如 "16核" -> 16
preg_match('/(\d+)/', $option['value'], $matches); preg_match('/(\d+)/', $option['value'], $matches);
if (!empty($matches)) { if (!empty($matches)) {
$cpuCores = intval($matches[1]); $cpuCores = intval($matches[1]);
} }
} }
if ($option['key'] === 'memory' && isset($option['value'])) { if ($option['key'] === 'memory' && isset($option['value'])) {
$memorySize = $option['value']; // 例如 "16G" $memorySize = $option['value'];
} }
} }
} }
@@ -100,6 +195,16 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
); );
} }
} }
} elseif ($config['site_type'] === 'tencent') {
// 腾讯云实例已在refreshAllTencentVpsLists中更新了详细信息,这里不需要额外处理
Logger::info("[refresh_vps_list] 腾讯云配置 {$config['id']} 已刷新", 'index.php');
} elseif ($config['site_type'] === 'aliyun') {
// 阿里云ECS实例已在refreshAllAliyunVpsLists中更新了详细信息,这里不需要额外处理
Logger::info("[refresh_vps_list] 阿里云配置 {$config['id']} 已刷新", 'index.php');
} elseif ($config['site_type'] === 'aliyun_swas') {
// 阿里云轻量应用服务器实例已在refreshAllAliyunVpsLists中更新了详细信息,这里不需要额外处理
Logger::info("[refresh_vps_list] 阿里云轻量配置 {$config['id']} 已刷新", 'index.php');
}
} }
$message .= '<div class="success-message">✅ 已更新VPS详细信息(CPU、内存等)</div>'; $message .= '<div class="success-message">✅ 已更新VPS详细信息(CPU、内存等)</div>';
@@ -113,47 +218,39 @@ $configs = $db->query('SELECT * FROM configs ORDER BY id');
// 构建配置ID到配置的映射 // 构建配置ID到配置的映射
$configMap = []; $configMap = [];
foreach ($configs as $config) { foreach ($configs as $config) {
$configMap[$config['id']] = $config; $configMap[$config['id']] = $config; // 存储完整配置信息
} }
// 获取所有VPS列表(只从vpslist.db查询) // 获取所有VPS列表(从vpslist.db查询)
$listDb = getVpsListDB(); $listDb = getVpsListDB();
$vpsList = $listDb->query('SELECT * FROM vps_list ORDER BY config_id, vps_id'); $vpsList = $listDb->query('SELECT * FROM vps_list ORDER BY config_id, vps_id');
// 为每个VPS添加site_type和site_url信息 // 为每个VPS添加api_label
foreach ($vpsList as &$vps) { foreach ($vpsList as &$vps) {
$configId = $vps['config_id']; $configId = $vps['config_id'];
if (isset($configMap[$configId])) { $vps['api_label'] = $configMap[$configId]['api_label'] ?? 'Unknown';
$vps['site_type'] = $configMap[$configId]['site_type'];
// 修正site_url:移除末尾的/v1或/v1/
$siteUrl = $configMap[$configId]['site_url'];
$siteUrl = rtrim($siteUrl, '/'); // 移除末尾的 /
if (substr($siteUrl, -3) === '/v1') {
$siteUrl = substr($siteUrl, 0, -3); // 移除 /v1
} }
$vps['site_url'] = $siteUrl; unset($vps);
} else {
$vps['site_type'] = 'unknown';
$vps['site_url'] = '';
}
}
unset($vps); // 解除引用
// 调试信息(临时) Logger::info("Total VPS count: " . count($vpsList), 'index.php');
error_log("Configs count: " . count($configs));
error_log("VPS List count: " . count($vpsList));
if (!empty($vpsList)) { if (!empty($vpsList)) {
error_log("First VPS: " . json_encode($vpsList[0])); Logger::debug("First VPS: " . json_encode($vpsList[0]), 'index.php');
} }
// 按配置分组 // 按api_label分组
$vpsByConfig = []; $vpsByApiLabel = [];
foreach ($vpsList as $vps) { foreach ($vpsList as $vps) {
$configId = $vps['config_id']; $apiLabel = $vps['api_label'];
if (!isset($vpsByConfig[$configId])) { if (!isset($vpsByApiLabel[$apiLabel])) {
$vpsByConfig[$configId] = []; $vpsByApiLabel[$apiLabel] = [];
} }
$vpsByConfig[$configId][] = $vps; $vpsByApiLabel[$apiLabel][] = $vps;
}
// 构建api_label到config_id的映射(用于单独刷新)
$apiLabelToConfigId = [];
foreach ($configs as $config) {
$apiLabelToConfigId[$config['api_label']] = $config['id'];
} }
// 统计信息 // 统计信息
@@ -200,6 +297,20 @@ foreach ($vpsList as $vps) {
.btn-refresh:hover { .btn-refresh:hover {
background-color: #0056b3; background-color: #0056b3;
} }
.btn-logout {
background-color: #6c757d;
color: white;
text-decoration: none;
}
.btn-logout:hover {
background-color: #5a6268;
color: white;
}
.config-title {
display: flex;
justify-content: space-between;
align-items: center;
}
/* 消息自动消失动画 */ /* 消息自动消失动画 */
.success-message, .error-message { .success-message, .error-message {
transition: opacity 0.5s ease-out; transition: opacity 0.5s ease-out;
@@ -248,6 +359,7 @@ foreach ($vpsList as $vps) {
font-size: 18px; font-size: 18px;
font-weight: bold; font-weight: bold;
color: #333; color: #333;
cursor: help;
} }
.status-badge { .status-badge {
padding: 4px 12px; padding: 4px 12px;
@@ -296,6 +408,15 @@ foreach ($vpsList as $vps) {
.power-off { .power-off {
background-color: #dc3545; background-color: #dc3545;
} }
.power-process {
background-color: #ffc107;
box-shadow: 0 0 8px #ffc107;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.power-unknown { .power-unknown {
background-color: #6c757d; background-color: #6c757d;
} }
@@ -362,15 +483,20 @@ foreach ($vpsList as $vps) {
<!-- 工具栏 --> <!-- 工具栏 -->
<div class="toolbar"> <div class="toolbar">
<form method="POST" style="display: inline;"> <form method="POST" style="display: inline;" onsubmit="return confirmRefreshAll()">
<button type="submit" name="action" value="refresh_vps_list" class="btn-refresh"> <button type="submit" name="action" value="refresh_vps_list" class="btn-refresh">
🔄 手动刷新VPS列表 🔄 刷新全部列表
</button> </button>
</form> </form>
<a href="config_add.php?pass=<?php echo urlencode($pass); ?>" class="btn btn-success"> <div style="display: flex; gap: 10px; align-items: center;">
<a href="config_add.php" class="btn btn-success">
➕ 添加配置源 ➕ 添加配置源
</a> </a>
<a href="index.php?logout=1" class="btn btn-logout" onclick="return confirm('确认退出登录?')">
🚪 退出登录
</a>
</div>
</div> </div>
<!-- 统计信息 --> <!-- 统计信息 -->
@@ -390,53 +516,64 @@ foreach ($vpsList as $vps) {
<div class="empty-state"> <div class="empty-state">
<h3>📭 暂无配置</h3> <h3>📭 暂无配置</h3>
<p>请先添加VPS配置才能开始管理</p> <p>请先添加VPS配置才能开始管理</p>
<a href="config_add.php?pass=<?php echo urlencode($pass); ?>" class="btn btn-success" style="margin-top: 20px;"> <a href="config_add.php" class="btn btn-success" style="margin-top: 20px;">
➕ 添加第一个配置 ➕ 添加第一个配置
</a> </a>
</div> </div>
<?php else: ?> <?php else: ?>
<!-- 按配置分组显示VPS --> <!-- 按api_label分组显示VPS -->
<?php foreach ($configs as $config): <?php foreach ($vpsByApiLabel as $apiLabel => $labelVps): ?>
$configVps = $vpsByConfig[$config['id']] ?? [];
$typeMap = [
'mofang' => '魔方平台',
'aliyun' => '阿里云',
'tencent' => '腾讯云'
];
$typeName = $typeMap[$config['site_type']] ?? $config['site_type'];
?>
<div class="config-section"> <div class="config-section">
<div class="config-title"> <div class="config-title">
<?php echo htmlspecialchars($config['api_label']); ?> <span>
(<?php echo htmlspecialchars($typeName); ?>) <?php echo htmlspecialchars($apiLabel); ?>
- <?php echo count($configVps); ?> 台VPS - <?php echo count($labelVps); ?> 台VPS
</span>
<form method="POST" style="display: inline; margin-left: 15px;" onsubmit="return confirm('确认刷新此配置的VPS列表?')">
<input type="hidden" name="config_id" value="<?php echo $apiLabelToConfigId[$apiLabel] ?? 0; ?>">
<button type="submit" name="action" value="refresh_single_config" class="btn-refresh" style="padding: 5px 12px; font-size: 13px;">
🔄 刷新此配置
</button>
</form>
</div> </div>
<?php if (empty($configVps)): ?> <?php if (empty($labelVps)): ?>
<div class="empty-state" style="background: white; padding: 40px;"> <div class="empty-state" style="background: white; padding: 40px;">
<p>此配置下暂无VPS,请点击"手动刷新VPS列表"获取</p> <p>此配置下暂无VPS,请点击右上角“🔄 刷新此配置”按钮获取</p>
</div> </div>
<?php else: ?> <?php else: ?>
<div class="vps-grid"> <div class="vps-grid">
<?php foreach ($configVps as $vps): <?php foreach ($labelVps as $vps):
$statusClass = 'power-unknown'; $statusClass = 'power-unknown';
$statusText = '未知'; $statusText = '未知';
$statusColor = '#999'; $statusColor = '#999';
if ($vps['status'] === 'on') { if ($vps['status'] === 'on' || $vps['status'] === 'running') {
$statusClass = 'power-on'; $statusClass = 'power-on';
$statusText = '运行中'; $statusText = '运行中';
$statusColor = '#28a745'; $statusColor = '#28a745';
} elseif ($vps['status'] === 'off') { } elseif ($vps['status'] === 'off' || $vps['status'] === 'stopped') {
$statusClass = 'power-off'; $statusClass = 'power-off';
$statusText = '已关机'; $statusText = '已关机';
$statusColor = '#dc3545'; $statusColor = '#dc3545';
} elseif ($vps['status'] === 'process' || $vps['status'] === 'pending' || $vps['status'] === 'rebooting') {
$statusClass = 'power-process';
$statusText = '处理中';
$statusColor = '#ffc107';
}
// 处理长ID显示
$vpsId = $vps['vps_id'];
$displayId = $vpsId;
$showTooltip = false;
if (strlen($vpsId) > 12) {
$displayId = substr($vpsId, 0, 10) . '...';
$showTooltip = true;
} }
?> ?>
<div class="vps-card"> <div class="vps-card">
<div class="card-header"> <div class="card-header">
<div class="vps-id">#<?php echo $vps['vps_id']; ?></div> <div class="vps-id" <?php if ($showTooltip): ?>title="<?php echo htmlspecialchars($vpsId); ?>"<?php endif; ?>>#<?php echo htmlspecialchars($displayId); ?></div>
<span class="status-badge" style="background-color: <?php echo $statusColor; ?>"> <span class="status-badge" style="background-color: <?php echo $statusColor; ?>">
<?php echo $statusText; ?> <?php echo $statusText; ?>
</span> </span>
@@ -482,6 +619,20 @@ foreach ($vpsList as $vps) {
<span class="info-value"><?php echo htmlspecialchars($vps['disk_size']) . ' / ' . htmlspecialchars($vps['bandwidth']) . ' / ' . htmlspecialchars($vps['os_type']); ?></span> <span class="info-value"><?php echo htmlspecialchars($vps['disk_size']) . ' / ' . htmlspecialchars($vps['bandwidth']) . ' / ' . htmlspecialchars($vps['os_type']); ?></span>
</div> </div>
<?php endif; ?> <?php endif; ?>
<?php if ($vps['amount']): ?>
<div class="info-row">
<span class="info-label">价格</span>
<span class="info-value"><?php echo htmlspecialchars($vps['amount']); ?></span>
</div>
<?php endif; ?>
<?php if ($vps['nextduedate']): ?>
<div class="info-row">
<span class="info-label">到期时间</span>
<span class="info-value"><?php echo date('Y-m-d', $vps['nextduedate']); ?></span>
</div>
<?php endif; ?>
</div> </div>
<div class="power-status"> <div class="power-status">
@@ -499,9 +650,29 @@ foreach ($vpsList as $vps) {
<button type="submit" name="action" value="off" class="btn btn-danger" onclick="return confirm('确认关机?')"> <button type="submit" name="action" value="off" class="btn btn-danger" onclick="return confirm('确认关机?')">
🔴 关机 🔴 关机
</button> </button>
<?php
// 根据平台类型显示不同的重启按钮
$configId = $vps['config_id'];
$siteType = isset($configMap[$configId]) ? $configMap[$configId]['site_type'] : '';
if ($siteType === 'tencent') {
// 腾讯云:普通重启
?>
<button type="submit" name="action" value="reboot" class="btn btn-warning" onclick="return confirm('确认重启?')">
🔄 重启
</button>
<?php } elseif ($siteType === 'aliyun' || $siteType === 'aliyun_swas') {
// 阿里云(ECS或轻量):普通重启
?>
<button type="submit" name="action" value="reboot" class="btn btn-warning" onclick="return confirm('确认重启?')">
🔄 重启
</button>
<?php } else {
// 魔方等其他平台:硬重启
?>
<button type="submit" name="action" value="reboot" class="btn btn-warning" onclick="return confirm('确认硬重启?')"> <button type="submit" name="action" value="reboot" class="btn btn-warning" onclick="return confirm('确认硬重启?')">
🔄 硬重启 🔄 硬重启
</button> </button>
<?php } ?>
</div> </div>
</form> </form>
</div> </div>
@@ -535,6 +706,17 @@ foreach ($vpsList as $vps) {
}, 5000); // 5秒后开始淡出 }, 5000); // 5秒后开始淡出
}); });
}); });
// 刷新全部列表确认
function confirmRefreshAll() {
return confirm('⚠️ 警告:资源消耗占用较高\n\n' +
'刷新全部列表会同时请求所有配置的API,可能会导致:\n' +
'• 页面卡顿或响应缓慢\n' +
'• API超时导致报错中断\n' +
'• 部分配置刷新失败\n\n' +
'建议优先使用分离式刷新功能(点击每个配置右上角的🔄按钮)\n\n' +
'确定要继续刷新全部列表吗?');
}
</script> </script>
</body> </body>
</html> </html>
+184 -95
View File
@@ -1,19 +1,12 @@
<?php <?php
/**
* 魔方平台API接口封装
* 所有智简魔方的操作API以及相关函数存储在此文件中
*/
require_once __DIR__ . '/app/db_helper.php'; require_once __DIR__ . '/app/db_helper.php';
require_once __DIR__ . '/app/logger.php';
// Token缓存文件路径
define('TOKEN_CACHE_FILE', __DIR__ . '/app/token.php'); define('TOKEN_CACHE_FILE', __DIR__ . '/app/token.php');
define('TOKEN_EXPIRE_TIME', 7200); // Token过期时间(秒),2小时 define('TOKEN_EXPIRE_TIME', 7200);
/** /**
* 获取缓存的Token * 获取缓存的Token
* @param int $configId 配置ID
* @return string|null Token字符串或null
*/ */
function getCachedToken($configId) { function getCachedToken($configId) {
if (!file_exists(TOKEN_CACHE_FILE)) { if (!file_exists(TOKEN_CACHE_FILE)) {
@@ -43,8 +36,6 @@ function getCachedToken($configId) {
/** /**
* 保存Token到缓存文件 * 保存Token到缓存文件
* @param int $configId 配置ID
* @param string $token Token字符串
*/ */
function saveToken($configId, $token) { function saveToken($configId, $token) {
$cached_tokens = []; $cached_tokens = [];
@@ -77,10 +68,6 @@ function saveTokensFile($cached_tokens) {
/** /**
* 魔方平台登录获取JWT Token * 魔方平台登录获取JWT Token
* @param string $siteUrl API基础URL
* @param string $account 账户
* @param string $apiKey API密钥
* @return string|null JWT Token或null
*/ */
function mofangLogin($siteUrl, $account, $apiKey) { function mofangLogin($siteUrl, $account, $apiKey) {
try { try {
@@ -104,7 +91,7 @@ function mofangLogin($siteUrl, $account, $apiKey) {
curl_close($ch); curl_close($ch);
if ($httpCode !== 200) { if ($httpCode !== 200) {
error_log("魔方登录请求失败,HTTP状态码: {$httpCode}"); Logger::error("魔方登录请求失败,HTTP状态码: {$httpCode}", 'mofangLogin');
return null; return null;
} }
@@ -113,20 +100,18 @@ function mofangLogin($siteUrl, $account, $apiKey) {
if (isset($result['status']) && $result['status'] === 200 && isset($result['jwt'])) { if (isset($result['status']) && $result['status'] === 200 && isset($result['jwt'])) {
return $result['jwt']; return $result['jwt'];
} else { } else {
error_log("魔方登录失败: " . ($result['msg'] ?? '未知错误')); Logger::error("魔方登录失败: " . ($result['msg'] ?? '未知错误'), 'mofangLogin');
return null; return null;
} }
} catch (Exception $e) { } catch (Exception $e) {
error_log("魔方登录异常: " . $e->getMessage()); Logger::error("魔方登录异常: " . $e->getMessage(), 'mofangLogin');
return null; return null;
} }
} }
/** /**
* 获取有效的Token(先查缓存,没有则重新登录) * 获取有效的Token(先查缓存,没有则重新登录)
* @param int $configId 配置ID
* @return string|null Token或null
*/ */
function getValidToken($configId) { function getValidToken($configId) {
// 先尝试从缓存获取 // 先尝试从缓存获取
@@ -140,7 +125,7 @@ function getValidToken($configId) {
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]); $config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config) { if (!$config) {
error_log("配置ID {$configId} 不存在"); Logger::error("配置ID {$configId} 不存在", 'getValidToken');
return null; return null;
} }
@@ -155,12 +140,6 @@ function getValidToken($configId) {
/** /**
* 发送魔方API请求 * 发送魔方API请求
* @param string $siteUrl API基础URL
* @param string $endpoint API端点
* @param string $method HTTP方法 (GET/POST/PUT)
* @param array $data 请求数据
* @param int $configId 配置ID
* @return array|null 响应数据或null
*/ */
function mofangApiRequest($siteUrl, $endpoint, $method = 'GET', $data = [], $configId = null) { function mofangApiRequest($siteUrl, $endpoint, $method = 'GET', $data = [], $configId = null) {
// 获取Token // 获取Token
@@ -233,10 +212,6 @@ function mofangApiRequest($siteUrl, $endpoint, $method = 'GET', $data = [], $con
/** /**
* 获取VPS列表 * 获取VPS列表
* @param int $configId 配置ID
* @param int $page 页码
* @param int $limit 每页数量
* @return array|null VPS列表数据或null
*/ */
function mofangGetVpsList($configId, $page = 1, $limit = 100) { function mofangGetVpsList($configId, $page = 1, $limit = 100) {
$db = getVpsDB(); $db = getVpsDB();
@@ -252,10 +227,6 @@ function mofangGetVpsList($configId, $page = 1, $limit = 100) {
/** /**
* 获取VPS状态 * 获取VPS状态
* @param int $configId 配置ID
* @param int $vpsId VPS ID
* @param bool $updateDb 是否更新数据库,默认true
* @return array|null 状态数据或null
*/ */
function mofangGetVpsStatus($configId, $vpsId, $updateDb = true) { function mofangGetVpsStatus($configId, $vpsId, $updateDb = true) {
$db = getVpsDB(); $db = getVpsDB();
@@ -271,43 +242,64 @@ function mofangGetVpsStatus($configId, $vpsId, $updateDb = true) {
// 如果获取成功且需要更新数据库 // 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200 && isset($result['data'])) { if ($updateDb && $result && isset($result['status']) && $result['status'] === 200 && isset($result['data'])) {
$statusData = $result['data']; $statusData = $result['data'];
$status = $statusData['status'] ?? 'unknown'; $rawStatus = $statusData['status'] ?? 'unknown';
// 状态映射:将魔方平台的原始状态转换为标准状态
$statusMap = [
'on' => 'on', // 开机
'off' => 'off', // 关机
'running' => 'on', // 运行中
'stopped' => 'off', // 已停止
'process' => 'process', // 处理中(开机/关机/重启过程中)
'pending' => 'process', // 等待中
'installing' => 'process', // 安装中
'rebooting' => 'process', // 重启中
'unknown' => 'unknown' // 未知
];
$status = $statusMap[$rawStatus] ?? $rawStatus;
// 只更新status字段,不影响其他字段
$listDb = getVpsListDB(); $listDb = getVpsListDB();
// 先检查记录是否存在 // 先获取该VPS的IP地址,用于精确匹配
$existing = $listDb->queryOne( $vpsInfo = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?', 'SELECT id, ip_address FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId] [$configId, $vpsId]
); );
if ($existing) { if ($vpsInfo) {
// 记录存在,执行UPDATE // 记录存在,执行UPDATE
$listDb->execute( $success = $listDb->execute(
'UPDATE vps_list SET status = ?, last_check = CURRENT_TIMESTAMP WHERE config_id = ? AND vps_id = ?', 'UPDATE vps_list SET status = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[$status, $configId, $vpsId] [$status, $vpsInfo['id']]
); );
error_log("[mofangGetVpsStatus] VPS {$vpsId} 状态已更新为: {$status}"); if ($success) {
Logger::info("[mofangGetVpsStatus] VPS {$vpsId} (IP: {$vpsInfo['ip_address']}) 状态已更新为: {$status}", 'mofangGetVpsStatus');
} else {
Logger::error("[mofangGetVpsStatus] VPS {$vpsId} 状态更新失败", 'mofangGetVpsStatus');
}
} else { } else {
// 记录不存在,插入新记录 // 记录不存在,插入新记录
$listDb->execute( $success = $listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, status, last_check) VALUES (?, ?, ?, CURRENT_TIMESTAMP)', 'INSERT INTO vps_list (config_id, vps_id, status, last_check) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
[$configId, $vpsId, $status] [$configId, $vpsId, $status]
); );
error_log("[mofangGetVpsStatus] VPS {$vpsId} 新记录已插入,状态: {$status}"); if ($success) {
Logger::info("[mofangGetVpsStatus] VPS {$vpsId} 新记录已插入,状态: {$status}", 'mofangGetVpsStatus');
} else {
Logger::error("[mofangGetVpsStatus] VPS {$vpsId} 新记录插入失败", 'mofangGetVpsStatus');
} }
} }
} elseif ($updateDb && (!$result || !isset($result['status']) || $result['status'] !== 200)) {
// API调用失败,不更新数据库,保留原有状态
Logger::warning("[mofangGetVpsStatus] VPS {$vpsId} API调用失败,保留原有状态", 'mofangGetVpsStatus');
}
return $result; return $result;
} }
/** /**
* 获取VPS详细信息 * 获取VPS详细信息
* @param int $configId 配置ID
* @param int $vpsId VPS ID
* @param bool $updateDb 是否更新数据库,默认true
* @return array|null 详细信息或null
*/ */
function mofangGetVpsDetails($configId, $vpsId, $updateDb = true) { function mofangGetVpsDetails($configId, $vpsId, $updateDb = true) {
$db = getVpsDB(); $db = getVpsDB();
@@ -328,6 +320,28 @@ function mofangGetVpsDetails($configId, $vpsId, $updateDb = true) {
$updates = []; // 存储要更新的字段 $updates = []; // 存储要更新的字段
$values = []; $values = [];
// 提取开关机状态(如果有)
if (isset($host['status'])) {
$rawStatus = $host['status'];
// 状态映射:将魔方平台的原始状态转换为标准状态
$statusMap = [
'on' => 'on', // 开机
'off' => 'off', // 关机
'running' => 'on', // 运行中
'stopped' => 'off', // 已停止
'process' => 'process', // 处理中(开机/关机/重启过程中)
'pending' => 'process', // 等待中
'installing' => 'process', // 安装中
'rebooting' => 'process', // 重启中
'unknown' => 'unknown' // 未知
];
$status = $statusMap[$rawStatus] ?? $rawStatus;
$updates[] = 'status = ?';
$values[] = $status;
}
if (isset($host['config_option']) && is_array($host['config_option'])) { if (isset($host['config_option']) && is_array($host['config_option'])) {
foreach ($host['config_option'] as $option) { foreach ($host['config_option'] as $option) {
switch ($option['key']) { switch ($option['key']) {
@@ -392,7 +406,7 @@ function mofangGetVpsDetails($configId, $vpsId, $updateDb = true) {
"UPDATE vps_list SET {$setClause} WHERE config_id = ? AND vps_id = ?", "UPDATE vps_list SET {$setClause} WHERE config_id = ? AND vps_id = ?",
$values $values
); );
error_log("[mofangGetVpsDetails] VPS {$vpsId} 详细信息已更新"); Logger::info("[mofangGetVpsDetails] VPS {$vpsId} 详细信息已更新" . (isset($status) ? ",状态: {$status}" : ""), 'mofangGetVpsDetails');
} else { } else {
// 记录不存在,插入新记录(只插入获取到的字段) // 记录不存在,插入新记录(只插入获取到的字段)
$columns = []; $columns = [];
@@ -422,7 +436,7 @@ function mofangGetVpsDetails($configId, $vpsId, $updateDb = true) {
"INSERT INTO vps_list ({$columnStr}) VALUES ({$placeholderStr})", "INSERT INTO vps_list ({$columnStr}) VALUES ({$placeholderStr})",
$insertValues $insertValues
); );
error_log("[mofangGetVpsDetails] VPS {$vpsId} 新记录已插入"); Logger::info("[mofangGetVpsDetails] VPS {$vpsId} 新记录已插入", 'mofangGetVpsDetails');
} }
} }
} }
@@ -433,9 +447,6 @@ function mofangGetVpsDetails($configId, $vpsId, $updateDb = true) {
/** /**
* VPS开机 * VPS开机
* @param int $configId 配置ID
* @param int $vpsId VPS ID
* @return array|null 响应数据或null
*/ */
function mofangPowerOn($configId, $vpsId) { function mofangPowerOn($configId, $vpsId) {
$db = getVpsDB(); $db = getVpsDB();
@@ -446,14 +457,19 @@ function mofangPowerOn($configId, $vpsId) {
} }
$endpoint = "/v1/hosts/{$vpsId}/module/on"; $endpoint = "/v1/hosts/{$vpsId}/module/on";
return mofangApiRequest($config['site_url'], $endpoint, 'PUT', [], $configId); $result = mofangApiRequest($config['site_url'], $endpoint, 'PUT', [], $configId);
// 开机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2); // 等待2秒让状态生效
mofangGetVpsStatus($configId, $vpsId, true);
}
return $result;
} }
/** /**
* VPS关机 * VPS关机
* @param int $configId 配置ID
* @param int $vpsId VPS ID
* @return array|null 响应数据或null
*/ */
function mofangPowerOff($configId, $vpsId) { function mofangPowerOff($configId, $vpsId) {
$db = getVpsDB(); $db = getVpsDB();
@@ -464,14 +480,19 @@ function mofangPowerOff($configId, $vpsId) {
} }
$endpoint = "/v1/hosts/{$vpsId}/module/off"; $endpoint = "/v1/hosts/{$vpsId}/module/off";
return mofangApiRequest($config['site_url'], $endpoint, 'PUT', [], $configId); $result = mofangApiRequest($config['site_url'], $endpoint, 'PUT', [], $configId);
// 关机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2); // 等待2秒让状态生效
mofangGetVpsStatus($configId, $vpsId, true);
}
return $result;
} }
/** /**
* VPS硬重启 * VPS硬重启
* @param int $configId 配置ID
* @param int $vpsId VPS ID
* @return array|null 响应数据或null
*/ */
function mofangHardReboot($configId, $vpsId) { function mofangHardReboot($configId, $vpsId) {
$db = getVpsDB(); $db = getVpsDB();
@@ -482,13 +503,19 @@ function mofangHardReboot($configId, $vpsId) {
} }
$endpoint = "/v1/hosts/{$vpsId}/module/hard_reboot"; $endpoint = "/v1/hosts/{$vpsId}/module/hard_reboot";
return mofangApiRequest($config['site_url'], $endpoint, 'PUT', [], $configId); $result = mofangApiRequest($config['site_url'], $endpoint, 'PUT', [], $configId);
// 硬重启操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(3); // 等待3秒让重启生效
mofangGetVpsStatus($configId, $vpsId, true);
}
return $result;
} }
/** /**
* 刷新指定配置的VPS列表并保存到数据库 * 刷新指定配置的VPS列表并保存到数据库
* @param int $configId 配置ID
* @return bool 是否成功
*/ */
function refreshVpsListForConfig($configId) { function refreshVpsListForConfig($configId) {
$db = getVpsDB(); $db = getVpsDB();
@@ -502,7 +529,7 @@ function refreshVpsListForConfig($configId) {
$result = mofangGetVpsList($configId); $result = mofangGetVpsList($configId);
if (!$result || !isset($result['status']) || $result['status'] !== 200) { if (!$result || !isset($result['status']) || $result['status'] !== 200) {
error_log("获取VPS列表失败: " . ($result['msg'] ?? '未知错误')); Logger::error("获取VPS列表失败: " . ($result['msg'] ?? '未知错误'), 'refreshVpsListForConfig');
return false; return false;
} }
@@ -559,17 +586,34 @@ function refreshVpsListForConfig($configId) {
} }
} }
// 使用INSERT OR REPLACE防止重复数据 // 基于vps_id和ip_address去重
// 注意:需要保留原有的status字段,避免被覆盖为NULL
$existing = $listDb->queryOne( $existing = $listDb->queryOne(
'SELECT status FROM vps_list WHERE config_id = ? AND vps_id = ?', 'SELECT id, status FROM vps_list WHERE vps_id = ? AND ip_address = ?',
[$configId, $host['id']] [$host['id'], $host['dedicatedip'] ?? null]
); );
$currentStatus = $existing ? $existing['status'] : null; if ($existing) {
// 记录已存在,只更新非status字段,保留原有status
$listDb->execute( $listDb->execute(
'INSERT OR REPLACE INTO vps_list (config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, status, section, last_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)', 'UPDATE vps_list SET domain = ?, product_name = ?, cpu_cores = ?, memory_size = ?, disk_size = ?, bandwidth = ?, os_type = ?, amount = ?, nextduedate = ?, section = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[
$host['domain'] ?? null,
$host['product_name'] ?? null,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$host['amount'] ?? null,
$host['nextduedate'] ?? null,
$config['auto_monitor'] ? 1 : 0,
$existing['id']
]
);
} else {
// 新记录,插入所有字段(status设为null,稍后通过状态接口获取)
$listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, amount, nextduedate, status, section, last_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, CURRENT_TIMESTAMP)',
[ [
$configId, $configId,
$host['id'], $host['id'],
@@ -581,18 +625,32 @@ function refreshVpsListForConfig($configId) {
$diskSize, $diskSize,
$bandwidth, $bandwidth,
$osType, $osType,
$currentStatus, // 保留原有状态 $host['amount'] ?? null,
$host['nextduedate'] ?? null,
$config['auto_monitor'] ? 1 : 0 $config['auto_monitor'] ? 1 : 0
] ]
); );
} }
}
// 刷新列表后,批量获取每个VPS的状态
Logger::info("[refreshVpsListForConfig] 开始批量获取 {$configId} 配置下 " . count($hosts) . " 台VPS的状态", 'refreshVpsListForConfig');
foreach ($hosts as $host) {
// 调用专门的状态接口获取开关机状态
mofangGetVpsStatus($configId, $host['id'], true);
// 避免频繁请求,每次请求间隔0.5秒
usleep(500000); // 500毫秒
}
Logger::info("[refreshVpsListForConfig] 配置 {$configId} 的VPS列表和状态刷新完成", 'refreshVpsListForConfig');
return true; return true;
} }
/** /**
* 刷新所有配置的VPS列表 * 刷新所有配置的VPS列表
* @return int 成功刷新的配置数量
*/ */
function refreshAllVpsLists() { function refreshAllVpsLists() {
$db = getVpsDB(); $db = getVpsDB();
@@ -611,16 +669,13 @@ function refreshAllVpsLists() {
/** /**
* 获取单个VPS的状态并更新到数据库 * 获取单个VPS的状态并更新到数据库
* @param int $configId 配置ID
* @param int $vpsId VPS ID
* @return array|null 状态信息或null
*/ */
function updateVpsStatusToDb($configId, $vpsId) { function updateVpsStatusToDb($configId, $vpsId) {
$db = getVpsDB(); $db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]); $config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config) { if (!$config) {
error_log("配置ID {$configId} 不存在"); Logger::error("配置ID {$configId} 不存在", 'updateVpsStatusToDb');
return null; return null;
} }
@@ -628,35 +683,60 @@ function updateVpsStatusToDb($configId, $vpsId) {
$result = mofangGetVpsStatus($configId, $vpsId, false); $result = mofangGetVpsStatus($configId, $vpsId, false);
if (!$result || !isset($result['status']) || $result['status'] !== 200) { if (!$result || !isset($result['status']) || $result['status'] !== 200) {
error_log("获取VPS {$vpsId} 状态失败: " . ($result['msg'] ?? '未知错误')); Logger::error("获取VPS {$vpsId} 状态失败,保留原有状态: " . ($result['msg'] ?? '未知错误'), 'updateVpsStatusToDb');
return null; return null;
} }
$statusData = $result['data']; $statusData = $result['data'];
$status = $statusData['status'] ?? 'unknown'; $rawStatus = $statusData['status'] ?? 'unknown';
$des = $statusData['des'] ?? '未知'; $des = $statusData['des'] ?? '未知';
// 状态映射:将魔方平台的原始状态转换为标准状态
$statusMap = [
'on' => 'on', // 开机
'off' => 'off', // 关机
'running' => 'on', // 运行中
'stopped' => 'off', // 已停止
'process' => 'process', // 处理中(开机/关机/重启过程中)
'pending' => 'process', // 等待中
'installing' => 'process', // 安装中
'rebooting' => 'process', // 重启中
'unknown' => 'unknown' // 未知
];
$status = $statusMap[$rawStatus] ?? $rawStatus;
// 检查记录是否存在 // 检查记录是否存在
$listDb = getVpsListDB(); $listDb = getVpsListDB();
$existing = $listDb->queryOne( $vpsInfo = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?', 'SELECT id, ip_address FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId] [$configId, $vpsId]
); );
if ($existing) { if ($vpsInfo) {
// 记录存在,执行UPDATE // 记录存在,执行UPDATE
$listDb->execute( $success = $listDb->execute(
'UPDATE vps_list SET status = ?, last_check = CURRENT_TIMESTAMP WHERE config_id = ? AND vps_id = ?', 'UPDATE vps_list SET status = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[$status, $configId, $vpsId] [$status, $vpsInfo['id']]
); );
error_log("[updateVpsStatusToDb] VPS {$vpsId} 状态已更新为: {$status}"); if ($success) {
Logger::info("[updateVpsStatusToDb] VPS {$vpsId} (IP: {$vpsInfo['ip_address']}) 状态已更新为: {$status}", 'updateVpsStatusToDb');
} else {
Logger::error("[updateVpsStatusToDb] VPS {$vpsId} 状态更新失败,保留原有状态", 'updateVpsStatusToDb');
return null;
}
} else { } else {
// 记录不存在,插入新记录 // 记录不存在,插入新记录
$listDb->execute( $success = $listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, status, last_check) VALUES (?, ?, ?, CURRENT_TIMESTAMP)', 'INSERT INTO vps_list (config_id, vps_id, status, last_check) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
[$configId, $vpsId, $status] [$configId, $vpsId, $status]
); );
error_log("[updateVpsStatusToDb] VPS {$vpsId} 新记录已插入,状态: {$status}"); if ($success) {
Logger::info("[updateVpsStatusToDb] VPS {$vpsId} 新记录已插入,状态: {$status}", 'updateVpsStatusToDb');
} else {
Logger::error("[updateVpsStatusToDb] VPS {$vpsId} 新记录插入失败", 'updateVpsStatusToDb');
return null;
}
} }
return [ return [
@@ -669,9 +749,6 @@ function updateVpsStatusToDb($configId, $vpsId) {
/** /**
* 批量获取VPS状态并更新到数据库 * 批量获取VPS状态并更新到数据库
* @param int $configId 配置ID
* @param array $vpsIds VPS ID数组,为空则更新该配置下所有VPS
* @return array 更新结果统计
*/ */
function batchUpdateVpsStatus($configId, $vpsIds = []) { function batchUpdateVpsStatus($configId, $vpsIds = []) {
$db = getVpsDB(); $db = getVpsDB();
@@ -696,6 +773,10 @@ function batchUpdateVpsStatus($configId, $vpsIds = []) {
$failedCount = 0; $failedCount = 0;
$results = []; $results = [];
$listDb = getVpsListDB();
$listDb->getConnection()->beginTransaction();
try {
foreach ($vpsIds as $vpsId) { foreach ($vpsIds as $vpsId) {
$result = updateVpsStatusToDb($configId, $vpsId); $result = updateVpsStatusToDb($configId, $vpsId);
@@ -713,6 +794,14 @@ function batchUpdateVpsStatus($configId, $vpsIds = []) {
} }
} }
$listDb->getConnection()->commit();
Logger::info("[batchUpdateVpsStatus] 批量更新完成: 成功{$successCount}, 失败{$failedCount}", 'batchUpdateVpsStatus');
} catch (Exception $e) {
$listDb->getConnection()->rollBack();
Logger::error("[batchUpdateVpsStatus] 批量更新失败,已回滚: " . $e->getMessage(), 'batchUpdateVpsStatus');
return ['success' => 0, 'failed' => count($vpsIds), 'error' => '批量更新失败: ' . $e->getMessage()];
}
return [ return [
'success' => $successCount, 'success' => $successCount,
'failed' => $failedCount, 'failed' => $failedCount,
+837
View File
@@ -0,0 +1,837 @@
<?php
require_once __DIR__ . '/app/db_helper.php';
require_once __DIR__ . '/app/logger.php';
/**
* 腾讯云API适配器
* 支持CVM云服务器和轻量应用服务器(Lighthouse)
*/
/**
* 生成腾讯云API签名 (HMAC-SHA1)
*/
function generateTencentSignature($method, $host, $uri, $params, $secretKey) {
// 按参数名排序
ksort($params);
// 构建签名字符串
$signStr = $method . $host . $uri . '?';
$queryStr = '';
foreach ($params as $key => $value) {
if ($queryStr !== '') {
$queryStr .= '&';
}
$queryStr .= rawurlencode($key) . '=' . rawurlencode($value);
}
$signStr .= $queryStr;
// 计算HMAC-SHA1签名
$signature = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
return $signature;
}
/**
* 发送腾讯云API请求
* @param string $configId 配置ID
* @param string $service 服务类型: cvm 或 lighthouse
* @param string $action API动作
* @param array $params 请求参数
* @param string $region 区域(可选,默认使用配置中的区域)
* @return array|null
*/
function tencentApiRequest($configId, $service, $action, $params = [], $region = null) {
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config) {
Logger::error("配置ID {$configId} 不存在", 'tencentApiRequest');
return null;
}
$secretId = $config['account'];
$secretKey = $config['api_key'];
// 确定使用的区域
if (!$region) {
$region = 'ap-guangzhou';
}
// 确定API域名
$host = ($service === 'lighthouse') ? 'lighthouse.tencentcloudapi.com' : 'cvm.tencentcloudapi.com';
// 公共参数
$commonParams = [
'Action' => $action,
'Version' => ($service === 'lighthouse') ? '2020-03-24' : '2017-03-12',
'Region' => $region,
'SecretId' => $secretId,
'Timestamp' => time(),
'Nonce' => rand(10000, 99999),
];
// 合并参数
$allParams = array_merge($commonParams, $params);
// 生成签名
$signature = generateTencentSignature(
'GET',
$host,
'/',
$allParams,
$secretKey
);
$allParams['Signature'] = $signature;
// 构建URL
$url = 'https://' . $host . '/?' . http_build_query($allParams);
// 发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
Logger::error("cURL错误: {$curlError}", 'tencentApiRequest');
return ['status' => 0, 'error' => $curlError];
}
if ($httpCode !== 200) {
Logger::error("HTTP请求失败: {$httpCode}", 'tencentApiRequest');
return ['status' => $httpCode, 'error' => 'HTTP请求失败'];
}
$result = json_decode($response, true);
if (!$result) {
Logger::error("JSON解析失败", 'tencentApiRequest');
return ['status' => 500, 'error' => '响应解析失败'];
}
// 检查响应
if (isset($result['Response']['Error'])) {
$error = $result['Response']['Error'];
Logger::error("API错误: {$error['Code']} - {$error['Message']}", 'tencentApiRequest');
return ['status' => 400, 'error' => $error['Message'], 'code' => $error['Code']];
}
return ['status' => 200, 'data' => $result['Response'], 'service' => $service, 'region' => $region];
}
/**
* 获取所有可用区域列表
*/
function getTencentRegions($configId, $service) {
return [
'ap-beijing', // 北京
'ap-chengdu', // 成都
'ap-guangzhou', // 广州
'ap-hongkong', // 香港
'ap-nanjing', // 南京
'ap-shanghai', // 上海
'ap-singapore', // 新加坡
'ap-tokyo', // 东京
'eu-frankfurt', // 法兰克福
'na-siliconvalley', // 硅谷
'na-toronto', // 多伦多
];
}
/**
* 获取CVM实例列表(单个区域)
*/
function tencentGetCvmList($configId, $region, $offset = 0, $limit = 100) {
$params = [
'Offset' => $offset,
'Limit' => $limit,
];
return tencentApiRequest($configId, 'cvm', 'DescribeInstances', $params, $region);
}
/**
* 获取轻量应用服务器列表(单个区域)
*/
function tencentGetLighthouseList($configId, $region, $offset = 0, $limit = 100) {
$params = [
'Offset' => $offset,
'Limit' => $limit,
];
return tencentApiRequest($configId, 'lighthouse', 'DescribeInstances', $params, $region);
}
/**
* 获取CVM实例详细信息
*/
function tencentGetCvmDetails($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'cvm', 'DescribeInstances', $params, $region);
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['InstanceSet'] ?? [];
if (!empty($instances)) {
updateCvmToDatabase($configId, $instances[0], 'cvm');
}
}
return $result;
}
/**
* 获取轻量应用服务器详细信息
*/
function tencentGetLighthouseDetails($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'lighthouse', 'DescribeInstances', $params, $region);
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['InstanceSet'] ?? [];
if (!empty($instances)) {
updateCvmToDatabase($configId, $instances[0], 'lighthouse');
}
}
return $result;
}
/**
* 获取CVM实例状态
*/
function tencentGetCvmStatus($configId, $instanceId, $region = null, $updateDb = true) {
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'cvm', 'DescribeInstancesStatus', $params, $region);
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$statusSet = $result['data']['InstanceStatusSet'] ?? [];
if (!empty($statusSet)) {
$statusInfo = $statusSet[0];
$rawStatus = $statusInfo['InstanceState'] ?? 'UNKNOWN';
// 状态映射
$statusMap = [
'PENDING' => 'process',
'LAUNCHING' => 'process',
'RUNNING' => 'on',
'STOPPING' => 'process',
'STOPPED' => 'off',
'REBOOTING' => 'process',
'SHUTDOWN' => 'off',
'TERMINATING' => 'process',
'UNKNOWN' => 'unknown'
];
$status = $statusMap[$rawStatus] ?? 'unknown';
updateVpsStatusInDatabase($configId, $instanceId, $status);
}
}
return $result;
}
/**
* 获取轻量应用服务器状态
* 注意:轻量服务器没有独立的DescribeInstancesStatus接口,需要使用DescribeInstances
*/
function tencentGetLighthouseStatus($configId, $instanceId, $region = null, $updateDb = true) {
// 轻量服务器使用DescribeInstances接口获取状态
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'lighthouse', 'DescribeInstances', $params, $region);
// 如果获取成功且需要更新数据库
if ($updateDb && $result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['InstanceSet'] ?? [];
if (!empty($instances)) {
$instanceInfo = $instances[0];
$rawStatus = $instanceInfo['InstanceState'] ?? 'UNKNOWN';
// 状态映射(轻量服务器状态与CVM类似)
$statusMap = [
'PENDING' => 'process',
'LAUNCHING' => 'process',
'RUNNING' => 'on',
'STOPPING' => 'process',
'STOPPED' => 'off',
'REBOOTING' => 'process',
'SHUTDOWN' => 'off',
'TERMINATING' => 'process',
'UNKNOWN' => 'unknown'
];
$status = $statusMap[$rawStatus] ?? 'unknown';
updateVpsStatusInDatabase($configId, $instanceId, $status);
}
}
return $result;
}
/**
* 启动CVM实例
*/
function tencentPowerOn($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[tencentPowerOn] 无法从数据库获取 region", 'tencentPowerOn');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'cvm', 'StartInstances', $params, $region);
// 开机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
tencentGetCvmStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 启动轻量应用服务器
*/
function tencentLighthousePowerOn($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[tencentLighthousePowerOn] 无法从数据库获取 region", 'tencentLighthousePowerOn');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'lighthouse', 'StartInstances', $params, $region);
// 开机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
tencentGetLighthouseStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 停止CVM实例
*/
function tencentPowerOff($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[tencentPowerOff] 无法从数据库获取 region", 'tencentPowerOff');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'cvm', 'StopInstances', $params, $region);
// 关机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
tencentGetCvmStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 停止轻量应用服务器
*/
function tencentLighthousePowerOff($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[tencentLighthousePowerOff] 无法从数据库获取 region", 'tencentLighthousePowerOff');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'lighthouse', 'StopInstances', $params, $region);
// 关机操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(2);
tencentGetLighthouseStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 重启CVM实例
*/
function tencentReboot($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[tencentReboot] 无法从数据库获取 region", 'tencentReboot');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'cvm', 'RebootInstances', $params, $region);
// 重启操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(3);
tencentGetCvmStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 重启轻量应用服务器
*/
function tencentLighthouseReboot($configId, $instanceId, $region = null) {
// 如果未提供region,从数据库获取
if (!$region) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT domain FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $instanceId]
);
if ($vpsInfo && !empty($vpsInfo['domain'])) {
$region = $vpsInfo['domain'];
} else {
Logger::error("[tencentLighthouseReboot] 无法从数据库获取 region", 'tencentLighthouseReboot');
return ['status' => 400, 'error' => '无法获取实例区域信息'];
}
}
$params = [
'InstanceIds.0' => $instanceId,
];
$result = tencentApiRequest($configId, 'lighthouse', 'RebootInstances', $params, $region);
// 重启操作后立即获取状态并更新数据库
if ($result && isset($result['status']) && $result['status'] === 200) {
sleep(3);
tencentGetLighthouseStatus($configId, $instanceId, $region, true);
}
return $result;
}
/**
* 将CVM/轻量服务器信息更新到数据库
*/
function updateCvmToDatabase($configId, $instance, $serviceType) {
$listDb = getVpsListDB();
$vpsId = $instance['InstanceId'];
$region = $instance['Placement']['Zone'] ?? '';
// 提取CPU和内存信息
$cpuCores = $instance['CPU'] ?? null;
// 注意:腾讯云API返回的Memory单位已经是GB,不需要转换
$memorySize = isset($instance['Memory']) ? $instance['Memory'] . 'G' : null;
// 提取系统盘信息
$diskSize = null;
if (isset($instance['SystemDisk']) && isset($instance['SystemDisk']['DiskSize'])) {
$diskSize = $instance['SystemDisk']['DiskSize'] . 'G';
}
// 提取带宽信息
$bandwidth = null;
// CVM和轻量服务器都使用InternetAccessible.InternetMaxBandwidthOut
if (isset($instance['InternetAccessible']) && isset($instance['InternetAccessible']['InternetMaxBandwidthOut'])) {
$bandwidth = $instance['InternetAccessible']['InternetMaxBandwidthOut'] . 'Mbps';
}
// 提取操作系统信息
$osType = $instance['OsName'] ?? ($instance['Platform'] ?? null);
// 提取IP地址
$ipAddress = null;
if ($serviceType === 'cvm') {
if (isset($instance['PublicIpAddresses']) && !empty($instance['PublicIpAddresses'])) {
$ipAddress = $instance['PublicIpAddresses'][0];
}
} else {
// 轻量服务器的公网IP
if (isset($instance['PublicAddresses']) && !empty($instance['PublicAddresses'])) {
$ipAddress = $instance['PublicAddresses'][0];
}
}
// 提取实例名称
$productName = $instance['InstanceName'] ?? null;
// 提取到期时间
$nextduedate = null;
if (isset($instance['ExpiredTime'])) {
$nextduedate = strtotime($instance['ExpiredTime']);
}
// 检查记录是否存在
$existing = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId]
);
if ($existing) {
// 更新现有记录
$listDb->execute(
'UPDATE vps_list SET domain = ?, ip_address = ?, product_name = ?, cpu_cores = ?, memory_size = ?, disk_size = ?, bandwidth = ?, os_type = ?, nextduedate = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[
$region,
$ipAddress,
$productName,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$nextduedate,
$existing['id']
]
);
Logger::info("[updateCvmToDatabase] {$serviceType} {$vpsId} 详细信息已更新", 'updateCvmToDatabase');
} else {
// 插入新记录
$listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, domain, ip_address, product_name, cpu_cores, memory_size, disk_size, bandwidth, os_type, status, nextduedate, last_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, CURRENT_TIMESTAMP)',
[
$configId,
$vpsId,
$region,
$ipAddress,
$productName,
$cpuCores,
$memorySize,
$diskSize,
$bandwidth,
$osType,
$nextduedate
]
);
Logger::info("[updateCvmToDatabase] {$serviceType} {$vpsId} 新记录已插入", 'updateCvmToDatabase');
}
}
/**
* 更新VPS状态到数据库
*/
function updateVpsStatusInDatabase($configId, $vpsId, $status) {
$listDb = getVpsListDB();
$vpsInfo = $listDb->queryOne(
'SELECT id FROM vps_list WHERE config_id = ? AND vps_id = ?',
[$configId, $vpsId]
);
if ($vpsInfo) {
$listDb->execute(
'UPDATE vps_list SET status = ?, last_check = CURRENT_TIMESTAMP WHERE id = ?',
[$status, $vpsInfo['id']]
);
Logger::info("[updateVpsStatusInDatabase] VPS {$vpsId} 状态已更新为: {$status}", 'updateVpsStatusInDatabase');
} else {
$listDb->execute(
'INSERT INTO vps_list (config_id, vps_id, status, last_check) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
[$configId, $vpsId, $status]
);
Logger::info("[updateVpsStatusInDatabase] VPS {$vpsId} 新记录已插入,状态: {$status}", 'updateVpsStatusInDatabase');
}
}
/**
* 刷新指定配置的CVM列表(遍历所有区域)
*/
function refreshTencentCvmListForConfig($configId) {
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config || $config['site_type'] !== 'tencent') {
return false;
}
// 先获取区域列表
$regions = getTencentRegions($configId, 'cvm');
$totalInstances = 0;
Logger::info("[refreshTencentCvmListForConfig] 开始遍历所有区域获取CVM列表", 'refreshTencentCvmListForConfig');
foreach ($regions as $region) {
try {
$result = tencentGetCvmList($configId, $region);
if ($result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['InstanceSet'] ?? [];
if (!empty($instances)) {
Logger::info("[refreshTencentCvmListForConfig] 区域 {$region} 找到 " . count($instances) . " 台CVM", 'refreshTencentCvmListForConfig');
foreach ($instances as $instance) {
updateCvmToDatabase($configId, $instance, 'cvm');
// 获取状态
tencentGetCvmStatus($configId, $instance['InstanceId'], $region, true);
$totalInstances++;
// 避免频繁请求
usleep(300000); // 300毫秒
}
}
} else {
Logger::warning("[refreshTencentCvmListForConfig] 区域 {$region} 获取失败: " . ($result['msg'] ?? '未知错误'), 'refreshTencentCvmListForConfig');
}
} catch (Exception $e) {
Logger::error("[refreshTencentCvmListForConfig] 区域 {$region} 异常: " . $e->getMessage(), 'refreshTencentCvmListForConfig');
}
// 区域之间稍作延迟
usleep(500000); // 500毫秒
}
Logger::info("[refreshTencentCvmListForConfig] CVM列表刷新完成,共获取 {$totalInstances} 台实例", 'refreshTencentCvmListForConfig');
return true;
}
/**
* 刷新指定配置的轻量应用服务器列表(遍历所有区域)
*/
function refreshTencentLighthouseListForConfig($configId) {
$db = getVpsDB();
$config = $db->queryOne('SELECT * FROM configs WHERE id = ?', [$configId]);
if (!$config || $config['site_type'] !== 'tencent') {
return false;
}
// 先获取区域列表
$regions = getTencentRegions($configId, 'lighthouse');
$totalInstances = 0;
Logger::info("[refreshTencentLighthouseListForConfig] 开始遍历所有区域获取轻量应用服务器列表", 'refreshTencentLighthouseListForConfig');
foreach ($regions as $region) {
try {
$result = tencentGetLighthouseList($configId, $region);
if ($result && isset($result['status']) && $result['status'] === 200) {
$instances = $result['data']['InstanceSet'] ?? [];
if (!empty($instances)) {
Logger::info("[refreshTencentLighthouseListForConfig] 区域 {$region} 找到 " . count($instances) . " 台轻量服务器", 'refreshTencentLighthouseListForConfig');
foreach ($instances as $instance) {
updateCvmToDatabase($configId, $instance, 'lighthouse');
// 获取状态
tencentGetLighthouseStatus($configId, $instance['InstanceId'], $region, true);
$totalInstances++;
// 避免频繁请求
usleep(300000); // 300毫秒
}
}
} else {
Logger::warning("[refreshTencentLighthouseListForConfig] 区域 {$region} 获取失败: " . ($result['msg'] ?? '未知错误'), 'refreshTencentLighthouseListForConfig');
}
} catch (Exception $e) {
Logger::error("[refreshTencentLighthouseListForConfig] 区域 {$region} 异常: " . $e->getMessage(), 'refreshTencentLighthouseListForConfig');
}
// 区域之间稍作延迟
usleep(500000); // 500毫秒
}
Logger::info("[refreshTencentLighthouseListForConfig] 轻量应用服务器列表刷新完成,共获取 {$totalInstances} 台实例", 'refreshTencentLighthouseListForConfig');
return true;
}
/**
* 刷新所有腾讯云配置的实例列表(CVM + 轻量)
*/
function refreshAllTencentVpsLists() {
$db = getVpsDB();
$configs = $db->query('SELECT * FROM configs WHERE site_type = ?', ['tencent']);
$successCount = 0;
foreach ($configs as $config) {
// 刷新CVM列表
if (refreshTencentCvmListForConfig($config['id'])) {
$successCount++;
}
// 刷新轻量应用服务器列表
if (refreshTencentLighthouseListForConfig($config['id'])) {
$successCount++;
}
}
return $successCount;
}
/**
* 根据实例ID判断是CVM还是轻量服务器,并执行相应操作
*/
function tencentGetInstanceType($instanceId) {
// CVM实例ID格式: ins-xxxxxxxx
// 轻量服务器实例ID格式: lhins-xxxxxxxx
if (strpos($instanceId, 'lhins-') === 0) {
return 'lighthouse';
}
return 'cvm';
}
/**
* 智能开机(自动识别实例类型)
*/
function tencentSmartPowerOn($configId, $instanceId, $region = null) {
$type = tencentGetInstanceType($instanceId);
if ($type === 'lighthouse') {
return tencentLighthousePowerOn($configId, $instanceId, $region);
} else {
return tencentPowerOn($configId, $instanceId, $region);
}
}
/**
* 智能关机(自动识别实例类型)
*/
function tencentSmartPowerOff($configId, $instanceId, $region = null) {
$type = tencentGetInstanceType($instanceId);
if ($type === 'lighthouse') {
return tencentLighthousePowerOff($configId, $instanceId, $region);
} else {
return tencentPowerOff($configId, $instanceId, $region);
}
}
/**
* 智能重启(自动识别实例类型)
*/
function tencentSmartReboot($configId, $instanceId, $region = null) {
$type = tencentGetInstanceType($instanceId);
if ($type === 'lighthouse') {
return tencentLighthouseReboot($configId, $instanceId, $region);
} else {
return tencentReboot($configId, $instanceId, $region);
}
}
/**
* 智能获取状态(自动识别实例类型)
*/
function tencentSmartGetStatus($configId, $instanceId, $region = null, $updateDb = true) {
$type = tencentGetInstanceType($instanceId);
if ($type === 'lighthouse') {
return tencentGetLighthouseStatus($configId, $instanceId, $region, $updateDb);
} else {
return tencentGetCvmStatus($configId, $instanceId, $region, $updateDb);
}
}
/**
* 智能获取详情(自动识别实例类型)
*/
function tencentSmartGetDetails($configId, $instanceId, $region = null, $updateDb = true) {
$type = tencentGetInstanceType($instanceId);
if ($type === 'lighthouse') {
return tencentGetLighthouseDetails($configId, $instanceId, $region, $updateDb);
} else {
return tencentGetCvmDetails($configId, $instanceId, $region, $updateDb);
}
}
?>
+313
View File
@@ -0,0 +1,313 @@
<?php
require_once __DIR__ . '/app/logger.php';
require_once __DIR__ . '/app/auth.php';
// 加载API_PASS(未设置则跳转到配置页)
if (!file_exists(__DIR__ . '/app/pass.php')) {
header('Location: config_add.php');
exit;
}
include __DIR__ . '/app/pass.php';
// 统一会话认证:前端输入密码验证后建立会话,30分钟滑动过期
requireAuth();
// 处理操作
$action = $_GET['action'] ?? '';
if ($action === 'clear' && $_SERVER['REQUEST_METHOD'] === 'POST') {
Logger::clear();
header('Location: view_log.php?cleared=1');
exit;
}
// 读取日志文件
$logFile = Logger::getLogFile();
$logContent = '';
$logLines = [];
if (file_exists($logFile)) {
$logContent = file_get_contents($logFile);
$logLines = array_filter(explode("\n", trim($logContent)));
// 反转数组,最新的在前面
$logLines = array_reverse($logLines);
}
// 过滤级别
$filterLevel = $_GET['level'] ?? 'ALL';
$filteredLines = $logLines;
if ($filterLevel !== 'ALL') {
$filteredLines = array_filter($logLines, function($line) use ($filterLevel) {
return strpos($line, "[{$filterLevel}]") !== false;
});
}
// 搜索关键词
$search = $_GET['search'] ?? '';
if ($search) {
$filteredLines = array_filter($filteredLines, function($line) use ($search) {
return stripos($line, $search) !== false;
});
}
// 限制显示行数
$limit = intval($_GET['limit'] ?? 100);
$filteredLines = array_slice($filteredLines, 0, $limit);
$cleared = isset($_GET['cleared']);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VPSHUB - 日志查看器</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f0f2f5;
padding: 20px;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px 30px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
font-size: 24px;
}
.controls {
padding: 20px 30px;
background: #f8f9fa;
border-bottom: 1px solid #e9ecef;
display: flex;
gap: 15px;
flex-wrap: wrap;
align-items: center;
}
.controls select,
.controls input,
.controls button {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.controls input {
flex: 1;
min-width: 200px;
}
.controls button {
background: #007bff;
color: white;
border: none;
cursor: pointer;
transition: background 0.2s;
}
.controls button:hover {
background: #0056b3;
}
.controls button.danger {
background: #dc3545;
}
.controls button.danger:hover {
background: #c82333;
}
.stats {
padding: 15px 30px;
background: #fff3cd;
border-bottom: 1px solid #ffc107;
display: flex;
gap: 20px;
font-size: 14px;
}
.stat-item {
display: flex;
align-items: center;
gap: 5px;
}
.log-container {
padding: 20px 30px;
max-height: 70vh;
overflow-y: auto;
}
.log-line {
padding: 8px 12px;
margin-bottom: 4px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 13px;
line-height: 1.5;
word-break: break-all;
}
.log-line.INFO {
background: #d1ecf1;
border-left: 3px solid #17a2b8;
}
.log-line.WARNING {
background: #fff3cd;
border-left: 3px solid #ffc107;
}
.log-line.ERROR {
background: #f8d7da;
border-left: 3px solid #dc3545;
}
.log-line.DEBUG {
background: #e2e3e5;
border-left: 3px solid #6c757d;
}
.timestamp {
color: #6c757d;
font-weight: bold;
}
.level {
display: inline-block;
padding: 2px 8px;
border-radius: 3px;
font-size: 11px;
font-weight: bold;
margin: 0 8px;
}
.level.INFO { background: #17a2b8; color: white; }
.level.WARNING { background: #ffc107; color: black; }
.level.ERROR { background: #dc3545; color: white; }
.level.DEBUG { background: #6c757d; color: white; }
.source {
color: #495057;
font-style: italic;
}
.message {
color: #212529;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #6c757d;
}
.empty-state svg {
width: 80px;
height: 80px;
margin-bottom: 20px;
opacity: 0.3;
}
.alert {
padding: 12px 20px;
margin: 20px 30px 0;
border-radius: 4px;
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>📋 VPSHUB 日志查看器</h1>
<div>
<span style="font-size: 14px; opacity: 0.9;">
<?php echo date('Y-m-d H:i:s'); ?>
</span>
</div>
</div>
<?php if ($cleared): ?>
<div class="alert">✅ 日志已清空</div>
<?php endif; ?>
<div class="controls">
<select name="level" onchange="window.location.href='view_log.php?level=' + this.value + '&search=<?php echo urlencode($search); ?>&limit=<?php echo $limit; ?>'">
<option value="ALL" <?php echo $filterLevel === 'ALL' ? 'selected' : ''; ?>>全部级别</option>
<option value="INFO" <?php echo $filterLevel === 'INFO' ? 'selected' : ''; ?>>INFO</option>
<option value="WARNING" <?php echo $filterLevel === 'WARNING' ? 'selected' : ''; ?>>WARNING</option>
<option value="ERROR" <?php echo $filterLevel === 'ERROR' ? 'selected' : ''; ?>>ERROR</option>
<option value="DEBUG" <?php echo $filterLevel === 'DEBUG' ? 'selected' : ''; ?>>DEBUG</option>
</select>
<form method="GET" style="flex: 1; display: flex; gap: 10px;">
<input type="hidden" name="level" value="<?php echo htmlspecialchars($filterLevel); ?>">
<input type="text" name="search" placeholder="搜索日志..." value="<?php echo htmlspecialchars($search); ?>">
<button type="submit">🔍 搜索</button>
</form>
<select onchange="window.location.href='view_log.php?level=<?php echo urlencode($filterLevel); ?>&search=<?php echo urlencode($search); ?>&limit=' + this.value">
<option value="50" <?php echo $limit === 50 ? 'selected' : ''; ?>>50行</option>
<option value="100" <?php echo $limit === 100 ? 'selected' : ''; ?>>100行</option>
<option value="200" <?php echo $limit === 200 ? 'selected' : ''; ?>>200行</option>
<option value="500" <?php echo $limit === 500 ? 'selected' : ''; ?>>500行</option>
<option value="1000" <?php echo $limit === 1000 ? 'selected' : ''; ?>>1000行</option>
</select>
<form method="POST" action="view_log.php?action=clear" onsubmit="return confirm('确定要清空所有日志吗?此操作不可恢复!');">
<button type="submit" class="danger">🗑️ 清空日志</button>
</form>
<button onclick="location.reload()">🔄 刷新</button>
</div>
<div class="stats">
<div class="stat-item">
<strong>总行数:</strong> <?php echo count($logLines); ?>
</div>
<div class="stat-item">
<strong>显示:</strong> <?php echo count($filteredLines); ?>
</div>
<div class="stat-item">
<strong>文件大小:</strong> <?php echo number_format(filesize($logFile) / 1024, 2); ?> KB
</div>
</div>
<div class="log-container">
<?php if (empty($filteredLines)): ?>
<div class="empty-state">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/>
</svg>
<h3>暂无日志记录</h3>
<p>当系统运行时,日志将显示在这里</p>
</div>
<?php else: ?>
<?php foreach ($filteredLines as $line): ?>
<?php
// 解析日志行
preg_match('/\[(.*?)\] \[(.*?)\] \[(.*?)\] (.*)/', $line, $matches);
if ($matches) {
$timestamp = $matches[1];
$level = $matches[2];
$source = $matches[3];
$message = $matches[4];
} else {
$timestamp = '';
$level = 'INFO';
$source = '';
$message = $line;
}
?>
<div class="log-line <?php echo htmlspecialchars($level); ?>">
<?php if ($timestamp): ?>
<span class="timestamp">[<?php echo htmlspecialchars($timestamp); ?>]</span>
<?php endif; ?>
<span class="level <?php echo htmlspecialchars($level); ?>"><?php echo htmlspecialchars($level); ?></span>
<?php if ($source): ?>
<span class="source">[<?php echo htmlspecialchars($source); ?>]</span>
<?php endif; ?>
<span class="message"><?php echo htmlspecialchars($message); ?></span>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</body>
</html>
+2 -3
View File
@@ -6,7 +6,7 @@
初次访问该php页面时,用户需设置网页自定义访问密码:API_PASS(运行输入大小写字母以及数字,最低8位数) 初次访问该php页面时,用户需设置网页自定义访问密码:API_PASS(运行输入大小写字母以及数字,最低8位数)
存在API_PASS时,需跟参数?pass=API_PASS才允许访问 存在API_PASS时,访问需先在前端输入访问密码(POST方式验证),验证成功后建立PHP会话,会话有效期30分钟(滑动过期,用户请求新数据后自动续期)
用户点击添加配置按钮,新列出一列,分别是: 用户点击添加配置按钮,新列出一列,分别是:
旧数据也会读取并展示 旧数据也会读取并展示
@@ -25,7 +25,7 @@
#### 首页 index.php #### 首页 index.php
1. 查询是否存在API_PASS,若存在,则需跟参数?pass=API_PASS才能访问 1. 查询是否存在API_PASS,若存在,访问时需先输入访问密码(POST方式验证)建立PHP会话,会话有效期30分钟(滑动过期)
2. 若不存在,则跳转至config_add.php页 2. 若不存在,则跳转至config_add.php页
@@ -66,4 +66,3 @@
(获取到的认证token存储于./app/token.php中,记录为两小时) (获取到的认证token存储于./app/token.php中,记录为两小时)
3. 若section为True,且ping测试失败,调用API对该机器进行状态查询,若返回状态为关机,则尝试开机,隔60秒后再进行状态查询并再次尝试开机,60秒后查询还是为异常的话,则记录异常,进入下一个循环(多台机器关机时,依次进行状态查询和开机,然后间隔60秒再进行操作,不同的机器不需要间隔) 3. 若section为True,且ping测试失败,调用API对该机器进行状态查询,若返回状态为关机,则尝试开机,隔60秒后再进行状态查询并再次尝试开机,60秒后查询还是为异常的话,则记录异常,进入下一个循环(多台机器关机时,依次进行状态查询和开机,然后间隔60秒再进行操作,不同的机器不需要间隔)