Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cbe9339316 | |||
| 79d6dad684 | |||
| 55c7a9796c | |||
| f4a15a0d90 | |||
| c7742319b2 | |||
| 01c14ecba6 | |||
| 989e1b6645 | |||
| da5eea5193 | |||
| 4de86c458f | |||
| baf213e769 | |||
| 819a79e00d | |||
| 18bee369c1 | |||
| 2463715e32 | |||
| fbc539ea47 | |||
| 875cd4716b | |||
| 6194b6e364 | |||
| 30d6b2d9f7 | |||
| 2f94498df2 | |||
| c303fe6d17 | |||
| eedb2d7fb0 | |||
| bfc98d043b | |||
| 0a4cf5c0bd | |||
| 54a608c19d | |||
| 73bd6934f9 | |||
| a35595edcf | |||
| b605df613e | |||
| 3cc8f7df7f | |||
| 744246c0a8 | |||
| aed512cb09 | |||
| b6f48acc4c | |||
| d83a5e3473 | |||
| 18c9d75a05 | |||
| b80e4817ef | |||
| 0b052f2217 | |||
| 80386d35ba | |||
| a45e063fc2 | |||
| e71adf6830 |
@@ -6,7 +6,7 @@ on:
|
||||
- main
|
||||
- master
|
||||
tags:
|
||||
- "v*"
|
||||
- 'v*'
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -25,31 +25,39 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
cache-dependency-path: |
|
||||
frontend/package-lock.json
|
||||
docs/package-lock.json
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.22.x"
|
||||
go-version: '1.24.5'
|
||||
cache-dependency-path: backend/go.sum
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: npm ci --prefix frontend
|
||||
|
||||
- name: Install docs dependencies
|
||||
run: npm ci --prefix docs
|
||||
|
||||
- name: Build docs
|
||||
run: npm run build --prefix docs
|
||||
|
||||
- name: Set version from tag
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
echo "CLICD_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
|
||||
echo "CLICD_VERSION=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_ENV"
|
||||
else
|
||||
echo "CLICD_VERSION=dev" >> $GITHUB_ENV
|
||||
echo "CLICD_VERSION=dev" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
- name: Build CLICD
|
||||
run: bash build.sh
|
||||
|
||||
- name: Package
|
||||
shell: bash
|
||||
- name: Package CLICD
|
||||
run: |
|
||||
mkdir -p dist package/clicd-linux-amd64
|
||||
cp build/clicd package/clicd-linux-amd64/clicd
|
||||
@@ -57,7 +65,24 @@ jobs:
|
||||
chmod +x package/clicd-linux-amd64/clicd package/clicd-linux-amd64/install.sh
|
||||
tar -C package -czf dist/clicd-linux-amd64.tar.gz clicd-linux-amd64
|
||||
cp build/clicd dist/clicd-linux-amd64
|
||||
sha256sum dist/* > dist/SHA256SUMS
|
||||
|
||||
- name: Package Mofang module
|
||||
run: |
|
||||
if [ ! -f Mofang/clicd.php ]; then
|
||||
echo "Mofang module not present; skipping package."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! command -v zip >/dev/null 2>&1; then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y zip
|
||||
fi
|
||||
|
||||
cd Mofang
|
||||
zip -r ../dist/clicd-mofang.zip clicd.php handlers templates -x '*.DS_Store' -x '*/.DS_Store'
|
||||
|
||||
- name: Generate checksums
|
||||
run: sha256sum dist/* > dist/SHA256SUMS
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -69,7 +94,6 @@ jobs:
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
shell: bash
|
||||
run: |
|
||||
gh release create "$GITHUB_REF_NAME" dist/* --generate-notes || \
|
||||
gh release upload "$GITHUB_REF_NAME" dist/* --clobber
|
||||
|
||||
@@ -13,6 +13,7 @@ backend/internal/server/web/*
|
||||
|
||||
# Build artifacts
|
||||
/build/
|
||||
Mofang/*.zip
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
# CLICD 魔方财务对接模块
|
||||
|
||||
这是用于智简魔方 / IDCSMART 的 CLICD 服务器模块。模块通过 CLICD API 完成实例开通、删除、开关机、重启、重装、改密、资源变更、流量重置、NAT 端口映射管理、实例信息展示和 WebSSH 入口。
|
||||
|
||||
## 文件结构
|
||||
|
||||
```text
|
||||
clicd.php
|
||||
README.md
|
||||
handlers/
|
||||
webssh.php
|
||||
templates/
|
||||
info.html
|
||||
nat.html
|
||||
```
|
||||
|
||||
安装时请保持目录结构不变,将整个 `clicd` 目录放入魔方服务器模块目录:
|
||||
|
||||
```text
|
||||
public/plugins/servers/clicd/
|
||||
```
|
||||
|
||||
## 服务器配置
|
||||
|
||||
在魔方后台添加服务器时,模块名称选择 `clicd`。
|
||||
|
||||
CLICD 面板地址建议使用 HTTPS:
|
||||
|
||||
```text
|
||||
主机名 = https://0.0.0.0:8999
|
||||
```
|
||||
|
||||
也可以拆分填写:
|
||||
|
||||
```text
|
||||
IP地址 = 0.0.0.0
|
||||
端口 = 8999
|
||||
secure = 开启
|
||||
```
|
||||
|
||||
API Key 可以填写在以下任意一个字段中:
|
||||
|
||||
```text
|
||||
Hash
|
||||
密码
|
||||
```
|
||||
|
||||
模块请求 CLICD 时会同时携带:
|
||||
|
||||
```text
|
||||
X-API-Key: clicd_sk_xxxx
|
||||
Authorization: Bearer clicd_sk_xxxx
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
## 产品配置项
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `virtualization` | 虚拟化类型,`lxc` 或 `kvm` |
|
||||
| `template_id` | CLICD 模板 / 镜像 ID |
|
||||
| `vcpu` | CPU 核心数 |
|
||||
| `cpu_percent` | CPU 使用率限制,`0` 表示不额外限制 |
|
||||
| `ram_mb` | 内存,单位 MB |
|
||||
| `disk_gb` | 系统盘,单位 GB |
|
||||
| `network_bw_mbps` | 带宽,单位 Mbps |
|
||||
| `traffic_mode` | `total` 总流量,或 `in_out` 入 / 出分开 |
|
||||
| `monthly_traffic_gb` | 月流量 GB |
|
||||
| `traffic_in_gb` | 入站流量 GB,`in_out` 模式使用 |
|
||||
| `traffic_out_gb` | 出站流量 GB,`in_out` 模式使用 |
|
||||
| `io_speed_mbps` | 磁盘 IO 限制,`0` 表示不限制 |
|
||||
| `port_mapping_count` | 开通时分配的 NAT 端口数量,最小 2 |
|
||||
| `snapshot_limit` | 快照配额 |
|
||||
| `extra_ports` | 额外映射的容器端口,逗号分隔,例如 `80,443` |
|
||||
| `assign_ipv6` | 开通时是否自动分配 IPv6 |
|
||||
| `sync_expiry` | 是否同步魔方到期时间到 CLICD |
|
||||
|
||||
客户产品的 `domain` 会作为 CLICD 容器名称。模块会自动把不适合作为容器名的字符替换为 `-`。
|
||||
|
||||
## 开通后字段同步
|
||||
|
||||
开通、同步、重装、改密后,模块会从 CLICD 容器详情拉取最新信息并写回魔方主机表:
|
||||
|
||||
| 魔方字段 | 写入内容 |
|
||||
| --- | --- |
|
||||
| `dedicatedip` | NAT 外网 IP,优先使用 API 返回的公网字段,否则使用服务器 IP |
|
||||
| `username` | 固定写入 `root` |
|
||||
| `password` | CLICD 返回的 SSH 密码,兼容魔方 `cmf_encrypt()` |
|
||||
| `port` | CLICD 返回的 `ssh_port` |
|
||||
| `domainstatus` | CLICD 状态为 `running` 时写 `Active`,否则写 `Suspended` |
|
||||
|
||||
如果接口返回的密码是 `***` 这类脱敏值,模块不会覆盖魔方里已有密码。
|
||||
|
||||
## 客户区页面
|
||||
|
||||
模块提供两个客户区选项卡:
|
||||
|
||||
```text
|
||||
实例信息
|
||||
NAT转发
|
||||
```
|
||||
|
||||
客户区按钮提供:
|
||||
|
||||
```text
|
||||
WebSSH
|
||||
```
|
||||
|
||||
## 实例信息
|
||||
|
||||
实例信息页展示:
|
||||
|
||||
- 实例名称、运行状态、SSH 地址、IPv6
|
||||
- CPU、内存、负载、磁盘圆环状态
|
||||
- 月流量进度
|
||||
- CPU 使用率、内存使用、网络流量、磁盘 IO 图表
|
||||
- IPv4、SSH 端口、SSH 密码、资源配置、到期时间
|
||||
|
||||
图表数据通过客户区懒加载接口获取,不会强制刷新整个魔方页面。页面首次打开会加载一次数据,之后由用户选择是否自动刷新:
|
||||
|
||||
```text
|
||||
不刷新
|
||||
10 秒
|
||||
1 分钟
|
||||
5 分钟
|
||||
10 分钟
|
||||
```
|
||||
|
||||
也可以点击“立即刷新”手动刷新一次。当前 CLICD 用量接口返回的是实时值,不是历史数组;图表曲线由客户区前端持续采样生成。若需要打开页面立即显示历史曲线,需要 CLICD 额外提供历史指标接口。
|
||||
|
||||
流量显示支持智能单位,小流量会显示 B / KB / MB,大流量显示 GB,例如:
|
||||
|
||||
```text
|
||||
370.5 KB / 100 GB
|
||||
```
|
||||
|
||||
模块会优先调用:
|
||||
|
||||
```text
|
||||
GET /api/v1/containers/{name}/usage
|
||||
GET /api/v1/containers/{name}/traffic
|
||||
```
|
||||
|
||||
如果 `/api/v1/containers/{name}/usage` 不可用,模块会在容器详情存在 `uuid` 时尝试兼容:
|
||||
|
||||
```text
|
||||
GET /api/containers/{uuid}/usage
|
||||
```
|
||||
|
||||
已兼容的常见用量字段包括:
|
||||
|
||||
```text
|
||||
cpu_usage_pct
|
||||
memory_usage_bytes
|
||||
disk_usage_bytes
|
||||
network_rx_bps
|
||||
network_tx_bps
|
||||
disk_read_bps
|
||||
disk_write_bps
|
||||
rx_used_bytes
|
||||
tx_used_bytes
|
||||
total_used_bytes
|
||||
limit_gb
|
||||
used_pct
|
||||
```
|
||||
|
||||
## NAT 转发
|
||||
|
||||
NAT 转发是独立页面,支持:
|
||||
|
||||
- 查看端口映射
|
||||
- 获取随机可用端口
|
||||
- 添加端口映射
|
||||
- 修改端口映射
|
||||
- 删除端口映射
|
||||
|
||||
删除端口映射时使用页面内确认弹窗,不使用浏览器自带确认框。
|
||||
|
||||
使用的 CLICD API:
|
||||
|
||||
```text
|
||||
GET /api/v1/containers/{id|uuid|name}
|
||||
GET /api/v1/containers/{id}/random-port
|
||||
POST /api/v1/containers/{id}/port-mappings
|
||||
PUT /api/v1/containers/{id}/port-mappings/{index}
|
||||
DELETE /api/v1/containers/{id}/port-mappings/{index}
|
||||
```
|
||||
|
||||
添加 / 修改 NAT 映射时必须使用 JSON 请求体,例如:
|
||||
|
||||
```json
|
||||
{
|
||||
"container_port": 8080,
|
||||
"host_port": 61320,
|
||||
"protocol": "tcp",
|
||||
"description": "HTTP"
|
||||
}
|
||||
```
|
||||
|
||||
## WebSSH
|
||||
|
||||
WebSSH 按钮会调用:
|
||||
|
||||
```text
|
||||
POST /api/v1/ssh-ticket
|
||||
```
|
||||
|
||||
请求体:
|
||||
|
||||
```json
|
||||
{
|
||||
"container_name": "example-vm"
|
||||
}
|
||||
```
|
||||
|
||||
接口返回 60 秒有效票据后,模块会打开本地 handler:
|
||||
|
||||
```text
|
||||
/plugins/servers/clicd/handlers/webssh.php
|
||||
```
|
||||
|
||||
浏览器会从该页面直连 CLICD:
|
||||
|
||||
```text
|
||||
wss://0.0.0.0:8999/api/ssh?container=example-vm
|
||||
Sec-WebSocket-Protocol: clicd-ticket.xxxxx
|
||||
```
|
||||
|
||||
注意:WebSSH 受浏览器安全策略和 CLICD 后端 Origin 校验影响。魔方客户区通常是 HTTPS,因此 CLICD 面板也必须启用 HTTPS/WSS。请把魔方服务器配置里的 `主机名` 改为 `https://0.0.0.0:8999`,或把 `secure` 设为 `开启`。
|
||||
|
||||
新版 CLICD 已支持 WebSSH Origin 放行。部署时需要在 CLICD 后端把魔方财务客户区域名加入 WebSSH Origin 白名单,例如:
|
||||
|
||||
```text
|
||||
https://www.example.com
|
||||
```
|
||||
|
||||
如果 WebSSH 页面显示 `WebSocket error`、`Disconnected code=1006`,但直接以 CLICD 自身 Origin 测试能返回 `101 Switching Protocols`,通常说明 CLICD 后端未放行魔方客户区域名的 WebSocket Origin。此时请检查 CLICD 的 WebSSH Origin 白名单配置;前端页面无法伪造浏览器 Origin。
|
||||
|
||||
## 支持的魔方操作
|
||||
|
||||
| 魔方操作 | CLICD API |
|
||||
| --- | --- |
|
||||
| 连接测试 | `GET /api/v1/dashboard` |
|
||||
| 开通 | `POST /api/v1/containers` |
|
||||
| 删除 | `DELETE /api/v1/containers/{name}/delete` |
|
||||
| 开机 | `POST /api/v1/containers/{name}/start` |
|
||||
| 关机 | `POST /api/v1/containers/{name}/stop` |
|
||||
| 重启 | `POST /api/v1/containers/{name}/restart` |
|
||||
| 重装 | `POST /api/v1/containers/{name}/reinstall` |
|
||||
| 改密 | `POST /api/v1/containers/{name}/reset-password` |
|
||||
| 重置流量 | `POST /api/v1/containers/{name}/traffic-reset` |
|
||||
| 变更资源 | `PUT /api/v1/containers/{name}/resource-limit` |
|
||||
| 变更流量 | `PUT /api/v1/containers/{name}/traffic-limit` |
|
||||
| 同步到期 | `PUT /api/v1/containers/{name}/expiry` |
|
||||
| WebSSH | `POST /api/v1/ssh-ticket` |
|
||||
|
||||
## 建议 API 权限
|
||||
|
||||
API Key 至少需要以下权限,具体名称以 CLICD 后端实际权限系统为准:
|
||||
|
||||
```text
|
||||
dashboard:read
|
||||
container:read
|
||||
container:create
|
||||
container:power
|
||||
container:delete
|
||||
container:reinstall
|
||||
container:password
|
||||
container:traffic
|
||||
container:resize
|
||||
container:port
|
||||
task:read
|
||||
ssh-ticket:create
|
||||
```
|
||||
|
||||
如果 API Key 使用 `*` 或 `admin:*`,通常可以覆盖上述权限。
|
||||
|
||||
## 建议先测试的 curl
|
||||
|
||||
连接测试:
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: clicd_sk_xxxx" \
|
||||
https://0.0.0.0:8999/api/v1/dashboard
|
||||
```
|
||||
|
||||
容器详情:
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: clicd_sk_xxxx" \
|
||||
https://0.0.0.0:8999/api/v1/containers/example-vm
|
||||
```
|
||||
|
||||
资源用量:
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: clicd_sk_xxxx" \
|
||||
https://0.0.0.0:8999/api/v1/containers/example-vm/usage
|
||||
```
|
||||
|
||||
流量统计:
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: clicd_sk_xxxx" \
|
||||
https://0.0.0.0:8999/api/v1/containers/example-vm/traffic
|
||||
```
|
||||
|
||||
修改 NAT:
|
||||
|
||||
```bash
|
||||
curl --location --request PUT \
|
||||
"https://0.0.0.0:8999/api/v1/containers/10/port-mappings/1" \
|
||||
--header "X-API-Key: clicd_sk_xxxx" \
|
||||
--header "Authorization: Bearer clicd_sk_xxxx" \
|
||||
--header "Content-Type: application/json" \
|
||||
--data-raw '{"container_port":8081,"host_port":61320,"protocol":"tcp","description":"HTTP"}'
|
||||
```
|
||||
|
||||
创建 WebSSH 票据:
|
||||
|
||||
```bash
|
||||
curl --location --request POST \
|
||||
"https://0.0.0.0:8999/api/v1/ssh-ticket" \
|
||||
--header "X-API-Key: clicd_sk_xxxx" \
|
||||
--header "Content-Type: application/json" \
|
||||
--data-raw '{"container_name":"example-vm"}'
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### NAT 修改不生效
|
||||
|
||||
确认请求体必须是 JSON,不要使用 `multipart/form-data`。正确请求头:
|
||||
|
||||
```text
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### 图表刚打开只有一条横线
|
||||
|
||||
CLICD 当前用量接口返回的是实时值,不是历史序列。页面刚打开时只有一个采样点,所以会显示当前值横线。选择 `10 秒` 自动刷新或点击“立即刷新”多采样几次后,会逐步形成折线。
|
||||
|
||||
### 流量显示为 0
|
||||
|
||||
旧版本只显示 GB,小流量换算后会被四舍五入成 `0 GB`。当前版本已改为智能单位,会显示 B / KB / MB / GB。
|
||||
|
||||
### WebSSH 打不开或提示不安全 WebSocket
|
||||
|
||||
请确认 CLICD 面板已经启用 HTTPS/WSS,并且魔方服务器配置使用 HTTPS:
|
||||
|
||||
```text
|
||||
server_host = https://0.0.0.0:8999
|
||||
```
|
||||
|
||||
如果仍然使用 `http://`,模块会生成 `ws://` 地址,HTTPS 客户区页面会被浏览器拦截。
|
||||
|
||||
如果 WSS 证书正常但仍返回 `Forbidden` 或浏览器显示 `code=1006`,请检查 CLICD 的 WebSSH Origin 白名单。新版 CLICD 已支持放行魔方财务域名,需要把魔方客户区访问域名完整加入白名单,例如:
|
||||
|
||||
```text
|
||||
https://www.example.com
|
||||
```
|
||||
|
||||
注意需要填写浏览器实际访问魔方客户区时的协议和域名,`http` / `https`、带不带 `www` 都要与实际访问地址一致。
|
||||
|
||||
### 开通后魔方里的 IP、端口、密码不对
|
||||
|
||||
执行“同步状态”或重装 / 改密后,模块会重新拉取容器详情。请确认 CLICD 容器详情接口能返回:
|
||||
|
||||
```text
|
||||
ssh_port
|
||||
ssh_password
|
||||
status
|
||||
```
|
||||
|
||||
公网 IP 优先使用 `nat_public_ip/public_ip/host_ip/external_ip/node_ip/nat_host` 等字段;如果接口没有返回,则使用魔方服务器配置的 IP。
|
||||
@@ -0,0 +1,384 @@
|
||||
<?php
|
||||
$ws = isset($_GET['ws']) ? (string)$_GET['ws'] : (isset($_GET['amp;ws']) ? (string)$_GET['amp;ws'] : '');
|
||||
$protocol = isset($_GET['protocol']) ? (string)$_GET['protocol'] : (isset($_GET['amp;protocol']) ? (string)$_GET['amp;protocol'] : '');
|
||||
$container = isset($_GET['container']) ? (string)$_GET['container'] : (isset($_GET['amp;container']) ? (string)$_GET['amp;container'] : '');
|
||||
|
||||
if ($ws === '' || $protocol === '') {
|
||||
http_response_code(400);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "Missing WebSSH parameters\n";
|
||||
echo "Received query: " . ($_SERVER['QUERY_STRING'] ?? '') . "\n";
|
||||
exit;
|
||||
}
|
||||
?>
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>WebSSH</title>
|
||||
<style>
|
||||
html,body{height:100%;margin:0;background:#0b1020;color:#e5e7eb;font-family:Consolas,Menlo,monospace}
|
||||
body{cursor:text}
|
||||
.bar{height:44px;display:flex;align-items:center;gap:12px;padding:0 14px;background:#111827;border-bottom:1px solid #243047}
|
||||
.dot{width:9px;height:9px;border-radius:50%;background:#f59e0b}
|
||||
.dot.ok{background:#22c55e}.dot.err{background:#ef4444}
|
||||
.title{font-size:14px;color:#cbd5e1;flex:1}
|
||||
.tools{display:flex;align-items:center;gap:8px;font-size:12px;color:#94a3b8;flex-wrap:wrap;justify-content:flex-end}
|
||||
.tools select{height:26px;background:#0f172a;color:#cbd5e1;border:1px solid #334155;border-radius:4px}
|
||||
.tools button{height:26px;border:1px solid #334155;background:#0f172a;color:#cbd5e1;border-radius:4px;padding:0 8px;cursor:pointer}
|
||||
#keyhint{min-width:44px;text-align:right}
|
||||
#iostat{min-width:120px;text-align:right}
|
||||
#term{height:calc(100% - 89px);box-sizing:border-box;padding:14px;overflow:auto;white-space:pre-wrap;word-break:break-word;font-size:14px;line-height:1.45;outline:none}
|
||||
.inputbar{height:44px;display:flex;align-items:center;gap:8px;padding:6px 10px;box-sizing:border-box;background:#111827;border-top:1px solid #243047}
|
||||
#cmd{flex:1;height:30px;background:#020617;color:#e5e7eb;border:1px solid #334155;border-radius:4px;padding:0 8px;font:14px Consolas,Menlo,monospace;outline:none}
|
||||
#sendcmd{height:30px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:0 12px;cursor:pointer}
|
||||
.hint{color:#94a3b8}
|
||||
.meta{color:#94a3b8}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="bar">
|
||||
<span id="state" class="dot"></span>
|
||||
<span class="title">WebSSH <?php echo htmlspecialchars($container, ENT_QUOTES, 'UTF-8'); ?></span>
|
||||
<span class="tools">
|
||||
<span>发送模式</span>
|
||||
<select id="send-mode">
|
||||
<option value="raw" selected>raw</option>
|
||||
<option value="binary">binary</option>
|
||||
<option value="json-input">json input</option>
|
||||
<option value="json-data">json data</option>
|
||||
<option value="json-stdin">json stdin</option>
|
||||
</select>
|
||||
<button id="send-enter" type="button">回车</button>
|
||||
<span id="iostat">S0 R0</span>
|
||||
<span id="keyhint"></span>
|
||||
</span>
|
||||
</div>
|
||||
<div id="term" tabindex="0"><span class="hint">正在连接...</span></div>
|
||||
<div class="inputbar">
|
||||
<input id="cmd" type="text" autocomplete="off" spellcheck="false" placeholder="在这里输入命令,例如 ls -la">
|
||||
<button id="sendcmd" type="button">发送</button>
|
||||
</div>
|
||||
<script>
|
||||
(function(){
|
||||
var wsUrl = <?php echo json_encode($ws, JSON_UNESCAPED_SLASHES); ?>;
|
||||
var protocol = <?php echo json_encode($protocol, JSON_UNESCAPED_SLASHES); ?>;
|
||||
var term = document.getElementById('term');
|
||||
var state = document.getElementById('state');
|
||||
var modeSelect = document.getElementById('send-mode');
|
||||
var keyhint = document.getElementById('keyhint');
|
||||
var iostat = document.getElementById('iostat');
|
||||
var sendEnter = document.getElementById('send-enter');
|
||||
var cmd = document.getElementById('cmd');
|
||||
var sendcmd = document.getElementById('sendcmd');
|
||||
var socket;
|
||||
var hintTimer;
|
||||
var sentCount = 0;
|
||||
var recvCount = 0;
|
||||
var decoder = window.TextDecoder ? new TextDecoder('utf-8') : null;
|
||||
var termLines = [''];
|
||||
var cursorRow = 0;
|
||||
var cursorCol = 0;
|
||||
var maxLines = 2000;
|
||||
|
||||
function append(text) {
|
||||
writeTerminal(stripTerminalControls(String(text || '')));
|
||||
renderTerminal();
|
||||
}
|
||||
|
||||
function clearTerminal() {
|
||||
termLines = [''];
|
||||
cursorRow = 0;
|
||||
cursorCol = 0;
|
||||
renderTerminal();
|
||||
}
|
||||
|
||||
function stripTerminalControls(text) {
|
||||
return text
|
||||
.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '')
|
||||
.replace(/\x1b\[(?:2J|H)/g, '\f')
|
||||
.replace(/\x1b\[[0-?]*[ -/]*K/g, '\v')
|
||||
.replace(/\ufffd\[[0-?]*[ -/]*K/g, '\v')
|
||||
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
|
||||
.replace(/\ufffd\[[0-?]*[ -/]*[@-~]/g, '')
|
||||
.replace(/\x1b[()][A-Za-z0-9]/g, '')
|
||||
.replace(/\x1b[@-Z\\-_]/g, '')
|
||||
.replace(/[\x00-\x08\x0e-\x1f\x7f]/g, '');
|
||||
}
|
||||
|
||||
function ensureLine() {
|
||||
while (cursorRow >= termLines.length) {
|
||||
termLines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
function trimTerminal() {
|
||||
if (termLines.length <= maxLines) {
|
||||
return;
|
||||
}
|
||||
var overflow = termLines.length - maxLines;
|
||||
termLines.splice(0, overflow);
|
||||
cursorRow = Math.max(0, cursorRow - overflow);
|
||||
}
|
||||
|
||||
function writeTerminal(text) {
|
||||
for (var i = 0; i < text.length; i++) {
|
||||
var ch = text.charAt(i);
|
||||
if (ch === '\f') {
|
||||
termLines = [''];
|
||||
cursorRow = 0;
|
||||
cursorCol = 0;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\v') {
|
||||
ensureLine();
|
||||
termLines[cursorRow] = termLines[cursorRow].slice(0, cursorCol);
|
||||
continue;
|
||||
}
|
||||
if (ch === '\r') {
|
||||
cursorCol = 0;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\n') {
|
||||
cursorRow++;
|
||||
cursorCol = 0;
|
||||
ensureLine();
|
||||
trimTerminal();
|
||||
continue;
|
||||
}
|
||||
if (ch === '\b') {
|
||||
cursorCol = Math.max(0, cursorCol - 1);
|
||||
continue;
|
||||
}
|
||||
if (ch === '\t') {
|
||||
var spaces = 4 - (cursorCol % 4);
|
||||
for (var s = 0; s < spaces; s++) {
|
||||
writePrintable(' ');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
writePrintable(ch);
|
||||
}
|
||||
trimTerminal();
|
||||
}
|
||||
|
||||
function writePrintable(ch) {
|
||||
ensureLine();
|
||||
var line = termLines[cursorRow];
|
||||
if (cursorCol > line.length) {
|
||||
line += new Array(cursorCol - line.length + 1).join(' ');
|
||||
}
|
||||
termLines[cursorRow] = line.slice(0, cursorCol) + ch + line.slice(cursorCol + 1);
|
||||
cursorCol++;
|
||||
}
|
||||
|
||||
function renderTerminal() {
|
||||
term.textContent = termLines.join('\n');
|
||||
term.scrollTop = term.scrollHeight;
|
||||
}
|
||||
|
||||
function setState(cls, text) {
|
||||
state.className = 'dot ' + cls;
|
||||
append(text);
|
||||
}
|
||||
|
||||
function updateIoStatus() {
|
||||
if (!iostat) return;
|
||||
var stateText = socket ? ['CONNECTING','OPEN','CLOSING','CLOSED'][socket.readyState] : '-';
|
||||
iostat.textContent = 'S' + sentCount + ' R' + recvCount + ' ' + stateText;
|
||||
}
|
||||
|
||||
try {
|
||||
socket = new WebSocket(wsUrl, protocol);
|
||||
socket.binaryType = 'arraybuffer';
|
||||
} catch (e) {
|
||||
setState('err', '\nWebSocket 创建失败:' + e.message + '\n');
|
||||
return;
|
||||
}
|
||||
|
||||
socket.onopen = function(){
|
||||
clearTerminal();
|
||||
setState('ok', '已连接。\r\n');
|
||||
updateIoStatus();
|
||||
if (cmd) cmd.focus();
|
||||
};
|
||||
socket.onmessage = function(event){
|
||||
recvCount++;
|
||||
updateIoStatus();
|
||||
if (typeof event.data === 'string') {
|
||||
handleIncomingText(event.data);
|
||||
return;
|
||||
}
|
||||
if (event.data instanceof ArrayBuffer) {
|
||||
handleIncomingText(decodeIncoming(event.data));
|
||||
return;
|
||||
}
|
||||
if (window.Blob && event.data instanceof Blob) {
|
||||
event.data.arrayBuffer().then(function(buffer){
|
||||
handleIncomingText(decodeIncoming(buffer));
|
||||
}).catch(function(){
|
||||
append('\n[WebSSH] 无法解码服务端返回内容。\n');
|
||||
});
|
||||
}
|
||||
};
|
||||
socket.onerror = function(){
|
||||
setState('err', '\nWebSocket 连接错误,请检查 HTTPS 证书、WSS 服务、Origin 策略和票据有效期。\n');
|
||||
};
|
||||
socket.onclose = function(event){
|
||||
updateIoStatus();
|
||||
setState('err', '\n连接已断开。code=' + event.code + ' reason=' + (event.reason || '-') + ' clean=' + event.wasClean + '\n');
|
||||
};
|
||||
|
||||
function flashKey(text) {
|
||||
if (!keyhint) return;
|
||||
keyhint.textContent = text;
|
||||
window.clearTimeout(hintTimer);
|
||||
hintTimer = window.setTimeout(function(){ keyhint.textContent = ''; }, 500);
|
||||
}
|
||||
|
||||
function decodeIncoming(buffer) {
|
||||
if (decoder) {
|
||||
return decoder.decode(new Uint8Array(buffer));
|
||||
}
|
||||
var bytes = new Uint8Array(buffer);
|
||||
var text = '';
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
text += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(escape(text));
|
||||
} catch (e) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
function handleIncomingText(text) {
|
||||
append(text);
|
||||
if (text.indexOf('SSH shell ready') !== -1) {
|
||||
window.setTimeout(function(){ send('\r'); }, 250);
|
||||
}
|
||||
}
|
||||
|
||||
function wsPayload(data) {
|
||||
var mode = modeSelect ? modeSelect.value : 'raw';
|
||||
if (mode === 'raw') {
|
||||
return data;
|
||||
}
|
||||
if (mode === 'binary') {
|
||||
return new TextEncoder().encode(data);
|
||||
}
|
||||
if (mode === 'json-data') {
|
||||
return JSON.stringify({type:'data', data:data});
|
||||
}
|
||||
if (mode === 'json-stdin') {
|
||||
return JSON.stringify({type:'stdin', data:data});
|
||||
}
|
||||
return JSON.stringify({type:'input', data:data});
|
||||
}
|
||||
|
||||
function send(data) {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||
return false;
|
||||
}
|
||||
socket.send(wsPayload(data));
|
||||
sentCount++;
|
||||
updateIoStatus();
|
||||
flashKey(data === '\r' ? '回车' : data === '\x7f' ? '退格' : data.length > 1 ? data.length + ' 字符' : data);
|
||||
return true;
|
||||
}
|
||||
|
||||
function keyToData(e) {
|
||||
if (e.ctrlKey && !e.altKey && !e.metaKey && e.key.length === 1) {
|
||||
var code = e.key.toUpperCase().charCodeAt(0);
|
||||
if (code >= 64 && code <= 95) {
|
||||
return String.fromCharCode(code - 64);
|
||||
}
|
||||
}
|
||||
var map = {
|
||||
Enter: '\r',
|
||||
Backspace: '\x7f',
|
||||
Tab: '\t',
|
||||
Escape: '\x1b',
|
||||
ArrowUp: '\x1b[A',
|
||||
ArrowDown: '\x1b[B',
|
||||
ArrowRight: '\x1b[C',
|
||||
ArrowLeft: '\x1b[D',
|
||||
Delete: '\x1b[3~',
|
||||
Home: '\x1b[H',
|
||||
End: '\x1b[F',
|
||||
PageUp: '\x1b[5~',
|
||||
PageDown: '\x1b[6~'
|
||||
};
|
||||
if (map[e.key]) {
|
||||
return map[e.key];
|
||||
}
|
||||
if (!e.ctrlKey && !e.altKey && !e.metaKey && e.key.length === 1) {
|
||||
return e.key;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function(e){
|
||||
if (e.target === cmd) {
|
||||
return;
|
||||
}
|
||||
var data = keyToData(e);
|
||||
if (data !== null && send(data)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('paste', function(e){
|
||||
if (e.target === cmd) {
|
||||
return;
|
||||
}
|
||||
var text = e.clipboardData ? e.clipboardData.getData('text/plain') : '';
|
||||
if (text && send(text)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('mousedown', function(){
|
||||
if (cmd) cmd.focus();
|
||||
});
|
||||
|
||||
function sendCommandLine() {
|
||||
if (!cmd) return;
|
||||
var value = cmd.value;
|
||||
if (value === '') {
|
||||
send('\r');
|
||||
return;
|
||||
}
|
||||
if (send(value + '\r')) {
|
||||
cmd.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
if (sendcmd) {
|
||||
sendcmd.addEventListener('click', sendCommandLine);
|
||||
}
|
||||
if (sendEnter) {
|
||||
sendEnter.addEventListener('click', function(){
|
||||
send('\r');
|
||||
if (cmd) cmd.focus();
|
||||
});
|
||||
}
|
||||
if (cmd) {
|
||||
cmd.addEventListener('keydown', function(e){
|
||||
if (e.key === 'Enter') {
|
||||
sendCommandLine();
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey && e.key.toLowerCase() === 'c') {
|
||||
send('\x03');
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
}
|
||||
window.setInterval(updateIoStatus, 1000);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,508 @@
|
||||
<style>
|
||||
.clicd-fw-panel{font-size:14px;color:#1f2937}
|
||||
.clicd-fw-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px}
|
||||
.clicd-fw-card{border:1px solid #e5e7eb;border-radius:6px;padding:12px;background:#fff}
|
||||
.clicd-fw-label{color:#6b7280;font-size:12px;margin-bottom:4px}
|
||||
.clicd-fw-value{font-size:18px;font-weight:600;word-break:break-all}
|
||||
.clicd-fw-section{border:1px solid #e5e7eb;border-radius:6px;background:#fff;padding:12px;margin-top:8px}
|
||||
.clicd-fw-title{font-weight:600;margin:18px 0 8px}
|
||||
.clicd-fw-muted{color:#6b7280}
|
||||
.clicd-fw-toggle-row{display:flex;align-items:center;gap:12px;margin-bottom:12px}
|
||||
.clicd-fw-toggle{position:relative;display:inline-flex;width:48px;height:26px;cursor:pointer}
|
||||
.clicd-fw-toggle input{opacity:0;width:0;height:0}
|
||||
.clicd-fw-toggle-slider{position:absolute;inset:0;background:#d1d5db;border-radius:26px;transition:.25s}
|
||||
.clicd-fw-toggle-slider:before{content:"";position:absolute;width:22px;height:22px;border-radius:50%;background:#fff;top:2px;left:2px;transition:.25s}.clicd-fw-toggle .clicd-fw-toggle-slider:before{width:16px;height:16px;top:2px;left:2px}
|
||||
.clicd-fw-toggle input:checked+.clicd-fw-toggle-slider{background:#10b981}
|
||||
.clicd-fw-toggle input:checked+.clicd-fw-toggle-slider:before{transform:translateX(22px)}
|
||||
.clicd-fw-toggle-label{font-size:14px;font-weight:500}
|
||||
.clicd-fw-status{font-size:13px;color:#6b7280}
|
||||
.clicd-fw-rule-form{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;align-items:end}
|
||||
.clicd-fw-field label{display:block;color:#6b7280;font-size:12px;margin-bottom:4px}
|
||||
.clicd-fw-input,.clicd-fw-select{width:100%;height:34px;border:1px solid #d1d5db;border-radius:4px;padding:6px 8px;box-sizing:border-box}
|
||||
.clicd-fw-input:focus,.clicd-fw-select:focus{border-color:#2563eb;outline:none}
|
||||
.clicd-fw-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:end}
|
||||
.clicd-fw-btn{height:34px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:0 12px;cursor:pointer;font-size:13px}
|
||||
.clicd-fw-btn[disabled]{opacity:.6;cursor:not-allowed}
|
||||
.clicd-fw-btn-secondary{border-color:#d1d5db;background:#fff;color:#374151}
|
||||
.clicd-fw-btn-danger{border-color:#dc2626;background:#dc2626;color:#fff}
|
||||
.clicd-fw-btn-sm{height:30px;padding:0 10px;font-size:12px}
|
||||
.clicd-fw-rules{display:flex;flex-direction:column;gap:10px;margin-top:8px}
|
||||
.clicd-fw-rule{border:1px solid #e5e7eb;border-radius:6px;background:#fff;padding:12px}
|
||||
.clicd-fw-rule-header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;flex-wrap:wrap}
|
||||
.clicd-fw-rule-direction{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600}
|
||||
.clicd-fw-direction-in{background:#dbeafe;color:#1d4ed8}
|
||||
.clicd-fw-direction-out{background:#fef3c7;color:#92400e}
|
||||
.clicd-fw-rule-action{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600}
|
||||
.clicd-fw-action-ACCEPT{background:#d1fae5;color:#065f46}
|
||||
.clicd-fw-action-DROP{background:#fee2e2;color:#991b1b}
|
||||
.clicd-fw-rule-desc{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px}
|
||||
.clicd-fw-rule-detail{font-size:13px;color:#374151;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||||
.clicd-fw-rule-detail .sep{color:#d1d5db}
|
||||
.clicd-fw-rule-edit-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:8px;margin-top:8px;padding-top:8px;border-top:1px solid #e5e7eb}
|
||||
.clicd-fw-message{border:1px solid #bfdbfe;background:#eff6ff;color:#1d4ed8;border-radius:6px;padding:10px 12px;margin-bottom:12px;display:none}
|
||||
.clicd-fw-message.error{border-color:#fecaca;background:#fef2f2;color:#b91c1c}
|
||||
.clicd-fw-debug{margin-top:12px;border:1px dashed #d1d5db;border-radius:6px;background:#f9fafb;padding:10px;color:#374151;white-space:pre-wrap;font-size:12px;display:none}
|
||||
.clicd-fw-modal-mask{position:fixed;inset:0;background:rgba(15,23,42,.42);display:none;align-items:center;justify-content:center;z-index:9999;padding:16px}
|
||||
.clicd-fw-modal{width:min(420px,100%);background:#fff;border-radius:6px;border:1px solid #e5e7eb;box-shadow:0 18px 48px rgba(15,23,42,.22);padding:16px}
|
||||
.clicd-fw-modal-title{font-size:16px;font-weight:700;color:#111827;margin-bottom:8px}
|
||||
.clicd-fw-modal-body{font-size:14px;color:#4b5563;line-height:1.6;margin-bottom:14px}
|
||||
.clicd-fw-modal-actions{display:flex;justify-content:flex-end;gap:8px}
|
||||
</style>
|
||||
|
||||
<div class="clicd-fw-panel" id="clicd-fw-panel" data-service-id="{$service_id}" data-area-key="{$area_key}">
|
||||
<div class="clicd-fw-message" id="clicd-fw-message"></div>
|
||||
|
||||
<div class="clicd-fw-grid">
|
||||
<div class="clicd-fw-card">
|
||||
<div class="clicd-fw-label">实例名称</div>
|
||||
<div class="clicd-fw-value">{$container_name}</div>
|
||||
</div>
|
||||
<div class="clicd-fw-card">
|
||||
<div class="clicd-fw-label">IP 地址</div>
|
||||
<div class="clicd-fw-value">{$server_ip}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-fw-section">
|
||||
<div class="clicd-fw-toggle-row">
|
||||
<label class="clicd-fw-toggle">
|
||||
<input type="checkbox" id="clicd-fw-enabled">
|
||||
<span class="clicd-fw-toggle-slider"></span>
|
||||
</label>
|
||||
<span class="clicd-fw-toggle-label">启用防火墙</span>
|
||||
<span class="clicd-fw-status" id="clicd-fw-status-text">加载中...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-fw-title">添加规则</div>
|
||||
<div class="clicd-fw-section" id="clicd-fw-add-section">
|
||||
<div class="clicd-fw-rule-form">
|
||||
<div class="clicd-fw-field">
|
||||
<label>方向</label>
|
||||
<select class="clicd-fw-select" id="clicd-fw-add-direction">
|
||||
<option value="in">入站 (In)</option>
|
||||
<option value="out">出站 (Out)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="clicd-fw-field">
|
||||
<label>协议</label>
|
||||
<select class="clicd-fw-select" id="clicd-fw-add-protocol">
|
||||
<option value="tcp">TCP</option>
|
||||
<option value="udp">UDP</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="clicd-fw-field">
|
||||
<label>端口</label>
|
||||
<input class="clicd-fw-input" id="clicd-fw-add-port" type="text" placeholder="22 / 80,443 / 8000-9000">
|
||||
</div>
|
||||
<div class="clicd-fw-field">
|
||||
<label>来源 IP</label>
|
||||
<input class="clicd-fw-input" id="clicd-fw-add-source-ip" type="text" placeholder="留空表示所有">
|
||||
</div>
|
||||
<div class="clicd-fw-field">
|
||||
<label>动作</label>
|
||||
<select class="clicd-fw-select" id="clicd-fw-add-action">
|
||||
<option value="ACCEPT">放行 (ACCEPT)</option>
|
||||
<option value="DROP">拒绝 (DROP)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="clicd-fw-field">
|
||||
<label>说明</label>
|
||||
<input class="clicd-fw-input" id="clicd-fw-add-desc" type="text" placeholder="例如 Allow SSH">
|
||||
</div>
|
||||
<div class="clicd-fw-actions">
|
||||
<button class="clicd-fw-btn" type="button" data-clicd-fw-action="add-rule">添加规则</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-fw-title">防火墙规则</div>
|
||||
<div id="clicd-fw-rules" class="clicd-fw-rules">
|
||||
<div class="clicd-fw-section clicd-fw-muted">加载中...</div>
|
||||
</div>
|
||||
|
||||
<pre class="clicd-fw-debug" id="clicd-fw-debug"></pre>
|
||||
|
||||
<div class="clicd-fw-modal-mask" id="clicd-fw-delete-modal">
|
||||
<div class="clicd-fw-modal">
|
||||
<div class="clicd-fw-modal-title">确认删除</div>
|
||||
<div class="clicd-fw-modal-body" id="clicd-fw-delete-text">确认删除该规则?</div>
|
||||
<div class="clicd-fw-modal-actions">
|
||||
<button class="clicd-fw-btn clicd-fw-btn-secondary" type="button" id="clicd-fw-delete-cancel">取消</button>
|
||||
<button class="clicd-fw-btn clicd-fw-btn-danger" type="button" id="clicd-fw-delete-confirm">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function(){
|
||||
var panel = document.getElementById('clicd-fw-panel');
|
||||
if (!panel || panel.getAttribute('data-bound') === '1') return;
|
||||
panel.setAttribute('data-bound', '1');
|
||||
|
||||
var message = document.getElementById('clicd-fw-message');
|
||||
var debugBox = document.getElementById('clicd-fw-debug');
|
||||
var rulesContainer = document.getElementById('clicd-fw-rules');
|
||||
var enabledCheckbox = document.getElementById('clicd-fw-enabled');
|
||||
var statusText = document.getElementById('clicd-fw-status-text');
|
||||
var deleteModal = document.getElementById('clicd-fw-delete-modal');
|
||||
var deleteText = document.getElementById('clicd-fw-delete-text');
|
||||
var deleteCancel = document.getElementById('clicd-fw-delete-cancel');
|
||||
var deleteConfirm = document.getElementById('clicd-fw-delete-confirm');
|
||||
var pendingDeleteRule = null;
|
||||
var currentRules = [];
|
||||
|
||||
function showMessage(type, text) {
|
||||
message.className = 'clicd-fw-message' + (type === 'error' ? ' error' : '');
|
||||
message.style.display = 'block';
|
||||
message.textContent = text || '';
|
||||
}
|
||||
|
||||
function showDebug(data) {
|
||||
debugBox.style.display = 'block';
|
||||
debugBox.textContent = JSON.stringify(data || {}, null, 2);
|
||||
}
|
||||
|
||||
function endpoint() {
|
||||
return "{$MODULE_CUSTOM_API}";
|
||||
}
|
||||
|
||||
function setBusy(busy) {
|
||||
panel.querySelectorAll('button, input, select').forEach(function(el){ el.disabled = !!busy; });
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function portDisplay(port) {
|
||||
return port || '所有';
|
||||
}
|
||||
|
||||
function sourceIpDisplay(ip) {
|
||||
return ip || '任意';
|
||||
}
|
||||
|
||||
function directionLabel(dir) {
|
||||
return dir === 'in' ? '入站' : '出站';
|
||||
}
|
||||
|
||||
function actionLabel(action) {
|
||||
return action === 'ACCEPT' ? '放行' : '拒绝';
|
||||
}
|
||||
|
||||
function renderRules(rules) {
|
||||
currentRules = Array.isArray(rules) ? rules : [];
|
||||
if (currentRules.length === 0) {
|
||||
rulesContainer.innerHTML = '<div class="clicd-fw-section clicd-fw-muted">暂无防火墙规则</div>';
|
||||
return;
|
||||
}
|
||||
rulesContainer.innerHTML = currentRules.map(function(rule, idx) {
|
||||
var dirRaw = String(rule.direction || 'in').toLowerCase();
|
||||
var protoRaw = String(rule.protocol || 'tcp').toLowerCase();
|
||||
var actionRaw = String(rule.action || 'ACCEPT').toUpperCase();
|
||||
var dir = (dirRaw === 'in' || dirRaw === 'out') ? dirRaw : 'in';
|
||||
var proto = (protoRaw === 'tcp' || protoRaw === 'udp' || protoRaw === 'icmp' || protoRaw === 'all') ? protoRaw : 'tcp';
|
||||
var action = (actionRaw === 'ACCEPT' || actionRaw === 'DROP' || actionRaw === 'REJECT') ? actionRaw : 'ACCEPT';
|
||||
var port = escapeHtml(portDisplay(rule.port));
|
||||
var srcIp = escapeHtml(sourceIpDisplay(rule.source_ip));
|
||||
var desc = escapeHtml(rule.description || '');
|
||||
var ruleId = escapeHtml(rule.id || '');
|
||||
var enabled = rule.enabled !== false;
|
||||
var enabledChecked = enabled ? 'checked' : '';
|
||||
var dirClass = dir === 'in' ? 'clicd-fw-direction-in' : 'clicd-fw-direction-out';
|
||||
var actionClass = 'clicd-fw-action-' + action;
|
||||
return '<div class="clicd-fw-rule" data-rule-id="' + ruleId + '" data-rule-index="' + idx + '">' +
|
||||
'<div class="clicd-fw-rule-header">' +
|
||||
'<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">' +
|
||||
'<span class="clicd-fw-rule-direction ' + dirClass + '">' + (dir === 'in' ? '↑ 入站' : '↓ 出站') + '</span>' +
|
||||
'<span class="clicd-fw-rule-action ' + actionClass + '">' + actionLabel(action) + '</span>' +
|
||||
'<span style="font-size:13px;color:#6b7280">' + proto.toUpperCase() + '</span>' +
|
||||
'<span style="font-size:13px;color:#374151">' +
|
||||
(port !== '所有' ? '端口: ' + port : '') +
|
||||
(srcIp !== '任意' && port !== '所有' ? ' | ' : '') +
|
||||
(srcIp !== '任意' ? '来源: ' + srcIp : '') +
|
||||
'</span>' +
|
||||
'</div>' +
|
||||
'<div style="display:flex;align-items:center;gap:6px">' +
|
||||
'<label class="clicd-fw-toggle" style="width:36px;height:20px">' +
|
||||
'<input type="checkbox" class="clicd-fw-rule-enabled" ' + enabledChecked + '>' +
|
||||
'<span class="clicd-fw-toggle-slider" style="border-radius:20px"></span>' +
|
||||
|
||||
'</label>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="clicd-fw-rule-desc">' +
|
||||
'<span style="font-size:13px;color:#374151;flex:1">' + (desc || '<span style="color:#9ca3af">无说明</span>') + '</span>' +
|
||||
'</div>' +
|
||||
'<div class="clicd-fw-rule-edit-row">' +
|
||||
'<div class="clicd-fw-field"><label>方向</label><select class="clicd-fw-select clicd-fw-edit-field" data-field="direction">' +
|
||||
'<option value="in"' + (dir === 'in' ? ' selected' : '') + '>入站</option>' +
|
||||
'<option value="out"' + (dir === 'out' ? ' selected' : '') + '>出站</option>' +
|
||||
'</select></div>' +
|
||||
'<div class="clicd-fw-field"><label>协议</label><select class="clicd-fw-select clicd-fw-edit-field" data-field="protocol">' +
|
||||
'<option value="tcp"' + (proto === 'tcp' ? ' selected' : '') + '>TCP</option>' +
|
||||
'<option value="udp"' + (proto === 'udp' ? ' selected' : '') + '>UDP</option>' +
|
||||
'</select></div>' +
|
||||
'<div class="clicd-fw-field"><label>端口</label><input class="clicd-fw-input clicd-fw-edit-field" data-field="port" type="text" value="' + escapeHtml(rule.port || '') + '"></div>' +
|
||||
'<div class="clicd-fw-field"><label>来源 IP</label><input class="clicd-fw-input clicd-fw-edit-field" data-field="source_ip" type="text" value="' + escapeHtml(rule.source_ip || '') + '"></div>' +
|
||||
'<div class="clicd-fw-field"><label>动作</label><select class="clicd-fw-select clicd-fw-edit-field" data-field="action">' +
|
||||
'<option value="ACCEPT"' + (action === 'ACCEPT' ? ' selected' : '') + '>放行</option>' +
|
||||
'<option value="DROP"' + (action === 'DROP' ? ' selected' : '') + '>拒绝</option>' +
|
||||
'</select></div>' +
|
||||
'<div class="clicd-fw-field"><label>说明</label><input class="clicd-fw-input clicd-fw-edit-field" data-field="description" type="text" value="' + desc + '"></div>' +
|
||||
'<div class="clicd-fw-actions" style="align-items:end">' +
|
||||
'<button class="clicd-fw-btn clicd-fw-btn-secondary clicd-fw-btn-sm" type="button" data-clicd-fw-action="update-rule">保存</button>' +
|
||||
'<button class="clicd-fw-btn clicd-fw-btn-danger clicd-fw-btn-sm" type="button" data-clicd-fw-action="delete-rule">删除</button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
|
||||
// Bind toggle events for rule enabled/disabled
|
||||
rulesContainer.querySelectorAll('.clicd-fw-rule-enabled').forEach(function(toggle, idx) {
|
||||
toggle.addEventListener('change', function() {
|
||||
var rule = currentRules[idx];
|
||||
if (!rule) return;
|
||||
rule.enabled = toggle.checked;
|
||||
saveFirewall();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getRuleFromItem(item) {
|
||||
var idx = parseInt(item.getAttribute('data-rule-index'), 10);
|
||||
if (isNaN(idx) || !currentRules[idx]) return null;
|
||||
return { index: idx, rule: currentRules[idx] };
|
||||
}
|
||||
|
||||
function getEditField(item, name) {
|
||||
return item.querySelector('[data-field="' + name + '"]');
|
||||
}
|
||||
|
||||
function updateRuleFromFields(item, idx) {
|
||||
currentRules[idx].direction = getEditField(item, 'direction') ? getEditField(item, 'direction').value : 'in';
|
||||
currentRules[idx].protocol = getEditField(item, 'protocol') ? getEditField(item, 'protocol').value : 'tcp';
|
||||
currentRules[idx].port = getEditField(item, 'port') ? getEditField(item, 'port').value : '';
|
||||
currentRules[idx].source_ip = getEditField(item, 'source_ip') ? getEditField(item, 'source_ip').value : '';
|
||||
currentRules[idx].action = getEditField(item, 'action') ? getEditField(item, 'action').value : 'ACCEPT';
|
||||
currentRules[idx].description = getEditField(item, 'description') ? getEditField(item, 'description').value : '';
|
||||
}
|
||||
|
||||
function getAddRulePayload() {
|
||||
return {
|
||||
direction: document.getElementById('clicd-fw-add-direction').value,
|
||||
protocol: document.getElementById('clicd-fw-add-protocol').value,
|
||||
port: document.getElementById('clicd-fw-add-port').value,
|
||||
source_ip: document.getElementById('clicd-fw-add-source-ip').value,
|
||||
action: document.getElementById('clicd-fw-add-action').value,
|
||||
description: document.getElementById('clicd-fw-add-desc').value,
|
||||
enabled: true
|
||||
};
|
||||
}
|
||||
|
||||
function clearAddForm() {
|
||||
document.getElementById('clicd-fw-add-port').value = '';
|
||||
document.getElementById('clicd-fw-add-source-ip').value = '';
|
||||
document.getElementById('clicd-fw-add-action').value = 'ACCEPT';
|
||||
document.getElementById('clicd-fw-add-desc').value = '';
|
||||
}
|
||||
|
||||
function saveFirewall() {
|
||||
var enabled = enabledCheckbox.checked;
|
||||
var rules = currentRules.map(function(r) {
|
||||
return {
|
||||
id: r.id || '',
|
||||
direction: r.direction || 'in',
|
||||
protocol: r.protocol || 'tcp',
|
||||
port: r.port || '',
|
||||
source_ip: r.source_ip || '',
|
||||
action: r.action || 'ACCEPT',
|
||||
description: r.description || '',
|
||||
enabled: r.enabled !== false
|
||||
};
|
||||
});
|
||||
|
||||
setBusy(true);
|
||||
var body = new URLSearchParams();
|
||||
body.set('id', panel.getAttribute('data-service-id') || '');
|
||||
body.set('func', 'firewallUpdate');
|
||||
body.set('enabled', enabled ? 'true' : 'false');
|
||||
body.set('rules', JSON.stringify(rules));
|
||||
|
||||
fetch(endpoint(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'Authorization': 'JWT {$Think.get.jwt}'
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
body: body.toString()
|
||||
})
|
||||
.then(function(res){ return res.text(); })
|
||||
.then(function(text){
|
||||
var data;
|
||||
try { data = JSON.parse(text); } catch(e) { data = {status:'error', msg:'非 JSON 响应: ' + text}; }
|
||||
showDebug((data.data && data.data.debug) || data.debug || data);
|
||||
if (data.status === 200 || data.status === 'success') {
|
||||
showMessage('success', data.msg || '防火墙设置已更新');
|
||||
if (data.data && data.data.rules) {
|
||||
currentRules = data.data.rules;
|
||||
renderRules(currentRules);
|
||||
}
|
||||
updateStatusText();
|
||||
} else {
|
||||
showMessage('error', data.msg || '更新失败');
|
||||
}
|
||||
})
|
||||
.catch(function(e){
|
||||
showMessage('error', e.message || '请求失败');
|
||||
showDebug({error: String(e)});
|
||||
})
|
||||
.finally(function(){
|
||||
setBusy(false);
|
||||
});
|
||||
}
|
||||
|
||||
function loadFirewall() {
|
||||
setBusy(true);
|
||||
var body = new URLSearchParams();
|
||||
body.set('id', panel.getAttribute('data-service-id') || '');
|
||||
body.set('func', 'firewallList');
|
||||
|
||||
fetch(endpoint(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'Authorization': 'JWT {$Think.get.jwt}'
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
body: body.toString()
|
||||
})
|
||||
.then(function(res){ return res.text(); })
|
||||
.then(function(text){
|
||||
var data;
|
||||
try { data = JSON.parse(text); } catch(e) { data = {status:'error', msg:'非 JSON 响应: ' + text}; }
|
||||
showDebug((data.data && data.data.debug) || data.debug || data);
|
||||
if (data.status === 200 || data.status === 'success') {
|
||||
if (data.data) {
|
||||
enabledCheckbox.checked = data.data.enabled === true || data.data.enabled === 'true' || data.data.enabled === 1;
|
||||
currentRules = Array.isArray(data.data.rules) ? data.data.rules : [];
|
||||
renderRules(currentRules);
|
||||
updateStatusText();
|
||||
}
|
||||
} else {
|
||||
showMessage('error', data.msg || '获取防火墙设置失败');
|
||||
rulesContainer.innerHTML = '<div class="clicd-fw-section clicd-fw-muted">加载失败</div>';
|
||||
}
|
||||
})
|
||||
.catch(function(e){
|
||||
showMessage('error', e.message || '请求失败');
|
||||
showDebug({error: String(e)});
|
||||
rulesContainer.innerHTML = '<div class="clicd-fw-section clicd-fw-muted">加载失败</div>';
|
||||
})
|
||||
.finally(function(){
|
||||
setBusy(false);
|
||||
});
|
||||
}
|
||||
|
||||
function updateStatusText() {
|
||||
if (enabledCheckbox.checked) {
|
||||
statusText.textContent = '已启用 - 默认拒绝所有流量,仅放行规则中定义的流量';
|
||||
} else {
|
||||
statusText.textContent = '已禁用 - 所有流量不受限制';
|
||||
}
|
||||
}
|
||||
|
||||
function openDeleteModal(rule, desc) {
|
||||
pendingDeleteRule = rule;
|
||||
if (deleteText) {
|
||||
deleteText.textContent = '确认删除规则: ' + (desc || '未命名规则') + ' ?';
|
||||
}
|
||||
if (deleteModal) {
|
||||
deleteModal.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
|
||||
function closeDeleteModal() {
|
||||
pendingDeleteRule = null;
|
||||
if (deleteModal) {
|
||||
deleteModal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// Event delegation
|
||||
panel.addEventListener('click', function(event) {
|
||||
var button = event.target.closest('[data-clicd-fw-action]');
|
||||
if (!button) return;
|
||||
var action = button.getAttribute('data-clicd-fw-action');
|
||||
|
||||
if (action === 'add-rule') {
|
||||
var payload = getAddRulePayload();
|
||||
currentRules.push({
|
||||
id: '',
|
||||
direction: payload.direction,
|
||||
protocol: payload.protocol,
|
||||
port: payload.port,
|
||||
source_ip: payload.source_ip,
|
||||
action: payload.action,
|
||||
description: payload.description,
|
||||
enabled: true
|
||||
});
|
||||
renderRules(currentRules);
|
||||
clearAddForm();
|
||||
saveFirewall();
|
||||
return;
|
||||
}
|
||||
|
||||
var item = button.closest('.clicd-fw-rule');
|
||||
if (!item) return;
|
||||
var idx = parseInt(item.getAttribute('data-rule-index'), 10);
|
||||
if (isNaN(idx) || !currentRules[idx]) return;
|
||||
|
||||
if (action === 'update-rule') {
|
||||
updateRuleFromFields(item, idx);
|
||||
saveFirewall();
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === 'delete-rule') {
|
||||
var desc = currentRules[idx].description || (currentRules[idx].protocol + '/' + (currentRules[idx].port || 'all'));
|
||||
openDeleteModal(idx, desc);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
enabledCheckbox.addEventListener('change', function() {
|
||||
saveFirewall();
|
||||
});
|
||||
|
||||
if (deleteCancel) {
|
||||
deleteCancel.addEventListener('click', closeDeleteModal);
|
||||
}
|
||||
if (deleteModal) {
|
||||
deleteModal.addEventListener('click', function(event){
|
||||
if (event.target === deleteModal) closeDeleteModal();
|
||||
});
|
||||
}
|
||||
if (deleteConfirm) {
|
||||
deleteConfirm.addEventListener('click', function(){
|
||||
if (pendingDeleteRule === null) return;
|
||||
var idx = pendingDeleteRule;
|
||||
closeDeleteModal();
|
||||
if (idx >= 0 && idx < currentRules.length) {
|
||||
currentRules.splice(idx, 1);
|
||||
saveFirewall();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loadFirewall();
|
||||
})();
|
||||
</script>
|
||||
@@ -0,0 +1,378 @@
|
||||
<style>
|
||||
.clicd-info{font-size:14px;color:#1f2937;background:#f6f8fb;padding:14px;border-radius:6px;max-width:100%;overflow:hidden}
|
||||
.clicd-info *{box-sizing:border-box}
|
||||
.clicd-head{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin-bottom:12px}
|
||||
.clicd-mini{background:#fff;border:1px solid #e5e7eb;border-radius:6px;padding:10px}
|
||||
.clicd-mini-label{font-size:12px;color:#6b7280;margin-bottom:4px}
|
||||
.clicd-mini-value{font-size:16px;font-weight:600;color:#111827;word-break:break-all}
|
||||
.clicd-section{background:#fff;border:1px solid #e5e7eb;border-radius:6px;margin-top:12px;padding:14px}
|
||||
.clicd-section-title{display:flex;align-items:center;justify-content:space-between;gap:10px;font-size:15px;font-weight:700;margin-bottom:12px;color:#111827;min-width:0;flex-wrap:wrap}
|
||||
.clicd-section-title>span:first-child{min-width:0}
|
||||
.clicd-refresh{display:flex;align-items:center;justify-content:flex-end;gap:8px;font-size:12px;color:#6b7280;font-weight:400;flex-wrap:wrap;min-width:0;max-width:100%}
|
||||
.clicd-refresh label{display:inline-flex;align-items:center;gap:4px;min-width:0;white-space:nowrap}
|
||||
.clicd-refresh-select{height:28px;border:1px solid #d1d5db;border-radius:4px;background:#fff;color:#374151;padding:3px 6px;font-size:12px}
|
||||
.clicd-refresh-btn{height:28px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:3px 8px;font-size:12px;cursor:pointer;white-space:nowrap;max-width:96px;overflow:hidden;text-overflow:ellipsis}
|
||||
.clicd-refresh-btn[disabled]{opacity:.6;cursor:not-allowed}
|
||||
.clicd-gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}
|
||||
.clicd-gauge{display:flex;align-items:center;gap:12px;min-height:92px}
|
||||
.clicd-ring{--p:0%;width:78px;height:78px;border-radius:50%;background:conic-gradient(#2f80ed var(--p),#e5e7eb 0);display:grid;place-items:center;flex:0 0 auto;position:relative}
|
||||
.clicd-ring:before{content:"";width:66px;height:66px;border-radius:50%;background:#fff;position:absolute}
|
||||
.clicd-ring span{position:relative;display:inline-flex;align-items:center;justify-content:center;max-width:62px;min-width:0;font-size:17px;font-weight:700;line-height:1;color:#111827;white-space:nowrap;text-align:center;background:#fff;border-radius:3px;padding:0 1px}
|
||||
.clicd-ring[data-tight="1"] span{font-size:15px}
|
||||
.clicd-ring[data-tight="2"] span{font-size:14px}
|
||||
.clicd-gauge-title{font-weight:700;color:#111827;margin-bottom:4px}
|
||||
.clicd-gauge-sub{font-size:12px;color:#6b7280;line-height:1.45}
|
||||
.clicd-progress{height:12px;background:#e5e7eb;border-radius:999px;overflow:hidden}
|
||||
.clicd-progress span{display:block;height:100%;width:0;background:linear-gradient(90deg,#2f80ed,#10b981);transition:width .25s ease}
|
||||
.clicd-traffic-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;margin-top:8px;color:#374151;min-width:0}
|
||||
.clicd-traffic-row>div{min-width:0;word-break:break-word}
|
||||
.clicd-charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
|
||||
.clicd-chart{border:1px solid #e5e7eb;border-radius:6px;padding:12px;background:#fff;min-height:190px;min-width:0;overflow:hidden}
|
||||
.clicd-chart-title{display:flex;justify-content:space-between;gap:8px;align-items:center;font-weight:700;margin-bottom:8px;color:#111827;min-width:0;flex-wrap:wrap}
|
||||
.clicd-chart-value{font-size:12px;color:#6b7280;font-weight:400;white-space:normal;overflow-wrap:anywhere;text-align:right}
|
||||
.clicd-chart canvas{width:100%;height:132px;display:block}
|
||||
.clicd-table{width:100%;border-collapse:collapse;background:#fff}
|
||||
.clicd-table th,.clicd-table td{border:1px solid #e5e7eb;padding:8px;text-align:left}
|
||||
.clicd-table th{width:16%;background:#f9fafb;color:#374151;font-weight:600}
|
||||
.clicd-debug{display:none;margin-top:10px;padding:8px;background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;border-radius:6px;font-size:12px}
|
||||
@media (max-width:640px){
|
||||
.clicd-info{padding:10px}
|
||||
.clicd-section-title{align-items:flex-start}
|
||||
.clicd-refresh{justify-content:flex-start;width:100%}
|
||||
.clicd-charts{grid-template-columns:1fr}
|
||||
.clicd-table th,.clicd-table td{display:block;width:100%}
|
||||
.clicd-ring{width:70px;height:70px}
|
||||
.clicd-ring:before{width:60px;height:60px}
|
||||
.clicd-ring span{max-width:56px;font-size:15px}
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="clicd-info" data-clicd-info-root="1">
|
||||
<div class="clicd-head">
|
||||
<div class="clicd-mini">
|
||||
<div class="clicd-mini-label">实例名称</div>
|
||||
<div class="clicd-mini-value">{$container.name|default='-'}</div>
|
||||
</div>
|
||||
<div class="clicd-mini">
|
||||
<div class="clicd-mini-label">运行状态</div>
|
||||
<div class="clicd-mini-value">{$status_text|default='-'}</div>
|
||||
</div>
|
||||
<div class="clicd-mini">
|
||||
<div class="clicd-mini-label">SSH 地址</div>
|
||||
<div class="clicd-mini-value">{$ssh_host|default='-'}:{$ssh_port|default='-'}</div>
|
||||
</div>
|
||||
<div class="clicd-mini">
|
||||
<div class="clicd-mini-label">IPv6</div>
|
||||
<div class="clicd-mini-value">{$ipv6|default='-'}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-section">
|
||||
<div class="clicd-section-title">
|
||||
<span>状态</span>
|
||||
<span class="clicd-refresh">
|
||||
<span>更新于 <span data-clicd-info="chart_time">-</span></span>
|
||||
<label>
|
||||
自动刷新
|
||||
<select class="clicd-refresh-select" id="clicd-info-refresh">
|
||||
<option value="0" selected>不刷新</option>
|
||||
<option value="10000">10 秒</option>
|
||||
<option value="60000">1 分钟</option>
|
||||
<option value="300000">5 分钟</option>
|
||||
<option value="600000">10 分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<button class="clicd-refresh-btn" type="button" id="clicd-info-refresh-now">立即刷新</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="clicd-gauges">
|
||||
<div class="clicd-gauge">
|
||||
<div class="clicd-ring" data-gauge="cpu_percent"><span><span data-clicd-info="cpu_percent">0</span>%</span></div>
|
||||
<div>
|
||||
<div class="clicd-gauge-title">CPU</div>
|
||||
<div class="clicd-gauge-sub" data-clicd-info="cpu_detail">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clicd-gauge">
|
||||
<div class="clicd-ring" data-gauge="mem_percent"><span><span data-clicd-info="mem_percent">0</span>%</span></div>
|
||||
<div>
|
||||
<div class="clicd-gauge-title">内存</div>
|
||||
<div class="clicd-gauge-sub" data-clicd-info="mem_detail">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clicd-gauge">
|
||||
<div class="clicd-ring" data-gauge="load_percent"><span><span data-clicd-info="load_percent">0</span>%</span></div>
|
||||
<div>
|
||||
<div class="clicd-gauge-title">负载</div>
|
||||
<div class="clicd-gauge-sub" data-clicd-info="load_detail">-</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clicd-gauge">
|
||||
<div class="clicd-ring" data-gauge="disk_percent"><span><span data-clicd-info="disk_percent">0</span>%</span></div>
|
||||
<div>
|
||||
<div class="clicd-gauge-title">磁盘</div>
|
||||
<div class="clicd-gauge-sub" data-clicd-info="disk_detail">-</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-top:14px">
|
||||
<div class="clicd-traffic-row">
|
||||
<div>月流量</div>
|
||||
<div><span data-clicd-info="traffic_used_text">{$traffic_used_text|default='-'}</span> / <span data-clicd-info="traffic_limit_text">{$traffic_limit_text|default='-'}</span></div>
|
||||
</div>
|
||||
<div class="clicd-progress"><span data-progress="traffic_percent"></span></div>
|
||||
<div class="clicd-traffic-row" style="font-size:12px;color:#6b7280">
|
||||
<div>入站 <span data-clicd-info="traffic_in_text">{$traffic_in_text|default='-'}</span></div>
|
||||
<div>出站 <span data-clicd-info="traffic_out_text">{$traffic_out_text|default='-'}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-section">
|
||||
<div class="clicd-section-title"><span>统计信息</span></div>
|
||||
<div class="clicd-charts">
|
||||
<div class="clicd-chart">
|
||||
<div class="clicd-chart-title">CPU 使用率 <span class="clicd-chart-value" data-clicd-info="cpu_detail">-</span></div>
|
||||
<canvas data-chart="cpu_percent"></canvas>
|
||||
</div>
|
||||
<div class="clicd-chart">
|
||||
<div class="clicd-chart-title">内存使用 <span class="clicd-chart-value" data-clicd-info="mem_detail">-</span></div>
|
||||
<canvas data-chart="mem_percent"></canvas>
|
||||
</div>
|
||||
<div class="clicd-chart">
|
||||
<div class="clicd-chart-title">网络流量 <span class="clicd-chart-value"><span data-clicd-info="net_in_rate">0 B/s</span> / <span data-clicd-info="net_out_rate">0 B/s</span></span></div>
|
||||
<canvas data-chart="network"></canvas>
|
||||
</div>
|
||||
<div class="clicd-chart">
|
||||
<div class="clicd-chart-title">磁盘 IO <span class="clicd-chart-value"><span data-clicd-info="disk_read_rate">0 B/s</span> / <span data-clicd-info="disk_write_rate">0 B/s</span></span></div>
|
||||
<canvas data-chart="diskio"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-section">
|
||||
<div class="clicd-section-title"><span>实例信息</span></div>
|
||||
<table class="clicd-table">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>IPv4</th><td>{$ipv4|default='-'}</td>
|
||||
<th>用户名</th><td>root</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>SSH 端口</th><td>{$ssh_port|default='-'}</td>
|
||||
<th>SSH 密码</th><td>{$ssh_password|default='-'}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>CPU</th><td>{$vcpu|default='-'} 核</td>
|
||||
<th>内存</th><td>{$ram_mb|default='-'} MB</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>硬盘</th><td>{$disk_gb|default='-'} GB</td>
|
||||
<th>带宽</th><td>{$bandwidth|default='-'} Mbps</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>到期时间</th><td colspan="3">{$expires_at|default='-'}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="clicd-debug" id="clicd-info-debug"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function(){
|
||||
var root = document.querySelector('[data-clicd-info-root="1"]:not([data-info-bound="1"])');
|
||||
if (!root) return;
|
||||
root.setAttribute('data-info-bound', '1');
|
||||
|
||||
var history = {
|
||||
cpu_percent: [],
|
||||
mem_percent: [],
|
||||
network_in: [],
|
||||
network_out: [],
|
||||
disk_read: [],
|
||||
disk_write: []
|
||||
};
|
||||
var maxPoints = 18;
|
||||
var refreshTimer = null;
|
||||
|
||||
function endpoint() {
|
||||
return "{$MODULE_CUSTOM_API}";
|
||||
}
|
||||
|
||||
function number(value) {
|
||||
var n = parseFloat(value);
|
||||
return isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
function push(name, value) {
|
||||
history[name].push(number(value));
|
||||
if (history[name].length > maxPoints) history[name].shift();
|
||||
}
|
||||
|
||||
function setText(key, value) {
|
||||
root.querySelectorAll('[data-clicd-info="' + key + '"]').forEach(function(node){
|
||||
if (typeof value !== 'object') node.textContent = value;
|
||||
});
|
||||
}
|
||||
|
||||
function setGauge(key, value) {
|
||||
var pct = Math.max(0, Math.min(100, number(value)));
|
||||
root.querySelectorAll('[data-gauge="' + key + '"]').forEach(function(node){
|
||||
node.style.setProperty('--p', pct + '%');
|
||||
});
|
||||
}
|
||||
|
||||
function fitGaugeText() {
|
||||
root.querySelectorAll('.clicd-ring').forEach(function(ring){
|
||||
var label = ring.querySelector('span');
|
||||
if (!label) return;
|
||||
ring.removeAttribute('data-tight');
|
||||
if (label.scrollWidth > label.clientWidth) {
|
||||
ring.setAttribute('data-tight', '1');
|
||||
}
|
||||
if (label.scrollWidth > label.clientWidth) {
|
||||
ring.setAttribute('data-tight', '2');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setProgress(key, value) {
|
||||
var pct = Math.max(0, Math.min(100, number(value)));
|
||||
root.querySelectorAll('[data-progress="' + key + '"]').forEach(function(node){
|
||||
node.style.width = pct + '%';
|
||||
});
|
||||
}
|
||||
|
||||
function draw(canvas, series, colors, maxValue) {
|
||||
if (!canvas || !canvas.getContext) return;
|
||||
var rect = canvas.getBoundingClientRect();
|
||||
var ratio = window.devicePixelRatio || 1;
|
||||
var width = Math.max(220, Math.floor(rect.width || canvas.clientWidth || 220));
|
||||
var height = Math.max(120, Math.floor(rect.height || canvas.clientHeight || 132));
|
||||
if (canvas.width !== width * ratio || canvas.height !== height * ratio) {
|
||||
canvas.width = width * ratio;
|
||||
canvas.height = height * ratio;
|
||||
}
|
||||
var ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
ctx.strokeStyle = '#e5e7eb';
|
||||
ctx.lineWidth = 1;
|
||||
for (var i = 1; i < 4; i++) {
|
||||
var y = Math.round((height / 4) * i);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, y);
|
||||
ctx.lineTo(width, y);
|
||||
ctx.stroke();
|
||||
}
|
||||
series.forEach(function(values, idx){
|
||||
if (!values.length) return;
|
||||
var color = colors[idx] || '#2f80ed';
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
if (values.length === 1) {
|
||||
var singleY = height - (Math.max(0, Math.min(maxValue, number(values[0]))) / maxValue) * (height - 6) - 3;
|
||||
ctx.moveTo(0, singleY);
|
||||
ctx.lineTo(width, singleY);
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = color;
|
||||
ctx.beginPath();
|
||||
ctx.arc(width - 8, singleY, 3, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
return;
|
||||
}
|
||||
values.forEach(function(value, i){
|
||||
var x = values.length <= 1 ? width : (i / (values.length - 1)) * width;
|
||||
var y = height - (Math.max(0, Math.min(maxValue, number(value))) / maxValue) * (height - 6) - 3;
|
||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
||||
});
|
||||
ctx.stroke();
|
||||
});
|
||||
}
|
||||
|
||||
function redraw() {
|
||||
draw(root.querySelector('[data-chart="cpu_percent"]'), [history.cpu_percent], ['#2f80ed'], 100);
|
||||
draw(root.querySelector('[data-chart="mem_percent"]'), [history.mem_percent], ['#10b981'], 100);
|
||||
var netMax = Math.max(1, Math.max.apply(null, history.network_in.concat(history.network_out, [1])));
|
||||
draw(root.querySelector('[data-chart="network"]'), [history.network_in, history.network_out], ['#2f80ed', '#f59e0b'], netMax);
|
||||
var ioMax = Math.max(1, Math.max.apply(null, history.disk_read.concat(history.disk_write, [1])));
|
||||
draw(root.querySelector('[data-chart="diskio"]'), [history.disk_read, history.disk_write], ['#10b981', '#ef4444'], ioMax);
|
||||
}
|
||||
|
||||
function showInfoError(text) {
|
||||
var debug = document.getElementById('clicd-info-debug');
|
||||
if (debug) {
|
||||
debug.style.display = 'block';
|
||||
debug.textContent = text || 'info load failed';
|
||||
}
|
||||
}
|
||||
|
||||
function loadInfo() {
|
||||
var refreshNow = document.getElementById('clicd-info-refresh-now');
|
||||
if (refreshNow) refreshNow.disabled = true;
|
||||
var body = new URLSearchParams();
|
||||
body.set('id', '{$service_id}');
|
||||
body.set('func', 'infoData');
|
||||
fetch(endpoint(), {
|
||||
method:'POST',
|
||||
headers:{
|
||||
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'Authorization':'JWT {$Think.get.jwt}'
|
||||
},
|
||||
credentials:'same-origin',
|
||||
body: body.toString()
|
||||
})
|
||||
.then(function(res){ return res.json(); })
|
||||
.then(function(json){
|
||||
if (!json || (json.status !== 200 && json.status !== 'success') || !json.data) {
|
||||
showInfoError(json && json.msg ? json.msg : 'info load failed');
|
||||
return;
|
||||
}
|
||||
var data = json.data;
|
||||
Object.keys(data).forEach(function(key){ setText(key, data[key]); });
|
||||
['cpu_percent','mem_percent','load_percent','disk_percent'].forEach(function(key){ setGauge(key, data[key]); });
|
||||
fitGaugeText();
|
||||
setProgress('traffic_percent', data.traffic_percent);
|
||||
push('cpu_percent', data.cpu_percent);
|
||||
push('mem_percent', data.mem_percent);
|
||||
push('network_in', data.net_in_bps);
|
||||
push('network_out', data.net_out_bps);
|
||||
push('disk_read', data.disk_read_bps);
|
||||
push('disk_write', data.disk_write_bps);
|
||||
redraw();
|
||||
})
|
||||
.catch(function(error){
|
||||
showInfoError(error && error.message ? error.message : 'info request failed');
|
||||
})
|
||||
.finally(function(){
|
||||
if (refreshNow) refreshNow.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
loadInfo();
|
||||
var refreshSelect = document.getElementById('clicd-info-refresh');
|
||||
var refreshNow = document.getElementById('clicd-info-refresh-now');
|
||||
if (refreshNow) {
|
||||
refreshNow.addEventListener('click', loadInfo);
|
||||
}
|
||||
if (refreshSelect) {
|
||||
refreshSelect.addEventListener('change', function(){
|
||||
if (refreshTimer) {
|
||||
window.clearInterval(refreshTimer);
|
||||
refreshTimer = null;
|
||||
}
|
||||
var ms = number(refreshSelect.value);
|
||||
if (ms > 0) {
|
||||
loadInfo();
|
||||
refreshTimer = window.setInterval(loadInfo, ms);
|
||||
}
|
||||
});
|
||||
}
|
||||
window.addEventListener('resize', function(){ window.setTimeout(function(){ fitGaugeText(); redraw(); }, 50); });
|
||||
})();
|
||||
</script>
|
||||
@@ -0,0 +1,328 @@
|
||||
<style>
|
||||
.clicd-nat-panel{font-size:14px;color:#1f2937}
|
||||
.clicd-nat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px}
|
||||
.clicd-nat-card{border:1px solid #e5e7eb;border-radius:6px;padding:12px;background:#fff}
|
||||
.clicd-nat-label{color:#6b7280;font-size:12px;margin-bottom:4px}
|
||||
.clicd-nat-value{font-size:18px;font-weight:600;word-break:break-all}
|
||||
.clicd-nat-title{font-weight:600;margin:18px 0 8px}
|
||||
.clicd-nat-muted{color:#6b7280}
|
||||
.clicd-nat-form{border:1px solid #e5e7eb;border-radius:6px;background:#fff;padding:12px;margin-top:8px}
|
||||
.clicd-nat-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;align-items:end}
|
||||
.clicd-nat-field label{display:block;color:#6b7280;font-size:12px;margin-bottom:4px}
|
||||
.clicd-nat-input,.clicd-nat-select{width:100%;height:34px;border:1px solid #d1d5db;border-radius:4px;padding:6px 8px;box-sizing:border-box}
|
||||
.clicd-nat-actions{display:flex;gap:8px;flex-wrap:wrap}
|
||||
.clicd-nat-btn{height:34px;border:1px solid #2563eb;background:#2563eb;color:#fff;border-radius:4px;padding:0 12px;cursor:pointer}
|
||||
.clicd-nat-btn[disabled]{opacity:.6;cursor:not-allowed}
|
||||
.clicd-nat-btn-secondary{border-color:#d1d5db;background:#fff;color:#374151}
|
||||
.clicd-nat-btn-danger{border-color:#dc2626;background:#dc2626;color:#fff}
|
||||
.clicd-nat-list{display:flex;flex-direction:column;gap:10px;margin-top:8px}
|
||||
.clicd-nat-item{border:1px solid #e5e7eb;border-radius:6px;background:#fff;padding:12px}
|
||||
.clicd-nat-message{border:1px solid #bfdbfe;background:#eff6ff;color:#1d4ed8;border-radius:6px;padding:10px 12px;margin-bottom:12px;display:none}
|
||||
.clicd-nat-message.error{border-color:#fecaca;background:#fef2f2;color:#b91c1c}
|
||||
.clicd-nat-debug{margin-top:12px;border:1px dashed #d1d5db;border-radius:6px;background:#f9fafb;padding:10px;color:#374151;white-space:pre-wrap;font-size:12px;display:none}
|
||||
.clicd-nat-modal-mask{position:fixed;inset:0;background:rgba(15,23,42,.42);display:none;align-items:center;justify-content:center;z-index:9999;padding:16px}
|
||||
.clicd-nat-modal{width:min(420px,100%);background:#fff;border-radius:6px;border:1px solid #e5e7eb;box-shadow:0 18px 48px rgba(15,23,42,.22);padding:16px}
|
||||
.clicd-nat-modal-title{font-size:16px;font-weight:700;color:#111827;margin-bottom:8px}
|
||||
.clicd-nat-modal-body{font-size:14px;color:#4b5563;line-height:1.6;margin-bottom:14px}
|
||||
.clicd-nat-modal-actions{display:flex;justify-content:flex-end;gap:8px}
|
||||
</style>
|
||||
|
||||
<div class="clicd-nat-panel" id="clicd-nat-panel" data-service-id="{$service_id}" data-area-key="{$area_key}">
|
||||
<div class="clicd-nat-message" id="clicd-nat-message"></div>
|
||||
|
||||
<div class="clicd-nat-grid">
|
||||
<div class="clicd-nat-card">
|
||||
<div class="clicd-nat-label">实例名称</div>
|
||||
<div class="clicd-nat-value">{$container_name}</div>
|
||||
</div>
|
||||
<div class="clicd-nat-card">
|
||||
<div class="clicd-nat-label">公网地址</div>
|
||||
<div class="clicd-nat-value">{$nat_host}</div>
|
||||
</div>
|
||||
<div class="clicd-nat-card">
|
||||
<div class="clicd-nat-label">SSH 端口</div>
|
||||
<div class="clicd-nat-value">{$ssh_port}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-nat-title">添加端口映射</div>
|
||||
<div class="clicd-nat-form">
|
||||
<div class="clicd-nat-row">
|
||||
<div class="clicd-nat-field">
|
||||
<label>公网端口</label>
|
||||
<input class="clicd-nat-input" id="clicd-add-host-port" type="number" min="1" max="65535" placeholder="61320">
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>容器端口</label>
|
||||
<input class="clicd-nat-input" id="clicd-add-container-port" type="number" min="1" max="65535" placeholder="8080">
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>协议</label>
|
||||
<select class="clicd-nat-select" id="clicd-add-protocol">
|
||||
<option value="tcp">TCP</option>
|
||||
<option value="udp">UDP</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>说明</label>
|
||||
<input class="clicd-nat-input" id="clicd-add-description" type="text" placeholder="HTTP">
|
||||
</div>
|
||||
<div class="clicd-nat-actions">
|
||||
<button class="clicd-nat-btn" type="button" data-clicd-action="add">添加</button>
|
||||
<button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" data-clicd-action="random-port">获取随机端口</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="clicd-nat-title">现有端口映射</div>
|
||||
<div id="clicd-nat-list" class="clicd-nat-list">
|
||||
{if condition="empty($port_mappings)"}
|
||||
<div class="clicd-nat-form clicd-nat-muted">暂无端口映射</div>
|
||||
{else/}
|
||||
{foreach name="port_mappings" item="mapping"}
|
||||
<div class="clicd-nat-item" data-index="{$mapping.index}">
|
||||
<div class="clicd-nat-row">
|
||||
<div class="clicd-nat-field">
|
||||
<label>索引</label>
|
||||
<div class="clicd-nat-value">{$mapping.index}</div>
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>公网访问</label>
|
||||
<div class="clicd-nat-value">{$nat_host}:{$mapping.host_port}</div>
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>公网端口</label>
|
||||
<input class="clicd-nat-input" data-field="host_port" type="number" min="1" max="65535" value="{$mapping.host_port}">
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>容器端口</label>
|
||||
<input class="clicd-nat-input" data-field="container_port" type="number" min="1" max="65535" value="{$mapping.container_port}">
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>协议</label>
|
||||
<select class="clicd-nat-select" data-field="protocol">
|
||||
<option value="tcp" {$mapping.tcp_selected}>TCP</option>
|
||||
<option value="udp" {$mapping.udp_selected}>UDP</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="clicd-nat-field">
|
||||
<label>说明</label>
|
||||
<input class="clicd-nat-input" data-field="description" type="text" value="{$mapping.description}">
|
||||
</div>
|
||||
<div class="clicd-nat-actions">
|
||||
<button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" data-clicd-action="update">保存</button>
|
||||
<button class="clicd-nat-btn clicd-nat-btn-danger" type="button" data-clicd-action="delete">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/foreach}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<pre class="clicd-nat-debug" id="clicd-nat-debug"></pre>
|
||||
<div class="clicd-nat-modal-mask" id="clicd-nat-delete-modal">
|
||||
<div class="clicd-nat-modal">
|
||||
<div class="clicd-nat-modal-title">确认删除</div>
|
||||
<div class="clicd-nat-modal-body" id="clicd-nat-delete-text">确认删除该端口映射?</div>
|
||||
<div class="clicd-nat-modal-actions">
|
||||
<button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" id="clicd-nat-delete-cancel">取消</button>
|
||||
<button class="clicd-nat-btn clicd-nat-btn-danger" type="button" id="clicd-nat-delete-confirm">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function(){
|
||||
var panel = document.getElementById('clicd-nat-panel');
|
||||
if (!panel || panel.getAttribute('data-bound') === '1') return;
|
||||
panel.setAttribute('data-bound', '1');
|
||||
|
||||
var message = document.getElementById('clicd-nat-message');
|
||||
var debugBox = document.getElementById('clicd-nat-debug');
|
||||
var list = document.getElementById('clicd-nat-list');
|
||||
var natHost = '{$nat_host}';
|
||||
var deleteModal = document.getElementById('clicd-nat-delete-modal');
|
||||
var deleteText = document.getElementById('clicd-nat-delete-text');
|
||||
var deleteCancel = document.getElementById('clicd-nat-delete-cancel');
|
||||
var deleteConfirm = document.getElementById('clicd-nat-delete-confirm');
|
||||
var pendingDeletePayload = null;
|
||||
|
||||
function showMessage(type, text) {
|
||||
message.className = 'clicd-nat-message' + (type === 'error' ? ' error' : '');
|
||||
message.style.display = 'block';
|
||||
message.textContent = text || '';
|
||||
}
|
||||
|
||||
function showDebug(data) {
|
||||
debugBox.style.display = 'block';
|
||||
debugBox.textContent = JSON.stringify(data || {}, null, 2);
|
||||
}
|
||||
|
||||
function endpoint() {
|
||||
return "{$MODULE_CUSTOM_API}";
|
||||
}
|
||||
|
||||
function field(item, name) {
|
||||
return item.querySelector('[data-field="' + name + '"]');
|
||||
}
|
||||
|
||||
function setBusy(busy) {
|
||||
panel.querySelectorAll('button').forEach(function(btn){ btn.disabled = !!busy; });
|
||||
}
|
||||
|
||||
function renderList(items) {
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
list.innerHTML = '<div class="clicd-nat-form clicd-nat-muted">暂无端口映射</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = items.map(function(item) {
|
||||
var protocol = (item.protocol || 'tcp').toLowerCase();
|
||||
var desc = escapeHtml(item.description || '');
|
||||
var index = escapeHtml(String(item.index));
|
||||
var hostPort = escapeHtml(String(item.host_port || ''));
|
||||
var containerPort = escapeHtml(String(item.container_port || ''));
|
||||
return '<div class="clicd-nat-item" data-index="' + index + '">' +
|
||||
'<div class="clicd-nat-row">' +
|
||||
'<div class="clicd-nat-field"><label>索引</label><div class="clicd-nat-value">' + index + '</div></div>' +
|
||||
'<div class="clicd-nat-field"><label>公网访问</label><div class="clicd-nat-value">' + escapeHtml(natHost) + ':' + hostPort + '</div></div>' +
|
||||
'<div class="clicd-nat-field"><label>公网端口</label><input class="clicd-nat-input" data-field="host_port" type="number" min="1" max="65535" value="' + hostPort + '"></div>' +
|
||||
'<div class="clicd-nat-field"><label>容器端口</label><input class="clicd-nat-input" data-field="container_port" type="number" min="1" max="65535" value="' + containerPort + '"></div>' +
|
||||
'<div class="clicd-nat-field"><label>协议</label><select class="clicd-nat-select" data-field="protocol">' +
|
||||
'<option value="tcp"' + (protocol === 'tcp' ? ' selected' : '') + '>TCP</option>' +
|
||||
'<option value="udp"' + (protocol === 'udp' ? ' selected' : '') + '>UDP</option>' +
|
||||
'</select></div>' +
|
||||
'<div class="clicd-nat-field"><label>说明</label><input class="clicd-nat-input" data-field="description" type="text" value="' + desc + '"></div>' +
|
||||
'<div class="clicd-nat-actions"><button class="clicd-nat-btn clicd-nat-btn-secondary" type="button" data-clicd-action="update">保存</button>' +
|
||||
'<button class="clicd-nat-btn clicd-nat-btn-danger" type="button" data-clicd-action="delete">删除</button></div>' +
|
||||
'</div></div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
async function request(action, payload, silent) {
|
||||
setBusy(true);
|
||||
try {
|
||||
var funcMap = {
|
||||
'random-port': 'randomPort',
|
||||
'add': 'addNat',
|
||||
'update': 'updateNat',
|
||||
'delete': 'deleteNat',
|
||||
'list': 'natList'
|
||||
};
|
||||
var body = new URLSearchParams();
|
||||
body.set('id', panel.getAttribute('data-service-id') || '');
|
||||
body.set('func', funcMap[action] || action);
|
||||
Object.keys(payload || {}).forEach(function(key){ body.set(key, payload[key]); });
|
||||
var res = await fetch(endpoint(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'Authorization': 'JWT {$Think.get.jwt}'
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
body: body.toString()
|
||||
});
|
||||
var text = await res.text();
|
||||
var data;
|
||||
try { data = JSON.parse(text); } catch (e) { data = {status:'error', msg:'\u975e JSON \u54cd\u5e94: ' + text}; }
|
||||
showDebug((data.data && data.data.debug) || data.debug || data);
|
||||
if (data.status === 200 || data.status === 'success') {
|
||||
if (!silent) {
|
||||
showMessage('success', data.msg || '\u64cd\u4f5c\u6210\u529f');
|
||||
}
|
||||
if (data.data && data.data.port) {
|
||||
document.getElementById('clicd-add-host-port').value = data.data.port;
|
||||
}
|
||||
if (data.data && Array.isArray(data.data.port_mappings)) {
|
||||
renderList(data.data.port_mappings);
|
||||
} else if (action !== 'random-port') {
|
||||
request('list', {}, true);
|
||||
}
|
||||
} else {
|
||||
showMessage('error', data.msg || '\u64cd\u4f5c\u5931\u8d25');
|
||||
}
|
||||
} catch (e) {
|
||||
showMessage('error', e.message || '\u8bf7\u6c42\u5931\u8d25');
|
||||
showDebug({error: String(e)});
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openDeleteModal(payload) {
|
||||
pendingDeletePayload = payload;
|
||||
if (deleteText) {
|
||||
deleteText.textContent = '\u786e\u8ba4\u5220\u9664\u7aef\u53e3\u6620\u5c04 ' + natHost + ':' + (payload.host_port || '-') + ' -> ' + (payload.container_port || '-') + '/' + (payload.protocol || 'tcp') + ' \u5417\uff1f';
|
||||
}
|
||||
if (deleteModal) {
|
||||
deleteModal.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
|
||||
function closeDeleteModal() {
|
||||
pendingDeletePayload = null;
|
||||
if (deleteModal) {
|
||||
deleteModal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
panel.addEventListener('click', function(event) {
|
||||
var button = event.target.closest('[data-clicd-action]');
|
||||
if (!button) return;
|
||||
var action = button.getAttribute('data-clicd-action');
|
||||
if (action === 'random-port') {
|
||||
request('random-port', {});
|
||||
return;
|
||||
}
|
||||
if (action === 'add') {
|
||||
request('add', {
|
||||
host_port: document.getElementById('clicd-add-host-port').value,
|
||||
container_port: document.getElementById('clicd-add-container-port').value,
|
||||
protocol: document.getElementById('clicd-add-protocol').value,
|
||||
description: document.getElementById('clicd-add-description').value
|
||||
});
|
||||
return;
|
||||
}
|
||||
var item = button.closest('.clicd-nat-item');
|
||||
if (!item) return;
|
||||
var payload = {
|
||||
index: item.getAttribute('data-index'),
|
||||
host_port: field(item, 'host_port') ? field(item, 'host_port').value : '',
|
||||
container_port: field(item, 'container_port') ? field(item, 'container_port').value : '',
|
||||
protocol: field(item, 'protocol') ? field(item, 'protocol').value : 'tcp',
|
||||
description: field(item, 'description') ? field(item, 'description').value : ''
|
||||
};
|
||||
if (action === 'delete') {
|
||||
openDeleteModal(payload);
|
||||
return;
|
||||
}
|
||||
request(action, payload);
|
||||
});
|
||||
|
||||
if (deleteCancel) {
|
||||
deleteCancel.addEventListener('click', closeDeleteModal);
|
||||
}
|
||||
if (deleteModal) {
|
||||
deleteModal.addEventListener('click', function(event){
|
||||
if (event.target === deleteModal) closeDeleteModal();
|
||||
});
|
||||
}
|
||||
if (deleteConfirm) {
|
||||
deleteConfirm.addEventListener('click', function(){
|
||||
if (!pendingDeletePayload) return;
|
||||
var payload = pendingDeletePayload;
|
||||
closeDeleteModal();
|
||||
request('delete', payload);
|
||||
});
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
@@ -2,10 +2,10 @@
|
||||
<img src="frontend/public/favicon.svg" width="96" alt="CLICD">
|
||||
</p>
|
||||
|
||||
<h1 align="center">CLICD</h1>
|
||||
<h1 align="center">CLICD <sub><sup>v1.1.18</sup></sub></h1>
|
||||
|
||||
<p align="center">
|
||||
<img alt="Go" src="https://img.shields.io/badge/Go-1.22-00ADD8?style=flat-square&logo=go&logoColor=white">
|
||||
<img alt="Go" src="https://img.shields.io/badge/Go-1.24-00ADD8?style=flat-square&logo=go&logoColor=white">
|
||||
<img alt="React" src="https://img.shields.io/badge/React-18-61DAFB?style=flat-square&logo=react&logoColor=111111">
|
||||
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5-3178C6?style=flat-square&logo=typescript&logoColor=white">
|
||||
<img alt="Vite" src="https://img.shields.io/badge/Vite-5-646CFF?style=flat-square&logo=vite&logoColor=white">
|
||||
@@ -27,41 +27,11 @@
|
||||
<img alt="TLS" src="https://img.shields.io/badge/TLS-Let's_Encrypt-003A70?style=flat-square&logo=letsencrypt&logoColor=white">
|
||||
</p>
|
||||
|
||||
CLICD is a lightweight virtualization management panel for LXC and KVM, featuring a web console, CLI management, batch operations, image management, NAT networking, IPv6 allocation, WebSSH, VNC access, resource controls, bandwidth limiting, and security alerting.
|
||||
It is designed for managing LXC containers and KVM virtual machines on VPS servers, and is particularly suitable for environments that require bulk provisioning and delegated access management through sub-user management links.
|
||||
CLICD is a lightweight virtualization management panel for LXC and KVM. It combines a web console, CLI tools, REST API, NAT/IPv6 networking, WebSSH/WebVNC access, resource quotas, traffic limits, snapshots, delegated sub-user access, and security alerts into a single deployable service.
|
||||
|
||||
CLICD 是一个面向 LXC/KVM 的轻量虚拟化管理面板,提供 Web 控制台、CLI、批量任务、镜像管理、NAT 端口、IPv6 分配、WebSSH、VNC、资源限制、流量限制和安全告警能力。它适合用来管理小型 VPS 上的 LXC 容器和 KVM 虚拟机,也适合需要批量创建和分发子用户管理链接的场景。
|
||||
CLICD 是一个面向 LXC/KVM 的轻量虚拟化管理面板,集成 Web 控制台、CLI、REST API、NAT/IPv6 网络、WebSSH/WebVNC、资源配额、流量限制、快照、子用户授权和安全告警能力,适合 VPS 商家、实验室、开发者自建虚拟化节点以及需要批量开通容器的场景。
|
||||
|
||||
## Features / 功能介绍
|
||||
|
||||
### English
|
||||
1. Supports Ubuntu, Debian, Alpine, CentOS, Arch Linux, Fedora, Rocky Linux, and other operating system images. Images can be downloaded on demand through the image management interface. For hosts with limited resources, lightweight distributions such as Alpine are recommended.
|
||||
2. Supports WebSSH management, allowing users to access container terminals directly from the browser without manually copying SSH credentials.
|
||||
3. Supports NAT4 port quotas, port forwarding, and protocol restrictions, as well as public IPv6 allocation. IPv6 assignment requires the host machine to have a routable IPv6 prefix.
|
||||
4. Supports both inbound and outbound traffic limits. Containers are automatically powered off when configured limits are reached, preventing bandwidth overuse.
|
||||
5. Supports container expiration dates. Expired containers are automatically shut down, and delegated users lose access until an administrator extends the expiration period.
|
||||
6. Includes lightweight conntrack-based security monitoring. The system does not store full logs of normal connections, but generates audit alerts for suspicious activities such as port scanning, lateral scanning, brute-force attempts, SMTP abuse, UDP reflection attacks, cryptocurrency mining ports, and proxy/VPN/Tor usage.
|
||||
7. Supports delegated management links. Administrators can assign specific containers to sub-users, while ensuring that each user can only manage the containers explicitly authorized to them.
|
||||
8. Provides a REST API for automating the management of containers, tasks, images, networking, traffic controls, and security alerts.
|
||||
9. Supports operating entirely through the CLI. When the web console is not required, administrators can stop and disable the systemd service and launch CLI-only mode using `clicd cli --no-web`.
|
||||
|
||||
### 中文
|
||||
1. 支持 Ubuntu、Debian、Alpine、CentOS、Arch Linux、Fedora、Rocky Linux 等系统镜像。镜像可以在镜像管理中按需下载;如果宿主机资源比较小,建议优先选择 Alpine 这类轻量镜像。
|
||||
2. 支持 WebSSH 管理,可以在浏览器里一键进入容器终端,不需要手动复制 SSH 密码。
|
||||
3. 支持设置 NAT4 端口数量、NAT 端口映射和协议限制,并支持分配公网 IPv6。IPv6 分配要求宿主机本身拥有可路由的 IPv6 地址段。
|
||||
4. 支持单向和双向网络流量限制。达到限制后容器会自动关机,避免流量超额。
|
||||
5. 支持设置容器有效期。到期后容器会自动关机,子用户无法继续操作,只有管理员重新设置延期日期后才能恢复使用。
|
||||
6. 内置基于 conntrack 的轻量安全告警。系统不会保存完整正常连接日志,但会对端口扫描、横向扫描、爆破倾向、SMTP 滥用、UDP 反射、挖矿端口、代理/VPN/Tor 等可疑行为生成告警并写入审计日志。
|
||||
7. 支持子用户管理链接,管理员可以把指定容器分发给拼车用户,子用户只能管理自己被授权的容器。
|
||||
8. 支持 API 接入,可以通过 API 完成容器、任务、镜像、端口、流量、安全告警等功能的自动化控制。
|
||||
9. 支持仅使用 CLI 管理。需要关闭 Web 控制台时,可以停止并禁用 systemd 服务,然后使用 `clicd cli --no-web` 进入命令行模式。
|
||||
|
||||
## Technology Stack / 技术栈
|
||||
|
||||
- Backend: Go, net/http, LXC, KVM/libvirt, cgroup v2, iptables, conntrack
|
||||
- Frontend: React, TypeScript, Vite, Tailwind CSS, lucide-react, xterm.js
|
||||
- Runtime: Linux, systemd, LXC, KVM/QEMU
|
||||
- Build: GitHub Actions, Node.js 20, Go 1.22
|
||||

|
||||
|
||||
## Installation / 安装
|
||||
|
||||
@@ -77,9 +47,52 @@ One-click Uninstall / 一键卸载:
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh -s -- uninstall
|
||||
```
|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
## Features / 功能介绍
|
||||
|
||||
### English
|
||||
|
||||
| Area | What CLICD provides |
|
||||
| --- | --- |
|
||||
| Virtualization | Manage LXC containers and KVM virtual machines from one panel, including create, reinstall, start, stop, restart, delete, password reset, expiry control, and batch actions. |
|
||||
| Images and templates | Built-in template and image management for Ubuntu, Debian, Alpine, CentOS, Arch Linux, Fedora, Rocky Linux, and other common distributions. Images can be enabled, disabled, downloaded, cancelled, or removed from cache. |
|
||||
| Networking | NAT4 port quotas, random available port allocation, TCP/UDP port mappings, public IPv4 pool management, IPv6 prefix detection, IPv6 status checks, and per-container IPv6 assignment. |
|
||||
| Resource control | CPU, memory, disk, swap, bandwidth usage, traffic reset, traffic limit, and resource limit management, with automatic shutdown behavior for expired or over-quota containers. |
|
||||
| Console access | Browser-based WebSSH and WebVNC ticket access, so users can open terminals or consoles without manually exchanging credentials. |
|
||||
| Snapshots | Snapshot overview, per-container snapshots, create/delete/restore operations, scheduled snapshots, and quota controls. |
|
||||
| Security | Conntrack-based security alerts for port scans, lateral scans, brute-force behavior, SMTP abuse, UDP reflection, mining ports, proxy/VPN/Tor usage, plus security logs, summaries, and configurable settings. |
|
||||
| Accounts and audit | Delegated sub-user links, sub-user password rotation, per-user container permissions, audit logs, login logs, and API key management. |
|
||||
| Automation | Versioned REST API under `/api/v1`, task queue endpoints, batch create/action endpoints, and a Mofang finance integration module packaged automatically by GitHub Actions. |
|
||||
| Operations | Dashboard statistics, host resource overview, routing overview, swap management, CLI-only mode, and release artifacts generated by GitHub Actions. |
|
||||
|
||||
### 中文
|
||||
|
||||
| 模块 | CLICD 提供的能力 |
|
||||
| --- | --- |
|
||||
| 虚拟化管理 | 在同一个面板里管理 LXC 容器和 KVM 虚拟机,支持创建、重装、开机、关机、重启、删除、重置密码、到期时间和批量操作。 |
|
||||
| 镜像与模板 | 内置模板和镜像管理,支持 Ubuntu、Debian、Alpine、CentOS、Arch Linux、Fedora、Rocky Linux 等常见发行版,镜像可按需下载、取消、启用、禁用和清理缓存。 |
|
||||
| 网络能力 | 支持 NAT4 端口配额、随机可用端口、TCP/UDP 端口映射、公网 IPv4 池管理、IPv6 前缀检测、IPv6 状态检查和容器级 IPv6 分配。 |
|
||||
| 资源限制 | 支持 CPU、内存、磁盘、Swap、独立上行/下行带宽、读/写 I/O 限速、流量重置、流量限制和资源限制管理;容器到期或超额后可自动关机,避免资源和流量失控。 |
|
||||
| 远程控制 | 内置 WebSSH 和 WebVNC 票据访问,用户可以直接在浏览器打开终端或控制台,不需要手动复制连接信息。 |
|
||||
| 快照能力 | 支持快照总览、容器快照、创建快照、删除快照、恢复快照、计划快照和快照配额。 |
|
||||
| 安全告警 | 基于 conntrack 做轻量安全检测,可识别端口扫描、横向扫描、爆破倾向、SMTP 滥用、UDP 反射、挖矿端口、代理/VPN/Tor 等风险,并提供安全日志、汇总和设置项。 |
|
||||
| 账号与审计 | 支持子用户管理链接、子用户密码轮换、按容器授权、操作日志、登录日志和 API Key 管理,适合分发给下游用户或拼车用户。 |
|
||||
| 自动化接入 | 全量接口统一使用 `/api/v1`,覆盖任务队列、容器、镜像、网络、流量、安全、批量创建和批量操作;同时提供魔方财务对接模块,并由 GitHub Actions 自动打包发布。 |
|
||||
| 运维入口 | 提供总览统计、主机资源、路由概览、Swap 管理、CLI-only 模式和 GitHub Actions 自动发布产物,便于在小型节点上长期维护。 |
|
||||
|
||||
## Technology Stack / 技术栈
|
||||
|
||||
- Backend: Go, net/http, LXC, KVM/libvirt, cgroup v2, iptables, conntrack
|
||||
- Frontend: React, TypeScript, Vite, Tailwind CSS, lucide-react, xterm.js
|
||||
- Runtime: Linux, systemd, LXC, KVM/QEMU
|
||||
- Build: GitHub Actions, Node.js 20, Go 1.24
|
||||
|
||||
## Preview / 预览
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
|
||||
## Disclaimer/免责声明
|
||||
@@ -99,10 +112,11 @@ This open-source software is intended solely for educational purposes, specifica
|
||||
本开源软件仅供学习和研究 LXC、KVM 等虚拟化技术原理之目的使用,不得用于任何违反适用法律法规、软件许可协议或第三方权益的行为。
|
||||
|
||||
本软件中涉及的 Windows 名称、标识、图标及相关知识产权均归 Microsoft Corporation 及其权利人所有。本项目与微软公司不存在任何关联、授权或合作关系。
|
||||
## Thanks/鸣谢
|
||||
|
||||
## Thanks / 鸣谢
|
||||
- [Nodeseek.com](https://www.nodeseek.com) — 一个专注于服务器的社区
|
||||
- [Linux.do](https://linux.do) — 一个充满灵感的科技社区
|
||||
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/?repos=MengMengCode%2FCLICD&type=date&legend=top-left">
|
||||
|
||||
@@ -90,7 +90,7 @@ func hasScope(r *http.Request, scope string) bool {
|
||||
|
||||
func subUserScopeAllowed(scope string) bool {
|
||||
switch scope {
|
||||
case "container:read", "container:power", "container:reinstall", "container:network",
|
||||
case "container:read", "container:power", "container:reinstall", "container:password", "container:network",
|
||||
"dashboard:read", "image:read", "task:read", "snapshot:read", "snapshot:create", "snapshot:delete", "snapshot:restore", "snapshot:schedule",
|
||||
"terminal:ssh", "terminal:vnc":
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"clicd/internal/config"
|
||||
"clicd/internal/lxc"
|
||||
)
|
||||
|
||||
func generateFirewallRuleID() string {
|
||||
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
b := make([]byte, 8)
|
||||
for i := range b {
|
||||
b[i] = chars[rand.Intn(len(chars))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func getFirewall(w http.ResponseWriter, r *http.Request, id int) {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
|
||||
return
|
||||
}
|
||||
jsonResponse(w, http.StatusOK, APIResponse{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"enabled": c.FirewallEnabled,
|
||||
"default_action": normalizeFirewallDefaultAction(c.FirewallDefaultAction),
|
||||
"rules": c.FirewallRules,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
DefaultAction *string `json:"default_action"`
|
||||
Rules *[]config.FirewallRule `json:"rules"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
oldEnabled := c.FirewallEnabled
|
||||
oldDefaultAction := c.FirewallDefaultAction
|
||||
oldRules := append([]config.FirewallRule(nil), c.FirewallRules...)
|
||||
|
||||
if req.Enabled != nil {
|
||||
c.FirewallEnabled = *req.Enabled
|
||||
}
|
||||
if req.DefaultAction != nil {
|
||||
action := normalizeFirewallDefaultAction(*req.DefaultAction)
|
||||
if action == "" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid default action"})
|
||||
return
|
||||
}
|
||||
c.FirewallDefaultAction = action
|
||||
} else if strings.TrimSpace(c.FirewallDefaultAction) == "" {
|
||||
c.FirewallDefaultAction = "DROP"
|
||||
}
|
||||
if req.Rules != nil {
|
||||
// Validate and assign IDs to new rules
|
||||
rules := *req.Rules
|
||||
for i := range rules {
|
||||
rules[i].Direction = strings.ToLower(strings.TrimSpace(rules[i].Direction))
|
||||
rules[i].Protocol = strings.ToLower(strings.TrimSpace(rules[i].Protocol))
|
||||
rules[i].Action = strings.ToUpper(strings.TrimSpace(rules[i].Action))
|
||||
rules[i].Network = normalizeFirewallNetwork(rules[i].Network)
|
||||
rules[i].SourceIP = strings.TrimSpace(rules[i].SourceIP)
|
||||
rules[i].Port = strings.TrimSpace(rules[i].Port)
|
||||
|
||||
if rules[i].Network == "" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid network"})
|
||||
return
|
||||
}
|
||||
if rules[i].Direction != "in" && rules[i].Direction != "out" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid direction: " + rules[i].Direction})
|
||||
return
|
||||
}
|
||||
if rules[i].Protocol != "tcp" && rules[i].Protocol != "udp" && rules[i].Protocol != "icmp" && rules[i].Protocol != "all" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid protocol: " + rules[i].Protocol})
|
||||
return
|
||||
}
|
||||
if rules[i].Action != "ACCEPT" && rules[i].Action != "DROP" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid action: " + rules[i].Action})
|
||||
return
|
||||
}
|
||||
if rules[i].SourceIP != "" {
|
||||
if err := validateFirewallIPSpec(rules[i].SourceIP, rules[i].Network); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid IP: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
if rules[i].ID == "" || strings.HasPrefix(rules[i].ID, "tmp-") {
|
||||
rules[i].ID = generateFirewallRuleID()
|
||||
}
|
||||
// Validate port spec
|
||||
if rules[i].Port != "" {
|
||||
if rules[i].Protocol != "tcp" && rules[i].Protocol != "udp" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Ports are only supported for TCP and UDP rules"})
|
||||
return
|
||||
}
|
||||
if err := validatePortSpec(rules[i].Port); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid port: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
c.FirewallRules = rules
|
||||
}
|
||||
|
||||
// Apply firewall rules to iptables if container is running
|
||||
if c.Status == "running" {
|
||||
if err := lxc.ApplyFirewallRules(id); err != nil {
|
||||
c.FirewallEnabled = oldEnabled
|
||||
c.FirewallDefaultAction = oldDefaultAction
|
||||
c.FirewallRules = oldRules
|
||||
_ = lxc.ApplyFirewallRules(id)
|
||||
config.SaveConfig()
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to apply firewall rules: " + err.Error()})
|
||||
return
|
||||
}
|
||||
} else if !c.FirewallEnabled {
|
||||
// If disabled and not running, clean any lingering rules
|
||||
lxc.CleanFirewallRules(id)
|
||||
}
|
||||
config.SaveConfig()
|
||||
|
||||
jsonResponse(w, http.StatusOK, APIResponse{
|
||||
Success: true,
|
||||
Message: "Firewall updated",
|
||||
Data: map[string]interface{}{
|
||||
"enabled": c.FirewallEnabled,
|
||||
"default_action": normalizeFirewallDefaultAction(c.FirewallDefaultAction),
|
||||
"rules": c.FirewallRules,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func normalizeFirewallDefaultAction(action string) string {
|
||||
action = strings.ToUpper(strings.TrimSpace(action))
|
||||
if action == "ACCEPT" || action == "DROP" {
|
||||
return action
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func normalizeFirewallNetwork(network string) string {
|
||||
network = strings.ToLower(strings.TrimSpace(network))
|
||||
switch network {
|
||||
case "", "ipv4", "nat4":
|
||||
return "ipv4"
|
||||
case "ipv6":
|
||||
return "ipv6"
|
||||
case "all", "both":
|
||||
return "all"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func validatePortSpec(port string) error {
|
||||
port = strings.TrimSpace(port)
|
||||
if port == "" {
|
||||
return nil
|
||||
}
|
||||
// Support: "22", "80,443", "8000-9000", "80,443,8000-9000"
|
||||
partCount := 0
|
||||
for _, part := range strings.Split(port, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
return &portValidationError{port}
|
||||
}
|
||||
partCount++
|
||||
if strings.Contains(part, "-") {
|
||||
// Range
|
||||
bounds := strings.SplitN(part, "-", 2)
|
||||
lo, err := strconv.Atoi(strings.TrimSpace(bounds[0]))
|
||||
if err != nil || lo < 1 || lo > 65535 {
|
||||
return &portValidationError{part}
|
||||
}
|
||||
hi, err := strconv.Atoi(strings.TrimSpace(bounds[1]))
|
||||
if err != nil || hi < 1 || hi > 65535 {
|
||||
return &portValidationError{part}
|
||||
}
|
||||
if hi < lo {
|
||||
return &portValidationError{part}
|
||||
}
|
||||
} else {
|
||||
p, err := strconv.Atoi(part)
|
||||
if err != nil || p < 1 || p > 65535 {
|
||||
return &portValidationError{part}
|
||||
}
|
||||
}
|
||||
}
|
||||
if partCount > 15 {
|
||||
return &portValidationError{"too many ports; maximum 15 items per rule"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFirewallIPSpec(value string, network string) error {
|
||||
var addr netip.Addr
|
||||
if strings.Contains(value, "/") {
|
||||
prefix, err := netip.ParsePrefix(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addr = prefix.Addr()
|
||||
} else {
|
||||
parsed, err := netip.ParseAddr(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addr = parsed
|
||||
}
|
||||
switch network {
|
||||
case "ipv4":
|
||||
if !addr.Is4() {
|
||||
return &ipValidationError{"IPv4 rule requires an IPv4 address or CIDR: " + value}
|
||||
}
|
||||
case "ipv6":
|
||||
if !addr.Is6() || addr.Is4In6() {
|
||||
return &ipValidationError{"IPv6 rule requires an IPv6 address or CIDR: " + value}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ipValidationError struct {
|
||||
value string
|
||||
}
|
||||
|
||||
func (e *ipValidationError) Error() string {
|
||||
return e.value
|
||||
}
|
||||
|
||||
type portValidationError struct {
|
||||
port string
|
||||
}
|
||||
|
||||
func (e *portValidationError) Error() string {
|
||||
return "invalid port value: " + e.port
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -182,6 +184,16 @@ func HandleSingleContainer(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
deletePortMapping(w, r, id, strings.TrimPrefix(action, "port-mappings/"))
|
||||
case action == "firewall" && r.Method == http.MethodGet:
|
||||
if !requireScope(w, r, "container:network") {
|
||||
return
|
||||
}
|
||||
getFirewall(w, r, id)
|
||||
case action == "firewall" && r.Method == http.MethodPut:
|
||||
if !requireScope(w, r, "container:network") {
|
||||
return
|
||||
}
|
||||
updateFirewall(w, r, id)
|
||||
case r.Method == http.MethodGet:
|
||||
if !requireScope(w, r, "container:read") {
|
||||
return
|
||||
@@ -200,10 +212,21 @@ func listContainers(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func createContainer(w http.ResponseWriter, r *http.Request) {
|
||||
var cfg lxc.ContainerConfig
|
||||
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
|
||||
return
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &cfg); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
|
||||
return
|
||||
}
|
||||
_ = json.Unmarshal(body, &fields)
|
||||
if err := normalizeCreateResourceLimits(&cfg, fields); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if cfg.Name == "" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Container name is required"})
|
||||
return
|
||||
@@ -376,10 +399,14 @@ func updateTrafficLimit(w http.ResponseWriter, r *http.Request, id int) {
|
||||
|
||||
func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
|
||||
var req struct {
|
||||
VCPU float64 `json:"vcpu"`
|
||||
RAMMB int `json:"ram_mb"`
|
||||
IOMBps int `json:"io_speed_mbps"`
|
||||
BWMbps int `json:"network_bw_mbps"`
|
||||
VCPU *float64 `json:"vcpu"`
|
||||
RAMMB *int `json:"ram_mb"`
|
||||
IOMBps *int `json:"io_speed_mbps"`
|
||||
IOReadMBps *int `json:"io_read_mbps"`
|
||||
IOWriteMBps *int `json:"io_write_mbps"`
|
||||
BWMbps *int `json:"network_bw_mbps"`
|
||||
NetworkDownMbps *int `json:"network_down_mbps"`
|
||||
NetworkUpMbps *int `json:"network_up_mbps"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request"})
|
||||
@@ -394,21 +421,35 @@ func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
|
||||
// Update config
|
||||
nextVCPU := c.VCPU
|
||||
nextRAMMB := c.RAMMB
|
||||
if req.VCPU > 0 {
|
||||
nextVCPU = req.VCPU
|
||||
if req.VCPU != nil {
|
||||
nextVCPU = *req.VCPU
|
||||
}
|
||||
if req.RAMMB > 0 {
|
||||
nextRAMMB = req.RAMMB
|
||||
if req.RAMMB != nil {
|
||||
nextRAMMB = *req.RAMMB
|
||||
}
|
||||
if err := validateRuntimeResourceRequest(c.Runtime(), nextVCPU, nextRAMMB, c.DiskGB); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
for name, value := range map[string]*int{
|
||||
"network_bw_mbps": req.BWMbps,
|
||||
"network_down_mbps": req.NetworkDownMbps,
|
||||
"network_up_mbps": req.NetworkUpMbps,
|
||||
"io_speed_mbps": req.IOMBps,
|
||||
"io_read_mbps": req.IOReadMBps,
|
||||
"io_write_mbps": req.IOWriteMBps,
|
||||
} {
|
||||
if err := rejectNegativeLimit(name, value); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.VCPU = nextVCPU
|
||||
c.RAMMB = nextRAMMB
|
||||
c.IOSpeedMBps = req.IOMBps
|
||||
c.NetworkBWMbps = req.BWMbps
|
||||
applyNetworkLimitPatch(c, req.BWMbps, req.NetworkDownMbps, req.NetworkUpMbps)
|
||||
applyIOLimitPatch(c, req.IOMBps, req.IOReadMBps, req.IOWriteMBps)
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
config.SaveConfig()
|
||||
|
||||
// Re-apply resource limits to running container
|
||||
@@ -426,6 +467,114 @@ func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: msg})
|
||||
}
|
||||
|
||||
func normalizeCreateResourceLimits(cfg *lxc.ContainerConfig, fields map[string]json.RawMessage) error {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
if err := rejectNegativeCreateLimits(*cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
bwSet := hasJSONField(fields, "network_bw_mbps")
|
||||
downSet := hasJSONField(fields, "network_down_mbps")
|
||||
upSet := hasJSONField(fields, "network_up_mbps")
|
||||
if bwSet {
|
||||
if !downSet {
|
||||
cfg.NetworkDownMbps = cfg.NetworkBWMbps
|
||||
}
|
||||
if !upSet {
|
||||
cfg.NetworkUpMbps = cfg.NetworkBWMbps
|
||||
}
|
||||
}
|
||||
ioSet := hasJSONField(fields, "io_speed_mbps")
|
||||
readSet := hasJSONField(fields, "io_read_mbps")
|
||||
writeSet := hasJSONField(fields, "io_write_mbps")
|
||||
if ioSet {
|
||||
if !readSet {
|
||||
cfg.IOReadMBps = cfg.IOSpeedMBps
|
||||
}
|
||||
if !writeSet {
|
||||
cfg.IOWriteMBps = cfg.IOSpeedMBps
|
||||
}
|
||||
}
|
||||
cfg.NormalizeResourceAliases()
|
||||
return nil
|
||||
}
|
||||
|
||||
func rejectNegativeCreateLimits(cfg lxc.ContainerConfig) error {
|
||||
for name, value := range map[string]int{
|
||||
"network_bw_mbps": cfg.NetworkBWMbps,
|
||||
"network_down_mbps": cfg.NetworkDownMbps,
|
||||
"network_up_mbps": cfg.NetworkUpMbps,
|
||||
"io_speed_mbps": cfg.IOSpeedMBps,
|
||||
"io_read_mbps": cfg.IOReadMBps,
|
||||
"io_write_mbps": cfg.IOWriteMBps,
|
||||
} {
|
||||
if value < 0 {
|
||||
return fmt.Errorf("%s cannot be negative", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasJSONField(fields map[string]json.RawMessage, name string) bool {
|
||||
if fields == nil {
|
||||
return false
|
||||
}
|
||||
_, ok := fields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
func rejectNegativeLimit(name string, value *int) error {
|
||||
if value != nil && *value < 0 {
|
||||
return fmt.Errorf("%s cannot be negative", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyNetworkLimitPatch(c *config.Container, legacy *int, down *int, up *int) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
nextDown := c.NetworkDownMbps
|
||||
nextUp := c.NetworkUpMbps
|
||||
if legacy != nil {
|
||||
nextDown = *legacy
|
||||
nextUp = *legacy
|
||||
}
|
||||
if down != nil {
|
||||
nextDown = *down
|
||||
}
|
||||
if up != nil {
|
||||
nextUp = *up
|
||||
}
|
||||
c.NetworkDownMbps = nextDown
|
||||
c.NetworkUpMbps = nextUp
|
||||
c.NetworkBWMbps = config.LegacySymmetricLimit(nextDown, nextUp)
|
||||
}
|
||||
|
||||
func applyIOLimitPatch(c *config.Container, legacy *int, read *int, write *int) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
nextRead := c.IOReadMBps
|
||||
nextWrite := c.IOWriteMBps
|
||||
if legacy != nil {
|
||||
nextRead = *legacy
|
||||
nextWrite = *legacy
|
||||
}
|
||||
if read != nil {
|
||||
nextRead = *read
|
||||
}
|
||||
if write != nil {
|
||||
nextWrite = *write
|
||||
}
|
||||
c.IOReadMBps = nextRead
|
||||
c.IOWriteMBps = nextWrite
|
||||
c.IOSpeedMBps = config.LegacySymmetricLimit(nextRead, nextWrite)
|
||||
}
|
||||
|
||||
func getRandomPort(w http.ResponseWriter, r *http.Request, id int) {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
|
||||
@@ -110,7 +110,8 @@ func HandleRoutingIPv4Scan(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
|
||||
if !requireScope(w, r, "routing:read") {
|
||||
if !hasAnyScope(r, "routing:read", "routing:write") {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Insufficient API key scope"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"clicd/internal/config"
|
||||
)
|
||||
|
||||
func TestHandleRoutingGetAllowsRoutingWriteScope(t *testing.T) {
|
||||
config.AppConfig = &config.ClicdConfig{}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/routing", nil)
|
||||
req = withAuthContext(req, AuthContext{
|
||||
Type: authTypeAPIKey,
|
||||
Scopes: []string{"routing:write"},
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handleRoutingGet(rec, req)
|
||||
|
||||
if rec.Code == http.StatusForbidden {
|
||||
t.Fatal("routing:write scope should be able to receive the routing response after updates")
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ func runtimeFromTemplateID(templateID string) string {
|
||||
|
||||
func createByRuntime(cfg lxc.ContainerConfig) error {
|
||||
cfg.Virtualization = runtimeFromRequest(cfg.Virtualization)
|
||||
cfg.NormalizeResourceAliases()
|
||||
if cfg.Virtualization == config.VirtualizationKVM {
|
||||
return kvmManager.CreateContainer(cfg)
|
||||
}
|
||||
|
||||
@@ -180,6 +180,12 @@ func (ss *SecurityScanner) monitorLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
func (ss *SecurityScanner) alertCount() int {
|
||||
ss.mu.Lock()
|
||||
defer ss.mu.Unlock()
|
||||
return len(ss.alerts)
|
||||
}
|
||||
|
||||
func (ss *SecurityScanner) checkAllContainers() {
|
||||
for _, c := range config.AppConfig.Containers {
|
||||
if c.Status != "running" || c.IP == "" {
|
||||
@@ -208,6 +214,7 @@ func (ss *SecurityScanner) checkContainer(name, ip string) {
|
||||
return
|
||||
}
|
||||
|
||||
alertBefore := ss.alertCount()
|
||||
ss.detectPortScans(name, ip, stats)
|
||||
ss.detectBruteForce(name, ip, stats)
|
||||
ss.detectSpam(name, ip, stats)
|
||||
@@ -216,6 +223,11 @@ func (ss *SecurityScanner) checkContainer(name, ip string) {
|
||||
ss.detectMining(name, ip, stats)
|
||||
ss.detectProxyAndTor(name, ip, stats)
|
||||
ss.detectMalware(name, ip, stats)
|
||||
|
||||
// If new alerts were generated, snapshot the conntrack data for later retrieval.
|
||||
if ss.alertCount() > alertBefore {
|
||||
config.SaveConntrackSnapshot(ip, lines)
|
||||
}
|
||||
}
|
||||
|
||||
func newTrafficStats() *trafficStats {
|
||||
@@ -759,28 +771,49 @@ func HandleSecurityLogs(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func getConnectionLogs(ip string) []map[string]interface{} {
|
||||
logs := make([]map[string]interface{}, 0)
|
||||
seen := map[string]bool{}
|
||||
|
||||
for _, line := range readConntrackLines(ip) {
|
||||
parseLine := func(line string) map[string]interface{} {
|
||||
srcIP := extractField(line, "src=")
|
||||
dstIP := extractField(line, "dst=")
|
||||
srcPort := extractField(line, "sport=")
|
||||
dstPort := extractField(line, "dport=")
|
||||
|
||||
sPort, _ := strconv.Atoi(srcPort)
|
||||
dPort, _ := strconv.Atoi(dstPort)
|
||||
|
||||
logs = append(logs, map[string]interface{}{
|
||||
return map[string]interface{}{
|
||||
"src_ip": srcIP,
|
||||
"dst_ip": dstIP,
|
||||
"src_port": sPort,
|
||||
"dst_port": dPort,
|
||||
"protocol": extractProtocol(line),
|
||||
"state": extractConnState(line),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// First, load stored snapshots from database (persisted at alert time).
|
||||
for _, line := range config.GetConntrackSnapshotLines(ip) {
|
||||
if len(logs) >= 100 {
|
||||
break
|
||||
}
|
||||
key := strings.TrimSpace(line)
|
||||
if key == "" || seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
logs = append(logs, parseLine(line))
|
||||
}
|
||||
|
||||
// Then, merge live conntrack data (deduplicated).
|
||||
for _, line := range readConntrackLines(ip) {
|
||||
if len(logs) >= 100 {
|
||||
break
|
||||
}
|
||||
key := strings.TrimSpace(line)
|
||||
if key == "" || seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
logs = append(logs, parseLine(line))
|
||||
}
|
||||
|
||||
return logs
|
||||
|
||||
@@ -373,6 +373,15 @@ func SubUserMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
imagesEnabledPath := "/api/images/enabled"
|
||||
if strings.HasPrefix(path, "/api/v1/") {
|
||||
imagesEnabledPath = "/api/v1/images/enabled"
|
||||
}
|
||||
if path == imagesEnabledPath && r.Method == http.MethodGet {
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
if path == containerListPath {
|
||||
if r.Method != http.MethodGet {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Sub-users cannot create containers"})
|
||||
@@ -503,7 +512,7 @@ func isSubUserContainerActionAllowed(action string, method string) bool {
|
||||
return method == http.MethodPost
|
||||
case strings.HasPrefix(action, "snapshots/"):
|
||||
return method == http.MethodDelete || method == http.MethodPost
|
||||
case action == "start" || action == "stop" || action == "restart" || action == "reinstall":
|
||||
case action == "start" || action == "stop" || action == "restart" || action == "reinstall" || action == "reset-password":
|
||||
return method == http.MethodPost
|
||||
case strings.HasPrefix(action, "port-mappings/"):
|
||||
return method == http.MethodPut
|
||||
|
||||
@@ -98,6 +98,7 @@ func (q *TaskQueue) EnqueueWithAudit(containerID int, containerName string, task
|
||||
}
|
||||
if cfg != nil {
|
||||
task.Config = *cfg
|
||||
task.Config.NormalizeResourceAliases()
|
||||
}
|
||||
q.enqueueTask(task)
|
||||
q.persistTasks()
|
||||
@@ -162,6 +163,7 @@ func (q *TaskQueue) enqueueBatchCreateList(configs []lxc.ContainerConfig, user s
|
||||
var result []string
|
||||
for _, cfg := range configs {
|
||||
cfgCopy := cfg
|
||||
cfgCopy.NormalizeResourceAliases()
|
||||
id := q.nextID
|
||||
q.nextID++
|
||||
task := &Task{
|
||||
@@ -246,6 +248,7 @@ func (q *TaskQueue) createWorker() {
|
||||
if task.Config.Name == "" {
|
||||
task.Config.Name = task.ContainerName
|
||||
}
|
||||
task.Config.NormalizeResourceAliases()
|
||||
if task.Config.Name == "" {
|
||||
task.Status = "failed"
|
||||
task.Error = "container name is required"
|
||||
@@ -592,6 +595,11 @@ func HandleBatchCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if req.Containers[i].VCPU <= 0 {
|
||||
req.Containers[i].VCPU = 1
|
||||
}
|
||||
if err := rejectNegativeCreateLimits(req.Containers[i]); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: name + ": " + err.Error()})
|
||||
return
|
||||
}
|
||||
req.Containers[i].NormalizeResourceAliases()
|
||||
req.Containers[i].Virtualization = runtimeFromRequest(req.Containers[i].Virtualization)
|
||||
if req.Containers[i].RAMMB < 128 {
|
||||
req.Containers[i].RAMMB = 512
|
||||
@@ -820,6 +828,7 @@ func RestoreTasks() {
|
||||
if cfg.Name == "" {
|
||||
cfg.Name = containerName
|
||||
}
|
||||
cfg.NormalizeResourceAliases()
|
||||
containerID := st.ContainerID
|
||||
if containerID <= 0 && containerName != "" {
|
||||
if c := config.FindContainerByName(containerName); c != nil {
|
||||
|
||||
@@ -34,7 +34,7 @@ var cliTranslations = map[string]string{
|
||||
"请选择操作": "Select an action",
|
||||
"再见": "Goodbye",
|
||||
"无效选择": "Invalid choice",
|
||||
"CLICD - LXC 容器管理器": "CLICD - LXC Container Manager",
|
||||
"CLICD - LXC 容器管理器": "CLICD - Container Manager",
|
||||
"Web 面板": "Web panel",
|
||||
"端口": "port",
|
||||
"运行中": "running",
|
||||
@@ -388,6 +388,7 @@ func cliCreateContainer(reader *bufio.Reader) {
|
||||
IOSpeedMBps: promptInt(reader, "IO 速度 (MB/s)", 500),
|
||||
ExtraPorts: promptPortList(reader, "额外 NAT 端口,多个用逗号分隔"),
|
||||
}
|
||||
cfg.NormalizeResourceAliases()
|
||||
|
||||
cliPrintf("\n正在创建容器 %s ...\n", name)
|
||||
if err := manager.CreateContainer(cfg); err != nil {
|
||||
|
||||
@@ -22,6 +22,18 @@ type PortMapping struct {
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type FirewallRule struct {
|
||||
ID string `json:"id"`
|
||||
Network string `json:"network,omitempty"` // "ipv4", "ipv6", or "all"; empty defaults to "ipv4"
|
||||
Direction string `json:"direction"` // "in" or "out"
|
||||
Protocol string `json:"protocol"` // "tcp", "udp", "icmp", "all"
|
||||
Port string `json:"port"` // "" = all, "22", "80,443", "8000-9000"
|
||||
SourceIP string `json:"source_ip"` // "" = any
|
||||
Action string `json:"action"` // "ACCEPT" or "DROP"
|
||||
Description string `json:"description"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type PublicIPv4Assignment struct {
|
||||
Address string `json:"address"`
|
||||
Interface string `json:"interface,omitempty"`
|
||||
@@ -103,6 +115,8 @@ type Container struct {
|
||||
RAMMB int `json:"ram_mb"`
|
||||
DiskGB int `json:"disk_gb"`
|
||||
NetworkBWMbps int `json:"network_bw_mbps"`
|
||||
NetworkDownMbps int `json:"network_down_mbps"`
|
||||
NetworkUpMbps int `json:"network_up_mbps"`
|
||||
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
|
||||
TrafficMode string `json:"traffic_mode"` // "total" or "in_out"
|
||||
TrafficInGB int `json:"traffic_in_gb"` // 0 = unlimited
|
||||
@@ -111,6 +125,8 @@ type Container struct {
|
||||
TrafficUsedTX int64 `json:"traffic_used_tx"`
|
||||
TrafficResetDate string `json:"traffic_reset_date"`
|
||||
IOSpeedMBps int `json:"io_speed_mbps"`
|
||||
IOReadMBps int `json:"io_read_mbps"`
|
||||
IOWriteMBps int `json:"io_write_mbps"`
|
||||
Status string `json:"status"`
|
||||
IP string `json:"ip"`
|
||||
PublicIPv4s []PublicIPv4Assignment `json:"public_ipv4s,omitempty"`
|
||||
@@ -124,6 +140,9 @@ type Container struct {
|
||||
SSHHostKey string `json:"ssh_host_key,omitempty"`
|
||||
PortMappings []PortMapping `json:"port_mappings"`
|
||||
PortMappingLimit int `json:"port_mapping_limit"`
|
||||
FirewallEnabled bool `json:"firewall_enabled"`
|
||||
FirewallDefaultAction string `json:"firewall_default_action"`
|
||||
FirewallRules []FirewallRule `json:"firewall_rules"`
|
||||
SnapshotLimit int `json:"snapshot_limit"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
@@ -689,6 +708,9 @@ func migrateLoadedConfig() bool {
|
||||
if ensureContainerNetworkAssignments() {
|
||||
changed = true
|
||||
}
|
||||
if ensureContainerResourceAliases() {
|
||||
changed = true
|
||||
}
|
||||
if ensureContainerSnapshotScheduleDefaults() {
|
||||
changed = true
|
||||
}
|
||||
@@ -787,6 +809,91 @@ func ensureContainerNetworkAssignments() bool {
|
||||
return changed
|
||||
}
|
||||
|
||||
func ensureContainerResourceAliases() bool {
|
||||
changed := false
|
||||
for i := range AppConfig.Containers {
|
||||
if NormalizeContainerResourceAliases(&AppConfig.Containers[i]) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func NormalizeContainerResourceAliases(c *Container) bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
if c.NetworkBWMbps < 0 {
|
||||
c.NetworkBWMbps = 0
|
||||
changed = true
|
||||
}
|
||||
if c.NetworkDownMbps < 0 {
|
||||
c.NetworkDownMbps = 0
|
||||
changed = true
|
||||
}
|
||||
if c.NetworkUpMbps < 0 {
|
||||
c.NetworkUpMbps = 0
|
||||
changed = true
|
||||
}
|
||||
if c.NetworkDownMbps == 0 && c.NetworkUpMbps == 0 && c.NetworkBWMbps > 0 {
|
||||
c.NetworkDownMbps = c.NetworkBWMbps
|
||||
c.NetworkUpMbps = c.NetworkBWMbps
|
||||
changed = true
|
||||
}
|
||||
nextNetworkBW := LegacySymmetricLimit(c.NetworkDownMbps, c.NetworkUpMbps)
|
||||
if c.NetworkBWMbps != nextNetworkBW {
|
||||
c.NetworkBWMbps = nextNetworkBW
|
||||
changed = true
|
||||
}
|
||||
|
||||
if c.IOSpeedMBps < 0 {
|
||||
c.IOSpeedMBps = 0
|
||||
changed = true
|
||||
}
|
||||
if c.IOReadMBps < 0 {
|
||||
c.IOReadMBps = 0
|
||||
changed = true
|
||||
}
|
||||
if c.IOWriteMBps < 0 {
|
||||
c.IOWriteMBps = 0
|
||||
changed = true
|
||||
}
|
||||
if c.IOReadMBps == 0 && c.IOWriteMBps == 0 && c.IOSpeedMBps > 0 {
|
||||
c.IOReadMBps = c.IOSpeedMBps
|
||||
c.IOWriteMBps = c.IOSpeedMBps
|
||||
changed = true
|
||||
}
|
||||
nextIO := LegacySymmetricLimit(c.IOReadMBps, c.IOWriteMBps)
|
||||
if c.IOSpeedMBps != nextIO {
|
||||
c.IOSpeedMBps = nextIO
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func LegacySymmetricLimit(a, b int) int {
|
||||
if a < 0 {
|
||||
a = 0
|
||||
}
|
||||
if b < 0 {
|
||||
b = 0
|
||||
}
|
||||
if a == b {
|
||||
return a
|
||||
}
|
||||
if a == 0 {
|
||||
return b
|
||||
}
|
||||
if b == 0 {
|
||||
return a
|
||||
}
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func migrateSubUsers() bool {
|
||||
changed := false
|
||||
for i := range AppConfig.SubUsers {
|
||||
@@ -871,6 +978,7 @@ func AddContainer(c Container) {
|
||||
c.UUID = NewContainerUUID()
|
||||
}
|
||||
c.Virtualization = NormalizeVirtualization(c.Virtualization)
|
||||
NormalizeContainerResourceAliases(&c)
|
||||
AppConfig.Containers = append(AppConfig.Containers, c)
|
||||
SaveConfig()
|
||||
}
|
||||
|
||||
@@ -28,11 +28,15 @@ type savedTaskConfig struct {
|
||||
RAMMB int `json:"ram_mb"`
|
||||
DiskGB int `json:"disk_gb"`
|
||||
NetworkBWMbps int `json:"network_bw_mbps"`
|
||||
NetworkDownMbps int `json:"network_down_mbps"`
|
||||
NetworkUpMbps int `json:"network_up_mbps"`
|
||||
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
|
||||
TrafficMode string `json:"traffic_mode"`
|
||||
TrafficInGB int `json:"traffic_in_gb"`
|
||||
TrafficOutGB int `json:"traffic_out_gb"`
|
||||
IOSpeedMBps int `json:"io_speed_mbps"`
|
||||
IOReadMBps int `json:"io_read_mbps"`
|
||||
IOWriteMBps int `json:"io_write_mbps"`
|
||||
ExtraPorts []int `json:"extra_ports"`
|
||||
PortMappingCount int `json:"port_mapping_count"`
|
||||
AssignNAT *bool `json:"assign_nat,omitempty"`
|
||||
@@ -55,10 +59,12 @@ func parseSavedTaskConfig(raw string) savedTaskConfig {
|
||||
}
|
||||
var cfg savedTaskConfig
|
||||
_ = json.Unmarshal([]byte(raw), &cfg)
|
||||
normalizeSavedTaskConfigLimits(&cfg)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func encodeSavedTaskConfig(cfg savedTaskConfig) string {
|
||||
normalizeSavedTaskConfigLimits(&cfg)
|
||||
data, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return ""
|
||||
@@ -66,6 +72,41 @@ func encodeSavedTaskConfig(cfg savedTaskConfig) string {
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func normalizeSavedTaskConfigLimits(cfg *savedTaskConfig) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if cfg.NetworkBWMbps < 0 {
|
||||
cfg.NetworkBWMbps = 0
|
||||
}
|
||||
if cfg.NetworkDownMbps < 0 {
|
||||
cfg.NetworkDownMbps = 0
|
||||
}
|
||||
if cfg.NetworkUpMbps < 0 {
|
||||
cfg.NetworkUpMbps = 0
|
||||
}
|
||||
if cfg.NetworkDownMbps == 0 && cfg.NetworkUpMbps == 0 && cfg.NetworkBWMbps > 0 {
|
||||
cfg.NetworkDownMbps = cfg.NetworkBWMbps
|
||||
cfg.NetworkUpMbps = cfg.NetworkBWMbps
|
||||
}
|
||||
cfg.NetworkBWMbps = LegacySymmetricLimit(cfg.NetworkDownMbps, cfg.NetworkUpMbps)
|
||||
|
||||
if cfg.IOSpeedMBps < 0 {
|
||||
cfg.IOSpeedMBps = 0
|
||||
}
|
||||
if cfg.IOReadMBps < 0 {
|
||||
cfg.IOReadMBps = 0
|
||||
}
|
||||
if cfg.IOWriteMBps < 0 {
|
||||
cfg.IOWriteMBps = 0
|
||||
}
|
||||
if cfg.IOReadMBps == 0 && cfg.IOWriteMBps == 0 && cfg.IOSpeedMBps > 0 {
|
||||
cfg.IOReadMBps = cfg.IOSpeedMBps
|
||||
cfg.IOWriteMBps = cfg.IOSpeedMBps
|
||||
}
|
||||
cfg.IOSpeedMBps = LegacySymmetricLimit(cfg.IOReadMBps, cfg.IOWriteMBps)
|
||||
}
|
||||
|
||||
func encodeStringSlice(values []string) string {
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
@@ -148,6 +189,8 @@ func ensureSchema() error {
|
||||
ram_mb INTEGER,
|
||||
disk_gb INTEGER,
|
||||
network_bw_mbps INTEGER,
|
||||
network_down_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
network_up_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
monthly_traffic_gb INTEGER,
|
||||
traffic_mode TEXT,
|
||||
traffic_in_gb INTEGER,
|
||||
@@ -156,6 +199,8 @@ func ensureSchema() error {
|
||||
traffic_used_tx INTEGER,
|
||||
traffic_reset_date TEXT,
|
||||
io_speed_mbps INTEGER,
|
||||
io_read_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
io_write_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
status TEXT,
|
||||
ip TEXT,
|
||||
ipv6 TEXT,
|
||||
@@ -254,6 +299,14 @@ func ensureSchema() error {
|
||||
success INTEGER,
|
||||
error TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS security_conntrack_snapshots (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
container_ip TEXT NOT NULL,
|
||||
line TEXT NOT NULL,
|
||||
captured_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_conntrack_snapshots_ip_time
|
||||
ON security_conntrack_snapshots(container_ip, captured_at)`,
|
||||
`CREATE TABLE IF NOT EXISTS tasks (
|
||||
id TEXT PRIMARY KEY,
|
||||
type TEXT,
|
||||
@@ -274,11 +327,15 @@ func ensureSchema() error {
|
||||
cfg_ram_mb INTEGER,
|
||||
cfg_disk_gb INTEGER,
|
||||
cfg_network_bw_mbps INTEGER,
|
||||
cfg_network_down_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
cfg_network_up_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
cfg_monthly_traffic_gb INTEGER,
|
||||
cfg_traffic_mode TEXT,
|
||||
cfg_traffic_in_gb INTEGER,
|
||||
cfg_traffic_out_gb INTEGER,
|
||||
cfg_io_speed_mbps INTEGER,
|
||||
cfg_io_read_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
cfg_io_write_mbps INTEGER NOT NULL DEFAULT 0,
|
||||
cfg_port_mapping_count INTEGER,
|
||||
cfg_assign_nat INTEGER,
|
||||
cfg_snapshot_limit INTEGER,
|
||||
@@ -332,6 +389,7 @@ func ensureSchema() error {
|
||||
}
|
||||
|
||||
func ensureSchemaMigrations() error {
|
||||
added := map[string]bool{}
|
||||
for _, column := range []struct {
|
||||
table string
|
||||
name string
|
||||
@@ -344,6 +402,10 @@ func ensureSchemaMigrations() error {
|
||||
{"api_keys", "last_used_ip", "TEXT"},
|
||||
{"tasks", "ip", "TEXT"},
|
||||
{"tasks", "user_agent", "TEXT"},
|
||||
{"tasks", "cfg_network_down_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"tasks", "cfg_network_up_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"tasks", "cfg_io_read_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"tasks", "cfg_io_write_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"tasks", "cfg_assign_ipv4", "INTEGER"},
|
||||
{"tasks", "cfg_ipv4_count", "INTEGER"},
|
||||
{"tasks", "cfg_public_ipv4s", "TEXT"},
|
||||
@@ -356,18 +418,61 @@ func ensureSchemaMigrations() error {
|
||||
{"port_mappings", "host_ip", "TEXT"},
|
||||
{"container_public_ipv4s", "prefix_len", "INTEGER"},
|
||||
{"container_public_ipv4s", "gateway", "TEXT"},
|
||||
{"containers", "network_down_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"containers", "network_up_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"containers", "io_read_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"containers", "io_write_mbps", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"containers", "firewall_enabled", "INTEGER NOT NULL DEFAULT 0"},
|
||||
{"containers", "firewall_default_action", "TEXT NOT NULL DEFAULT 'DROP'"},
|
||||
{"containers", "firewall_rules", "TEXT"},
|
||||
} {
|
||||
if err := ensureColumn(column.table, column.name, column.def); err != nil {
|
||||
wasAdded, err := ensureColumn(column.table, column.name, column.def)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if wasAdded {
|
||||
added[column.table+"."+column.name] = true
|
||||
}
|
||||
}
|
||||
if added["containers.network_down_mbps"] || added["containers.network_up_mbps"] {
|
||||
if _, err := db.Exec(`UPDATE containers
|
||||
SET network_down_mbps = COALESCE(NULLIF(network_down_mbps, 0), COALESCE(network_bw_mbps, 0)),
|
||||
network_up_mbps = COALESCE(NULLIF(network_up_mbps, 0), COALESCE(network_bw_mbps, 0))
|
||||
WHERE COALESCE(network_bw_mbps, 0) > 0`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if added["containers.io_read_mbps"] || added["containers.io_write_mbps"] {
|
||||
if _, err := db.Exec(`UPDATE containers
|
||||
SET io_read_mbps = COALESCE(NULLIF(io_read_mbps, 0), COALESCE(io_speed_mbps, 0)),
|
||||
io_write_mbps = COALESCE(NULLIF(io_write_mbps, 0), COALESCE(io_speed_mbps, 0))
|
||||
WHERE COALESCE(io_speed_mbps, 0) > 0`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if added["tasks.cfg_network_down_mbps"] || added["tasks.cfg_network_up_mbps"] {
|
||||
if _, err := db.Exec(`UPDATE tasks
|
||||
SET cfg_network_down_mbps = COALESCE(NULLIF(cfg_network_down_mbps, 0), COALESCE(cfg_network_bw_mbps, 0)),
|
||||
cfg_network_up_mbps = COALESCE(NULLIF(cfg_network_up_mbps, 0), COALESCE(cfg_network_bw_mbps, 0))
|
||||
WHERE COALESCE(cfg_network_bw_mbps, 0) > 0`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if added["tasks.cfg_io_read_mbps"] || added["tasks.cfg_io_write_mbps"] {
|
||||
if _, err := db.Exec(`UPDATE tasks
|
||||
SET cfg_io_read_mbps = COALESCE(NULLIF(cfg_io_read_mbps, 0), COALESCE(cfg_io_speed_mbps, 0)),
|
||||
cfg_io_write_mbps = COALESCE(NULLIF(cfg_io_write_mbps, 0), COALESCE(cfg_io_speed_mbps, 0))
|
||||
WHERE COALESCE(cfg_io_speed_mbps, 0) > 0`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureColumn(table, name, def string) error {
|
||||
func ensureColumn(table, name, def string) (bool, error) {
|
||||
rows, err := db.Query("PRAGMA table_info(" + table + ")")
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
@@ -376,17 +481,17 @@ func ensureColumn(table, name, def string) error {
|
||||
var notNull, pk int
|
||||
var defaultValue interface{}
|
||||
if err := rows.Scan(&cid, &columnName, &columnType, ¬Null, &defaultValue, &pk); err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
if columnName == name {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
_, err = db.Exec("ALTER TABLE " + table + " ADD COLUMN " + name + " " + def)
|
||||
return err
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func loadConfigFromDB() (*ClicdConfig, bool, error) {
|
||||
@@ -567,24 +672,31 @@ func saveMeta(tx *sql.Tx) error {
|
||||
|
||||
func saveContainers(tx *sql.Tx) error {
|
||||
for _, c := range AppConfig.Containers {
|
||||
NormalizeContainerResourceAliases(&c)
|
||||
if _, err := tx.Exec(`INSERT INTO containers (
|
||||
id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, mac_address, template,
|
||||
vcpu, ram_mb, disk_gb, network_bw_mbps, monthly_traffic_gb, traffic_mode, traffic_in_gb,
|
||||
traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date, io_speed_mbps,
|
||||
vcpu, ram_mb, disk_gb, network_bw_mbps, network_down_mbps, network_up_mbps,
|
||||
monthly_traffic_gb, traffic_mode, traffic_in_gb,
|
||||
traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date,
|
||||
io_speed_mbps, io_read_mbps, io_write_mbps,
|
||||
status, ip, ipv6, ipv6_prefix_len, ipv6_interface, vnc_port, ssh_port, ssh_password,
|
||||
ssh_host_key, port_mapping_limit, snapshot_limit, created_at, expires_at,
|
||||
snapshot_schedule_enabled, snapshot_schedule_interval_hours, snapshot_schedule_time,
|
||||
snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by,
|
||||
policy_blocked, policy_blocked_reason, policy_blocked_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
policy_blocked, policy_blocked_reason, policy_blocked_at,
|
||||
firewall_enabled, firewall_default_action, firewall_rules
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
c.ID, c.UUID, c.Name, c.Virtualization, c.LXCName, c.KVMName, c.DiskImage, c.MACAddress, c.Template,
|
||||
c.VCPU, c.RAMMB, c.DiskGB, c.NetworkBWMbps, c.MonthlyTrafficGB, c.TrafficMode, c.TrafficInGB,
|
||||
c.TrafficOutGB, c.TrafficUsedRX, c.TrafficUsedTX, c.TrafficResetDate, c.IOSpeedMBps,
|
||||
c.VCPU, c.RAMMB, c.DiskGB, c.NetworkBWMbps, c.NetworkDownMbps, c.NetworkUpMbps,
|
||||
c.MonthlyTrafficGB, c.TrafficMode, c.TrafficInGB,
|
||||
c.TrafficOutGB, c.TrafficUsedRX, c.TrafficUsedTX, c.TrafficResetDate,
|
||||
c.IOSpeedMBps, c.IOReadMBps, c.IOWriteMBps,
|
||||
c.Status, c.IP, c.IPv6, c.IPv6PrefixLen, c.IPv6Interface, c.VNCPort, c.SSHPort, c.SSHPassword,
|
||||
c.SSHHostKey, c.PortMappingLimit, c.SnapshotLimit, c.CreatedAt, c.ExpiresAt,
|
||||
boolInt(c.SnapshotScheduleEnabled), c.SnapshotScheduleIntervalHours, c.SnapshotScheduleTime,
|
||||
c.SnapshotScheduleLastRun, c.SnapshotScheduleNextRun, c.SnapshotScheduleCreatedBy,
|
||||
boolInt(c.PolicyBlocked), c.PolicyBlockedReason, c.PolicyBlockedAt,
|
||||
boolInt(c.FirewallEnabled), normalizeFirewallDefaultAction(c.FirewallDefaultAction), marshalFirewallRules(c.FirewallRules),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -642,6 +754,59 @@ func saveAPIKeys(tx *sql.Tx) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveConntrackSnapshot stores raw conntrack lines for a container IP.
|
||||
func SaveConntrackSnapshot(containerIP string, lines []string) {
|
||||
if db == nil || len(lines) == 0 || strings.TrimSpace(containerIP) == "" {
|
||||
return
|
||||
}
|
||||
now := time.Now().Format("2006-01-02 15:04:05")
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
stmt, err := tx.Prepare(`INSERT INTO security_conntrack_snapshots (container_ip, line, captured_at) VALUES (?, ?, ?)`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer stmt.Close()
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
stmt.Exec(containerIP, line, now)
|
||||
}
|
||||
tx.Commit()
|
||||
|
||||
// Cleanup old snapshots (>1 hour)
|
||||
db.Exec(`DELETE FROM security_conntrack_snapshots WHERE captured_at < ?`,
|
||||
time.Now().Add(-1*time.Hour).Format("2006-01-02 15:04:05"))
|
||||
}
|
||||
|
||||
// GetConntrackSnapshotLines returns stored conntrack lines for a container IP.
|
||||
func GetConntrackSnapshotLines(containerIP string) []string {
|
||||
if db == nil || strings.TrimSpace(containerIP) == "" {
|
||||
return nil
|
||||
}
|
||||
rows, err := db.Query(
|
||||
`SELECT line FROM security_conntrack_snapshots WHERE container_ip = ? ORDER BY captured_at DESC LIMIT 200`,
|
||||
containerIP,
|
||||
)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer rows.Close()
|
||||
var lines []string
|
||||
for rows.Next() {
|
||||
var line string
|
||||
if rows.Scan(&line) == nil {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func saveAuditLogs(tx *sql.Tx) error {
|
||||
for _, log := range AppConfig.AuditLogs {
|
||||
successSet := 0
|
||||
@@ -666,15 +831,19 @@ func saveTasksDB(tx *sql.Tx) error {
|
||||
if _, err := tx.Exec(`INSERT INTO tasks(
|
||||
id, type, container_id, container_name, status, error, created_at, template_id, user, ip, user_agent,
|
||||
cfg_name, cfg_virtualization, cfg_template_id, cfg_vcpu, cfg_cpu_percent, cfg_ram_mb, cfg_disk_gb,
|
||||
cfg_network_bw_mbps, cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
|
||||
cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
|
||||
cfg_network_bw_mbps, cfg_network_down_mbps, cfg_network_up_mbps,
|
||||
cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
|
||||
cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_io_read_mbps, cfg_io_write_mbps,
|
||||
cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
|
||||
cfg_assign_ipv4, cfg_ipv4_count, cfg_public_ipv4s, cfg_assign_ipv6, cfg_ipv6_count, cfg_ipv6_addresses,
|
||||
cfg_ssh_auth_mode, cfg_ssh_password, cfg_ssh_public_key, cfg_expires_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
task.ID, task.Type, task.ContainerID, task.ContainerName, task.Status, task.Error, task.CreatedAt, task.TemplateID, task.User, task.IP, task.UserAgent,
|
||||
cfg.Name, cfg.Virtualization, cfg.TemplateID, cfg.VCPU, cfg.CPUPercent, cfg.RAMMB, cfg.DiskGB,
|
||||
cfg.NetworkBWMbps, cfg.MonthlyTrafficGB, cfg.TrafficMode, cfg.TrafficInGB,
|
||||
cfg.TrafficOutGB, cfg.IOSpeedMBps, cfg.PortMappingCount, boolPtrInt(cfg.AssignNAT), cfg.SnapshotLimit,
|
||||
cfg.NetworkBWMbps, cfg.NetworkDownMbps, cfg.NetworkUpMbps,
|
||||
cfg.MonthlyTrafficGB, cfg.TrafficMode, cfg.TrafficInGB,
|
||||
cfg.TrafficOutGB, cfg.IOSpeedMBps, cfg.IOReadMBps, cfg.IOWriteMBps,
|
||||
cfg.PortMappingCount, boolPtrInt(cfg.AssignNAT), cfg.SnapshotLimit,
|
||||
boolInt(cfg.AssignIPv4), cfg.IPv4Count, encodeStringSlice(cfg.PublicIPv4s),
|
||||
boolInt(cfg.AssignIPv6), cfg.IPv6Count, encodeStringSlice(cfg.IPv6Addresses),
|
||||
cfg.SSHAuthMode, cfg.SSHPassword, cfg.SSHPublicKey, cfg.ExpiresAt,
|
||||
@@ -722,13 +891,16 @@ func saveSnapshots(tx *sql.Tx) error {
|
||||
func loadContainers() ([]Container, error) {
|
||||
rows, err := db.Query(`SELECT
|
||||
id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, mac_address, template,
|
||||
vcpu, ram_mb, disk_gb, network_bw_mbps, monthly_traffic_gb, traffic_mode, traffic_in_gb,
|
||||
traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date, io_speed_mbps,
|
||||
vcpu, ram_mb, disk_gb, network_bw_mbps, network_down_mbps, network_up_mbps,
|
||||
monthly_traffic_gb, traffic_mode, traffic_in_gb,
|
||||
traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date,
|
||||
io_speed_mbps, io_read_mbps, io_write_mbps,
|
||||
status, ip, ipv6, ipv6_prefix_len, ipv6_interface, vnc_port, ssh_port, ssh_password,
|
||||
ssh_host_key, port_mapping_limit, snapshot_limit, created_at, expires_at,
|
||||
snapshot_schedule_enabled, snapshot_schedule_interval_hours, snapshot_schedule_time,
|
||||
snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by,
|
||||
policy_blocked, policy_blocked_reason, policy_blocked_at
|
||||
policy_blocked, policy_blocked_reason, policy_blocked_at,
|
||||
firewall_enabled, firewall_default_action, firewall_rules
|
||||
FROM containers ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -738,21 +910,32 @@ func loadContainers() ([]Container, error) {
|
||||
result := []Container{}
|
||||
for rows.Next() {
|
||||
var c Container
|
||||
var scheduleEnabled, policyBlocked int
|
||||
var scheduleEnabled, policyBlocked, firewallEnabled int
|
||||
var firewallDefaultAction string
|
||||
var firewallRulesJSON sql.NullString
|
||||
if err := rows.Scan(
|
||||
&c.ID, &c.UUID, &c.Name, &c.Virtualization, &c.LXCName, &c.KVMName, &c.DiskImage, &c.MACAddress, &c.Template,
|
||||
&c.VCPU, &c.RAMMB, &c.DiskGB, &c.NetworkBWMbps, &c.MonthlyTrafficGB, &c.TrafficMode, &c.TrafficInGB,
|
||||
&c.TrafficOutGB, &c.TrafficUsedRX, &c.TrafficUsedTX, &c.TrafficResetDate, &c.IOSpeedMBps,
|
||||
&c.VCPU, &c.RAMMB, &c.DiskGB, &c.NetworkBWMbps, &c.NetworkDownMbps, &c.NetworkUpMbps,
|
||||
&c.MonthlyTrafficGB, &c.TrafficMode, &c.TrafficInGB,
|
||||
&c.TrafficOutGB, &c.TrafficUsedRX, &c.TrafficUsedTX, &c.TrafficResetDate,
|
||||
&c.IOSpeedMBps, &c.IOReadMBps, &c.IOWriteMBps,
|
||||
&c.Status, &c.IP, &c.IPv6, &c.IPv6PrefixLen, &c.IPv6Interface, &c.VNCPort, &c.SSHPort, &c.SSHPassword,
|
||||
&c.SSHHostKey, &c.PortMappingLimit, &c.SnapshotLimit, &c.CreatedAt, &c.ExpiresAt,
|
||||
&scheduleEnabled, &c.SnapshotScheduleIntervalHours, &c.SnapshotScheduleTime,
|
||||
&c.SnapshotScheduleLastRun, &c.SnapshotScheduleNextRun, &c.SnapshotScheduleCreatedBy,
|
||||
&policyBlocked, &c.PolicyBlockedReason, &c.PolicyBlockedAt,
|
||||
&firewallEnabled, &firewallDefaultAction, &firewallRulesJSON,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.SnapshotScheduleEnabled = scheduleEnabled != 0
|
||||
c.PolicyBlocked = policyBlocked != 0
|
||||
c.FirewallEnabled = firewallEnabled != 0
|
||||
c.FirewallDefaultAction = normalizeFirewallDefaultAction(firewallDefaultAction)
|
||||
if firewallRulesJSON.Valid && strings.TrimSpace(firewallRulesJSON.String) != "" {
|
||||
_ = json.Unmarshal([]byte(firewallRulesJSON.String), &c.FirewallRules)
|
||||
}
|
||||
NormalizeContainerResourceAliases(&c)
|
||||
result = append(result, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
@@ -946,8 +1129,10 @@ func loadTasks() ([]SavedTask, error) {
|
||||
rows, err := db.Query(`SELECT
|
||||
id, type, container_id, container_name, status, error, created_at, template_id, user, ip, user_agent,
|
||||
cfg_name, cfg_virtualization, cfg_template_id, cfg_vcpu, cfg_cpu_percent, cfg_ram_mb, cfg_disk_gb,
|
||||
cfg_network_bw_mbps, cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
|
||||
cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
|
||||
cfg_network_bw_mbps, cfg_network_down_mbps, cfg_network_up_mbps,
|
||||
cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
|
||||
cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_io_read_mbps, cfg_io_write_mbps,
|
||||
cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
|
||||
cfg_assign_ipv4, cfg_ipv4_count, cfg_public_ipv4s, cfg_assign_ipv6, cfg_ipv6_count, cfg_ipv6_addresses,
|
||||
cfg_ssh_auth_mode, cfg_ssh_password, cfg_ssh_public_key, cfg_expires_at
|
||||
FROM tasks ORDER BY created_at, id`)
|
||||
@@ -967,8 +1152,10 @@ func loadTasks() ([]SavedTask, error) {
|
||||
if err := rows.Scan(
|
||||
&t.ID, &t.Type, &t.ContainerID, &t.ContainerName, &t.Status, &t.Error, &t.CreatedAt, &t.TemplateID, &t.User, &ip, &userAgent,
|
||||
&cfg.Name, &cfg.Virtualization, &cfg.TemplateID, &cfg.VCPU, &cfg.CPUPercent, &cfg.RAMMB, &cfg.DiskGB,
|
||||
&cfg.NetworkBWMbps, &cfg.MonthlyTrafficGB, &cfg.TrafficMode, &cfg.TrafficInGB,
|
||||
&cfg.TrafficOutGB, &cfg.IOSpeedMBps, &cfg.PortMappingCount, &assignNAT, &cfg.SnapshotLimit,
|
||||
&cfg.NetworkBWMbps, &cfg.NetworkDownMbps, &cfg.NetworkUpMbps,
|
||||
&cfg.MonthlyTrafficGB, &cfg.TrafficMode, &cfg.TrafficInGB,
|
||||
&cfg.TrafficOutGB, &cfg.IOSpeedMBps, &cfg.IOReadMBps, &cfg.IOWriteMBps,
|
||||
&cfg.PortMappingCount, &assignNAT, &cfg.SnapshotLimit,
|
||||
&assignIPv4, &ipv4Count, &publicIPv4s, &assignIPv6, &ipv6Count, &ipv6Addresses,
|
||||
&sshAuthMode, &sshPassword, &sshPublicKey, &cfg.ExpiresAt,
|
||||
); err != nil {
|
||||
@@ -993,6 +1180,7 @@ func loadTasks() ([]SavedTask, error) {
|
||||
cfg.SSHAuthMode = sshAuthMode.String
|
||||
cfg.SSHPassword = sshPassword.String
|
||||
cfg.SSHPublicKey = sshPublicKey.String
|
||||
normalizeSavedTaskConfigLimits(&cfg)
|
||||
result = append(result, t)
|
||||
configs = append(configs, cfg)
|
||||
}
|
||||
@@ -1106,6 +1294,25 @@ func boolInt(value bool) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func marshalFirewallRules(rules []FirewallRule) interface{} {
|
||||
if len(rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
data, err := json.Marshal(rules)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func normalizeFirewallDefaultAction(action string) string {
|
||||
action = strings.ToUpper(strings.TrimSpace(action))
|
||||
if action == "ACCEPT" {
|
||||
return "ACCEPT"
|
||||
}
|
||||
return "DROP"
|
||||
}
|
||||
|
||||
func boolPtrInt(value *bool) interface{} {
|
||||
if value == nil {
|
||||
return nil
|
||||
|
||||
@@ -84,6 +84,7 @@ var (
|
||||
lastTrafficSnapshot = map[string]trafficSample{}
|
||||
kvmSnapshotMu sync.Mutex
|
||||
kvmSSHEnsureLocks sync.Map
|
||||
knownSSHHostKeys sync.Map // TOFU host key store: host:port → ssh.PublicKey
|
||||
portMapApplyMu sync.Mutex
|
||||
lastPortMapApply = map[int]time.Time{}
|
||||
windowsMetricsMu sync.Mutex
|
||||
@@ -345,6 +346,7 @@ func normalizeQCOW2(ctx context.Context, src, target string) error {
|
||||
}
|
||||
|
||||
func (m *Manager) CreateContainer(cfg lxc.ContainerConfig) error {
|
||||
cfg.NormalizeResourceAliases()
|
||||
image := FindImage(cfg.TemplateID)
|
||||
if image == nil {
|
||||
return fmt.Errorf("KVM image not found: %s", cfg.TemplateID)
|
||||
@@ -407,6 +409,7 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
mac := randomMAC()
|
||||
sshPassword := generateRandomString(16)
|
||||
sshPublicKey := ""
|
||||
sshAuthMode := ""
|
||||
if !IsWindowsImage(image.ID) {
|
||||
sshAccess, err := lxc.ResolveCreateSSHAccess(cfg)
|
||||
if err != nil {
|
||||
@@ -414,6 +417,7 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
}
|
||||
sshPassword = sshAccess.Password
|
||||
sshPublicKey = sshAccess.PublicKey
|
||||
sshAuthMode = sshAccess.Mode
|
||||
}
|
||||
publicIPv4s, err := lxc.AllocatePublicIPv4Assignments(id, cfg.PublicIPv4s, cfg.IPv4Count, cfg.AssignIPv4)
|
||||
if err != nil {
|
||||
@@ -429,7 +433,9 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
ipv6Assignments = assigned
|
||||
}
|
||||
ipv6List := configIPv6AssignmentAddresses(ipv6Assignments)
|
||||
defaultHostIP := lxc.DefaultPortMappingHostIP(publicIPv4s)
|
||||
ipv4List := configIPv4AssignmentAddresses(publicIPv4s)
|
||||
// NAT4 port mappings should bind to the host IP, not the VM's independent public IPv4.
|
||||
defaultHostIP := ""
|
||||
|
||||
var xml string
|
||||
winAdminPassword := ""
|
||||
@@ -448,10 +454,10 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
}
|
||||
winAdminPassword = generateWindowsPassword()
|
||||
unattendPath := filepath.Join(m.instanceDir(vmName), "unattend.iso")
|
||||
if err := createWindowsUnattendISO(unattendPath, cfg.Name, winAdminPassword, ipv6List); err != nil {
|
||||
if err := createWindowsUnattendISO(unattendPath, cfg.Name, winAdminPassword, ipv6List, ipv4List); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
xml = windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, ImagePath(image.ID), unattendPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps)
|
||||
xml = windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, ImagePath(image.ID), unattendPath, mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps)
|
||||
} else {
|
||||
if image.Desktop != "" {
|
||||
if cfg.RAMMB < 2048 {
|
||||
@@ -464,10 +470,10 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
if err := createOverlayDisk(ImagePath(image.ID), diskPath, cfg.DiskGB); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := createSeedISO(seedPath, vmName, cfg.Name, sshPassword, sshPublicKey, mac, ipv6List, *image); err != nil {
|
||||
if err := createSeedISO(seedPath, vmName, cfg.Name, sshPassword, sshPublicKey, mac, ipv6List, ipv4List, *image, sshAuthMode); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
xml = domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, seedPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps, image.Desktop != "")
|
||||
xml = domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, seedPath, mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps, image.Desktop != "")
|
||||
}
|
||||
xmlPath := filepath.Join(m.instanceDir(vmName), "domain.xml")
|
||||
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
|
||||
@@ -537,12 +543,16 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
RAMMB: cfg.RAMMB,
|
||||
DiskGB: cfg.DiskGB,
|
||||
NetworkBWMbps: cfg.NetworkBWMbps,
|
||||
NetworkDownMbps: cfg.NetworkDownMbps,
|
||||
NetworkUpMbps: cfg.NetworkUpMbps,
|
||||
MonthlyTrafficGB: cfg.MonthlyTrafficGB,
|
||||
TrafficMode: trafficMode,
|
||||
TrafficInGB: cfg.TrafficInGB,
|
||||
TrafficOutGB: cfg.TrafficOutGB,
|
||||
TrafficResetDate: now[:7],
|
||||
IOSpeedMBps: cfg.IOSpeedMBps,
|
||||
IOReadMBps: cfg.IOReadMBps,
|
||||
IOWriteMBps: cfg.IOWriteMBps,
|
||||
PublicIPv4s: publicIPv4s,
|
||||
IPv6Addresses: ipv6Assignments,
|
||||
Status: "stopped",
|
||||
@@ -585,7 +595,7 @@ func (m *Manager) StartContainer(id int) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
config.UpdateContainerStatus(id, "running")
|
||||
config.UpdateContainerStatus(id, "initializing")
|
||||
// Detect VNC port
|
||||
if _, err := m.RefreshVNCPort(id); err != nil {
|
||||
fmt.Printf("Warning: failed to refresh VNC port for %s: %v\n", name, err)
|
||||
@@ -621,7 +631,15 @@ func (m *Manager) StartContainer(id int) error {
|
||||
if err := lxc.NewManager().ApplyPortMappings(id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lxc.ApplyFirewallRules(id); err != nil {
|
||||
fmt.Printf("Warning: failed to apply firewall rules: %v\n", err)
|
||||
}
|
||||
}
|
||||
// Wait for cloud-init to finish and SSH to be reachable (password-only mode)
|
||||
if !isWindows && c.IP != "" {
|
||||
m.waitForCloudInitReady(name, c.IP, c.SSHPassword)
|
||||
}
|
||||
config.UpdateContainerStatus(id, "running")
|
||||
if c.IPv6 != "" || len(c.IPv6Addresses) > 0 {
|
||||
if err := m.applyIPv6Runtime(c); err != nil {
|
||||
return err
|
||||
@@ -632,12 +650,71 @@ func (m *Manager) StartContainer(id int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitForCloudInitReady waits for cloud-init to finish and SSH to be reachable.
|
||||
// tofuHostKeyCallback implements Trust-On-First-Use host key verification.
|
||||
// On the first connection to a host, the key is accepted and remembered.
|
||||
// Subsequent connections must present the same key or the connection is rejected.
|
||||
func tofuHostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
if stored, ok := knownSSHHostKeys.Load(hostname); ok {
|
||||
if bytes.Equal(stored.(ssh.PublicKey).Marshal(), key.Marshal()) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("host key mismatch for %s (possible MitM attack)", hostname)
|
||||
}
|
||||
knownSSHHostKeys.Store(hostname, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) waitForCloudInitReady(vmName, ip, password string) {
|
||||
if ip == "" || password == "" {
|
||||
return
|
||||
}
|
||||
deadline := time.Now().Add(3 * time.Minute)
|
||||
target := net.JoinHostPort(ip, "22")
|
||||
sshWasUp := false
|
||||
qgaAttempted := false
|
||||
|
||||
for time.Now().Before(deadline) {
|
||||
client, err := ssh.Dial("tcp", target, &ssh.ClientConfig{
|
||||
User: "root",
|
||||
Auth: []ssh.AuthMethod{ssh.Password(password)},
|
||||
HostKeyCallback: tofuHostKeyCallback,
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if err == nil {
|
||||
client.Close()
|
||||
if !sshWasUp {
|
||||
sshWasUp = true
|
||||
fmt.Printf("KVM %s SSH up, waiting for cloud-init to settle...\n", vmName)
|
||||
time.Sleep(10 * time.Second)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("KVM %s ready\n", vmName)
|
||||
return
|
||||
}
|
||||
|
||||
// Try guest agent ONCE to speed things up, with timeout to avoid blocking
|
||||
if !qgaAttempted && qemuGuestPing(vmName) == nil {
|
||||
qgaAttempted = true
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
cmd := exec.CommandContext(ctx, "virsh", "qemu-agent-command", vmName,
|
||||
`{"execute":"guest-exec","arguments":{"path":"/bin/sh","arg":["-c","cloud-init status --wait 2>/dev/null; systemctl restart sshd 2>/dev/null || systemctl restart ssh 2>/dev/null; true"],"capture-output":false}}`)
|
||||
cmd.Run()
|
||||
cancel()
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
fmt.Printf("Warning: KVM %s not ready after 3 minutes\n", vmName)
|
||||
}
|
||||
|
||||
func (m *Manager) StopContainer(id int) error {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
return fmt.Errorf("container not found: %d", id)
|
||||
}
|
||||
_ = lxc.NewManager().CleanPortMappings(id)
|
||||
lxc.CleanFirewallRules(id)
|
||||
name := c.VirshName()
|
||||
status, _ := m.GetContainerStatus(name)
|
||||
if status != "running" {
|
||||
@@ -709,11 +786,15 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...lx
|
||||
RAMMB: c.RAMMB,
|
||||
DiskGB: c.DiskGB,
|
||||
NetworkBWMbps: c.NetworkBWMbps,
|
||||
NetworkDownMbps: c.NetworkDownMbps,
|
||||
NetworkUpMbps: c.NetworkUpMbps,
|
||||
MonthlyTrafficGB: c.MonthlyTrafficGB,
|
||||
TrafficMode: c.TrafficMode,
|
||||
TrafficInGB: c.TrafficInGB,
|
||||
TrafficOutGB: c.TrafficOutGB,
|
||||
IOSpeedMBps: c.IOSpeedMBps,
|
||||
IOReadMBps: c.IOReadMBps,
|
||||
IOWriteMBps: c.IOWriteMBps,
|
||||
PortMappingCount: c.PortMappingLimit,
|
||||
SnapshotLimit: c.SnapshotLimit,
|
||||
ExpiresAt: c.ExpiresAt,
|
||||
@@ -810,6 +891,7 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
|
||||
if c == nil || !c.IsKVM() {
|
||||
return nil
|
||||
}
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
if c.Status == "running" {
|
||||
// Config already saved; domain definition will be refreshed on next start
|
||||
return nil
|
||||
@@ -821,10 +903,10 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
|
||||
if IsWindowsImage(c.Template) {
|
||||
winISO := ImagePath(c.Template)
|
||||
unattendISO := existingWindowsUnattendISO(m.instanceDir(c.VirshName()))
|
||||
xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
|
||||
xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps)
|
||||
} else {
|
||||
seedPath := filepath.Join(m.instanceDir(c.VirshName()), "seed.iso")
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps, isKVMDesktopTemplate(c.Template))
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps, isKVMDesktopTemplate(c.Template))
|
||||
}
|
||||
xmlPath := filepath.Join(m.instanceDir(c.VirshName()), "domain.xml")
|
||||
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
|
||||
@@ -841,15 +923,16 @@ func (m *Manager) ensureDomainDefinition(c *config.Container) error {
|
||||
if c == nil || !c.IsKVM() || c.DiskImage == "" || c.MACAddress == "" {
|
||||
return nil
|
||||
}
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
var xml string
|
||||
xmlPath := filepath.Join(m.instanceDir(c.VirshName()), "domain.xml")
|
||||
if IsWindowsImage(c.Template) {
|
||||
winISO := ImagePath(c.Template)
|
||||
unattendISO := existingWindowsUnattendISO(m.instanceDir(c.VirshName()))
|
||||
xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
|
||||
xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps)
|
||||
} else {
|
||||
seedPath := filepath.Join(m.instanceDir(c.VirshName()), "seed.iso")
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps, isKVMDesktopTemplate(c.Template))
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps, isKVMDesktopTemplate(c.Template))
|
||||
}
|
||||
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
|
||||
return err
|
||||
@@ -1115,6 +1198,7 @@ func (m *Manager) prepareVMForColdCopy(id int, name string) (bool, error) {
|
||||
time.Sleep(time.Second)
|
||||
} else {
|
||||
_ = lxc.NewManager().CleanPortMappings(id)
|
||||
lxc.CleanFirewallRules(id)
|
||||
}
|
||||
return wasRunning, nil
|
||||
}
|
||||
@@ -1389,7 +1473,7 @@ func (m *Manager) RefreshNetwork(id int) (string, error) {
|
||||
if changed {
|
||||
config.SaveConfig()
|
||||
}
|
||||
if c.Status == "running" && len(c.PortMappings) > 0 && shouldApplyPortMappings(id, changed) {
|
||||
if c.Status == "running" && shouldApplyPortMappings(id, changed) {
|
||||
if err := lxc.NewManager().ApplyPortMappings(id); err != nil {
|
||||
return ip, err
|
||||
}
|
||||
@@ -1596,7 +1680,7 @@ func createEmptyDisk(target string, diskGB int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func createWindowsUnattendISO(target, hostname, adminPassword string, ipv6s []string) error {
|
||||
func createWindowsUnattendISO(target, hostname, adminPassword string, ipv6s []string, ipv4s []string) error {
|
||||
tool := firstAvailableCommand("genisoimage", "mkisofs", "xorriso")
|
||||
if tool == "" {
|
||||
return fmt.Errorf("one of genisoimage, mkisofs, xorriso is required for Windows unattended setup")
|
||||
@@ -1622,13 +1706,13 @@ func createWindowsUnattendISO(target, hostname, adminPassword string, ipv6s []st
|
||||
if err := os.WriteFile(filepath.Join(setupScriptsDir, "SetupComplete.cmd"), []byte(windowsSetupCompleteCMD()), 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(clicdDir, "FirstLogon.ps1"), []byte(windowsFirstLogonPowerShell(adminPassword, ipv6s)), 0600); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(clicdDir, "FirstLogon.ps1"), []byte(windowsFirstLogonPowerShell(adminPassword, ipv6s, ipv4s)), 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "SetupComplete.cmd"), []byte(windowsSetupCompleteCMD()), 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "FirstLogon.ps1"), []byte(windowsFirstLogonPowerShell(adminPassword, ipv6s)), 0600); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(dir, "FirstLogon.ps1"), []byte(windowsFirstLogonPowerShell(adminPassword, ipv6s, ipv4s)), 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(target)
|
||||
@@ -1738,7 +1822,7 @@ exit /b 0
|
||||
`
|
||||
}
|
||||
|
||||
func windowsFirstLogonPowerShell(adminPassword string, ipv6s []string) string {
|
||||
func windowsFirstLogonPowerShell(adminPassword string, ipv6s []string, ipv4s []string) string {
|
||||
commands := []string{
|
||||
"$ErrorActionPreference='Continue'",
|
||||
"$ProgressPreference='SilentlyContinue'",
|
||||
@@ -1774,6 +1858,12 @@ func windowsFirstLogonPowerShell(adminPassword string, ipv6s []string) string {
|
||||
windowsIPv6PowerShell(ipv6s),
|
||||
)
|
||||
}
|
||||
ipv4s = normalizeKVMIPv4List(ipv4s)
|
||||
if len(ipv4s) > 0 {
|
||||
commands = append(commands,
|
||||
windowsIPv4PowerShell(ipv4s),
|
||||
)
|
||||
}
|
||||
commands = append(commands,
|
||||
"New-Item -ItemType File -Force -Path 'C:\\CLICD\\init.done' | Out-Null",
|
||||
"} finally { Stop-Transcript | Out-Null }",
|
||||
@@ -1792,8 +1882,7 @@ func windowsIPv6PowerShell(ipv6s []string) string {
|
||||
}
|
||||
return strings.Join([]string{
|
||||
"$clicdIPv6=@(" + strings.Join(quoted, ",") + ")",
|
||||
"$iface=$null",
|
||||
"for ($i=0; $i -lt 60 -and -not $iface; $i++) { $iface=Get-NetAdapter | Where-Object { $_.Status -eq 'Up' -and $_.HardwareInterface } | Sort-Object ifIndex | Select-Object -First 1; if (-not $iface) { Start-Sleep -Seconds 5 } }",
|
||||
// Reuse $iface already found by the main script
|
||||
"if ($iface) {",
|
||||
" foreach ($ip in $clicdIPv6) {",
|
||||
" Get-NetIPAddress -InterfaceIndex $iface.ifIndex -AddressFamily IPv6 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -eq $ip } | Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue",
|
||||
@@ -1806,12 +1895,48 @@ func windowsIPv6PowerShell(ipv6s []string) string {
|
||||
}, "\r\n")
|
||||
}
|
||||
|
||||
func windowsIPv4PowerShell(ipv4s []string) string {
|
||||
ipv4s = normalizeKVMIPv4List(ipv4s)
|
||||
if len(ipv4s) == 0 {
|
||||
return ""
|
||||
}
|
||||
quoted := make([]string, 0, len(ipv4s))
|
||||
for _, ipv4 := range ipv4s {
|
||||
quoted = append(quoted, "'"+strings.ReplaceAll(ipv4, "'", "''")+"'")
|
||||
}
|
||||
return strings.Join([]string{
|
||||
"$clicdIPv4=@(" + strings.Join(quoted, ",") + ")",
|
||||
// Reuse $iface already found by the main script
|
||||
"if ($iface) {",
|
||||
" foreach ($ip in $clicdIPv4) {",
|
||||
" Get-NetIPAddress -InterfaceIndex $iface.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -eq $ip } | Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue",
|
||||
" New-NetIPAddress -IPAddress $ip -PrefixLength 32 -InterfaceIndex $iface.ifIndex -SkipAsSource:$false -ErrorAction SilentlyContinue | Out-Null",
|
||||
" }",
|
||||
"}",
|
||||
}, "\r\n")
|
||||
}
|
||||
|
||||
func normalizeKVMIPv4List(values []string) []string {
|
||||
seen := map[string]bool{}
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || seen[value] {
|
||||
continue
|
||||
}
|
||||
seen[value] = true
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func shellQuoteWindows(value string) string {
|
||||
return `"` + strings.ReplaceAll(value, `"`, `\"`) + `"`
|
||||
}
|
||||
|
||||
func createSeedISO(seedPath, instanceID, hostname, password, publicKey, mac string, ipv6s []string, image Image) error {
|
||||
guestSetup := kvmSSHSetupScript(password, publicKey)
|
||||
func createSeedISO(seedPath, instanceID, hostname, password, publicKey, mac string, ipv6s []string, ipv4s []string, image Image, sshAuthMode string) error {
|
||||
disablePubkey := sshAuthMode == "password" || sshAuthMode == "auto_password"
|
||||
guestSetup := kvmSSHSetupScript(password, disablePubkey, publicKey)
|
||||
if desktopSetup := kvmDesktopSetupScript(image); desktopSetup != "" {
|
||||
guestSetup += "\n" + desktopSetup
|
||||
}
|
||||
@@ -1846,29 +1971,40 @@ runcmd:
|
||||
%s
|
||||
`, hostname, password, authorizedKeys, setupScript)
|
||||
metaData := fmt.Sprintf("instance-id: %s\nlocal-hostname: %s\n", instanceID, hostname)
|
||||
ipv6Block := ""
|
||||
|
||||
// Build static address block (IPv4 + IPv6)
|
||||
ipv4s = normalizeKVMIPv4List(ipv4s)
|
||||
addressBlock := ""
|
||||
addressLines := make([]string, 0, len(ipv4s)+len(ipv6s))
|
||||
for _, ipv4 := range ipv4s {
|
||||
addressLines = append(addressLines, fmt.Sprintf(" - %s/32", ipv4))
|
||||
}
|
||||
for _, ipv6 := range ipv6s {
|
||||
addressLines = append(addressLines, fmt.Sprintf(" - %s/128", ipv6))
|
||||
}
|
||||
if len(addressLines) > 0 {
|
||||
addressBlock = fmt.Sprintf("\n addresses:\n%s", strings.Join(addressLines, "\n"))
|
||||
}
|
||||
|
||||
// IPv6 routes (only needed when IPv6 addresses are configured)
|
||||
ipv6RouteBlock := ""
|
||||
if len(ipv6s) > 0 {
|
||||
addressLines := make([]string, 0, len(ipv6s))
|
||||
for _, ipv6 := range ipv6s {
|
||||
addressLines = append(addressLines, fmt.Sprintf(" - %s/128", ipv6))
|
||||
}
|
||||
ipv6Block = fmt.Sprintf(`
|
||||
addresses:
|
||||
%s
|
||||
ipv6RouteBlock = fmt.Sprintf(`
|
||||
routes:
|
||||
- to: default
|
||||
via: %s
|
||||
on-link: true
|
||||
metric: 100`, strings.Join(addressLines, "\n"), ipv6GatewayLinkLocal)
|
||||
metric: 100`, ipv6GatewayLinkLocal)
|
||||
}
|
||||
|
||||
networkConfig := fmt.Sprintf(`version: 2
|
||||
ethernets:
|
||||
nic0:
|
||||
match:
|
||||
macaddress: "%s"
|
||||
dhcp4: true
|
||||
dhcp6: false%s
|
||||
`, strings.ToLower(mac), ipv6Block)
|
||||
dhcp6: false%s%s
|
||||
`, strings.ToLower(mac), addressBlock, ipv6RouteBlock)
|
||||
dir := filepath.Dir(seedPath)
|
||||
userPath := filepath.Join(dir, "user-data")
|
||||
metaPath := filepath.Join(dir, "meta-data")
|
||||
@@ -1900,6 +2036,16 @@ func configIPv6AssignmentAddresses(assignments []config.IPv6Assignment) []string
|
||||
return values
|
||||
}
|
||||
|
||||
func configIPv4AssignmentAddresses(assignments []config.PublicIPv4Assignment) []string {
|
||||
values := make([]string, 0, len(assignments))
|
||||
for _, item := range assignments {
|
||||
if strings.TrimSpace(item.Address) != "" {
|
||||
values = append(values, strings.TrimSpace(item.Address))
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func normalizeKVMIPv6List(values []string) []string {
|
||||
seen := map[string]bool{}
|
||||
result := make([]string, 0, len(values))
|
||||
@@ -1944,7 +2090,7 @@ func isKVMDesktopTemplate(templateID string) bool {
|
||||
return image != nil && image.Desktop != ""
|
||||
}
|
||||
|
||||
func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string, ioSpeedMBps int, networkBWMbps int, desktop bool) string {
|
||||
func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string, ioReadMBps int, ioWriteMBps int, networkDownMbps int, networkUpMbps int, desktop bool) string {
|
||||
if vcpu < 1 {
|
||||
vcpu = 1
|
||||
}
|
||||
@@ -1952,21 +2098,32 @@ func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string,
|
||||
ramMB = 512
|
||||
}
|
||||
iotune := ""
|
||||
if ioSpeedMBps > 0 {
|
||||
bytesPerSecond := int64(ioSpeedMBps) * 1024 * 1024
|
||||
if ioReadMBps > 0 || ioWriteMBps > 0 {
|
||||
var parts []string
|
||||
if ioReadMBps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <read_bytes_sec>%d</read_bytes_sec>", int64(ioReadMBps)*1024*1024))
|
||||
}
|
||||
if ioWriteMBps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <write_bytes_sec>%d</write_bytes_sec>", int64(ioWriteMBps)*1024*1024))
|
||||
}
|
||||
iotune = fmt.Sprintf(`
|
||||
<iotune>
|
||||
<total_bytes_sec>%d</total_bytes_sec>
|
||||
</iotune>`, bytesPerSecond)
|
||||
%s
|
||||
</iotune>`, strings.Join(parts, "\n"))
|
||||
}
|
||||
bandwidth := ""
|
||||
if networkBWMbps > 0 {
|
||||
averageKiB := networkBWMbps * 128
|
||||
if networkDownMbps > 0 || networkUpMbps > 0 {
|
||||
var parts []string
|
||||
if networkDownMbps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <inbound average='%d'/>", networkDownMbps*128))
|
||||
}
|
||||
if networkUpMbps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <outbound average='%d'/>", networkUpMbps*128))
|
||||
}
|
||||
bandwidth = fmt.Sprintf(`
|
||||
<bandwidth>
|
||||
<inbound average='%d'/>
|
||||
<outbound average='%d'/>
|
||||
</bandwidth>`, averageKiB, averageKiB)
|
||||
%s
|
||||
</bandwidth>`, strings.Join(parts, "\n"))
|
||||
}
|
||||
video := "<video><model type='virtio'/></video>"
|
||||
input := ""
|
||||
@@ -2023,7 +2180,7 @@ func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string,
|
||||
</domain>`, xmlEscape(name), domainUUIDXML(name), ramMB, ramMB, vcpu, vcpu, xmlEscape(diskPath), iotune, xmlEscape(seedPath), xmlEscape(mac), bandwidth, input, video)
|
||||
}
|
||||
|
||||
func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, unattendISOPath, mac string, ioSpeedMBps int, networkBWMbps int) string {
|
||||
func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, unattendISOPath, mac string, ioReadMBps int, ioWriteMBps int, networkDownMbps int, networkUpMbps int) string {
|
||||
if vcpu < 1 {
|
||||
vcpu = 1
|
||||
}
|
||||
@@ -2031,21 +2188,32 @@ func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, un
|
||||
ramMB = 2048
|
||||
}
|
||||
iotune := ""
|
||||
if ioSpeedMBps > 0 {
|
||||
bytesPerSecond := int64(ioSpeedMBps) * 1024 * 1024
|
||||
if ioReadMBps > 0 || ioWriteMBps > 0 {
|
||||
var parts []string
|
||||
if ioReadMBps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <read_bytes_sec>%d</read_bytes_sec>", int64(ioReadMBps)*1024*1024))
|
||||
}
|
||||
if ioWriteMBps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <write_bytes_sec>%d</write_bytes_sec>", int64(ioWriteMBps)*1024*1024))
|
||||
}
|
||||
iotune = fmt.Sprintf(`
|
||||
<iotune>
|
||||
<total_bytes_sec>%d</total_bytes_sec>
|
||||
</iotune>`, bytesPerSecond)
|
||||
%s
|
||||
</iotune>`, strings.Join(parts, "\n"))
|
||||
}
|
||||
bandwidth := ""
|
||||
if networkBWMbps > 0 {
|
||||
averageKiB := networkBWMbps * 128
|
||||
if networkDownMbps > 0 || networkUpMbps > 0 {
|
||||
var parts []string
|
||||
if networkDownMbps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <inbound average='%d'/>", networkDownMbps*128))
|
||||
}
|
||||
if networkUpMbps > 0 {
|
||||
parts = append(parts, fmt.Sprintf(" <outbound average='%d'/>", networkUpMbps*128))
|
||||
}
|
||||
bandwidth = fmt.Sprintf(`
|
||||
<bandwidth>
|
||||
<inbound average='%d'/>
|
||||
<outbound average='%d'/>
|
||||
</bandwidth>`, averageKiB, averageKiB)
|
||||
%s
|
||||
</bandwidth>`, strings.Join(parts, "\n"))
|
||||
}
|
||||
virtioWinISO := virtioWinISOPath()
|
||||
unattendDisk := ""
|
||||
@@ -2356,6 +2524,9 @@ func (m *Manager) EnsureSSH(id int) error {
|
||||
if mapErr := lxc.NewManager().ApplyPortMappings(id); mapErr != nil {
|
||||
return mapErr
|
||||
}
|
||||
if err := lxc.ApplyFirewallRules(id); err != nil {
|
||||
fmt.Printf("Warning: failed to apply firewall rules: %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if lastErr == nil {
|
||||
@@ -2368,11 +2539,11 @@ func runKVMGuestAgentSSHSetup(name string, password string) error {
|
||||
if err := qemuGuestPing(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return qemuGuestExec(name, kvmSSHSetupScript(password), 180*time.Second)
|
||||
return qemuGuestExec(name, kvmSSHSetupScript(password, false), 180*time.Second)
|
||||
}
|
||||
|
||||
func runKVMSSHSetup(client *ssh.Client, password string) error {
|
||||
return runKVMSSHScript(client, kvmSSHSetupScript(password), "KVM SSH", 150*time.Second)
|
||||
return runKVMSSHScript(client, kvmSSHSetupScript(password, false), "KVM SSH", 150*time.Second)
|
||||
}
|
||||
|
||||
func runKVMSSHScript(client *ssh.Client, script string, description string, timeout time.Duration) error {
|
||||
@@ -2385,7 +2556,8 @@ func runKVMSSHScript(client *ssh.Client, script string, description string, time
|
||||
var output []byte
|
||||
go func() {
|
||||
var err error
|
||||
output, err = session.CombinedOutput(script)
|
||||
session.Stdin = strings.NewReader(script)
|
||||
output, err = session.CombinedOutput("sh -s")
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
@@ -2400,12 +2572,16 @@ func runKVMSSHScript(client *ssh.Client, script string, description string, time
|
||||
}
|
||||
}
|
||||
|
||||
func kvmSSHSetupScript(password string, publicKeys ...string) string {
|
||||
func kvmSSHSetupScript(password string, disablePubkeyAuth bool, publicKeys ...string) string {
|
||||
publicKey := ""
|
||||
if len(publicKeys) > 0 {
|
||||
publicKey = strings.TrimSpace(publicKeys[0])
|
||||
}
|
||||
return `set -u
|
||||
pubkeyValue := "yes"
|
||||
if disablePubkeyAuth {
|
||||
pubkeyValue = "no"
|
||||
}
|
||||
script := `set -u
|
||||
ROOT_PASSWORD=` + shellQuote(password) + `
|
||||
SSH_PUBLIC_KEY=` + shellQuote(publicKey) + `
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
@@ -2434,7 +2610,7 @@ fi
|
||||
mkdir -p /etc/ssh/sshd_config.d
|
||||
cat > /etc/ssh/sshd_config.d/99-clicd-root.conf <<'EOF'
|
||||
PermitRootLogin yes
|
||||
PubkeyAuthentication yes
|
||||
PubkeyAuthentication __CLICD_PUBKEY_AUTH__
|
||||
PasswordAuthentication yes
|
||||
KbdInteractiveAuthentication yes
|
||||
ChallengeResponseAuthentication yes
|
||||
@@ -2442,8 +2618,8 @@ EOF
|
||||
if [ -f /etc/ssh/sshd_config ]; then
|
||||
grep -q '^PermitRootLogin ' /etc/ssh/sshd_config && sed -i 's/^PermitRootLogin .*/PermitRootLogin yes/' /etc/ssh/sshd_config || printf '\nPermitRootLogin yes\n' >> /etc/ssh/sshd_config
|
||||
grep -q '^#PermitRootLogin ' /etc/ssh/sshd_config && sed -i 's/^#PermitRootLogin .*/PermitRootLogin yes/' /etc/ssh/sshd_config || true
|
||||
grep -q '^PubkeyAuthentication ' /etc/ssh/sshd_config && sed -i 's/^PubkeyAuthentication .*/PubkeyAuthentication yes/' /etc/ssh/sshd_config || printf '\nPubkeyAuthentication yes\n' >> /etc/ssh/sshd_config
|
||||
grep -q '^#PubkeyAuthentication ' /etc/ssh/sshd_config && sed -i 's/^#PubkeyAuthentication .*/PubkeyAuthentication yes/' /etc/ssh/sshd_config || true
|
||||
grep -q '^PubkeyAuthentication ' /etc/ssh/sshd_config && sed -i 's/^PubkeyAuthentication .*/PubkeyAuthentication __CLICD_PUBKEY_AUTH__/' /etc/ssh/sshd_config || printf '\nPubkeyAuthentication __CLICD_PUBKEY_AUTH__\n' >> /etc/ssh/sshd_config
|
||||
grep -q '^#PubkeyAuthentication ' /etc/ssh/sshd_config && sed -i 's/^#PubkeyAuthentication .*/PubkeyAuthentication __CLICD_PUBKEY_AUTH__/' /etc/ssh/sshd_config || true
|
||||
grep -q '^PasswordAuthentication ' /etc/ssh/sshd_config && sed -i 's/^PasswordAuthentication .*/PasswordAuthentication yes/' /etc/ssh/sshd_config || printf '\nPasswordAuthentication yes\n' >> /etc/ssh/sshd_config
|
||||
grep -q '^#PasswordAuthentication ' /etc/ssh/sshd_config && sed -i 's/^#PasswordAuthentication .*/PasswordAuthentication yes/' /etc/ssh/sshd_config || true
|
||||
grep -q '^KbdInteractiveAuthentication ' /etc/ssh/sshd_config && sed -i 's/^KbdInteractiveAuthentication .*/KbdInteractiveAuthentication yes/' /etc/ssh/sshd_config || printf '\nKbdInteractiveAuthentication yes\n' >> /etc/ssh/sshd_config
|
||||
@@ -2458,7 +2634,10 @@ if [ -n "$SSH_PUBLIC_KEY" ]; then
|
||||
chown -R root:root /root/.ssh 2>/dev/null || true
|
||||
fi
|
||||
if command -v chpasswd >/dev/null 2>&1; then
|
||||
printf 'root:%s\n' "$ROOT_PASSWORD" | chpasswd || true
|
||||
printf 'root:%s\n' "$ROOT_PASSWORD" | chpasswd 2>/tmp/clicd-chpasswd.log && echo "root password set via chpasswd" || echo "WARNING: chpasswd failed: $(cat /tmp/clicd-chpasswd.log 2>/dev/null)"
|
||||
elif command -v openssl >/dev/null 2>&1 && command -v usermod >/dev/null 2>&1; then
|
||||
HASH=$(echo "$ROOT_PASSWORD" | openssl passwd -6 -stdin 2>/dev/null)
|
||||
[ -n "$HASH" ] && usermod -p "$HASH" root 2>/dev/null && echo "root password set via openssl/usermod" || echo "WARNING: openssl/usermod failed"
|
||||
fi
|
||||
ssh-keygen -A >/dev/null 2>&1 || true
|
||||
if command -v systemctl >/dev/null 2>&1; then
|
||||
@@ -2484,6 +2663,8 @@ if [ -w /dev/tty1 ]; then
|
||||
printf '\nCLICD VNC console is ready. Press Enter for login prompt.\n' >/dev/tty1 || true
|
||||
fi
|
||||
`
|
||||
script = strings.ReplaceAll(script, "__CLICD_PUBKEY_AUTH__", pubkeyValue)
|
||||
return script
|
||||
}
|
||||
|
||||
func kvmDesktopSetupScript(image Image) string {
|
||||
@@ -3083,6 +3264,11 @@ func (m *Manager) applyIPv6Runtime(c *config.Container) error {
|
||||
}
|
||||
ensureKVMIPv6NAT66(assignment.Address, uplink)
|
||||
}
|
||||
if c.Status == "running" {
|
||||
if err := lxc.ApplyFirewallRules(c.ID); err != nil {
|
||||
fmt.Printf("Warning: failed to re-apply firewall rules after KVM IPv6 setup for %s: %v\n", c.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3159,7 +3345,7 @@ func ensureKVMIPv6ForwardRules(ipv6 string, bridge string) {
|
||||
}
|
||||
for _, rule := range rules {
|
||||
check := append([]string{"-C"}, rule...)
|
||||
add := append([]string{"-I"}, append([]string{rule[0], "1"}, rule[1:]...)...)
|
||||
add := append([]string{"-A"}, rule...)
|
||||
if exec.Command("ip6tables", check...).Run() != nil {
|
||||
exec.Command("ip6tables", add...).Run()
|
||||
}
|
||||
@@ -3437,11 +3623,10 @@ func (m *Manager) allocateIPv6ForContainer(id int) (string, int, string, error)
|
||||
}
|
||||
|
||||
func (m *Manager) allocateIPv6AssignmentsForContainer(id int, requested []string, count int, auto bool) ([]config.IPv6Assignment, error) {
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
if len(requested) > count {
|
||||
count = len(requested)
|
||||
var err error
|
||||
count, err = lxc.NormalizePublicIPAllocationCount(requested, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefixes := lxc.DetectPublicIPv6Prefixes()
|
||||
if len(prefixes) == 0 {
|
||||
@@ -3483,7 +3668,7 @@ func (m *Manager) allocateIPv6AssignmentsForContainer(id int, requested []string
|
||||
}
|
||||
}
|
||||
}
|
||||
result := make([]config.IPv6Assignment, 0, count)
|
||||
result := []config.IPv6Assignment{}
|
||||
selected := map[string]bool{}
|
||||
for _, raw := range requested {
|
||||
raw = strings.TrimSpace(raw)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
)
|
||||
|
||||
const ipv6GatewayLinkLocal = "fe80::1"
|
||||
const MaxPublicIPAssignments = 64
|
||||
|
||||
type IPv6PrefixInfo struct {
|
||||
Interface string `json:"interface"`
|
||||
@@ -836,11 +837,10 @@ func detectPublicIPv4LocalAddresses() []PublicIPInfo {
|
||||
}
|
||||
|
||||
func AllocatePublicIPv4Assignments(id int, requested []string, count int, auto bool) ([]config.PublicIPv4Assignment, error) {
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
if len(requested) > count {
|
||||
count = len(requested)
|
||||
var err error
|
||||
count, err = NormalizePublicIPAllocationCount(requested, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
candidates := DetectPublicIPv4Candidates()
|
||||
if len(candidates) == 0 {
|
||||
@@ -866,7 +866,7 @@ func AllocatePublicIPv4Assignments(id int, requested []string, count int, auto b
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]config.PublicIPv4Assignment, 0, count)
|
||||
result := []config.PublicIPv4Assignment{}
|
||||
selected := map[string]bool{}
|
||||
for _, raw := range requested {
|
||||
raw = strings.TrimSpace(raw)
|
||||
@@ -916,6 +916,22 @@ func AllocatePublicIPv4Assignments(id int, requested []string, count int, auto b
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func NormalizePublicIPAllocationCount(requested []string, count int) (int, error) {
|
||||
if len(requested) > MaxPublicIPAssignments {
|
||||
return 0, fmt.Errorf("IP address count cannot exceed %d", MaxPublicIPAssignments)
|
||||
}
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
if len(requested) > count {
|
||||
count = len(requested)
|
||||
}
|
||||
if count > MaxPublicIPAssignments {
|
||||
return 0, fmt.Errorf("IP address count cannot exceed %d", MaxPublicIPAssignments)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func EnsureAssignedPublicIPv4s(assignments []config.PublicIPv4Assignment) {
|
||||
for _, assignment := range assignments {
|
||||
addr := strings.TrimSpace(assignment.Address)
|
||||
@@ -1210,13 +1226,37 @@ func isTunnelLikeInterface(iface string) bool {
|
||||
}
|
||||
|
||||
func operState(iface string) string {
|
||||
data, err := os.ReadFile("/sys/class/net/" + iface + "/operstate")
|
||||
path, err := safeSysClassNetFile(iface, "operstate")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func safeSysClassNetFile(iface string, filename string) (string, error) {
|
||||
iface = strings.TrimSpace(iface)
|
||||
filename = strings.TrimSpace(filename)
|
||||
if iface == "" || filename == "" || len(iface) > 64 || len(filename) > 64 {
|
||||
return "", fmt.Errorf("invalid sysfs network path")
|
||||
}
|
||||
if iface == "." || iface == ".." || filename == "." || filename == ".." {
|
||||
return "", fmt.Errorf("invalid sysfs network path")
|
||||
}
|
||||
if strings.ContainsAny(iface, "/\\\x00") || strings.ContainsAny(filename, "/\\\x00") {
|
||||
return "", fmt.Errorf("invalid sysfs network path")
|
||||
}
|
||||
base := filepath.Clean("/sys/class/net")
|
||||
path := filepath.Clean(filepath.Join(base, iface, filename))
|
||||
if !strings.HasPrefix(path, base+string(os.PathSeparator)) {
|
||||
return "", fmt.Errorf("invalid sysfs network path")
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func isPublicIPv4(addr netip.Addr) bool {
|
||||
if !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsLinkLocalUnicast() {
|
||||
return false
|
||||
@@ -1289,11 +1329,10 @@ func (m *Manager) allocateIPv6ForContainer(id int) (string, int, string, error)
|
||||
}
|
||||
|
||||
func (m *Manager) allocateIPv6AssignmentsForContainer(id int, requested []string, count int, auto bool) ([]config.IPv6Assignment, error) {
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
if len(requested) > count {
|
||||
count = len(requested)
|
||||
var err error
|
||||
count, err = NormalizePublicIPAllocationCount(requested, count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status := m.DetectIPv6Status()
|
||||
if !status.Available {
|
||||
@@ -1336,7 +1375,7 @@ func (m *Manager) allocateIPv6AssignmentsForContainer(id int, requested []string
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]config.IPv6Assignment, 0, count)
|
||||
result := []config.IPv6Assignment{}
|
||||
selected := map[string]bool{}
|
||||
for _, raw := range requested {
|
||||
raw = strings.TrimSpace(raw)
|
||||
@@ -1571,6 +1610,9 @@ func (m *Manager) ApplyIPv6(id int) error {
|
||||
ensureIPv6NAT66(assignment.Address, uplink)
|
||||
}
|
||||
}
|
||||
if err := ApplyFirewallRules(c.ID); err != nil {
|
||||
fmt.Printf("Warning: failed to re-apply firewall rules after IPv6 setup for %s: %v\n", c.Name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -226,11 +226,15 @@ type ContainerConfig struct {
|
||||
RAMMB int `json:"ram_mb"`
|
||||
DiskGB int `json:"disk_gb"`
|
||||
NetworkBWMbps int `json:"network_bw_mbps"`
|
||||
NetworkDownMbps int `json:"network_down_mbps"`
|
||||
NetworkUpMbps int `json:"network_up_mbps"`
|
||||
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
|
||||
TrafficMode string `json:"traffic_mode"` // "total" or "in_out"
|
||||
TrafficInGB int `json:"traffic_in_gb"` // 0=unlimited
|
||||
TrafficOutGB int `json:"traffic_out_gb"` // 0=unlimited
|
||||
IOSpeedMBps int `json:"io_speed_mbps"`
|
||||
IOReadMBps int `json:"io_read_mbps"`
|
||||
IOWriteMBps int `json:"io_write_mbps"`
|
||||
ExtraPorts []int `json:"extra_ports"`
|
||||
PortMappingCount int `json:"port_mapping_count"`
|
||||
AssignNAT *bool `json:"assign_nat,omitempty"`
|
||||
@@ -247,12 +251,48 @@ type ContainerConfig struct {
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
|
||||
func (cfg *ContainerConfig) NormalizeResourceAliases() {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if cfg.NetworkBWMbps < 0 {
|
||||
cfg.NetworkBWMbps = 0
|
||||
}
|
||||
if cfg.NetworkDownMbps < 0 {
|
||||
cfg.NetworkDownMbps = 0
|
||||
}
|
||||
if cfg.NetworkUpMbps < 0 {
|
||||
cfg.NetworkUpMbps = 0
|
||||
}
|
||||
if cfg.NetworkDownMbps == 0 && cfg.NetworkUpMbps == 0 && cfg.NetworkBWMbps > 0 {
|
||||
cfg.NetworkDownMbps = cfg.NetworkBWMbps
|
||||
cfg.NetworkUpMbps = cfg.NetworkBWMbps
|
||||
}
|
||||
cfg.NetworkBWMbps = config.LegacySymmetricLimit(cfg.NetworkDownMbps, cfg.NetworkUpMbps)
|
||||
|
||||
if cfg.IOSpeedMBps < 0 {
|
||||
cfg.IOSpeedMBps = 0
|
||||
}
|
||||
if cfg.IOReadMBps < 0 {
|
||||
cfg.IOReadMBps = 0
|
||||
}
|
||||
if cfg.IOWriteMBps < 0 {
|
||||
cfg.IOWriteMBps = 0
|
||||
}
|
||||
if cfg.IOReadMBps == 0 && cfg.IOWriteMBps == 0 && cfg.IOSpeedMBps > 0 {
|
||||
cfg.IOReadMBps = cfg.IOSpeedMBps
|
||||
cfg.IOWriteMBps = cfg.IOSpeedMBps
|
||||
}
|
||||
cfg.IOSpeedMBps = config.LegacySymmetricLimit(cfg.IOReadMBps, cfg.IOWriteMBps)
|
||||
}
|
||||
|
||||
func (cfg ContainerConfig) WantsNAT() bool {
|
||||
return cfg.AssignNAT == nil || *cfg.AssignNAT
|
||||
}
|
||||
|
||||
// CreateContainer creates a new LXC container. Uses ct-{id} as LXC name internally.
|
||||
func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
cfg.NormalizeResourceAliases()
|
||||
tmpl := FindTemplate(cfg.TemplateID)
|
||||
if tmpl == nil {
|
||||
return fmt.Errorf("template not found: %s", cfg.TemplateID)
|
||||
@@ -345,12 +385,7 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
|
||||
// Setup default port mappings (SSH only)
|
||||
portMappings = SetupDefaultPortMappings(sshPort)
|
||||
defaultHostIP := defaultPortMappingHostIP(publicIPv4s)
|
||||
if defaultHostIP != "" {
|
||||
for i := range portMappings {
|
||||
portMappings[i].HostIP = defaultHostIP
|
||||
}
|
||||
}
|
||||
// NAT4 port mappings should bind to the host IP, not the container's independent public IPv4.
|
||||
tempC := &config.Container{ID: id, PublicIPv4s: publicIPv4s, PortMappings: portMappings}
|
||||
|
||||
extraPorts := cfg.ExtraPorts
|
||||
@@ -364,7 +399,7 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
pm, err := normalizePortMapping(tempC, -1, config.PortMapping{
|
||||
ContainerPort: containerPort,
|
||||
HostPort: containerPort,
|
||||
HostIP: defaultHostIP,
|
||||
HostIP: "",
|
||||
Protocol: "tcp",
|
||||
Description: fmt.Sprintf("Port-%d", containerPort),
|
||||
})
|
||||
@@ -394,12 +429,16 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
RAMMB: cfg.RAMMB,
|
||||
DiskGB: cfg.DiskGB,
|
||||
NetworkBWMbps: cfg.NetworkBWMbps,
|
||||
NetworkDownMbps: cfg.NetworkDownMbps,
|
||||
NetworkUpMbps: cfg.NetworkUpMbps,
|
||||
MonthlyTrafficGB: cfg.MonthlyTrafficGB,
|
||||
TrafficMode: trafficMode,
|
||||
TrafficInGB: cfg.TrafficInGB,
|
||||
TrafficOutGB: cfg.TrafficOutGB,
|
||||
TrafficResetDate: trafficResetDate,
|
||||
IOSpeedMBps: cfg.IOSpeedMBps,
|
||||
IOReadMBps: cfg.IOReadMBps,
|
||||
IOWriteMBps: cfg.IOWriteMBps,
|
||||
Status: "stopped",
|
||||
IP: "",
|
||||
PublicIPv4s: publicIPv4s,
|
||||
@@ -424,7 +463,7 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
fmt.Printf("Warning: failed to install IPv6 init in %s: %v\n", lxcName, err)
|
||||
}
|
||||
}
|
||||
if err := m.preconfigureSSH(rootfsPath, cfg.TemplateID); err != nil {
|
||||
if err := m.preconfigureSSH(rootfsPath, cfg.TemplateID, sshAccess.Mode); err != nil {
|
||||
fmt.Printf("Warning: failed to pre-configure SSH in %s: %v\n", lxcName, err)
|
||||
}
|
||||
if sshAccess.PublicKey != "" {
|
||||
@@ -512,11 +551,13 @@ IPv6AcceptRA=no
|
||||
}
|
||||
|
||||
// preconfigureSSH installs and configures SSH directly in the rootfs before first boot.
|
||||
func (m *Manager) preconfigureSSH(rootfsPath, templateID string) error {
|
||||
func (m *Manager) preconfigureSSH(rootfsPath, templateID string, sshAuthMode string) error {
|
||||
_ = templateID
|
||||
// Disable pubkey auth when user chose password-only mode (password or auto_password)
|
||||
disablePubkey := sshAuthMode == SSHAuthPassword || sshAuthMode == SSHAuthAutoPassword
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
cmd, err := m.rootfsCommand(rootfsPath, "sh", "-c", sshSetupScript(false))
|
||||
cmd, err := m.rootfsCommand(rootfsPath, "sh", "-c", sshSetupScript(false, disablePubkey))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -534,6 +575,7 @@ func (m *Manager) preconfigureSSH(rootfsPath, templateID string) error {
|
||||
|
||||
// applyResourceLimits applies cgroup v2 limits and mandatory security hardening to container config.
|
||||
func (m *Manager) applyResourceLimits(lxcName string, cfg ContainerConfig) error {
|
||||
cfg.NormalizeResourceAliases()
|
||||
configFile := filepath.Join(m.LxcPath, lxcName, "config")
|
||||
|
||||
data, err := os.ReadFile(configFile)
|
||||
@@ -602,12 +644,12 @@ func (m *Manager) applyResourceLimits(lxcName string, cfg ContainerConfig) error
|
||||
ramBytes := int64(cfg.RAMMB) * 1024 * 1024
|
||||
newLines = append(newLines, fmt.Sprintf("lxc.cgroup2.memory.max = %d", ramBytes))
|
||||
}
|
||||
if cfg.IOSpeedMBps > 0 {
|
||||
if cfg.IOReadMBps > 0 || cfg.IOWriteMBps > 0 {
|
||||
// Note: lxc.cgroup2.io.max is skipped for unprivileged containers because
|
||||
// LXC's cgfsng_setup_limits cannot resolve host device numbers (e.g. 8:1)
|
||||
// in the unprivileged namespace context.
|
||||
// IO limits are instead applied post-start via direct cgroup2 writes.
|
||||
fmt.Printf("Info: IO limit (%d MB/s) for %s will be applied post-start via cgroup2\n", cfg.IOSpeedMBps, lxcName)
|
||||
fmt.Printf("Info: IO limit (read=%d MB/s write=%d MB/s) for %s will be applied post-start via cgroup2\n", cfg.IOReadMBps, cfg.IOWriteMBps, lxcName)
|
||||
}
|
||||
|
||||
newContent := strings.Join(newLines, "\n")
|
||||
@@ -617,18 +659,28 @@ func (m *Manager) applyResourceLimits(lxcName string, cfg ContainerConfig) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) ioLimitLines(lxcName string, mbps int) ([]string, error) {
|
||||
if mbps <= 0 {
|
||||
return nil, nil
|
||||
func (m *Manager) ioLimitLines(lxcName string, readMBps int, writeMBps int) ([]string, error) {
|
||||
if readMBps < 0 {
|
||||
readMBps = 0
|
||||
}
|
||||
if writeMBps < 0 {
|
||||
writeMBps = 0
|
||||
}
|
||||
devices, err := m.rootfsBlockDevices(lxcName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ioBytes := mbps * 1024 * 1024
|
||||
readValue := "max"
|
||||
if readMBps > 0 {
|
||||
readValue = strconv.Itoa(readMBps * 1024 * 1024)
|
||||
}
|
||||
writeValue := "max"
|
||||
if writeMBps > 0 {
|
||||
writeValue = strconv.Itoa(writeMBps * 1024 * 1024)
|
||||
}
|
||||
lines := make([]string, 0, len(devices))
|
||||
for _, device := range devices {
|
||||
lines = append(lines, fmt.Sprintf("%s rbps=%d wbps=%d", device, ioBytes, ioBytes))
|
||||
lines = append(lines, fmt.Sprintf("%s rbps=%s wbps=%s", device, readValue, writeValue))
|
||||
}
|
||||
return lines, nil
|
||||
}
|
||||
@@ -1256,8 +1308,12 @@ func (m *Manager) StartContainer(id int) error {
|
||||
RAMMB: c.RAMMB,
|
||||
DiskGB: c.DiskGB,
|
||||
NetworkBWMbps: c.NetworkBWMbps,
|
||||
NetworkDownMbps: c.NetworkDownMbps,
|
||||
NetworkUpMbps: c.NetworkUpMbps,
|
||||
MonthlyTrafficGB: c.MonthlyTrafficGB,
|
||||
IOSpeedMBps: c.IOSpeedMBps,
|
||||
IOReadMBps: c.IOReadMBps,
|
||||
IOWriteMBps: c.IOWriteMBps,
|
||||
AssignIPv6: c.IPv6 != "" || len(c.IPv6Addresses) > 0,
|
||||
ExpiresAt: c.ExpiresAt,
|
||||
}); err != nil {
|
||||
@@ -1327,6 +1383,9 @@ func (m *Manager) StartContainer(id int) error {
|
||||
if err := m.ApplyPortMappings(id); err != nil {
|
||||
fmt.Printf("Warning: failed to apply port mappings: %v\n", err)
|
||||
}
|
||||
if err := ApplyFirewallRules(id); err != nil {
|
||||
fmt.Printf("Warning: failed to apply firewall rules: %v\n", err)
|
||||
}
|
||||
if c.IPv6 != "" || len(c.IPv6Addresses) > 0 {
|
||||
if err := m.ApplyIPv6(id); err != nil {
|
||||
fmt.Printf("Warning: failed to apply IPv6 routing for %s: %v\n", lxcName, err)
|
||||
@@ -1378,6 +1437,7 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
|
||||
if c == nil || c.Status != "running" {
|
||||
return nil
|
||||
}
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
lxcName := c.LxcName()
|
||||
|
||||
// CPU: write cpu.max
|
||||
@@ -1400,48 +1460,52 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
|
||||
os.WriteFile(path, []byte(memLine), 0644)
|
||||
}
|
||||
|
||||
// IO speed: write io.max
|
||||
if c.IOSpeedMBps > 0 {
|
||||
ioLines, err := m.ioLimitLines(lxcName, c.IOSpeedMBps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ioLine := strings.Join(ioLines, "\n")
|
||||
for _, path := range []string{
|
||||
fmt.Sprintf("/sys/fs/cgroup/lxc/%s/io.max", lxcName),
|
||||
fmt.Sprintf("/sys/fs/cgroup/lxc.payload.%s/io.max", lxcName),
|
||||
} {
|
||||
os.WriteFile(path, []byte(ioLine), 0644)
|
||||
}
|
||||
// IO speed: write io.max, including max values to clear old per-direction limits.
|
||||
ioLines, err := m.ioLimitLines(lxcName, c.IOReadMBps, c.IOWriteMBps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ioLine := strings.Join(ioLines, "\n")
|
||||
for _, path := range []string{
|
||||
fmt.Sprintf("/sys/fs/cgroup/lxc/%s/io.max", lxcName),
|
||||
fmt.Sprintf("/sys/fs/cgroup/lxc.payload.%s/io.max", lxcName),
|
||||
} {
|
||||
os.WriteFile(path, []byte(ioLine), 0644)
|
||||
}
|
||||
|
||||
// Network bandwidth
|
||||
if c.NetworkBWMbps > 0 {
|
||||
m.applyBandwidthLimit(lxcName, c.NetworkBWMbps)
|
||||
} else {
|
||||
m.cleanupBandwidthLimit(lxcName)
|
||||
}
|
||||
m.applyBandwidthLimit(lxcName, c.NetworkDownMbps, c.NetworkUpMbps)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) applyBandwidthLimit(lxcName string, mbps int) {
|
||||
func (m *Manager) applyBandwidthLimit(lxcName string, downMbps int, upMbps int) {
|
||||
veth := m.getContainerVethByNS(lxcName)
|
||||
if veth == "" {
|
||||
fmt.Printf("Warning: could not find veth for %s\n", lxcName)
|
||||
return
|
||||
}
|
||||
rate := fmt.Sprintf("%dmbit", mbps)
|
||||
burst := fmt.Sprintf("%dkbit", mbps*100)
|
||||
exec.Command("tc", "qdisc", "del", "dev", veth, "root").Run()
|
||||
exec.Command("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:", "htb", "default", "10").Run()
|
||||
exec.Command("tc", "class", "add", "dev", veth, "parent", "1:", "classid", "1:10", "htb", "rate", rate, "burst", burst).Run()
|
||||
fmt.Printf("Bandwidth limit: %s = %d Mbps on %s\n", lxcName, mbps, veth)
|
||||
exec.Command("tc", "qdisc", "del", "dev", veth, "ingress").Run()
|
||||
if downMbps > 0 {
|
||||
rate := fmt.Sprintf("%dmbit", downMbps)
|
||||
burst := fmt.Sprintf("%dkbit", downMbps*100)
|
||||
exec.Command("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:", "htb", "default", "10").Run()
|
||||
exec.Command("tc", "class", "add", "dev", veth, "parent", "1:", "classid", "1:10", "htb", "rate", rate, "burst", burst).Run()
|
||||
}
|
||||
if upMbps > 0 {
|
||||
rate := fmt.Sprintf("%dmbit", upMbps)
|
||||
burst := fmt.Sprintf("%dkbit", upMbps*100)
|
||||
exec.Command("tc", "qdisc", "add", "dev", veth, "handle", "ffff:", "ingress").Run()
|
||||
exec.Command("tc", "filter", "add", "dev", veth, "parent", "ffff:", "protocol", "all", "u32", "match", "u32", "0", "0", "police", "rate", rate, "burst", burst, "drop", "flowid", ":1").Run()
|
||||
}
|
||||
fmt.Printf("Bandwidth limit: %s down=%d Mbps up=%d Mbps on %s\n", lxcName, downMbps, upMbps, veth)
|
||||
}
|
||||
|
||||
func (m *Manager) cleanupBandwidthLimit(lxcName string) {
|
||||
veth := m.getContainerVethByNS(lxcName)
|
||||
if veth != "" {
|
||||
exec.Command("tc", "qdisc", "del", "dev", veth, "root").Run()
|
||||
exec.Command("tc", "qdisc", "del", "dev", veth, "ingress").Run()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1475,11 +1539,13 @@ func (m *Manager) StopContainer(id int) error {
|
||||
if status != "running" {
|
||||
config.UpdateContainerStatus(id, "stopped")
|
||||
m.CleanPortMappings(id)
|
||||
CleanFirewallRules(id)
|
||||
m.cleanupBandwidthLimit(lxcName)
|
||||
return nil
|
||||
}
|
||||
|
||||
m.CleanPortMappings(id)
|
||||
CleanFirewallRules(id)
|
||||
m.cleanupBandwidthLimit(lxcName)
|
||||
|
||||
cmd := exec.Command("lxc-stop", "-n", lxcName)
|
||||
@@ -1758,7 +1824,7 @@ func (m *Manager) EnsureSSH(id int) error {
|
||||
config.SaveConfig()
|
||||
}
|
||||
|
||||
script := sshSetupScript(true)
|
||||
script := sshSetupScript(true, false) // keep pubkey enabled for runtime ensure
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
@@ -1826,7 +1892,11 @@ func (m *Manager) containerPortListening(lxcName string, port int) bool {
|
||||
return exec.CommandContext(ctx, "lxc-attach", "-n", lxcName, "--", "sh", "-c", check).Run() == nil
|
||||
}
|
||||
|
||||
func sshSetupScript(startService bool) string {
|
||||
func sshSetupScript(startService bool, disablePubkeyAuth bool) string {
|
||||
pubkeyValue := "yes"
|
||||
if disablePubkeyAuth {
|
||||
pubkeyValue = "no"
|
||||
}
|
||||
script := `set -u
|
||||
|
||||
# DNS setup: handle both traditional /etc/resolv.conf and systemd-resolved (Ubuntu 24.04).
|
||||
@@ -1945,7 +2015,7 @@ ssh-keygen -A >/dev/null 2>&1 || true
|
||||
|
||||
cat >/etc/ssh/sshd_config.d/99-clicd.conf <<'EOF'
|
||||
PermitRootLogin yes
|
||||
PubkeyAuthentication yes
|
||||
PubkeyAuthentication __CLICD_PUBKEY_AUTH__
|
||||
PasswordAuthentication yes
|
||||
KbdInteractiveAuthentication no
|
||||
ChallengeResponseAuthentication no
|
||||
@@ -1953,7 +2023,7 @@ UsePAM no
|
||||
EOF
|
||||
|
||||
set_sshd_option PermitRootLogin yes
|
||||
set_sshd_option PubkeyAuthentication yes
|
||||
set_sshd_option PubkeyAuthentication __CLICD_PUBKEY_AUTH__
|
||||
set_sshd_option PasswordAuthentication yes
|
||||
set_sshd_option KbdInteractiveAuthentication no
|
||||
set_sshd_option ChallengeResponseAuthentication no
|
||||
@@ -1981,6 +2051,7 @@ ensure_sshd_runtime_dir
|
||||
exit 32
|
||||
}
|
||||
`
|
||||
script = strings.ReplaceAll(script, "__CLICD_PUBKEY_AUTH__", pubkeyValue)
|
||||
if !startService {
|
||||
return script
|
||||
}
|
||||
@@ -2054,7 +2125,7 @@ func (m *Manager) ResetSSHPassword(id int, password string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
rootfsPath := filepath.Join(m.LxcPath, lxcName, "rootfs")
|
||||
if err := m.preconfigureSSH(rootfsPath, c.Template); err != nil {
|
||||
if err := m.preconfigureSSH(rootfsPath, c.Template, ""); err != nil {
|
||||
return "", fmt.Errorf("failed to configure SSH: %v", err)
|
||||
}
|
||||
if err := m.setRootfsPassword(rootfsPath, newPassword); err != nil {
|
||||
@@ -2440,6 +2511,8 @@ func (m *Manager) ImportExistingClicdContainers() ([]config.Container, error) {
|
||||
RAMMB: 512,
|
||||
DiskGB: 10,
|
||||
NetworkBWMbps: 100,
|
||||
NetworkDownMbps: 100,
|
||||
NetworkUpMbps: 100,
|
||||
MonthlyTrafficGB: 1000,
|
||||
TrafficMode: "total",
|
||||
Status: status,
|
||||
@@ -2583,6 +2656,7 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co
|
||||
|
||||
// Clean port mappings temporarily
|
||||
m.CleanPortMappings(id)
|
||||
CleanFirewallRules(id)
|
||||
|
||||
// Download the new OS into a temporary container, then replace only the
|
||||
// existing rootfs. The target container directory and config are preserved.
|
||||
@@ -2602,8 +2676,12 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co
|
||||
RAMMB: c.RAMMB,
|
||||
DiskGB: c.DiskGB,
|
||||
NetworkBWMbps: c.NetworkBWMbps,
|
||||
NetworkDownMbps: c.NetworkDownMbps,
|
||||
NetworkUpMbps: c.NetworkUpMbps,
|
||||
MonthlyTrafficGB: c.MonthlyTrafficGB,
|
||||
IOSpeedMBps: c.IOSpeedMBps,
|
||||
IOReadMBps: c.IOReadMBps,
|
||||
IOWriteMBps: c.IOWriteMBps,
|
||||
AssignIPv6: c.IPv6 != "" || len(c.IPv6Addresses) > 0,
|
||||
ExpiresAt: c.ExpiresAt,
|
||||
}
|
||||
@@ -2626,7 +2704,7 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co
|
||||
}
|
||||
}
|
||||
c.SSHPassword = sshAccess.Password
|
||||
if err := m.preconfigureSSH(rootfsPath, templateID); err != nil {
|
||||
if err := m.preconfigureSSH(rootfsPath, templateID, sshAccess.Mode); err != nil {
|
||||
fmt.Printf("Warning: failed to pre-configure SSH in %s after reinstall: %v\n", lxcName, err)
|
||||
}
|
||||
if sshAccess.PublicKey != "" {
|
||||
@@ -2686,9 +2764,8 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co
|
||||
}
|
||||
}
|
||||
// Apply bandwidth limit after reinstall
|
||||
if c.NetworkBWMbps > 0 {
|
||||
m.applyBandwidthLimit(c.LxcName(), c.NetworkBWMbps)
|
||||
}
|
||||
config.NormalizeContainerResourceAliases(c)
|
||||
m.applyBandwidthLimit(c.LxcName(), c.NetworkDownMbps, c.NetworkUpMbps)
|
||||
if c.IPv6 != "" || len(c.IPv6Addresses) > 0 {
|
||||
if err := m.ApplyIPv6(id); err != nil {
|
||||
fmt.Printf("Warning: failed to apply IPv6 after reinstall: %v\n", err)
|
||||
|
||||
@@ -59,11 +59,54 @@ func (m *Manager) ApplyPortMappings(id int) error {
|
||||
}
|
||||
}
|
||||
|
||||
// When container has public IPv4, apply full port passthrough DNAT so the
|
||||
// container owns all ports on its public IP (no NAT management needed).
|
||||
if len(c.PublicIPv4s) > 0 {
|
||||
ensureIndependentIPv4Ingress(c, tag)
|
||||
}
|
||||
|
||||
applyIPv4EgressPolicy(c, bridge, subnet, tag)
|
||||
|
||||
if err := ApplyFirewallRules(id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureIndependentIPv4Ingress(c *config.Container, tag string) {
|
||||
if c == nil || c.IP == "" || len(c.PublicIPv4s) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, assignment := range c.PublicIPv4s {
|
||||
hostIP := strings.TrimSpace(assignment.Address)
|
||||
if hostIP == "" {
|
||||
continue
|
||||
}
|
||||
// Full port passthrough: DNAT all TCP+UDP traffic on this public IP to the container.
|
||||
for _, proto := range []string{"tcp", "udp"} {
|
||||
args := []string{
|
||||
"-t", "nat",
|
||||
"-I", "PREROUTING", "1",
|
||||
"-d", hostIP,
|
||||
"-p", proto,
|
||||
"-j", "DNAT",
|
||||
"--to-destination", c.IP,
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-%s-all-%s", tag, natRuleIPTag(hostIP), proto),
|
||||
}
|
||||
cmd := exec.Command("iptables", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Printf("Warning: failed to apply %s passthrough %s->%s: %v, output: %s\n",
|
||||
proto, hostIP, c.IP, err, string(output))
|
||||
continue
|
||||
}
|
||||
fmt.Printf("IPv4 passthrough (%s): %s -> %s (all ports)\n", proto, hostIP, c.IP)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func applyIPv4EgressPolicy(c *config.Container, bridge, subnet, tag string) {
|
||||
if c == nil || strings.TrimSpace(c.IP) == "" {
|
||||
return
|
||||
@@ -221,8 +264,8 @@ func EnsureForwardRules(bridge string) {
|
||||
break
|
||||
}
|
||||
}
|
||||
insertArgs := append([]string{"-I", "FORWARD", "1"}, args...)
|
||||
exec.Command("iptables", insertArgs...).Run()
|
||||
appendArgs := append([]string{"-A", "FORWARD"}, args...)
|
||||
exec.Command("iptables", appendArgs...).Run()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,3 +572,374 @@ func hostPortKey(hostIP string, port int) int {
|
||||
}
|
||||
return port + (sum % 1000000 * 100000)
|
||||
}
|
||||
|
||||
// CleanFirewallRules removes all firewall rules for a container from the FORWARD chain.
|
||||
func CleanFirewallRules(id int) {
|
||||
tag := clicdTag(id)
|
||||
// Remove all rules with the firewall tag prefix
|
||||
cmd := exec.Command("bash", "-c",
|
||||
fmt.Sprintf("iptables -S FORWARD 2>/dev/null | grep 'clicd-%s-fw-' | sed 's/^-A /-D /' | while read rule; do iptables $rule; done", tag))
|
||||
cmd.CombinedOutput()
|
||||
cmd = exec.Command("bash", "-c",
|
||||
fmt.Sprintf("ip6tables -S FORWARD 2>/dev/null | grep 'clicd-%s-fw-' | sed 's/^-A /-D /' | while read rule; do ip6tables $rule; done", tag))
|
||||
cmd.CombinedOutput()
|
||||
|
||||
// Also remove legacy default policy rules (without specific rule ID)
|
||||
for _, suffix := range []string{"default-in", "default-out"} {
|
||||
for _, proto := range []string{"tcp", "udp"} {
|
||||
exec.Command("iptables", "-D", "FORWARD",
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-%s-%s", tag, suffix, proto),
|
||||
).CombinedOutput()
|
||||
}
|
||||
exec.Command("ip6tables", "-D", "FORWARD",
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-%s", tag, suffix),
|
||||
).CombinedOutput()
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyFirewallRules applies iptables FORWARD rules for a container's firewall configuration.
|
||||
func ApplyFirewallRules(id int) error {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
return fmt.Errorf("container not found: %d", id)
|
||||
}
|
||||
|
||||
// Always clean existing firewall rules first
|
||||
CleanFirewallRules(id)
|
||||
|
||||
// If firewall is disabled or no rules, nothing to apply
|
||||
if !c.FirewallEnabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
bridge := "lxcbr0"
|
||||
if c.IsKVM() {
|
||||
bridge = "virbr0"
|
||||
}
|
||||
containerIP := strings.TrimSpace(c.IP)
|
||||
containerIPv6s := firewallIPv6Addresses(c)
|
||||
if containerIP == "" && len(containerIPv6s) == 0 {
|
||||
return nil
|
||||
}
|
||||
tag := clicdTag(id)
|
||||
|
||||
defaultAction := normalizeFirewallDefaultAction(c.FirewallDefaultAction)
|
||||
if defaultAction == "DROP" {
|
||||
if containerIP != "" {
|
||||
if err := applyDefaultFirewallPolicy(tag, bridge, containerIP); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := applyDefaultFirewallIPv6Policy(tag, bridge, containerIPv6s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for i := len(c.FirewallRules) - 1; i >= 0; i-- {
|
||||
rule := c.FirewallRules[i]
|
||||
if !rule.Enabled {
|
||||
continue
|
||||
}
|
||||
if containerIP != "" && firewallRuleAppliesToFamily(rule, true) {
|
||||
if err := applyOneFirewallRule(tag, bridge, containerIP, rule); err != nil {
|
||||
return fmt.Errorf("failed to apply firewall rule %s for container %d: %w", rule.ID, id, err)
|
||||
}
|
||||
}
|
||||
if len(containerIPv6s) > 0 && firewallRuleAppliesToFamily(rule, false) {
|
||||
if err := applyOneFirewallIPv6Rule(tag, bridge, containerIPv6s, rule); err != nil {
|
||||
return fmt.Errorf("failed to apply IPv6 firewall rule %s for container %d: %w", rule.ID, id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeFirewallDefaultAction(action string) string {
|
||||
action = strings.ToUpper(strings.TrimSpace(action))
|
||||
if action == "ACCEPT" {
|
||||
return "ACCEPT"
|
||||
}
|
||||
return "DROP"
|
||||
}
|
||||
|
||||
func normalizeFirewallNetwork(network string) string {
|
||||
network = strings.ToLower(strings.TrimSpace(network))
|
||||
switch network {
|
||||
case "", "ipv4", "nat4":
|
||||
return "ipv4"
|
||||
case "ipv6":
|
||||
return "ipv6"
|
||||
case "all", "both":
|
||||
return "all"
|
||||
default:
|
||||
return "ipv4"
|
||||
}
|
||||
}
|
||||
|
||||
func firewallRuleAppliesToFamily(rule config.FirewallRule, ipv4 bool) bool {
|
||||
network := normalizeFirewallNetwork(rule.Network)
|
||||
if network == "ipv4" {
|
||||
return ipv4
|
||||
}
|
||||
if network == "ipv6" {
|
||||
return !ipv4
|
||||
}
|
||||
if rule.SourceIP == "" {
|
||||
return true
|
||||
}
|
||||
addr := firewallIPSpecAddr(rule.SourceIP)
|
||||
if !addr.IsValid() {
|
||||
return true
|
||||
}
|
||||
if ipv4 {
|
||||
return addr.Is4()
|
||||
}
|
||||
return addr.Is6() && !addr.Is4In6()
|
||||
}
|
||||
|
||||
func firewallIPSpecAddr(value string) netip.Addr {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return netip.Addr{}
|
||||
}
|
||||
if strings.Contains(value, "/") {
|
||||
prefix, err := netip.ParsePrefix(value)
|
||||
if err != nil {
|
||||
return netip.Addr{}
|
||||
}
|
||||
return prefix.Addr()
|
||||
}
|
||||
addr, err := netip.ParseAddr(value)
|
||||
if err != nil {
|
||||
return netip.Addr{}
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
func firewallIPv6Addresses(c *config.Container) []string {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
c.NormalizeNetworkAssignments()
|
||||
seen := map[string]bool{}
|
||||
result := []string{}
|
||||
for _, assignment := range c.IPv6Addresses {
|
||||
ip := strings.TrimSpace(assignment.Address)
|
||||
if ip == "" || seen[ip] {
|
||||
continue
|
||||
}
|
||||
if addr, err := netip.ParseAddr(ip); err == nil && addr.Is6() && !addr.Is4In6() {
|
||||
seen[ip] = true
|
||||
result = append(result, ip)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallRule) error {
|
||||
commentTag := fmt.Sprintf("clicd-%s-fw-%s", tag, rule.ID)
|
||||
|
||||
// Build base iptables args
|
||||
args := []string{"-I", "FORWARD", "1"}
|
||||
|
||||
// Direction: in = traffic arriving at container (-o bridge -d containerIP)
|
||||
// out = traffic leaving container (-i bridge -s containerIP)
|
||||
switch rule.Direction {
|
||||
case "in":
|
||||
args = append(args, "-o", bridge, "-d", containerIP+"/32")
|
||||
case "out":
|
||||
args = append(args, "-i", bridge, "-s", containerIP+"/32")
|
||||
default:
|
||||
return fmt.Errorf("invalid direction: %s", rule.Direction)
|
||||
}
|
||||
|
||||
// Protocol
|
||||
switch rule.Protocol {
|
||||
case "tcp", "udp":
|
||||
args = append(args, "-p", rule.Protocol)
|
||||
case "icmp":
|
||||
args = append(args, "-p", "icmp")
|
||||
case "all":
|
||||
// no protocol filter
|
||||
default:
|
||||
return fmt.Errorf("invalid protocol: %s", rule.Protocol)
|
||||
}
|
||||
|
||||
// Port matching (only for tcp/udp)
|
||||
if rule.Port != "" && (rule.Protocol == "tcp" || rule.Protocol == "udp") {
|
||||
// For "in" direction, traffic going TO the container uses --dport
|
||||
// For "out" direction, traffic going FROM the container uses --dport (destination port on remote)
|
||||
args = append(args, firewallPortArgs(rule.Port)...)
|
||||
}
|
||||
|
||||
// Source IP filter (for "out" direction, this matches the remote source; for "in", it matches the sender)
|
||||
if rule.SourceIP != "" {
|
||||
switch rule.Direction {
|
||||
case "in":
|
||||
args = append(args, "-s", rule.SourceIP)
|
||||
case "out":
|
||||
args = append(args, "-d", rule.SourceIP)
|
||||
}
|
||||
}
|
||||
|
||||
// Action
|
||||
action := "DROP"
|
||||
if rule.Action == "ACCEPT" {
|
||||
action = "ACCEPT"
|
||||
}
|
||||
args = append(args, "-j", action)
|
||||
|
||||
// Comment tag for cleanup
|
||||
args = append(args, "-m", "comment", "--comment", commentTag)
|
||||
|
||||
cmd := exec.Command("iptables", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("iptables error: %s", string(output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyOneFirewallIPv6Rule(tag, bridge string, containerIPs []string, rule config.FirewallRule) error {
|
||||
for _, containerIP := range containerIPs {
|
||||
commentTag := fmt.Sprintf("clicd-%s-fw-%s-v6-%s", tag, rule.ID, firewallCommentIPTag(containerIP))
|
||||
args := []string{"-I", "FORWARD", "1"}
|
||||
|
||||
switch rule.Direction {
|
||||
case "in":
|
||||
args = append(args, "-o", bridge, "-d", containerIP+"/128")
|
||||
case "out":
|
||||
args = append(args, "-i", bridge, "-s", containerIP+"/128")
|
||||
default:
|
||||
return fmt.Errorf("invalid direction: %s", rule.Direction)
|
||||
}
|
||||
|
||||
switch rule.Protocol {
|
||||
case "tcp", "udp":
|
||||
args = append(args, "-p", rule.Protocol)
|
||||
case "icmp":
|
||||
args = append(args, "-p", "ipv6-icmp")
|
||||
case "all":
|
||||
default:
|
||||
return fmt.Errorf("invalid protocol: %s", rule.Protocol)
|
||||
}
|
||||
|
||||
if rule.Port != "" && (rule.Protocol == "tcp" || rule.Protocol == "udp") {
|
||||
args = append(args, firewallPortArgs(rule.Port)...)
|
||||
}
|
||||
|
||||
if rule.SourceIP != "" {
|
||||
switch rule.Direction {
|
||||
case "in":
|
||||
args = append(args, "-s", rule.SourceIP)
|
||||
case "out":
|
||||
args = append(args, "-d", rule.SourceIP)
|
||||
}
|
||||
}
|
||||
|
||||
action := "DROP"
|
||||
if rule.Action == "ACCEPT" {
|
||||
action = "ACCEPT"
|
||||
}
|
||||
args = append(args, "-j", action)
|
||||
args = append(args, "-m", "comment", "--comment", commentTag)
|
||||
|
||||
cmd := exec.Command("ip6tables", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ip6tables error: %s", string(output))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func firewallPortArgs(port string) []string {
|
||||
spec := normalizePortSpec(port)
|
||||
if strings.Contains(spec, ",") {
|
||||
return []string{"-m", "multiport", "--dports", spec}
|
||||
}
|
||||
return []string{"--dport", spec}
|
||||
}
|
||||
|
||||
// normalizePortSpec converts user port input to iptables-compatible port spec.
|
||||
// "80,443" -> "80,443", "8000-9000" -> "8000:9000", "80,443,8000-9000" -> "80,443,8000:9000"
|
||||
func normalizePortSpec(port string) string {
|
||||
port = strings.TrimSpace(port)
|
||||
if port == "" {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(port, ",")
|
||||
for i, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if strings.Contains(part, "-") && !strings.Contains(part, ":") {
|
||||
bounds := strings.SplitN(part, "-", 2)
|
||||
if len(bounds) == 2 {
|
||||
part = strings.TrimSpace(bounds[0]) + ":" + strings.TrimSpace(bounds[1])
|
||||
}
|
||||
}
|
||||
parts[i] = part
|
||||
}
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
|
||||
func applyDefaultFirewallPolicy(tag, bridge, containerIP string) error {
|
||||
defaults := [][]string{
|
||||
{
|
||||
"-I", "FORWARD", "1",
|
||||
"-o", bridge,
|
||||
"-d", containerIP + "/32",
|
||||
"-j", "DROP",
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-in", tag),
|
||||
},
|
||||
{
|
||||
"-I", "FORWARD", "1",
|
||||
"-i", bridge,
|
||||
"-s", containerIP + "/32",
|
||||
"-j", "DROP",
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-out", tag),
|
||||
},
|
||||
}
|
||||
for _, args := range defaults {
|
||||
cmd := exec.Command("iptables", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("iptables default firewall error: %s", string(output))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyDefaultFirewallIPv6Policy(tag, bridge string, containerIPs []string) error {
|
||||
for _, containerIP := range containerIPs {
|
||||
defaults := [][]string{
|
||||
{
|
||||
"-I", "FORWARD", "1",
|
||||
"-o", bridge,
|
||||
"-d", containerIP + "/128",
|
||||
"-j", "DROP",
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-in-v6-%s", tag, firewallCommentIPTag(containerIP)),
|
||||
},
|
||||
{
|
||||
"-I", "FORWARD", "1",
|
||||
"-i", bridge,
|
||||
"-s", containerIP + "/128",
|
||||
"-j", "DROP",
|
||||
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-out-v6-%s", tag, firewallCommentIPTag(containerIP)),
|
||||
},
|
||||
}
|
||||
for _, args := range defaults {
|
||||
cmd := exec.Command("ip6tables", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ip6tables default firewall error: %s", string(output))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func firewallCommentIPTag(ip string) string {
|
||||
replacer := strings.NewReplacer(":", "_", ".", "_", "/", "_")
|
||||
return replacer.Replace(ip)
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package version
|
||||
|
||||
var (
|
||||
Version = "1.1.12"
|
||||
Version = "1.1.19"
|
||||
Repo = "MengMengCode/CLICD"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,105 @@
|
||||
import { defineConfig } from 'vitepress'
|
||||
|
||||
const zhNav = [
|
||||
{ text: '指南', link: '/guide/introduction' },
|
||||
{ text: '功能', link: '/features/dashboard' },
|
||||
{ text: '运维', link: '/operations/deployment' },
|
||||
{ text: '开发', link: '/developer/architecture' },
|
||||
]
|
||||
|
||||
const enNav = [
|
||||
{ text: 'Guide', link: '/en/guide/introduction' },
|
||||
{ text: 'Features', link: '/en/features/dashboard' },
|
||||
{ text: 'Operations', link: '/en/operations/deployment' },
|
||||
{ text: 'Developer', link: '/en/developer/architecture' },
|
||||
]
|
||||
|
||||
const zhSidebar = [
|
||||
{
|
||||
text: '开始',
|
||||
items: [
|
||||
{ text: '项目介绍', link: '/guide/introduction' },
|
||||
{ text: '安装', link: '/guide/installation' },
|
||||
{ text: '升级', link: '/guide/upgrade' },
|
||||
{ text: '快速上手', link: '/guide/quick-start' },
|
||||
{ text: '配置说明', link: '/guide/configuration' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '功能',
|
||||
items: [
|
||||
{ text: '控制面板', link: '/features/dashboard' },
|
||||
{ text: '容器管理', link: '/features/containers' },
|
||||
{ text: '镜像管理', link: '/features/images' },
|
||||
{ text: '网络与路由', link: '/features/networking' },
|
||||
{ text: '快照管理', link: '/features/snapshots' },
|
||||
{ text: '安全告警', link: '/features/security' },
|
||||
{ text: '子用户', link: '/features/sub-users' },
|
||||
{ text: 'API 集成', link: '/features/api' },
|
||||
{ text: '主机报告', link: '/features/host-report' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '运维',
|
||||
items: [
|
||||
{ text: '部署建议', link: '/operations/deployment' },
|
||||
{ text: '故障排查', link: '/operations/troubleshooting' },
|
||||
{ text: '常见问题', link: '/operations/faq' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '开发',
|
||||
items: [
|
||||
{ text: '系统架构', link: '/developer/architecture' },
|
||||
{ text: '本地构建', link: '/developer/build' },
|
||||
{ text: '发布流程', link: '/developer/release' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const enSidebar = [
|
||||
{
|
||||
text: 'Get Started',
|
||||
items: [
|
||||
{ text: 'Introduction', link: '/en/guide/introduction' },
|
||||
{ text: 'Installation', link: '/en/guide/installation' },
|
||||
{ text: 'Upgrade', link: '/en/guide/upgrade' },
|
||||
{ text: 'Quick Start', link: '/en/guide/quick-start' },
|
||||
{ text: 'Configuration', link: '/en/guide/configuration' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Features',
|
||||
items: [
|
||||
{ text: 'Dashboard', link: '/en/features/dashboard' },
|
||||
{ text: 'Containers', link: '/en/features/containers' },
|
||||
{ text: 'Images', link: '/en/features/images' },
|
||||
{ text: 'Networking & Routing', link: '/en/features/networking' },
|
||||
{ text: 'Snapshots', link: '/en/features/snapshots' },
|
||||
{ text: 'Security Alerts', link: '/en/features/security' },
|
||||
{ text: 'Sub-users', link: '/en/features/sub-users' },
|
||||
{ text: 'API Integration', link: '/en/features/api' },
|
||||
{ text: 'Host Report', link: '/en/features/host-report' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Operations',
|
||||
items: [
|
||||
{ text: 'Deployment', link: '/en/operations/deployment' },
|
||||
{ text: 'Troubleshooting', link: '/en/operations/troubleshooting' },
|
||||
{ text: 'FAQ', link: '/en/operations/faq' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Developer',
|
||||
items: [
|
||||
{ text: 'Architecture', link: '/en/developer/architecture' },
|
||||
{ text: 'Local Build', link: '/en/developer/build' },
|
||||
{ text: 'Release Process', link: '/en/developer/release' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export default defineConfig({
|
||||
title: 'CLICD',
|
||||
description: '面向 LXC/KVM 的轻量虚拟化管理面板文档',
|
||||
@@ -10,59 +110,48 @@ export default defineConfig({
|
||||
head: [
|
||||
['link', { rel: 'icon', href: '/favicon.svg' }],
|
||||
],
|
||||
locales: {
|
||||
root: {
|
||||
label: '简体中文',
|
||||
lang: 'zh-CN',
|
||||
description: '面向 LXC/KVM 的轻量虚拟化管理面板文档',
|
||||
themeConfig: {
|
||||
nav: zhNav,
|
||||
sidebar: zhSidebar,
|
||||
outline: {
|
||||
label: '页面导航',
|
||||
},
|
||||
darkModeSwitchLabel: '外观',
|
||||
sidebarMenuLabel: '菜单',
|
||||
returnToTopLabel: '返回顶部',
|
||||
},
|
||||
},
|
||||
en: {
|
||||
label: 'English',
|
||||
lang: 'en-US',
|
||||
link: '/en/',
|
||||
description: 'Documentation for the lightweight LXC/KVM virtualization management panel.',
|
||||
themeConfig: {
|
||||
nav: enNav,
|
||||
sidebar: enSidebar,
|
||||
outline: {
|
||||
label: 'On This Page',
|
||||
},
|
||||
darkModeSwitchLabel: 'Appearance',
|
||||
sidebarMenuLabel: 'Menu',
|
||||
returnToTopLabel: 'Return to Top',
|
||||
footer: {
|
||||
message: 'CLICD documentation for deployment, usage, operations, and integration.',
|
||||
copyright: 'Copyright © CLICD contributors',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
themeConfig: {
|
||||
logo: '/favicon.svg',
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
nav: [
|
||||
{ text: '指南', link: '/guide/introduction' },
|
||||
{ text: '功能', link: '/features/dashboard' },
|
||||
{ text: '运维', link: '/operations/deployment' },
|
||||
{ text: '开发', link: '/developer/architecture' },
|
||||
],
|
||||
sidebar: [
|
||||
{
|
||||
text: '开始',
|
||||
items: [
|
||||
{ text: '项目介绍', link: '/guide/introduction' },
|
||||
{ text: '安装', link: '/guide/installation' },
|
||||
{ text: '升级', link: '/guide/upgrade' },
|
||||
{ text: '快速上手', link: '/guide/quick-start' },
|
||||
{ text: '配置说明', link: '/guide/configuration' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '功能',
|
||||
items: [
|
||||
{ text: '控制面板', link: '/features/dashboard' },
|
||||
{ text: '容器管理', link: '/features/containers' },
|
||||
{ text: '镜像管理', link: '/features/images' },
|
||||
{ text: '网络与路由', link: '/features/networking' },
|
||||
{ text: '快照管理', link: '/features/snapshots' },
|
||||
{ text: '安全告警', link: '/features/security' },
|
||||
{ text: '子用户', link: '/features/sub-users' },
|
||||
{ text: 'API 集成', link: '/features/api' },
|
||||
{ text: '主机报告', link: '/features/host-report' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '运维',
|
||||
items: [
|
||||
{ text: '部署建议', link: '/operations/deployment' },
|
||||
{ text: '故障排查', link: '/operations/troubleshooting' },
|
||||
{ text: '常见问题', link: '/operations/faq' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '开发',
|
||||
items: [
|
||||
{ text: '系统架构', link: '/developer/architecture' },
|
||||
{ text: '本地构建', link: '/developer/build' },
|
||||
{ text: '发布流程', link: '/developer/release' },
|
||||
],
|
||||
},
|
||||
],
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/MengMengCode/CLICD' },
|
||||
],
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Architecture
|
||||
|
||||
CLICD consists of a Go backend, a React frontend, and host virtualization capabilities.
|
||||
|
||||
## Backend
|
||||
|
||||
The backend entry point is `backend/main.go`, and HTTP routes are centralized in `backend/internal/server/server.go`. Main modules:
|
||||
|
||||
- `internal/api`: HTTP APIs for the web panel and `/api/v1`.
|
||||
- `internal/config`: configuration and SQLite storage.
|
||||
- `internal/lxc`: LXC container management.
|
||||
- `internal/kvm`: KVM/libvirt virtual machine management.
|
||||
- `internal/cli`: command-line management entry point.
|
||||
- `internal/server`: embedded frontend assets and HTTP service.
|
||||
- `internal/version`: version number.
|
||||
|
||||
## Frontend
|
||||
|
||||
The frontend entry point is `frontend/src/main.tsx`. Pages live in `frontend/src/pages`, and shared components live in `frontend/src/components`.
|
||||
|
||||
Main pages:
|
||||
|
||||
- Dashboard: `Dashboard.tsx`
|
||||
- Container list: `Containers.tsx`
|
||||
- Container details: `ContainerDetail.tsx`
|
||||
- Image Management: `ImageManagement.tsx`
|
||||
- Security Alerts: `Security.tsx`
|
||||
- Snapshot Management: `Snapshots.tsx`
|
||||
- Routing Management: `Routing.tsx`
|
||||
- API Integration: `ApiIntegration.tsx`
|
||||
- Host Report: `HostReport.tsx`
|
||||
- Sub-user Management: `SubUserManagement.tsx`
|
||||
|
||||
## Frontend Embedding
|
||||
|
||||
For production builds, frontend artifacts are placed in `backend/internal/server/web`. The backend serves them through Go embed and returns the SPA entry for non-API routes.
|
||||
|
||||
## API Layers
|
||||
|
||||
- `/api/*`: web panel and compatibility APIs.
|
||||
- `/api/v1/*`: versioned APIs recommended for external automation.
|
||||
- WebSSH and WebVNC use short-lived tickets before opening WebSocket connections.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Local Build
|
||||
|
||||
## Frontend Build
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
Build output is written to `frontend/dist`.
|
||||
|
||||
## Backend Build
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go test ./...
|
||||
go build -o ../build/clicd .
|
||||
```
|
||||
|
||||
To package the embedded web panel, sync the frontend build output into the backend embed directory first.
|
||||
|
||||
## One-command Build
|
||||
|
||||
The project root provides a build script:
|
||||
|
||||
```bash
|
||||
bash build.sh
|
||||
```
|
||||
|
||||
The script chains frontend build, static asset sync, and Go binary build.
|
||||
|
||||
## Docs Build
|
||||
|
||||
```bash
|
||||
cd docs
|
||||
npm install
|
||||
npm run dev
|
||||
npm run build
|
||||
```
|
||||
|
||||
`npm run dev` starts a local preview, and `npm run build` generates static documentation.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Release Process
|
||||
|
||||
CLICD installation and upgrade rely on GitHub Release artifacts. Use semantic version tags such as `v1.1.6`.
|
||||
|
||||
## Version Number
|
||||
|
||||
Check the version in:
|
||||
|
||||
- `backend/internal/version/version.go`
|
||||
- `frontend/package.json`
|
||||
- Release tag.
|
||||
|
||||
## Release Artifacts
|
||||
|
||||
The installer first tries to download the Linux AMD64 archive:
|
||||
|
||||
```text
|
||||
clicd-linux-amd64.tar.gz
|
||||
```
|
||||
|
||||
In some cases, it may also try the standalone binary:
|
||||
|
||||
```text
|
||||
clicd-linux-amd64
|
||||
```
|
||||
|
||||
## Installer Behavior
|
||||
|
||||
- `CLICD_VERSION=latest`: use GitHub `releases/latest`.
|
||||
- `CLICD_VERSION=vX.Y.Z`: download artifacts from the specified release tag.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
CLICD_VERSION=v1.1.6 sh install.sh
|
||||
```
|
||||
|
||||
## Post-release Verification
|
||||
|
||||
- The installer can download the new version.
|
||||
- `systemctl status clicd` is healthy.
|
||||
- `/api/version` returns the new version.
|
||||
- The web panel can load frontend assets.
|
||||
- Container list, task queue, and API Key pages open correctly.
|
||||
@@ -0,0 +1,674 @@
|
||||
# API Integration
|
||||
|
||||
CLICD remains compatible with legacy `/api` endpoints, so existing integrations do not need to change. New integrations should use `/api/v1`; the list below is all v1, and the recommended container list endpoint is `GET /api/v1/containers`.
|
||||
|
||||
## Authentication
|
||||
|
||||
API keys can be created and managed from the API Integration page. Requests support either of these headers:
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: YOUR_API_KEY" https://panel.example.com/api/v1/containers
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/dashboard
|
||||
```
|
||||
|
||||
## Response Shape
|
||||
|
||||
All APIs use the same response envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "OK",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
Integrations should read only the business fields they need. New capabilities are added as optional fields where possible, without requiring existing plugins to rename current fields.
|
||||
|
||||
## Creation and Reinstall
|
||||
|
||||
Container creation, batch creation, reinstall, and batch reinstall support mixed NAT, public IPv4, IPv6 networking, plus Linux SSH login configuration. Public IPv4/IPv6 pools can be viewed with `GET /api/v1/routing` and updated with `PUT /api/v1/routing`.
|
||||
|
||||
Create container example:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "demo-lxc-01",
|
||||
"virtualization": "lxc",
|
||||
"template_id": "debian-bookworm",
|
||||
"vcpu": 1,
|
||||
"ram_mb": 512,
|
||||
"disk_gb": 10,
|
||||
"assign_nat": true,
|
||||
"port_mapping_count": 2,
|
||||
"assign_ipv4": false,
|
||||
"ipv4_count": 1,
|
||||
"public_ipv4s": [],
|
||||
"assign_ipv6": true,
|
||||
"ipv6_count": 1,
|
||||
"ipv6_addresses": [],
|
||||
"ssh_auth_mode": "auto_password",
|
||||
"ssh_password": "",
|
||||
"ssh_public_key": "",
|
||||
"expires_at": ""
|
||||
}
|
||||
```
|
||||
|
||||
Field notes:
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| `assign_nat` | Whether to allocate NAT port mappings. If omitted, default NAT behavior is preserved. |
|
||||
| `assign_ipv4` | Whether to allocate public IPv4. |
|
||||
| `ipv4_count` | Number of public IPv4 addresses to allocate automatically. |
|
||||
| `public_ipv4s` | Explicit public IPv4 address list. |
|
||||
| `assign_ipv6` | Whether to allocate IPv6. |
|
||||
| `ipv6_count` | Number of IPv6 addresses to allocate automatically. |
|
||||
| `ipv6_addresses` | Explicit IPv6 address list. |
|
||||
| `ssh_auth_mode` | Linux creation supports `auto_password`, `password`, and `key`; reinstall also supports `keep`. |
|
||||
| `ssh_password` | Custom password for `password` mode. It must be 8-64 characters, include letters and digits, and contain no whitespace. |
|
||||
| `ssh_public_key` | One-line SSH public key for `key` mode. |
|
||||
|
||||
Reinstall example:
|
||||
|
||||
```json
|
||||
{
|
||||
"template_id": "debian-bookworm",
|
||||
"ssh_auth_mode": "keep",
|
||||
"ssh_password": "",
|
||||
"ssh_public_key": ""
|
||||
}
|
||||
```
|
||||
|
||||
`keep` is only for reinstall and keeps the current SSH password. Windows KVM images ignore Linux SSH public key fields.
|
||||
|
||||
## Python Example
|
||||
|
||||
Fetch containers:
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
BASE_URL = "https://panel.example.com"
|
||||
API_KEY = "YOUR_API_KEY"
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"X-API-Key": API_KEY,
|
||||
"Content-Type": "application/json",
|
||||
})
|
||||
|
||||
resp = session.get(f"{BASE_URL}/api/v1/containers", timeout=15)
|
||||
resp.raise_for_status()
|
||||
print(resp.json())
|
||||
```
|
||||
|
||||
Create a port mapping:
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
BASE_URL = "https://panel.example.com"
|
||||
API_KEY = "YOUR_API_KEY"
|
||||
CONTAINER_ID = "example-vm"
|
||||
|
||||
payload = {
|
||||
"protocol": "tcp",
|
||||
"host_port": 18080,
|
||||
"container_port": 80,
|
||||
"description": "web",
|
||||
}
|
||||
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/api/v1/containers/{CONTAINER_ID}/port-mappings",
|
||||
headers={"X-API-Key": API_KEY},
|
||||
json=payload,
|
||||
timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
print(resp.json())
|
||||
```
|
||||
|
||||
## Endpoint List
|
||||
|
||||
### Overview
|
||||
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/dashboard` | Dashboard statistics |
|
||||
| GET | `/api/v1/host-info` | Host resources |
|
||||
| GET | `/api/v1/routing` | NAT/IPv4/IPv6 routing |
|
||||
| PUT | `/api/v1/routing` | Update public IPv4/IPv6 pools |
|
||||
| POST | `/api/v1/routing/ipv4-scan` | Scan a public IPv4 segment |
|
||||
| GET | `/api/v1/ipv6/status` | IPv6 status |
|
||||
| GET | `/api/v1/tasks` | Task queue |
|
||||
| DELETE | `/api/v1/tasks/{task_id}` | Delete a task |
|
||||
|
||||
### Containers
|
||||
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/containers` | Container list |
|
||||
| POST | `/api/v1/containers/list` | Compatible POST form for container list |
|
||||
| POST | `/api/v1/containers` | Create container |
|
||||
| GET | `/api/v1/containers/{id|uuid|name}` | Container details |
|
||||
| POST | `/api/v1/containers/{id}/start` | Start |
|
||||
| POST | `/api/v1/containers/{id}/stop` | Stop |
|
||||
| POST | `/api/v1/containers/{id}/restart` | Restart |
|
||||
| POST | `/api/v1/containers/{id}/reinstall` | Reinstall |
|
||||
| DELETE | `/api/v1/containers/{id}/delete` | Delete |
|
||||
| GET | `/api/v1/containers/{id}/usage` | Resource usage |
|
||||
| GET | `/api/v1/containers/{id}/traffic` | Traffic statistics |
|
||||
| POST | `/api/v1/containers/{id}/traffic-reset` | Reset traffic |
|
||||
| PUT | `/api/v1/containers/{id}/traffic-limit` | Update traffic limits |
|
||||
| PUT | `/api/v1/containers/{id}/resource-limit` | Update resource limits |
|
||||
| PUT | `/api/v1/containers/{id}/expiry` | Update expiration time |
|
||||
| POST | `/api/v1/containers/{id}/reset-password` | Reset SSH password |
|
||||
| POST | `/api/v1/containers/{id}/ipv6` | Assign IPv6 |
|
||||
|
||||
### Ports and Snapshots
|
||||
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/containers/{id}/random-port` | Random available port |
|
||||
| POST | `/api/v1/containers/{id}/port-mappings` | Add port mapping |
|
||||
| PUT | `/api/v1/containers/{id}/port-mappings/{index}` | Update port mapping |
|
||||
| DELETE | `/api/v1/containers/{id}/port-mappings/{index}` | Delete port mapping |
|
||||
| GET | `/api/v1/snapshots` | Snapshot overview |
|
||||
| GET | `/api/v1/containers/{id}/snapshots` | Container snapshots |
|
||||
| POST | `/api/v1/containers/{id}/snapshots` | Create snapshot |
|
||||
| DELETE | `/api/v1/containers/{id}/snapshots/{snapshot_id}` | Delete snapshot |
|
||||
| POST | `/api/v1/containers/{id}/snapshots/{snapshot_id}/restore` | Restore snapshot |
|
||||
| POST | `/api/v1/containers/{id}/snapshots/schedule` | Schedule snapshots |
|
||||
| PUT | `/api/v1/containers/{id}/snapshots/quota` | Snapshot quota |
|
||||
|
||||
### Platform Management
|
||||
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/templates` | Template list |
|
||||
| GET | `/api/v1/images` | Image management list |
|
||||
| POST | `/api/v1/images/download` | Download image |
|
||||
| POST | `/api/v1/images/cancel` | Cancel image download |
|
||||
| DELETE | `/api/v1/images/delete` | Delete image cache |
|
||||
| PUT | `/api/v1/images/toggle` | Enable or disable image |
|
||||
| GET | `/api/v1/security/alerts` | Security alerts |
|
||||
| POST | `/api/v1/security/check` | Run security check |
|
||||
| GET | `/api/v1/security/logs?container={name}` | Security connection logs |
|
||||
| GET | `/api/v1/security/summary` | Security summary |
|
||||
| GET | `/api/v1/security/settings` | Security settings |
|
||||
| PUT | `/api/v1/security/settings` | Update security settings |
|
||||
| GET | `/api/v1/swap` | Swap information |
|
||||
| POST | `/api/v1/swap` | Adjust Swap |
|
||||
| POST | `/api/v1/batch-create` | Batch create containers |
|
||||
| POST | `/api/v1/batch-action` | Batch power action, delete, or reinstall |
|
||||
| POST | `/api/v1/ssh-ticket` | Create WebSSH ticket |
|
||||
| POST | `/api/v1/vnc-ticket` | Create WebVNC ticket |
|
||||
|
||||
### Accounts and Logs
|
||||
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/v1/sub-user/create` | Create sub-user link |
|
||||
| GET | `/api/v1/sub-users` | Sub-user list |
|
||||
| POST | `/api/v1/sub-users/{id}/rotate-password` | Rotate sub-user password |
|
||||
| GET | `/api/v1/sub-users/{id}/audit-logs` | Sub-user audit logs |
|
||||
| GET | `/api/v1/sub-users/{id}/login-logs` | Sub-user login logs |
|
||||
| GET | `/api/v1/audit-logs` | Audit logs |
|
||||
| GET | `/api/v1/login-logs` | Login logs |
|
||||
| GET | `/api/v1/api-keys` | API key list |
|
||||
| POST | `/api/v1/api-keys` | Create API key |
|
||||
| PATCH | `/api/v1/api-keys/{id}` | Update API key |
|
||||
| DELETE | `/api/v1/api-keys/{id}` | Delete API key |
|
||||
|
||||
## Response Samples
|
||||
|
||||
The samples below are grouped by endpoint path. Resource numbers, task IDs, container IDs, timestamps, IP addresses, and keys will differ in real environments. Passwords, tickets, and API keys are masked.
|
||||
|
||||
### Overview
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/dashboard": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"running": 31,
|
||||
"stopped": 0,
|
||||
"total_containers": 31
|
||||
}
|
||||
},
|
||||
"GET /api/v1/host-info": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"cpu": { "cores": 8, "usage_pct": 1.16 },
|
||||
"ram": { "total_mb": 31825, "used_mb": 1275, "free_mb": 30550 },
|
||||
"disk": { "total_gb": 1750.49, "used_gb": 123.98, "free_gb": 1626.51 },
|
||||
"network": {
|
||||
"public_ipv4": "203.0.113.10",
|
||||
"public_ipv4_interface": "eth0",
|
||||
"public_ipv6": "2001:db8:100::2",
|
||||
"public_ipv6_interface": "eth0"
|
||||
},
|
||||
"load": { "load1": 0.01, "load5": 0.03, "load15": 0.01 }
|
||||
}
|
||||
},
|
||||
"GET /api/v1/routing": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"nat4": { "used": 62, "remaining": "45474", "total": "45536" },
|
||||
"ipv4": { "used": 1, "remaining": "3", "total": "4" },
|
||||
"ipv6": { "used": 31, "remaining": "large", "total": "large" },
|
||||
"public_ipv4_addresses": [
|
||||
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
|
||||
],
|
||||
"ipv4_assignments": [
|
||||
{ "container_id": 5, "container_name": "example-vm", "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
|
||||
],
|
||||
"nat4_mappings": [
|
||||
{ "container_id": 5, "container_name": "example-vm", "status": "running", "ip": "10.0.0.10", "host_port": 22004, "container_port": 22, "protocol": "tcp" }
|
||||
],
|
||||
"ipv6_assignments": [
|
||||
{ "container_id": 5, "container_name": "example-vm", "address": "2001:db8:100::1005", "prefix_len": 64, "interface": "eth0" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"PUT /api/v1/routing": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"ipv4": { "used": 1, "remaining": "3", "total": "4" },
|
||||
"public_ipv4_addresses": [
|
||||
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
|
||||
],
|
||||
"ipv6_prefixes": [
|
||||
{ "interface": "eth0", "address": "2001:db8:100::2", "prefix": "2001:db8:100::/64", "prefix_len": 64, "gateway": "2001:db8:100::1" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"POST /api/v1/routing/ipv4-scan": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1", "status": "available", "usable": true, "reason": "" }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/ipv6/status": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"available": true,
|
||||
"reachable": true,
|
||||
"reason": "usable public IPv6 prefix detected",
|
||||
"prefixes": [
|
||||
{ "interface": "eth0", "address": "2001:db8:100::2", "prefix": "2001:db8:100::/64", "prefix_len": 64, "gateway": "2001:db8:100::1" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"GET /api/v1/tasks": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"DELETE /api/v1/tasks/{task_id}": {
|
||||
"success": true,
|
||||
"message": "Task deleted"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Containers
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/containers": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"id": 5,
|
||||
"uuid": "00000000-0000-4000-8000-000000000005",
|
||||
"name": "example-vm",
|
||||
"virtualization": "lxc",
|
||||
"template": "debian-bullseye",
|
||||
"vcpu": 1,
|
||||
"ram_mb": 512,
|
||||
"disk_gb": 10,
|
||||
"status": "running",
|
||||
"ip": "10.0.0.10",
|
||||
"ipv6": "2001:db8:100::1005",
|
||||
"ssh_port": 22004,
|
||||
"ssh_password": "***",
|
||||
"port_mappings": [
|
||||
{ "container_port": 22, "host_port": 22004, "protocol": "tcp", "description": "SSH" },
|
||||
{ "container_port": 20000, "host_port": 20000, "protocol": "tcp", "description": "Port-20000" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"POST /api/v1/containers/list": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": 5, "uuid": "00000000-0000-4000-8000-000000000005", "name": "example-vm", "status": "running", "ip": "10.0.0.10" }
|
||||
]
|
||||
},
|
||||
"POST /api/v1/containers": {
|
||||
"success": true,
|
||||
"message": "Container created successfully"
|
||||
},
|
||||
"GET /api/v1/containers/{id|uuid|name}": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"id": 5,
|
||||
"uuid": "00000000-0000-4000-8000-000000000005",
|
||||
"name": "example-vm",
|
||||
"status": "running",
|
||||
"ip": "10.0.0.10",
|
||||
"ipv6": "2001:db8:100::1005",
|
||||
"ssh_port": 22004,
|
||||
"ssh_password": "***",
|
||||
"policy_blocked": false
|
||||
}
|
||||
},
|
||||
"POST /api/v1/containers/{id}/start": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "start" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/stop": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "stop" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/restart": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "restart" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/reinstall": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "reinstall" }
|
||||
},
|
||||
"DELETE /api/v1/containers/{id}/delete": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "delete" }
|
||||
},
|
||||
"GET /api/v1/containers/{id}/usage": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"cpu_usage_pct": 0,
|
||||
"cpu_usage_usec": 3908852,
|
||||
"memory_usage_bytes": 29331456,
|
||||
"disk_usage_bytes": 515100672,
|
||||
"network_rx_bytes": 131232,
|
||||
"network_tx_bytes": 16828,
|
||||
"load1": 0.1,
|
||||
"load5": 0.06,
|
||||
"load15": 0.01
|
||||
}
|
||||
},
|
||||
"GET /api/v1/containers/{id}/traffic": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"mode": "total",
|
||||
"limit_gb": 0,
|
||||
"in_limit_gb": 0,
|
||||
"out_limit_gb": 0,
|
||||
"total_used_bytes": 142082,
|
||||
"rx_used_bytes": 127212,
|
||||
"tx_used_bytes": 14870,
|
||||
"used_pct": 0,
|
||||
"reset_date": "2026-06"
|
||||
}
|
||||
},
|
||||
"POST /api/v1/containers/{id}/traffic-reset": {
|
||||
"success": true,
|
||||
"message": "Traffic reset"
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/traffic-limit": {
|
||||
"success": true,
|
||||
"message": "Traffic limit updated"
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/resource-limit": {
|
||||
"success": true,
|
||||
"message": "Resource limits updated"
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/expiry": {
|
||||
"success": true,
|
||||
"message": "Expiry updated"
|
||||
},
|
||||
"POST /api/v1/containers/{id}/reset-password": {
|
||||
"success": true,
|
||||
"message": "SSH password reset successfully",
|
||||
"data": { "password": "***" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/ipv6": {
|
||||
"success": true,
|
||||
"message": "IPv6 assigned",
|
||||
"data": { "id": 5, "name": "example-vm", "ipv6": "2001:db8:100::1005" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Ports and Snapshots
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/containers/{id}/random-port": {
|
||||
"success": true,
|
||||
"data": { "port": 61320 }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/port-mappings": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "container_port": 22, "host_port": 22004, "protocol": "tcp", "description": "SSH" },
|
||||
{ "container_port": 8080, "host_port": 61320, "protocol": "tcp", "description": "HTTP" }
|
||||
]
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/port-mappings/{index}": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "container_port": 8081, "host_port": 61320, "protocol": "tcp", "description": "HTTP" }
|
||||
]
|
||||
},
|
||||
"DELETE /api/v1/containers/{id}/port-mappings/{index}": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/snapshots": {
|
||||
"success": true,
|
||||
"data": null
|
||||
},
|
||||
"GET /api/v1/containers/{id}/snapshots": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"quota": 1,
|
||||
"schedule": { "enabled": false, "interval_hours": 0, "last_run": "", "next_run": "", "time": "", "created_by": "" },
|
||||
"snapshots": []
|
||||
}
|
||||
},
|
||||
"POST /api/v1/containers/{id}/snapshots": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"id": "snap-20260608-001",
|
||||
"container_id": 5,
|
||||
"container_name": "example-vm",
|
||||
"created_at": "2026-06-08 16:00:00",
|
||||
"created_by": "api:Automation",
|
||||
"scheduled": false,
|
||||
"size_bytes": 10485760
|
||||
}
|
||||
},
|
||||
"DELETE /api/v1/containers/{id}/snapshots/{snapshot_id}": {
|
||||
"success": true,
|
||||
"message": "Snapshot deleted"
|
||||
},
|
||||
"POST /api/v1/containers/{id}/snapshots/{snapshot_id}/restore": {
|
||||
"success": true,
|
||||
"message": "Snapshot restored"
|
||||
},
|
||||
"POST /api/v1/containers/{id}/snapshots/schedule": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"container": { "id": 5, "name": "example-vm", "snapshot_schedule_enabled": true, "snapshot_schedule_interval_hours": 24, "snapshot_schedule_time": "03:00" }
|
||||
}
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/snapshots/quota": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"quota": 2,
|
||||
"container": { "id": 5, "name": "example-vm", "snapshot_limit": 2 }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Platform Management
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/templates": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "distro": "ubuntu", "release": "noble", "arch": "amd64", "description": "Ubuntu 24.04 LTS" },
|
||||
{ "id": "debian-bookworm", "name": "Debian 12", "distro": "debian", "release": "bookworm", "arch": "amd64", "description": "Debian 12 (Bookworm)" }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/images": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "type": "lxc", "downloaded": true, "enabled": true, "downloading": false, "progress": 0, "size_bytes": 135005452 }
|
||||
]
|
||||
},
|
||||
"POST /api/v1/images/download": {
|
||||
"success": true,
|
||||
"message": "Already downloaded"
|
||||
},
|
||||
"POST /api/v1/images/cancel": {
|
||||
"success": true,
|
||||
"message": "Cancel requested"
|
||||
},
|
||||
"DELETE /api/v1/images/delete": {
|
||||
"success": true,
|
||||
"message": "Deleted"
|
||||
},
|
||||
"PUT /api/v1/images/toggle": {
|
||||
"success": true,
|
||||
"message": "OK"
|
||||
},
|
||||
"GET /api/v1/security/alerts": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"POST /api/v1/security/check": {
|
||||
"success": true,
|
||||
"message": "Security check completed"
|
||||
},
|
||||
"GET /api/v1/security/logs?container={name}": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/security/summary": {
|
||||
"success": true,
|
||||
"data": { "critical": 0, "high": 0, "medium": 0, "low": 0, "total_alerts": 0 }
|
||||
},
|
||||
"GET /api/v1/security/settings": {
|
||||
"success": true,
|
||||
"data": { "auto_shutdown": false }
|
||||
},
|
||||
"PUT /api/v1/security/settings": {
|
||||
"success": true,
|
||||
"data": { "auto_shutdown": false }
|
||||
},
|
||||
"GET /api/v1/swap": {
|
||||
"success": true,
|
||||
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
|
||||
},
|
||||
"POST /api/v1/swap": {
|
||||
"success": true,
|
||||
"message": "SWAP 已调整为 16384 MB",
|
||||
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
|
||||
},
|
||||
"POST /api/v1/batch-create": {
|
||||
"success": true,
|
||||
"data": ["task-12"]
|
||||
},
|
||||
"POST /api/v1/batch-action": {
|
||||
"success": true,
|
||||
"data": ["task-13"]
|
||||
},
|
||||
"POST /api/v1/ssh-ticket": {
|
||||
"success": true,
|
||||
"data": { "ticket": "***60 seconds valid***" }
|
||||
},
|
||||
"POST /api/v1/vnc-ticket": {
|
||||
"success": true,
|
||||
"data": { "ticket": "***60 seconds valid***" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Accounts and Logs
|
||||
|
||||
```json
|
||||
{
|
||||
"POST /api/v1/sub-user/create": {
|
||||
"success": true,
|
||||
"message": "Sub-user created",
|
||||
"data": {
|
||||
"id": "sub-xxxxxxxx",
|
||||
"username": "user-xxxxxxxx",
|
||||
"password": "***",
|
||||
"container_names": ["example-vm"],
|
||||
"access_code": "********",
|
||||
"created_at": "2026-06-08 16:00:00"
|
||||
}
|
||||
},
|
||||
"GET /api/v1/sub-users": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"POST /api/v1/sub-users/{id}/rotate-password": {
|
||||
"success": true,
|
||||
"data": { "username": "user-xxxxxxxx", "password": "***", "access_code": "********" }
|
||||
},
|
||||
"GET /api/v1/sub-users/{id}/audit-logs": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/sub-users/{id}/login-logs": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/audit-logs": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "time": "2026-06-08 15:44:40", "action": "apikey.create", "target": "Test", "detail": "scopes=*", "user": "admin", "success": true }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/login-logs": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "time": "2026-06-08 08:24:00 UTC", "username": "admin", "ip": "198.51.100.23", "user_agent": "Mozilla/5.0 ...", "success": true }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/api-keys": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "last_used_ip": "198.51.100.23" }
|
||||
]
|
||||
},
|
||||
"POST /api/v1/api-keys": {
|
||||
"success": true,
|
||||
"message": "API key created. Save this key now - it won't be shown again.",
|
||||
"data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"] }
|
||||
},
|
||||
"PATCH /api/v1/api-keys/{id}": {
|
||||
"success": true,
|
||||
"data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "disabled": false }
|
||||
},
|
||||
"DELETE /api/v1/api-keys/{id}": {
|
||||
"success": true,
|
||||
"message": "API key deleted"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# Container Management
|
||||
|
||||
Container Management is the core CLICD module. It covers creation, lifecycle operations, resource limits, network mappings, traffic statistics, password resets, and console access.
|
||||
|
||||
## Container List
|
||||
|
||||
The list page scans container status. Administrators can view all containers. Sub-users only see containers within their authorization scope.
|
||||
|
||||
Common fields include:
|
||||
|
||||
- ID, UUID, and name.
|
||||
- Virtualization type.
|
||||
- Runtime status.
|
||||
- IP and IPv6.
|
||||
- CPU, memory, and disk limits.
|
||||
- Traffic usage and traffic limits.
|
||||
- Expiration time.
|
||||
|
||||
## Create Containers
|
||||
|
||||
Creation requires a template and resource quotas. Batch creation is available from the panel or API and is useful for issuing multiple containers at once.
|
||||
|
||||
```http
|
||||
POST /api/v1/containers
|
||||
POST /api/v1/batch-create
|
||||
```
|
||||
|
||||
Linux containers and Linux KVM virtual machines support SSH login configuration during creation:
|
||||
|
||||
- `auto_password`: generate a root SSH password automatically.
|
||||
- `password`: use a custom `ssh_password`.
|
||||
- `key`: write a one-line `ssh_public_key`; a password is still kept for WebSSH.
|
||||
|
||||
Network allocation can combine NAT, public IPv4, and IPv6 as needed. API fields such as `assign_nat`, `assign_ipv4`, `public_ipv4s`, `assign_ipv6`, and `ipv6_addresses` are optional. If they are omitted, default behavior is preserved.
|
||||
|
||||
## Lifecycle Operations
|
||||
|
||||
```http
|
||||
POST /api/v1/containers/{id}/start
|
||||
POST /api/v1/containers/{id}/stop
|
||||
POST /api/v1/containers/{id}/restart
|
||||
POST /api/v1/containers/{id}/reinstall
|
||||
DELETE /api/v1/containers/{id}/delete
|
||||
```
|
||||
|
||||
Start, stop, reinstall, and delete actions enter the task queue. Call `GET /api/v1/tasks` afterwards to check execution status.
|
||||
|
||||
When reinstalling a Linux system, you may pass `ssh_auth_mode`, `ssh_password`, and `ssh_public_key`. `ssh_auth_mode=keep` keeps the current SSH password. If these fields are omitted, the old behavior is preserved.
|
||||
|
||||
## Resources and Traffic
|
||||
|
||||
The container details page supports resource usage, traffic limit changes, resource limit changes, and expiration changes.
|
||||
|
||||
```http
|
||||
GET /api/v1/containers/{id}/usage
|
||||
GET /api/v1/containers/{id}/traffic
|
||||
POST /api/v1/containers/{id}/traffic-reset
|
||||
PUT /api/v1/containers/{id}/traffic-limit
|
||||
PUT /api/v1/containers/{id}/resource-limit
|
||||
PUT /api/v1/containers/{id}/expiry
|
||||
```
|
||||
|
||||
## NAT Port Management
|
||||
|
||||
The NAT port management section supports adding, editing, and deleting mappings. Add and edit actions use a dialog so name, protocol, external port, and internal port can be filled in together.
|
||||
|
||||
```http
|
||||
GET /api/v1/containers/{id}/random-port
|
||||
POST /api/v1/containers/{id}/port-mappings
|
||||
PUT /api/v1/containers/{id}/port-mappings/{index}
|
||||
DELETE /api/v1/containers/{id}/port-mappings/{index}
|
||||
```
|
||||
|
||||
In sub-user mode, administrators can limit sub-users to changing only the internal port, preventing changes to the host-facing port and protocol.
|
||||
|
||||
## Remote Console
|
||||
|
||||
```http
|
||||
POST /api/v1/ssh-ticket
|
||||
POST /api/v1/vnc-ticket
|
||||
```
|
||||
|
||||
Tickets are short-lived. Use them immediately for WebSSH or WebVNC and do not persist them.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Dashboard
|
||||
|
||||
The dashboard shows the overall state of the host and virtualization resources.
|
||||
|
||||
## Metrics
|
||||
|
||||
- Total containers, running containers, and stopped containers.
|
||||
- CPU, memory, disk, and Swap overview.
|
||||
- Entry points for host network and routing status.
|
||||
- Task queue status.
|
||||
- Security alert summary.
|
||||
|
||||
## Related APIs
|
||||
|
||||
```http
|
||||
GET /api/v1/dashboard
|
||||
GET /api/v1/host-info
|
||||
GET /api/v1/routing
|
||||
GET /api/v1/ipv6/status
|
||||
GET /api/v1/tasks
|
||||
```
|
||||
|
||||
API requests must include an API key:
|
||||
|
||||
```bash
|
||||
curl -H "X-API-Key: YOUR_API_KEY" https://panel.example.com/api/v1/dashboard
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
# Host Report
|
||||
|
||||
The host report summarizes the host runtime environment, resource status, and virtualization dependencies. It is useful for post-installation checks, troubleshooting, or sharing environment information with maintainers.
|
||||
|
||||
## Contents
|
||||
|
||||
- System version and kernel information.
|
||||
- CPU, memory, disk, and Swap.
|
||||
- Network status.
|
||||
- LXC/KVM dependency status.
|
||||
- CLICD service status.
|
||||
|
||||
## Related APIs
|
||||
|
||||
```http
|
||||
GET /api/v1/host-report
|
||||
GET /api/v1/host-info
|
||||
GET /api/v1/swap
|
||||
```
|
||||
|
||||
Before sending a report externally, check whether it contains public IPs, private networks, usernames, keys, tickets, or business domains.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Image Management
|
||||
|
||||
Image Management maintains templates used to create containers or virtual machines.
|
||||
|
||||
## Supported Template Types
|
||||
|
||||
The project includes common Linux distribution templates such as Debian, Ubuntu, Alpine, CentOS, Fedora, Arch Linux, and Rocky Linux. KVM templates use the corresponding distribution cloud image resources.
|
||||
|
||||
## Management Actions
|
||||
|
||||
```http
|
||||
GET /api/v1/templates
|
||||
GET /api/v1/images
|
||||
POST /api/v1/images/download
|
||||
POST /api/v1/images/cancel
|
||||
DELETE /api/v1/images/delete
|
||||
PUT /api/v1/images/toggle
|
||||
```
|
||||
|
||||
- `templates` returns available template definitions.
|
||||
- `images` returns local image status.
|
||||
- `download` downloads a specific template.
|
||||
- `cancel` cancels a download task.
|
||||
- `delete` removes the local image cache.
|
||||
- `toggle` controls whether a template can be used during creation.
|
||||
|
||||
## Windows Images
|
||||
|
||||
This project does not distribute Windows system images and does not provide features to bypass or avoid Windows activation. Windows download links should point to official Microsoft resources, and users must obtain valid licenses themselves.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Networking and Routing
|
||||
|
||||
CLICD provides NAT4 port mapping, random available ports, public IPv4 assignment, IPv6 status checks, and IPv6 assignment. During container creation, you can use NAT only, public IPv4 only, IPv6 only, or a mixed network setup.
|
||||
|
||||
## NAT4
|
||||
|
||||
NAT4 forwards host ports to container internal ports. Common uses include:
|
||||
|
||||
- Forwarding SSH.
|
||||
- Exposing web services.
|
||||
- Assigning fixed external ports to sub-users.
|
||||
|
||||
Port mappings include:
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| Name | A purpose label such as `ssh` or `web`. |
|
||||
| Protocol | `tcp` or `udp`. |
|
||||
| External port | The host port exposed to the outside. |
|
||||
| Internal port | The service port inside the container. |
|
||||
|
||||
## IPv6
|
||||
|
||||
IPv6 assignment requires the host to have a routable IPv6 prefix, plus correct routing, neighbor discovery, or proxy configuration.
|
||||
|
||||
```http
|
||||
GET /api/v1/ipv6/status
|
||||
POST /api/v1/containers/{id}/ipv6
|
||||
```
|
||||
|
||||
If the host has no public IPv6 or the upstream network is not routing the prefix correctly, assigned addresses will not be reachable from the public internet.
|
||||
|
||||
## Public IPv4
|
||||
|
||||
Public IPv4 assignment selects from public IPv4 addresses detected on the host, or from `public_ipv4s` specified through the API. Creation fields include:
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| `assign_nat` | Whether to enable NAT port mappings. |
|
||||
| `assign_ipv4` | Whether to assign public IPv4. |
|
||||
| `ipv4_count` | Number of public IPv4 addresses to allocate automatically. |
|
||||
| `public_ipv4s` | Explicit public IPv4 address list. |
|
||||
| `assign_ipv6` | Whether to assign IPv6. |
|
||||
| `ipv6_count` | Number of IPv6 addresses to allocate automatically. |
|
||||
| `ipv6_addresses` | Explicit IPv6 address list. |
|
||||
|
||||
Public address pool APIs:
|
||||
|
||||
```http
|
||||
GET /api/v1/routing
|
||||
PUT /api/v1/routing
|
||||
POST /api/v1/routing/ipv4-scan
|
||||
```
|
||||
|
||||
## Routing Status
|
||||
|
||||
```http
|
||||
GET /api/v1/routing
|
||||
```
|
||||
|
||||
This endpoint shows runtime status for NAT, IPv4, IPv6, and port capacity.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Security Alerts
|
||||
|
||||
CLICD includes lightweight security alerts based on connection behavior. It does not keep full normal connection logs; it focuses on abnormal behavior and high-risk patterns.
|
||||
|
||||
## Covered Scenarios
|
||||
|
||||
- Port scanning.
|
||||
- Lateral scanning.
|
||||
- Brute-force tendencies.
|
||||
- SMTP abuse.
|
||||
- UDP reflection risk.
|
||||
- Suspicious ports related to mining, proxies, VPNs, Tor, and similar services.
|
||||
|
||||
## APIs
|
||||
|
||||
```http
|
||||
GET /api/v1/security/alerts
|
||||
POST /api/v1/security/check
|
||||
GET /api/v1/security/logs?container={name}
|
||||
GET /api/v1/security/summary
|
||||
GET /api/v1/security/settings
|
||||
PUT /api/v1/security/settings
|
||||
```
|
||||
|
||||
## Automatic Shutdown
|
||||
|
||||
Security settings can enable automatic shutdown after alerts. Before enabling it, observe for a while and make sure the rules do not affect normal services.
|
||||
|
||||
## Logging Advice
|
||||
|
||||
Security alerts are risk signals. They should not replace a professional firewall, intrusion detection, or centralized logging system. For public services, still combine them with security groups, firewall rules, Fail2ban, and similar tools.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Snapshot Management
|
||||
|
||||
Snapshots save the current state of a container so it can be rolled back before upgrades, configuration changes, or delivery.
|
||||
|
||||
## Global Overview
|
||||
|
||||
```http
|
||||
GET /api/v1/snapshots
|
||||
```
|
||||
|
||||
Use this endpoint to view snapshot summaries for all containers.
|
||||
|
||||
## Container Snapshots
|
||||
|
||||
```http
|
||||
GET /api/v1/containers/{id}/snapshots
|
||||
POST /api/v1/containers/{id}/snapshots
|
||||
DELETE /api/v1/containers/{id}/snapshots/{snapshot_id}
|
||||
POST /api/v1/containers/{id}/snapshots/{snapshot_id}/restore
|
||||
```
|
||||
|
||||
Restoring a snapshot changes container state. In production, confirm that the current workload can be interrupted first.
|
||||
|
||||
## Scheduled Snapshots and Quotas
|
||||
|
||||
```http
|
||||
POST /api/v1/containers/{id}/snapshots/schedule
|
||||
PUT /api/v1/containers/{id}/snapshots/quota
|
||||
```
|
||||
|
||||
Scheduled snapshots are useful for long-running containers. Quotas prevent snapshots from growing without limit and filling the host disk.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Sub-users
|
||||
|
||||
Sub-users let administrators grant specific container access to other users. They are useful for temporary delivery, shared-host allocation, teaching labs, or multi-user host scenarios.
|
||||
|
||||
## Create an Access Link
|
||||
|
||||
After selecting a container, the administrator can create a sub-user link:
|
||||
|
||||
```http
|
||||
POST /api/v1/sub-user/create
|
||||
```
|
||||
|
||||
The response may include a username, initial password, access code, or access link. When sharing externally, mask sensitive values and send the real values only to the intended user.
|
||||
|
||||
## Manage Sub-users
|
||||
|
||||
```http
|
||||
GET /api/v1/sub-users
|
||||
POST /api/v1/sub-users/{id}/rotate-password
|
||||
GET /api/v1/sub-users/{id}/audit-logs
|
||||
GET /api/v1/sub-users/{id}/login-logs
|
||||
```
|
||||
|
||||
Rotating the password invalidates old credentials. Audit logs and login logs help investigate mistakes or abnormal access.
|
||||
|
||||
## Permission Scope
|
||||
|
||||
Sub-users can only manage authorized containers. Global configuration, image management, security policy, API keys, and other administrator features are not exposed to sub-users.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Configuration
|
||||
|
||||
After installation, CLICD runs as a systemd service. Runtime configuration and the database are stored locally on the host. The exact path may vary with installer options, but the default installation should mainly be checked under `/root/.clicd/`.
|
||||
|
||||
## Common Settings
|
||||
|
||||
| Setting | Description |
|
||||
| --- | --- |
|
||||
| Web port | Defaults to `8999`, listening on `0.0.0.0:8999`. |
|
||||
| Administrator account | Used to log in to the web panel and manage API keys. |
|
||||
| Database | SQLite storage for container metadata, sub-users, audit logs, API keys, and more. |
|
||||
| NAT port range | Used for random ports and port mapping allocation. |
|
||||
| IPv6 prefixes | Used when the host has routable IPv6 prefixes. |
|
||||
| Security alerts | Policies such as automatic shutdown can be configured. |
|
||||
|
||||
## Service Commands
|
||||
|
||||
```bash
|
||||
systemctl status clicd
|
||||
systemctl restart clicd
|
||||
journalctl -u clicd -n 100 --no-pager
|
||||
```
|
||||
|
||||
## Security Recommendations
|
||||
|
||||
- Do not expose the web panel directly to untrusted networks.
|
||||
- Use a strong administrator password and rotate it regularly.
|
||||
- Split API keys by purpose and avoid long-lived full-access keys.
|
||||
- WebSSH and WebVNC tickets are short-lived credentials and should not be written to logs or shared publicly.
|
||||
- Do not paste real IPs, passwords, API keys, or tickets into public docs, screenshots, or support tickets.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Installation
|
||||
|
||||
CLICD provides a one-line installer. By default, it installs the latest version from GitHub Releases. You can also pin a specific version with an environment variable.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Linux x86_64 host.
|
||||
- Root privileges.
|
||||
- systemd.
|
||||
- Network access to GitHub Release downloads.
|
||||
- LXC runtime support if you want to use LXC.
|
||||
- KVM virtualization enabled with libvirt/QEMU installed if you want to use KVM.
|
||||
|
||||
## Install the Latest Version
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh
|
||||
```
|
||||
|
||||
The script defaults to `CLICD_VERSION=latest`, which downloads `clicd-linux-amd64.tar.gz` from `releases/latest`.
|
||||
|
||||
## Install a Specific Version
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo CLICD_VERSION=v1.1.6 sh
|
||||
```
|
||||
|
||||
Replace `v1.1.6` with the release tag you want to install.
|
||||
|
||||
## Open the Panel
|
||||
|
||||
After installation, open:
|
||||
|
||||
```text
|
||||
http://YOUR_SERVER_IP:8999
|
||||
```
|
||||
|
||||
Use the administrator credentials printed by the installer for the first login. In production, restrict access at the firewall or reverse proxy layer and change the default username and password as soon as possible.
|
||||
|
||||
## Uninstall
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh -s -- uninstall
|
||||
```
|
||||
|
||||
Before uninstalling, decide whether you need to keep containers, image cache, database files, or configuration files.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Introduction
|
||||
|
||||
CLICD is a lightweight virtualization management panel for LXC and KVM. It brings common host operations into a web console and CLI, making it suitable for small VPS nodes, dedicated servers, and scenarios where container access needs to be distributed in batches.
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
- Manage LXC containers and KVM virtual machines.
|
||||
- Create, start, stop, restart, reinstall, and delete containers.
|
||||
- Configure CPU, memory, disk, traffic limits, and expiration time.
|
||||
- Manage NAT4 port mappings, public IPv4 assignment, and public IPv6 assignment when the host network supports it.
|
||||
- Open WebSSH or WebVNC from the browser.
|
||||
- Manage image downloads, enablement, and local cache.
|
||||
- Create, restore, and delete snapshots, plus scheduled snapshots and quotas.
|
||||
- Generate security alerts based on connection behavior and keep audit logs.
|
||||
- Create sub-user access links for specific containers.
|
||||
- Integrate automation through API keys and `/api/v1`.
|
||||
|
||||
## Use Cases
|
||||
|
||||
- Quickly allocate multiple Linux containers on one host.
|
||||
- Give users temporary access to a container console, SSH, VNC, or NAT port management.
|
||||
- Automate container creation, resource changes, password resets, or resource cleanup through the API.
|
||||
- Use a panel that is clearer than pure CLI workflows without becoming a heavy platform.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Backend: Go, `net/http`, SQLite, systemd, LXC, KVM/libvirt, cgroup v2, iptables, conntrack.
|
||||
- Frontend: React, TypeScript, Vite, Tailwind CSS, lucide-react, xterm.js, noVNC.
|
||||
- Release: GitHub Actions builds Linux AMD64 release artifacts. The installer fetches the latest release by default.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Quick Start
|
||||
|
||||
This is a common path from a fresh installation to your first container.
|
||||
|
||||
## 1. Log In
|
||||
|
||||
Open `http://YOUR_SERVER_IP:8999` and sign in with the administrator account.
|
||||
|
||||
After entering the panel, check:
|
||||
|
||||
- Whether the dashboard shows host resources.
|
||||
- Whether Image Management can list templates.
|
||||
- Whether NAT and IPv6 status in Routing match your host network.
|
||||
|
||||
## 2. Download an Image
|
||||
|
||||
Open Image Management, choose a template, and download it. On small hosts, lightweight images such as Alpine or Debian are a good first choice.
|
||||
|
||||
Image downloads run asynchronously. You can watch progress in the task queue.
|
||||
|
||||
## 3. Create a Container
|
||||
|
||||
Open Container Management and click Create:
|
||||
|
||||
- Select virtualization type and template.
|
||||
- Set CPU, memory, and disk.
|
||||
- Set traffic limits and expiration time.
|
||||
- If external access is required, add NAT port mappings or assign IPv6 from the container details page after creation.
|
||||
|
||||
## 4. Open a Terminal
|
||||
|
||||
After the container is created, open WebSSH from the details page. KVM virtual machines can use WebVNC for console access.
|
||||
|
||||
## 5. Share with a Sub-user
|
||||
|
||||
If another user needs to manage a container, create an access link in Sub-user Management. The sub-user only sees authorized containers and is limited by the operation scope configured by the administrator.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Upgrade
|
||||
|
||||
The CLICD installer and CLI are built around GitHub Release artifacts. Before upgrading, check the current version and back up configuration and database files.
|
||||
|
||||
## Check the Version
|
||||
|
||||
The current version is shown at the bottom of the web panel sidebar. You can also run:
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8999/api/version
|
||||
```
|
||||
|
||||
Example response:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"version": "1.1.6"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Upgrade with the Installer
|
||||
|
||||
The installer uses the latest release by default:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo sh
|
||||
```
|
||||
|
||||
Install a specific version:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo CLICD_VERSION=v1.1.6 sh
|
||||
```
|
||||
|
||||
## Pre-upgrade Checklist
|
||||
|
||||
- Back up `/root/.clicd/` or the actual configuration directory.
|
||||
- Make sure no critical tasks are currently running.
|
||||
- If an image download or snapshot restore is running, wait for it to finish first.
|
||||
- After upgrading, check `systemctl status clicd` and the version shown in the web panel.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: CLICD
|
||||
text: Lightweight LXC/KVM Virtualization Panel
|
||||
tagline: Web console, CLI, container orchestration, NAT/IPv4/IPv6 routing, snapshots, security alerts, sub-users, and API automation.
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Install
|
||||
link: /en/guide/installation
|
||||
- theme: alt
|
||||
text: API Reference
|
||||
link: /en/features/api
|
||||
|
||||
features:
|
||||
- title: Built for Small Hosts
|
||||
details: Manage LXC containers and KVM virtual machines on a single VPS or dedicated server.
|
||||
- title: Web and CLI Together
|
||||
details: Use the web panel for daily operations, or drop into the clicd CLI for maintenance tasks.
|
||||
- title: Automation Friendly
|
||||
details: /api/v1 exposes containers, images, snapshots, security, logs, sub-users, and API key management.
|
||||
---
|
||||
@@ -0,0 +1,46 @@
|
||||
# Deployment
|
||||
|
||||
CLICD can run directly on the host or behind a reverse proxy. In production, set up access control before exposing it to administrators.
|
||||
|
||||
## Service Exposure
|
||||
|
||||
The default web port is `8999`:
|
||||
|
||||
```text
|
||||
http://YOUR_SERVER_IP:8999
|
||||
```
|
||||
|
||||
Recommendations:
|
||||
|
||||
- Allow only fixed administrator IPs.
|
||||
- Use a reverse proxy with HTTPS.
|
||||
- Do not expose the real login URL in public docs or screenshots.
|
||||
|
||||
## systemd
|
||||
|
||||
Common commands:
|
||||
|
||||
```bash
|
||||
systemctl status clicd
|
||||
systemctl restart clicd
|
||||
systemctl enable clicd
|
||||
journalctl -u clicd -f
|
||||
```
|
||||
|
||||
## Firewall
|
||||
|
||||
At minimum, confirm:
|
||||
|
||||
- The panel port is open only to trusted sources.
|
||||
- NAT mapped ports are opened only as needed.
|
||||
- The SSH management port does not conflict with container mappings.
|
||||
- IPv6 firewall rules are planned together with IPv4 rules.
|
||||
|
||||
## Backups
|
||||
|
||||
Back up regularly:
|
||||
|
||||
- CLICD configuration directory.
|
||||
- SQLite database.
|
||||
- Container configuration.
|
||||
- Snapshots or external data backups for important containers.
|
||||
@@ -0,0 +1,29 @@
|
||||
# FAQ
|
||||
|
||||
## Which version does the installer install by default?
|
||||
|
||||
It installs the latest version from GitHub Releases. The script default is `CLICD_VERSION=latest`, which downloads the Linux AMD64 artifact from `releases/latest`.
|
||||
|
||||
## Can I pin a specific version?
|
||||
|
||||
Yes:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | sudo CLICD_VERSION=v1.1.6 sh
|
||||
```
|
||||
|
||||
## Can sub-users see every container?
|
||||
|
||||
No. Sub-users only see containers authorized by the administrator.
|
||||
|
||||
## Is an API key the same as the login password?
|
||||
|
||||
No. API keys are created on the API Integration page for programmatic access. The login password is used for the web panel.
|
||||
|
||||
## What happens after a container reaches its traffic limit?
|
||||
|
||||
The container is automatically shut down to avoid further overage. The administrator can adjust the limit or reset traffic usage.
|
||||
|
||||
## Why is IPv6 unreachable after assignment?
|
||||
|
||||
IPv6 reachability depends on the host and upstream network. Confirm that the host has a routable IPv6 prefix and that routing, firewall, neighbor discovery, or proxy configuration is correct.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Troubleshooting
|
||||
|
||||
## Service Not Reachable
|
||||
|
||||
Check service status:
|
||||
|
||||
```bash
|
||||
systemctl status clicd
|
||||
journalctl -u clicd -n 100 --no-pager
|
||||
```
|
||||
|
||||
Check port listening:
|
||||
|
||||
```bash
|
||||
ss -lntp | grep 8999
|
||||
```
|
||||
|
||||
If a reverse proxy is used, check proxy logs and upstream address settings as well.
|
||||
|
||||
## Image Download Failed
|
||||
|
||||
- Make sure the host can access image sources and GitHub Releases.
|
||||
- Check disk space.
|
||||
- Review the failure reason in the task queue.
|
||||
- If a download is stuck, cancel it and start again.
|
||||
|
||||
## Container Cannot Access the Network
|
||||
|
||||
- Check host NAT and forwarding rules.
|
||||
- Confirm that the container IP was assigned successfully.
|
||||
- Check whether the firewall is blocking forwarded traffic.
|
||||
- For IPv6, confirm that the upstream network routes the prefix to the host.
|
||||
|
||||
## WebSSH or WebVNC Connection Failed
|
||||
|
||||
- Confirm that the container or virtual machine is running.
|
||||
- WebSSH requires SSH service inside the container.
|
||||
- WebVNC requires the KVM console to be reachable.
|
||||
- Tickets expire quickly. Create a new ticket after expiration.
|
||||
|
||||
## API Returns Unauthorized
|
||||
|
||||
- Confirm that the API key is not disabled.
|
||||
- Use `X-API-Key` or `Authorization: Bearer`.
|
||||
- Confirm that the key scope covers the target endpoint.
|
||||
- Do not use the panel login password as an API key.
|
||||
@@ -1,6 +1,6 @@
|
||||
# API 集成
|
||||
|
||||
CLICD 对外推荐使用 `/api/v1` 接口。旧版未带版本号的接口主要用于 Web 面板和兼容场景,新接入请优先使用 `/api/v1`。
|
||||
CLICD 继续兼容旧版 `/api` 接口,已有对接无需修改。新接入推荐使用 `/api/v1` 接口,下面的清单均为 v1;容器列表推荐 `GET /api/v1/containers`。
|
||||
|
||||
## 认证
|
||||
|
||||
@@ -14,8 +14,81 @@ curl -H "X-API-Key: YOUR_API_KEY" https://panel.example.com/api/v1/containers
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/dashboard
|
||||
```
|
||||
|
||||
## 响应结构
|
||||
|
||||
所有接口保持统一响应包裹:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "OK",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
对接时建议只读取业务所需字段。新增能力会优先追加可选字段,不会要求已有插件改掉现有字段名。
|
||||
|
||||
## 创建与重装
|
||||
|
||||
创建容器、批量创建、重装和批量重装已支持 NAT、公网 IPv4、IPv6 混合网络,以及 Linux SSH 登录方式配置。公网 IPv4/IPv6 地址池可通过 `GET /api/v1/routing` 查看,并可通过 `PUT /api/v1/routing` 更新。
|
||||
|
||||
创建容器示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "demo-lxc-01",
|
||||
"virtualization": "lxc",
|
||||
"template_id": "debian-bookworm",
|
||||
"vcpu": 1,
|
||||
"ram_mb": 512,
|
||||
"disk_gb": 10,
|
||||
"assign_nat": true,
|
||||
"port_mapping_count": 2,
|
||||
"assign_ipv4": false,
|
||||
"ipv4_count": 1,
|
||||
"public_ipv4s": [],
|
||||
"assign_ipv6": true,
|
||||
"ipv6_count": 1,
|
||||
"ipv6_addresses": [],
|
||||
"ssh_auth_mode": "auto_password",
|
||||
"ssh_password": "",
|
||||
"ssh_public_key": "",
|
||||
"expires_at": ""
|
||||
}
|
||||
```
|
||||
|
||||
字段说明:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `assign_nat` | 是否分配 NAT 端口映射;不传时保持默认 NAT 行为。 |
|
||||
| `assign_ipv4` | 是否分配公网 IPv4。 |
|
||||
| `ipv4_count` | 自动分配公网 IPv4 数量。 |
|
||||
| `public_ipv4s` | 指定公网 IPv4 地址列表。 |
|
||||
| `assign_ipv6` | 是否分配 IPv6。 |
|
||||
| `ipv6_count` | 自动分配 IPv6 数量。 |
|
||||
| `ipv6_addresses` | 指定 IPv6 地址列表。 |
|
||||
| `ssh_auth_mode` | Linux 创建支持 `auto_password`、`password`、`key`;重装额外支持 `keep`。 |
|
||||
| `ssh_password` | `password` 模式下的自定义密码;8-64 位,至少包含字母和数字,不能包含空白字符。 |
|
||||
| `ssh_public_key` | `key` 模式下的一行 SSH 公钥。 |
|
||||
|
||||
重装示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"template_id": "debian-bookworm",
|
||||
"ssh_auth_mode": "keep",
|
||||
"ssh_password": "",
|
||||
"ssh_public_key": ""
|
||||
}
|
||||
```
|
||||
|
||||
`keep` 仅用于重装,表示沿用当前 SSH 密码。Windows KVM 镜像会忽略 Linux SSH 公钥相关字段。
|
||||
|
||||
## Python 示例
|
||||
|
||||
获取容器列表:
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
@@ -30,9 +103,7 @@ session.headers.update({
|
||||
|
||||
resp = session.get(f"{BASE_URL}/api/v1/containers", timeout=15)
|
||||
resp.raise_for_status()
|
||||
containers = resp.json()
|
||||
|
||||
print(containers)
|
||||
print(resp.json())
|
||||
```
|
||||
|
||||
创建端口映射:
|
||||
@@ -45,10 +116,10 @@ API_KEY = "YOUR_API_KEY"
|
||||
CONTAINER_ID = "example-vm"
|
||||
|
||||
payload = {
|
||||
"name": "web",
|
||||
"protocol": "tcp",
|
||||
"host_port": 18080,
|
||||
"container_port": 80,
|
||||
"description": "web",
|
||||
}
|
||||
|
||||
resp = requests.post(
|
||||
@@ -61,76 +132,543 @@ resp.raise_for_status()
|
||||
print(resp.json())
|
||||
```
|
||||
|
||||
## 返回结构示例
|
||||
## 接口清单
|
||||
|
||||
容器列表:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"id": 5,
|
||||
"uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
||||
"name": "example-vm",
|
||||
"status": "running",
|
||||
"ip": "10.0.3.25",
|
||||
"ipv6": "2001:db8:100::1005",
|
||||
"cpu_limit": 2,
|
||||
"memory_limit": 2048,
|
||||
"disk_limit": 20480,
|
||||
"traffic_limit": 107374182400,
|
||||
"expires_at": "2026-12-31 23:59:59"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
任务队列:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"id": "task-13",
|
||||
"type": "restart",
|
||||
"status": "running",
|
||||
"created_at": "2026-06-09T10:00:00+08:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
WebSSH 票据:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"ticket": "***60秒有效票据***"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 常用接口
|
||||
### 总览
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/dashboard` | 控制面板统计 |
|
||||
| GET | `/api/v1/host-info` | 主机资源 |
|
||||
| GET | `/api/v1/routing` | NAT/IPv4/IPv6 路由 |
|
||||
| PUT | `/api/v1/routing` | 更新公网 IPv4/IPv6 池 |
|
||||
| POST | `/api/v1/routing/ipv4-scan` | 扫描公网 IPv4 段 |
|
||||
| GET | `/api/v1/ipv6/status` | IPv6 状态 |
|
||||
| GET | `/api/v1/tasks` | 任务队列 |
|
||||
| DELETE | `/api/v1/tasks/{task_id}` | 删除任务 |
|
||||
|
||||
### 容器
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/containers` | 容器列表 |
|
||||
| POST | `/api/v1/containers/list` | 容器列表兼容 POST 写法 |
|
||||
| POST | `/api/v1/containers` | 创建容器 |
|
||||
| GET | `/api/v1/containers/{id|uuid|name}` | 容器详情 |
|
||||
| POST | `/api/v1/containers/{id}/start` | 开机 |
|
||||
| POST | `/api/v1/containers/{id}/stop` | 关机 |
|
||||
| POST | `/api/v1/containers/{id}/restart` | 重启 |
|
||||
| POST | `/api/v1/containers/{id}/reinstall` | 重装 |
|
||||
| DELETE | `/api/v1/containers/{id}/delete` | 删除 |
|
||||
| GET | `/api/v1/tasks` | 任务队列 |
|
||||
| GET | `/api/v1/containers/{id}/usage` | 资源用量 |
|
||||
| GET | `/api/v1/containers/{id}/traffic` | 流量统计 |
|
||||
| POST | `/api/v1/containers/{id}/traffic-reset` | 重置流量 |
|
||||
| PUT | `/api/v1/containers/{id}/traffic-limit` | 调整流量限制 |
|
||||
| PUT | `/api/v1/containers/{id}/resource-limit` | 调整资源限制 |
|
||||
| PUT | `/api/v1/containers/{id}/expiry` | 调整到期时间 |
|
||||
| POST | `/api/v1/containers/{id}/reset-password` | 重置 SSH 密码 |
|
||||
| POST | `/api/v1/containers/{id}/ipv6` | 分配 IPv6 |
|
||||
|
||||
### 端口与快照
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/containers/{id}/random-port` | 随机可用端口 |
|
||||
| POST | `/api/v1/containers/{id}/port-mappings` | 添加端口映射 |
|
||||
| PUT | `/api/v1/containers/{id}/port-mappings/{index}` | 更新端口映射 |
|
||||
| DELETE | `/api/v1/containers/{id}/port-mappings/{index}` | 删除端口映射 |
|
||||
| GET | `/api/v1/snapshots` | 快照总览 |
|
||||
| GET | `/api/v1/containers/{id}/snapshots` | 容器快照 |
|
||||
| POST | `/api/v1/containers/{id}/snapshots` | 创建快照 |
|
||||
| DELETE | `/api/v1/containers/{id}/snapshots/{snapshot_id}` | 删除快照 |
|
||||
| POST | `/api/v1/containers/{id}/snapshots/{snapshot_id}/restore` | 恢复快照 |
|
||||
| POST | `/api/v1/containers/{id}/snapshots/schedule` | 计划快照 |
|
||||
| PUT | `/api/v1/containers/{id}/snapshots/quota` | 快照配额 |
|
||||
|
||||
### 平台管理
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/v1/templates` | 模板列表 |
|
||||
| GET | `/api/v1/images` | 镜像管理列表 |
|
||||
| GET | `/api/v1/snapshots` | 快照总览 |
|
||||
| POST | `/api/v1/images/download` | 下载镜像 |
|
||||
| POST | `/api/v1/images/cancel` | 取消镜像下载 |
|
||||
| DELETE | `/api/v1/images/delete` | 删除镜像缓存 |
|
||||
| PUT | `/api/v1/images/toggle` | 启用/禁用镜像 |
|
||||
| GET | `/api/v1/security/alerts` | 安全告警 |
|
||||
| GET | `/api/v1/audit-logs` | 操作日志 |
|
||||
| GET | `/api/v1/api-keys` | API Key 列表 |
|
||||
| POST | `/api/v1/security/check` | 立即安全检查 |
|
||||
| GET | `/api/v1/security/logs?container={name}` | 安全连接日志 |
|
||||
| GET | `/api/v1/security/summary` | 安全汇总 |
|
||||
| GET | `/api/v1/security/settings` | 安全设置 |
|
||||
| PUT | `/api/v1/security/settings` | 更新安全设置 |
|
||||
| GET | `/api/v1/swap` | Swap 信息 |
|
||||
| POST | `/api/v1/swap` | 调整 Swap |
|
||||
| POST | `/api/v1/batch-create` | 批量创建容器 |
|
||||
| POST | `/api/v1/batch-action` | 批量开关机/删除/重装 |
|
||||
| POST | `/api/v1/ssh-ticket` | 创建 WebSSH 票据 |
|
||||
| POST | `/api/v1/vnc-ticket` | 创建 WebVNC 票据 |
|
||||
|
||||
完整接口清单请以面板内“API 集成”页面为准。
|
||||
### 账号与日志
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/v1/sub-user/create` | 创建子用户链接 |
|
||||
| GET | `/api/v1/sub-users` | 子用户列表 |
|
||||
| POST | `/api/v1/sub-users/{id}/rotate-password` | 轮换子用户密码 |
|
||||
| GET | `/api/v1/sub-users/{id}/audit-logs` | 子用户操作日志 |
|
||||
| GET | `/api/v1/sub-users/{id}/login-logs` | 子用户登录日志 |
|
||||
| GET | `/api/v1/audit-logs` | 操作日志 |
|
||||
| GET | `/api/v1/login-logs` | 登录日志 |
|
||||
| GET | `/api/v1/api-keys` | API Key 列表 |
|
||||
| POST | `/api/v1/api-keys` | 创建 API Key |
|
||||
| PATCH | `/api/v1/api-keys/{id}` | 更新 API Key |
|
||||
| DELETE | `/api/v1/api-keys/{id}` | 删除 API Key |
|
||||
|
||||
## 返回样例
|
||||
|
||||
以下样例按接口路径分组。真实环境中的资源数值、任务 ID、容器 ID、时间、IP 和密钥会不同,示例中的密码、票据和 API Key 均已脱敏。
|
||||
|
||||
### 总览
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/dashboard": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"running": 31,
|
||||
"stopped": 0,
|
||||
"total_containers": 31
|
||||
}
|
||||
},
|
||||
"GET /api/v1/host-info": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"cpu": { "cores": 8, "usage_pct": 1.16 },
|
||||
"ram": { "total_mb": 31825, "used_mb": 1275, "free_mb": 30550 },
|
||||
"disk": { "total_gb": 1750.49, "used_gb": 123.98, "free_gb": 1626.51 },
|
||||
"network": {
|
||||
"public_ipv4": "203.0.113.10",
|
||||
"public_ipv4_interface": "eth0",
|
||||
"public_ipv6": "2001:db8:100::2",
|
||||
"public_ipv6_interface": "eth0"
|
||||
},
|
||||
"load": { "load1": 0.01, "load5": 0.03, "load15": 0.01 }
|
||||
}
|
||||
},
|
||||
"GET /api/v1/routing": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"nat4": { "used": 62, "remaining": "45474", "total": "45536" },
|
||||
"ipv4": { "used": 1, "remaining": "3", "total": "4" },
|
||||
"ipv6": { "used": 31, "remaining": "large", "total": "large" },
|
||||
"public_ipv4_addresses": [
|
||||
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
|
||||
],
|
||||
"ipv4_assignments": [
|
||||
{ "container_id": 5, "container_name": "example-vm", "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
|
||||
],
|
||||
"nat4_mappings": [
|
||||
{ "container_id": 5, "container_name": "example-vm", "status": "running", "ip": "10.0.0.10", "host_port": 22004, "container_port": 22, "protocol": "tcp" }
|
||||
],
|
||||
"ipv6_assignments": [
|
||||
{ "container_id": 5, "container_name": "example-vm", "address": "2001:db8:100::1005", "prefix_len": 64, "interface": "eth0" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"PUT /api/v1/routing": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"ipv4": { "used": 1, "remaining": "3", "total": "4" },
|
||||
"public_ipv4_addresses": [
|
||||
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1" }
|
||||
],
|
||||
"ipv6_prefixes": [
|
||||
{ "interface": "eth0", "address": "2001:db8:100::2", "prefix": "2001:db8:100::/64", "prefix_len": 64, "gateway": "2001:db8:100::1" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"POST /api/v1/routing/ipv4-scan": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "address": "203.0.113.10", "interface": "eth0", "prefix_len": 32, "gateway": "203.0.113.1", "status": "available", "usable": true, "reason": "" }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/ipv6/status": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"available": true,
|
||||
"reachable": true,
|
||||
"reason": "usable public IPv6 prefix detected",
|
||||
"prefixes": [
|
||||
{ "interface": "eth0", "address": "2001:db8:100::2", "prefix": "2001:db8:100::/64", "prefix_len": 64, "gateway": "2001:db8:100::1" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"GET /api/v1/tasks": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"DELETE /api/v1/tasks/{task_id}": {
|
||||
"success": true,
|
||||
"message": "Task deleted"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 容器
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/containers": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"id": 5,
|
||||
"uuid": "00000000-0000-4000-8000-000000000005",
|
||||
"name": "example-vm",
|
||||
"virtualization": "lxc",
|
||||
"template": "debian-bullseye",
|
||||
"vcpu": 1,
|
||||
"ram_mb": 512,
|
||||
"disk_gb": 10,
|
||||
"status": "running",
|
||||
"ip": "10.0.0.10",
|
||||
"ipv6": "2001:db8:100::1005",
|
||||
"ssh_port": 22004,
|
||||
"ssh_password": "***",
|
||||
"port_mappings": [
|
||||
{ "container_port": 22, "host_port": 22004, "protocol": "tcp", "description": "SSH" },
|
||||
{ "container_port": 20000, "host_port": 20000, "protocol": "tcp", "description": "Port-20000" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"POST /api/v1/containers/list": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": 5, "uuid": "00000000-0000-4000-8000-000000000005", "name": "example-vm", "status": "running", "ip": "10.0.0.10" }
|
||||
]
|
||||
},
|
||||
"POST /api/v1/containers": {
|
||||
"success": true,
|
||||
"message": "Container created successfully"
|
||||
},
|
||||
"GET /api/v1/containers/{id|uuid|name}": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"id": 5,
|
||||
"uuid": "00000000-0000-4000-8000-000000000005",
|
||||
"name": "example-vm",
|
||||
"status": "running",
|
||||
"ip": "10.0.0.10",
|
||||
"ipv6": "2001:db8:100::1005",
|
||||
"ssh_port": 22004,
|
||||
"ssh_password": "***",
|
||||
"policy_blocked": false
|
||||
}
|
||||
},
|
||||
"POST /api/v1/containers/{id}/start": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "start" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/stop": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "stop" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/restart": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "restart" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/reinstall": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "reinstall" }
|
||||
},
|
||||
"DELETE /api/v1/containers/{id}/delete": {
|
||||
"success": true,
|
||||
"message": "Task queued",
|
||||
"data": { "task_id": "task-10", "container_name": "example-vm", "status": "pending", "action": "delete" }
|
||||
},
|
||||
"GET /api/v1/containers/{id}/usage": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"cpu_usage_pct": 0,
|
||||
"cpu_usage_usec": 3908852,
|
||||
"memory_usage_bytes": 29331456,
|
||||
"disk_usage_bytes": 515100672,
|
||||
"network_rx_bytes": 131232,
|
||||
"network_tx_bytes": 16828,
|
||||
"load1": 0.1,
|
||||
"load5": 0.06,
|
||||
"load15": 0.01
|
||||
}
|
||||
},
|
||||
"GET /api/v1/containers/{id}/traffic": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"mode": "total",
|
||||
"limit_gb": 0,
|
||||
"in_limit_gb": 0,
|
||||
"out_limit_gb": 0,
|
||||
"total_used_bytes": 142082,
|
||||
"rx_used_bytes": 127212,
|
||||
"tx_used_bytes": 14870,
|
||||
"used_pct": 0,
|
||||
"reset_date": "2026-06"
|
||||
}
|
||||
},
|
||||
"POST /api/v1/containers/{id}/traffic-reset": {
|
||||
"success": true,
|
||||
"message": "Traffic reset"
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/traffic-limit": {
|
||||
"success": true,
|
||||
"message": "Traffic limit updated"
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/resource-limit": {
|
||||
"success": true,
|
||||
"message": "Resource limits updated"
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/expiry": {
|
||||
"success": true,
|
||||
"message": "Expiry updated"
|
||||
},
|
||||
"POST /api/v1/containers/{id}/reset-password": {
|
||||
"success": true,
|
||||
"message": "SSH password reset successfully",
|
||||
"data": { "password": "***" }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/ipv6": {
|
||||
"success": true,
|
||||
"message": "IPv6 assigned",
|
||||
"data": { "id": 5, "name": "example-vm", "ipv6": "2001:db8:100::1005" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 端口与快照
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/containers/{id}/random-port": {
|
||||
"success": true,
|
||||
"data": { "port": 61320 }
|
||||
},
|
||||
"POST /api/v1/containers/{id}/port-mappings": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "container_port": 22, "host_port": 22004, "protocol": "tcp", "description": "SSH" },
|
||||
{ "container_port": 8080, "host_port": 61320, "protocol": "tcp", "description": "HTTP" }
|
||||
]
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/port-mappings/{index}": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "container_port": 8081, "host_port": 61320, "protocol": "tcp", "description": "HTTP" }
|
||||
]
|
||||
},
|
||||
"DELETE /api/v1/containers/{id}/port-mappings/{index}": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/snapshots": {
|
||||
"success": true,
|
||||
"data": null
|
||||
},
|
||||
"GET /api/v1/containers/{id}/snapshots": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"quota": 1,
|
||||
"schedule": { "enabled": false, "interval_hours": 0, "last_run": "", "next_run": "", "time": "", "created_by": "" },
|
||||
"snapshots": []
|
||||
}
|
||||
},
|
||||
"POST /api/v1/containers/{id}/snapshots": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"id": "snap-20260608-001",
|
||||
"container_id": 5,
|
||||
"container_name": "example-vm",
|
||||
"created_at": "2026-06-08 16:00:00",
|
||||
"created_by": "api:Automation",
|
||||
"scheduled": false,
|
||||
"size_bytes": 10485760
|
||||
}
|
||||
},
|
||||
"DELETE /api/v1/containers/{id}/snapshots/{snapshot_id}": {
|
||||
"success": true,
|
||||
"message": "Snapshot deleted"
|
||||
},
|
||||
"POST /api/v1/containers/{id}/snapshots/{snapshot_id}/restore": {
|
||||
"success": true,
|
||||
"message": "Snapshot restored"
|
||||
},
|
||||
"POST /api/v1/containers/{id}/snapshots/schedule": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"container": { "id": 5, "name": "example-vm", "snapshot_schedule_enabled": true, "snapshot_schedule_interval_hours": 24, "snapshot_schedule_time": "03:00" }
|
||||
}
|
||||
},
|
||||
"PUT /api/v1/containers/{id}/snapshots/quota": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"quota": 2,
|
||||
"container": { "id": 5, "name": "example-vm", "snapshot_limit": 2 }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 平台管理
|
||||
|
||||
```json
|
||||
{
|
||||
"GET /api/v1/templates": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "distro": "ubuntu", "release": "noble", "arch": "amd64", "description": "Ubuntu 24.04 LTS" },
|
||||
{ "id": "debian-bookworm", "name": "Debian 12", "distro": "debian", "release": "bookworm", "arch": "amd64", "description": "Debian 12 (Bookworm)" }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/images": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "type": "lxc", "downloaded": true, "enabled": true, "downloading": false, "progress": 0, "size_bytes": 135005452 }
|
||||
]
|
||||
},
|
||||
"POST /api/v1/images/download": {
|
||||
"success": true,
|
||||
"message": "Already downloaded"
|
||||
},
|
||||
"POST /api/v1/images/cancel": {
|
||||
"success": true,
|
||||
"message": "Cancel requested"
|
||||
},
|
||||
"DELETE /api/v1/images/delete": {
|
||||
"success": true,
|
||||
"message": "Deleted"
|
||||
},
|
||||
"PUT /api/v1/images/toggle": {
|
||||
"success": true,
|
||||
"message": "OK"
|
||||
},
|
||||
"GET /api/v1/security/alerts": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"POST /api/v1/security/check": {
|
||||
"success": true,
|
||||
"message": "Security check completed"
|
||||
},
|
||||
"GET /api/v1/security/logs?container={name}": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/security/summary": {
|
||||
"success": true,
|
||||
"data": { "critical": 0, "high": 0, "medium": 0, "low": 0, "total_alerts": 0 }
|
||||
},
|
||||
"GET /api/v1/security/settings": {
|
||||
"success": true,
|
||||
"data": { "auto_shutdown": false }
|
||||
},
|
||||
"PUT /api/v1/security/settings": {
|
||||
"success": true,
|
||||
"data": { "auto_shutdown": false }
|
||||
},
|
||||
"GET /api/v1/swap": {
|
||||
"success": true,
|
||||
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
|
||||
},
|
||||
"POST /api/v1/swap": {
|
||||
"success": true,
|
||||
"message": "SWAP 已调整为 16384 MB",
|
||||
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
|
||||
},
|
||||
"POST /api/v1/batch-create": {
|
||||
"success": true,
|
||||
"data": ["task-12"]
|
||||
},
|
||||
"POST /api/v1/batch-action": {
|
||||
"success": true,
|
||||
"data": ["task-13"]
|
||||
},
|
||||
"POST /api/v1/ssh-ticket": {
|
||||
"success": true,
|
||||
"data": { "ticket": "***60秒有效票据***" }
|
||||
},
|
||||
"POST /api/v1/vnc-ticket": {
|
||||
"success": true,
|
||||
"data": { "ticket": "***60秒有效票据***" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 账号与日志
|
||||
|
||||
```json
|
||||
{
|
||||
"POST /api/v1/sub-user/create": {
|
||||
"success": true,
|
||||
"message": "Sub-user created",
|
||||
"data": {
|
||||
"id": "sub-xxxxxxxx",
|
||||
"username": "user-xxxxxxxx",
|
||||
"password": "***",
|
||||
"container_names": ["example-vm"],
|
||||
"access_code": "********",
|
||||
"created_at": "2026-06-08 16:00:00"
|
||||
}
|
||||
},
|
||||
"GET /api/v1/sub-users": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"POST /api/v1/sub-users/{id}/rotate-password": {
|
||||
"success": true,
|
||||
"data": { "username": "user-xxxxxxxx", "password": "***", "access_code": "********" }
|
||||
},
|
||||
"GET /api/v1/sub-users/{id}/audit-logs": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/sub-users/{id}/login-logs": {
|
||||
"success": true,
|
||||
"data": []
|
||||
},
|
||||
"GET /api/v1/audit-logs": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "time": "2026-06-08 15:44:40", "action": "apikey.create", "target": "Test", "detail": "scopes=*", "user": "admin", "success": true }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/login-logs": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "time": "2026-06-08 08:24:00 UTC", "username": "admin", "ip": "198.51.100.23", "user_agent": "Mozilla/5.0 ...", "success": true }
|
||||
]
|
||||
},
|
||||
"GET /api/v1/api-keys": {
|
||||
"success": true,
|
||||
"data": [
|
||||
{ "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "last_used_ip": "198.51.100.23" }
|
||||
]
|
||||
},
|
||||
"POST /api/v1/api-keys": {
|
||||
"success": true,
|
||||
"message": "API key created. Save this key now - it won't be shown again.",
|
||||
"data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"] }
|
||||
},
|
||||
"PATCH /api/v1/api-keys/{id}": {
|
||||
"success": true,
|
||||
"data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "disabled": false }
|
||||
},
|
||||
"DELETE /api/v1/api-keys/{id}": {
|
||||
"success": true,
|
||||
"message": "API key deleted"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -25,6 +25,14 @@ POST /api/v1/containers
|
||||
POST /api/v1/batch-create
|
||||
```
|
||||
|
||||
Linux 容器和 Linux KVM 虚拟机创建时支持配置 SSH 登录方式:
|
||||
|
||||
- `auto_password`:自动生成 root SSH 密码。
|
||||
- `password`:使用自定义 `ssh_password`。
|
||||
- `key`:写入一行 `ssh_public_key`,仍会保留可用于 WebSSH 的密码。
|
||||
|
||||
网络分配可以按需组合 NAT、公网 IPv4 和 IPv6。API 字段保持为 `assign_nat`、`assign_ipv4`、`public_ipv4s`、`assign_ipv6`、`ipv6_addresses` 等可选字段,未传时沿用默认行为。
|
||||
|
||||
## 生命周期操作
|
||||
|
||||
```http
|
||||
@@ -37,6 +45,8 @@ DELETE /api/v1/containers/{id}/delete
|
||||
|
||||
开关机、重装、删除等操作会进入任务队列。调用后可通过 `GET /api/v1/tasks` 查看执行状态。
|
||||
|
||||
重装 Linux 系统时可传 `ssh_auth_mode`、`ssh_password`、`ssh_public_key`。`ssh_auth_mode=keep` 表示沿用当前 SSH 密码;不传这些字段时保持旧行为。
|
||||
|
||||
## 资源与流量
|
||||
|
||||
容器详情页支持查看资源用量,调整流量限制、资源限制和到期时间。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 网络与路由
|
||||
|
||||
CLICD 提供 NAT4 端口映射、随机可用端口、IPv6 状态检查和 IPv6 分配能力。
|
||||
CLICD 提供 NAT4 端口映射、随机可用端口、公网 IPv4 分配、IPv6 状态检查和 IPv6 分配能力。创建容器时可以只分配 NAT、只分配公网 IPv4、只分配 IPv6,或按需混合使用。
|
||||
|
||||
## NAT4
|
||||
|
||||
@@ -30,6 +30,28 @@ POST /api/v1/containers/{id}/ipv6
|
||||
|
||||
如果宿主机没有公网 IPv6 或上游没有正确路由,面板中分配出的地址也无法从公网访问。
|
||||
|
||||
## 公网 IPv4
|
||||
|
||||
公网 IPv4 分配会从主机检测到的可用公网 IPv4 中选择地址,或使用 API 指定的 `public_ipv4s`。创建容器时可使用:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `assign_nat` | 是否启用 NAT 端口映射。 |
|
||||
| `assign_ipv4` | 是否分配公网 IPv4。 |
|
||||
| `ipv4_count` | 自动分配公网 IPv4 数量。 |
|
||||
| `public_ipv4s` | 指定公网 IPv4 地址列表。 |
|
||||
| `assign_ipv6` | 是否分配 IPv6。 |
|
||||
| `ipv6_count` | 自动分配 IPv6 数量。 |
|
||||
| `ipv6_addresses` | 指定 IPv6 地址列表。 |
|
||||
|
||||
公网地址池相关接口:
|
||||
|
||||
```http
|
||||
GET /api/v1/routing
|
||||
PUT /api/v1/routing
|
||||
POST /api/v1/routing/ipv4-scan
|
||||
```
|
||||
|
||||
## 路由状态
|
||||
|
||||
```http
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CLICD - LXC Container Manager</title>
|
||||
<title>CLICD - Container Manager</title>
|
||||
<script>
|
||||
(function() {
|
||||
var theme = localStorage.getItem('clicd_theme');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "clicd-frontend",
|
||||
"private": true,
|
||||
"version": "1.1.12",
|
||||
"version": "1.1.19",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -90,7 +90,7 @@ export default function ContainerCard({ container, onRefresh }: ContainerCardPro
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
<Globe className="w-3.5 h-3.5" />
|
||||
<span>{container.network_bw_mbps} Mbps</span>
|
||||
<span>{formatNetworkLimit(container)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -140,3 +140,10 @@ export default function ContainerCard({ container, onRefresh }: ContainerCardPro
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatNetworkLimit(container: { network_bw_mbps?: number; network_down_mbps?: number; network_up_mbps?: number }) {
|
||||
const down = Math.max(0, Number(container.network_down_mbps || container.network_bw_mbps || 0))
|
||||
const up = Math.max(0, Number(container.network_up_mbps || container.network_bw_mbps || 0))
|
||||
if (down === 0 && up === 0) return '不限速'
|
||||
return `下 ${down || '不限'} / 上 ${up || '不限'} Mbps`
|
||||
}
|
||||
|
||||
@@ -21,11 +21,15 @@ const defaultForm: CreateContainerRequest = {
|
||||
ram_mb: 512,
|
||||
disk_gb: 10,
|
||||
network_bw_mbps: 0,
|
||||
network_down_mbps: 0,
|
||||
network_up_mbps: 0,
|
||||
monthly_traffic_gb: 0,
|
||||
traffic_mode: 'total',
|
||||
traffic_in_gb: 0,
|
||||
traffic_out_gb: 0,
|
||||
io_speed_mbps: 0,
|
||||
io_read_mbps: 0,
|
||||
io_write_mbps: 0,
|
||||
extra_ports: [],
|
||||
port_mapping_count: 2,
|
||||
assign_nat: true,
|
||||
@@ -321,7 +325,12 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
|
||||
type="checkbox"
|
||||
checked={!!form.assign_ipv4}
|
||||
disabled={!ipv4Available}
|
||||
onChange={(event) => setForm({ ...form, assign_ipv4: event.target.checked, public_ipv4s: event.target.checked ? form.public_ipv4s : [] })}
|
||||
onChange={(event) => setForm({
|
||||
...form,
|
||||
assign_ipv4: event.target.checked,
|
||||
public_ipv4s: event.target.checked ? form.public_ipv4s : [],
|
||||
...(event.target.checked ? { assign_nat: false, port_mapping_count: 0, extra_ports: [] } : {}),
|
||||
})}
|
||||
className="mt-1"
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
@@ -429,6 +438,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
|
||||
assign_nat: checked,
|
||||
port_mapping_count: checked ? Math.max(2, form.port_mapping_count || 2) : 0,
|
||||
extra_ports: [],
|
||||
...(checked ? { assign_ipv4: false, public_ipv4s: [], ipv4_count: 0 } : {}),
|
||||
})
|
||||
}}
|
||||
className="mt-1"
|
||||
@@ -492,7 +502,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<Field label="磁盘 (GB)">
|
||||
<NumberInput
|
||||
value={form.disk_gb}
|
||||
@@ -503,52 +513,62 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
|
||||
/>
|
||||
{resourceErrors.disk_gb && <p className="mt-1 text-xs text-red-500">{resourceErrors.disk_gb}</p>}
|
||||
</Field>
|
||||
<Field label="带宽 (Mbps)">
|
||||
<NumberInput value={form.network_bw_mbps} min={0} onChange={(value) => setForm({ ...form, network_bw_mbps: value })} />
|
||||
</Field>
|
||||
<Field label="IO 速度 (MB/s)">
|
||||
<NumberInput value={form.io_speed_mbps} min={0} onChange={(value) => setForm({ ...form, io_speed_mbps: value })} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{/* Traffic control */}
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<label className="text-sm font-medium text-gray-700">月流量</label>
|
||||
<select
|
||||
value={form.traffic_mode}
|
||||
onChange={(e) => setForm({ ...form, traffic_mode: e.target.value })}
|
||||
className="h-8 px-2 border border-gray-300 rounded text-xs text-gray-600 bg-white"
|
||||
>
|
||||
<option value="total">双向统计</option>
|
||||
<option value="in_out">入/出分离</option>
|
||||
</select>
|
||||
<div className="grid grid-cols-2 gap-3 md:col-span-2">
|
||||
<Field label="下行带宽 (Mbps)">
|
||||
<NumberInput value={form.network_down_mbps} min={0} onChange={(value) => setForm({ ...form, network_down_mbps: value, network_bw_mbps: symmetricLimit(value, form.network_up_mbps) })} />
|
||||
</Field>
|
||||
<Field label="上行带宽 (Mbps)">
|
||||
<NumberInput value={form.network_up_mbps} min={0} onChange={(value) => setForm({ ...form, network_up_mbps: value, network_bw_mbps: symmetricLimit(form.network_down_mbps, value) })} />
|
||||
</Field>
|
||||
<Field label="读取 IO (MB/s)">
|
||||
<NumberInput value={form.io_read_mbps} min={0} onChange={(value) => setForm({ ...form, io_read_mbps: value, io_speed_mbps: symmetricLimit(value, form.io_write_mbps) })} />
|
||||
</Field>
|
||||
<Field label="写入 IO (MB/s)">
|
||||
<NumberInput value={form.io_write_mbps} min={0} onChange={(value) => setForm({ ...form, io_write_mbps: value, io_speed_mbps: symmetricLimit(form.io_read_mbps, value) })} />
|
||||
</Field>
|
||||
</div>
|
||||
{form.traffic_mode === 'total' ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<NumberInput value={form.monthly_traffic_gb} min={0} onChange={(value) => setForm({ ...form, monthly_traffic_gb: value })} />
|
||||
<span className="text-xs text-gray-400">GB (0=不限制)</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="入站 (GB)">
|
||||
<NumberInput value={form.traffic_in_gb} min={0} onChange={(value) => setForm({ ...form, traffic_in_gb: value || 0 })} />
|
||||
</Field>
|
||||
<Field label="出站 (GB)">
|
||||
<NumberInput value={form.traffic_out_gb} min={0} onChange={(value) => setForm({ ...form, traffic_out_gb: value || 0 })} />
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Field label="子用户快照上限">
|
||||
<NumberInput
|
||||
value={form.snapshot_limit}
|
||||
min={1}
|
||||
max={999}
|
||||
onChange={(value) => setForm({ ...form, snapshot_limit: Math.max(1, Math.round(value || 1)) })}
|
||||
/>
|
||||
</Field>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
{/* Traffic control */}
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<label className="text-sm font-medium text-gray-700">月流量</label>
|
||||
<select
|
||||
value={form.traffic_mode}
|
||||
onChange={(e) => setForm({ ...form, traffic_mode: e.target.value })}
|
||||
className="h-8 px-2 border border-gray-300 rounded text-xs text-gray-600 bg-white"
|
||||
>
|
||||
<option value="total">双向统计</option>
|
||||
<option value="in_out">入/出分离</option>
|
||||
</select>
|
||||
</div>
|
||||
{form.traffic_mode === 'total' ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<NumberInput value={form.monthly_traffic_gb} min={0} onChange={(value) => setForm({ ...form, monthly_traffic_gb: value })} />
|
||||
<span className="text-xs text-gray-400">GB (0=不限制)</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="入站 (GB)">
|
||||
<NumberInput value={form.traffic_in_gb} min={0} onChange={(value) => setForm({ ...form, traffic_in_gb: value || 0 })} />
|
||||
</Field>
|
||||
<Field label="出站 (GB)">
|
||||
<NumberInput value={form.traffic_out_gb} min={0} onChange={(value) => setForm({ ...form, traffic_out_gb: value || 0 })} />
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Field label="子用户快照上限">
|
||||
<NumberInput
|
||||
value={form.snapshot_limit}
|
||||
min={1}
|
||||
max={999}
|
||||
onChange={(value) => setForm({ ...form, snapshot_limit: Math.max(1, Math.round(value || 1)) })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field label="到期时间">
|
||||
<div className="relative">
|
||||
@@ -678,9 +698,10 @@ function validateResourceInputs(form: CreateContainerRequest, maxVCPU: number, m
|
||||
|
||||
function normalizeCreateForm(form: CreateContainerRequest): CreateContainerRequest {
|
||||
const normalized = applyTemplateDefaults(form)
|
||||
const wantsNAT = normalized.assign_nat !== false
|
||||
const wantsIPv4 = !!normalized.assign_ipv4
|
||||
const wantsIPv6 = !!normalized.assign_ipv6
|
||||
// IPv4 and NAT are mutually exclusive
|
||||
const wantsNAT = wantsIPv4 ? false : normalized.assign_nat !== false
|
||||
const linuxTemplate = !isWindowsTemplate(normalized.template_id)
|
||||
const sshAuthMode = linuxTemplate ? (normalized.ssh_auth_mode || 'auto_password') : 'auto_password'
|
||||
return {
|
||||
@@ -770,5 +791,14 @@ function formatNATPortCount(count: number, language: Language) {
|
||||
: `将分配 ${count} 个 NAT 端口`
|
||||
}
|
||||
|
||||
function symmetricLimit(a: number, b: number) {
|
||||
const left = Math.max(0, Number(a) || 0)
|
||||
const right = Math.max(0, Number(b) || 0)
|
||||
if (left === right) return left
|
||||
if (left === 0) return right
|
||||
if (right === 0) return left
|
||||
return Math.min(left, right)
|
||||
}
|
||||
|
||||
const inputClass =
|
||||
'w-full px-3 py-2 border border-gray-300 rounded-md text-sm text-black bg-white focus:outline-none focus:ring-2 focus:ring-black focus:border-black'
|
||||
|
||||
@@ -50,7 +50,7 @@ function LanguageIcon({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||
<path
|
||||
d="M213.333333 640v85.333333a85.333333 85.333333 0 0 0 78.933334 85.12L298.666667 810.666667h128v85.333333H298.666667a170.666667 170.666667 0 0 1-170.666667-170.666667v-85.333333h85.333333z m554.666667-213.333333l187.733333 469.333333h-91.946666l-51.242667-128h-174.506667l-51.157333 128h-91.904L682.666667 426.666667h85.333333z m-42.666667 123.093333L672.128 682.666667h106.325333L725.333333 549.76zM341.333333 85.333333v85.333334h170.666667v298.666666H341.333333v128H256v-128H85.333333V170.666667h170.666667V85.333333h85.333333z m384 42.666667a170.666667 170.666667 0 0 1 170.666667 170.666667v85.333333h-85.333333V298.666667a85.333333 85.333333 0 0 0-85.333334-85.333334h-128V128h128zM256 256H170.666667v128h85.333333V256z m170.666667 0H341.333333v128h85.333334V256z"
|
||||
d="M128 170.6496A42.6496 42.6496 0 0 0 128 256V170.6496zM640 256a42.6496 42.6496 0 1 0 0-85.3504V256zM426.6496 128a42.6496 42.6496 0 0 0-85.2992 0h85.2992zM341.3504 213.3504a42.6496 42.6496 0 0 0 85.2992 0H341.3504z m56.6784 434.944a42.6496 42.6496 0 0 0 61.44-59.2896l-61.44 59.2896zM312.8832 367.4112a42.6496 42.6496 0 0 0-78.592 33.1776l78.592-33.1776z m220.4672 357.888a42.6496 42.6496 0 1 0 0 85.3504v-85.2992z m298.6496 85.3504a42.6496 42.6496 0 1 0 0-85.2992v85.2992z m-400.8448 66.2528a42.6496 42.6496 0 1 0 76.3392 38.1952l-76.288-38.1952z m251.4944-407.552l38.1952-19.0976a42.6496 42.6496 0 0 0-76.3392 0l38.144 19.0976z m175.2064 445.7472a42.6496 42.6496 0 1 0 76.288-38.1952l-76.288 38.1952zM586.1376 220.3648a42.6496 42.6496 0 1 0-84.1728-14.08l84.1728 14.08zM109.0048 735.2832a42.6496 42.6496 0 0 0 37.9904 76.4416l-37.9904-76.4416zM128 256h512V170.6496h-512V256z m213.3504-128v85.3504h85.2992V128H341.3504z m118.0672 461.0048a726.3232 726.3232 0 0 1-146.5344-221.5936l-78.592 33.1776a811.6224 811.6224 0 0 0 163.7376 247.7056l61.44-59.2896z m73.9328 221.696h298.6496v-85.3504h-298.6496v85.2992z m-25.856 104.3968l213.3504-426.7008-76.3392-38.144-213.3504 426.6496 76.3392 38.1952z m137.0112-426.7008l213.3504 426.7008 76.288-38.1952-213.2992-426.6496-76.3392 38.144zM501.9648 206.336C463.0016 438.6304 313.3952 633.7536 109.056 735.232l37.9904 76.4416c228.2496-113.4592 395.52-331.3152 439.1424-591.36L501.9648 206.336z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
@@ -62,7 +62,7 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
|
||||
const location = useLocation()
|
||||
const { logout, isSubUser } = useAuth()
|
||||
const { theme, toggleTheme } = useTheme()
|
||||
const { language, toggleLanguage, t } = useLanguage()
|
||||
const { toggleLanguage, t } = useLanguage()
|
||||
const [version, setVersion] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
@@ -282,10 +282,11 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
|
||||
|
||||
<button
|
||||
onClick={() => { void toggleLanguage() }}
|
||||
className={`${collapsed ? 'w-full' : 'w-10'} flex items-center justify-center rounded-md px-2 py-2.5 text-sm text-gray-600 hover:bg-gray-100 transition-colors dark:text-gray-400 dark:hover:bg-gray-800`}
|
||||
title={language === 'en' ? '切换中文' : 'Switch to English'}
|
||||
className={`${collapsed ? 'w-full justify-center' : 'flex-1 justify-center'} flex items-center gap-2 rounded-md px-3 py-2.5 text-sm text-gray-600 hover:bg-gray-100 transition-colors dark:text-gray-400 dark:hover:bg-gray-800`}
|
||||
title="Language"
|
||||
>
|
||||
<LanguageIcon className="h-4 w-4" />
|
||||
<LanguageIcon className="h-4 w-4 shrink-0" />
|
||||
{!collapsed && <span>Language</span>}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import api, { APIResponse, Container } from '../services/api'
|
||||
import { useLanguage } from '../contexts/LanguageContext'
|
||||
import { copyToClipboard } from '../utils/clipboard'
|
||||
|
||||
interface ApiKeyItem {
|
||||
@@ -63,8 +64,10 @@ const scopeGroups = [
|
||||
['dashboard:read', '控制面板'],
|
||||
['host:read', '主机资源'],
|
||||
['routing:read', '路由信息'],
|
||||
['routing:write', '路由配置'],
|
||||
['ipv6:read', 'IPv6 状态'],
|
||||
['task:read', '任务列表'],
|
||||
['task:delete', '删除任务'],
|
||||
['image:read', '镜像列表'],
|
||||
],
|
||||
},
|
||||
@@ -137,7 +140,9 @@ const endpointGroups: Array<{ title: string; endpoints: EndpointTuple[] }> = [
|
||||
endpoints: [
|
||||
['GET', '/api/v1/dashboard', '控制面板统计'],
|
||||
['GET', '/api/v1/host-info', '主机资源'],
|
||||
['GET', '/api/v1/routing', 'NAT/IPv6 路由'],
|
||||
['GET', '/api/v1/routing', 'NAT/IPv4/IPv6 路由'],
|
||||
['PUT', '/api/v1/routing', '更新公网 IPv4/IPv6 池'],
|
||||
['POST', '/api/v1/routing/ipv4-scan', '扫描公网 IPv4 段'],
|
||||
['GET', '/api/v1/ipv6/status', 'IPv6 状态'],
|
||||
['GET', '/api/v1/tasks', '任务队列'],
|
||||
['DELETE', '/api/v1/tasks/{task_id}', '删除任务'],
|
||||
@@ -147,7 +152,7 @@ const endpointGroups: Array<{ title: string; endpoints: EndpointTuple[] }> = [
|
||||
title: '容器',
|
||||
endpoints: [
|
||||
['GET', '/api/v1/containers', '容器列表'],
|
||||
['POST', '/api/v1/containers/list', '容器列表(兼容旧接口)'],
|
||||
['POST', '/api/v1/containers/list', '容器列表(兼容 POST 写法)'],
|
||||
['POST', '/api/v1/containers', '创建容器'],
|
||||
['GET', '/api/v1/containers/{id|uuid|name}', '容器详情'],
|
||||
['POST', '/api/v1/containers/{id}/start', '开机'],
|
||||
@@ -172,6 +177,8 @@ const endpointGroups: Array<{ title: string; endpoints: EndpointTuple[] }> = [
|
||||
['POST', '/api/v1/containers/{id}/port-mappings', '添加端口映射'],
|
||||
['PUT', '/api/v1/containers/{id}/port-mappings/{index}', '更新端口映射'],
|
||||
['DELETE', '/api/v1/containers/{id}/port-mappings/{index}', '删除端口映射'],
|
||||
['GET', '/api/v1/containers/{id}/firewall', '获取防火墙设置'],
|
||||
['PUT', '/api/v1/containers/{id}/firewall', '更新防火墙设置'],
|
||||
['GET', '/api/v1/snapshots', '快照总览'],
|
||||
['GET', '/api/v1/containers/{id}/snapshots', '容器快照'],
|
||||
['POST', '/api/v1/containers/{id}/snapshots', '创建快照'],
|
||||
@@ -232,6 +239,7 @@ const emptyForm = (): ApiKeyForm => ({
|
||||
})
|
||||
|
||||
export default function ApiIntegration() {
|
||||
const { t } = useLanguage()
|
||||
const [keys, setKeys] = useState<ApiKeyItem[]>([])
|
||||
const [containers, setContainers] = useState<Container[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -323,7 +331,7 @@ export default function ApiIntegration() {
|
||||
}
|
||||
|
||||
const deleteKey = async (id: string) => {
|
||||
if (!window.confirm('确定删除这个 API Key 吗?')) return
|
||||
if (!window.confirm(t('确定删除这个 API Key 吗?'))) return
|
||||
try {
|
||||
await api.delete(`/api-keys/${id}`)
|
||||
setKeys(prev => prev.filter(k => k.id !== id))
|
||||
@@ -501,7 +509,6 @@ export default function ApiIntegration() {
|
||||
<div className="rounded-lg bg-gray-900 p-4 font-mono text-xs text-gray-100">
|
||||
<div>curl -X GET {BASE_URL}/api/v1/containers -H "X-API-Key: clicd_sk_xxxx"</div>
|
||||
<div className="mt-2 text-gray-400">curl -X GET {BASE_URL}/api/v1/dashboard -H "Authorization: Bearer clicd_sk_xxxx"</div>
|
||||
<div className="mt-2 text-amber-300">旧版 /api/containers/list 已兼容,但新接入请使用 GET /api/v1/containers</div>
|
||||
</div>
|
||||
|
||||
{endpointGroups.map(group => (
|
||||
@@ -725,15 +732,25 @@ const requestBodySamples: Record<string, Record<string, unknown>> = {
|
||||
ram_mb: 512,
|
||||
disk_gb: 10,
|
||||
network_bw_mbps: 0,
|
||||
network_down_mbps: 100,
|
||||
network_up_mbps: 20,
|
||||
monthly_traffic_gb: 0,
|
||||
traffic_mode: 'total',
|
||||
traffic_in_gb: 0,
|
||||
traffic_out_gb: 0,
|
||||
io_speed_mbps: 0,
|
||||
io_read_mbps: 80,
|
||||
io_write_mbps: 30,
|
||||
extra_ports: [8080],
|
||||
port_mapping_count: 2,
|
||||
assign_nat: true,
|
||||
snapshot_limit: 1,
|
||||
assign_ipv4: false,
|
||||
ipv4_count: 1,
|
||||
public_ipv4s: [],
|
||||
assign_ipv6: true,
|
||||
ipv6_count: 1,
|
||||
ipv6_addresses: [],
|
||||
ssh_auth_mode: 'auto_password',
|
||||
ssh_password: '',
|
||||
ssh_public_key: '',
|
||||
@@ -754,8 +771,12 @@ const requestBodySamples: Record<string, Record<string, unknown>> = {
|
||||
'PUT /api/v1/containers/{id}/resource-limit': {
|
||||
vcpu: 1,
|
||||
ram_mb: 512,
|
||||
io_speed_mbps: 0,
|
||||
network_bw_mbps: 0,
|
||||
network_down_mbps: 100,
|
||||
network_up_mbps: 20,
|
||||
io_read_mbps: 80,
|
||||
io_write_mbps: 30,
|
||||
network_bw_mbps: 20,
|
||||
io_speed_mbps: 30,
|
||||
},
|
||||
'PUT /api/v1/containers/{id}/expiry': { expires_at: '2026-12-31 23:59:59' },
|
||||
'POST /api/v1/containers/{id}/reset-password': { password: 'NewPass123456' },
|
||||
@@ -781,7 +802,42 @@ const requestBodySamples: Record<string, Record<string, unknown>> = {
|
||||
'POST /api/v1/images/cancel': { template_id: 'debian-bookworm' },
|
||||
'DELETE /api/v1/images/delete': { template_id: 'debian-bookworm' },
|
||||
'PUT /api/v1/images/toggle': { template_id: 'debian-bookworm', enabled: true },
|
||||
'PUT /api/v1/routing': {
|
||||
items: [
|
||||
{
|
||||
address: '203.0.113.10',
|
||||
interface: 'eth0',
|
||||
prefix_len: 32,
|
||||
gateway: '203.0.113.1',
|
||||
},
|
||||
],
|
||||
ipv6_prefixes: [
|
||||
{
|
||||
address: '2001:db8:100::2',
|
||||
prefix: '2001:db8:100::/64',
|
||||
prefix_len: 64,
|
||||
interface: 'eth0',
|
||||
gateway: '2001:db8:100::1',
|
||||
},
|
||||
],
|
||||
},
|
||||
'POST /api/v1/routing/ipv4-scan': {
|
||||
cidr: '203.0.113.0/29',
|
||||
interface: 'eth0',
|
||||
gateway: '203.0.113.1',
|
||||
verify: true,
|
||||
limit: 64,
|
||||
},
|
||||
'POST /api/v1/security/check': { container_name: 'example-vm' },
|
||||
'PUT /api/v1/containers/{id}/firewall': {
|
||||
enabled: true,
|
||||
default_action: 'DROP',
|
||||
rules: [
|
||||
{ id: '', network: 'ipv4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv4/NAT4', enabled: true },
|
||||
{ id: '', network: 'ipv6', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv6', enabled: true },
|
||||
{ id: '', network: 'all', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow outbound TCP', enabled: true },
|
||||
],
|
||||
},
|
||||
'PUT /api/v1/security/settings': { auto_shutdown: false },
|
||||
'POST /api/v1/swap': { action: 'resize', size_mb: 16384 },
|
||||
'POST /api/v1/batch-create': {
|
||||
@@ -793,15 +849,28 @@ const requestBodySamples: Record<string, Record<string, unknown>> = {
|
||||
vcpu: 1,
|
||||
ram_mb: 512,
|
||||
disk_gb: 10,
|
||||
assign_nat: true,
|
||||
port_mapping_count: 2,
|
||||
snapshot_limit: 1,
|
||||
assign_ipv4: false,
|
||||
ipv4_count: 1,
|
||||
public_ipv4s: [],
|
||||
assign_ipv6: true,
|
||||
ipv6_count: 1,
|
||||
ipv6_addresses: [],
|
||||
ssh_auth_mode: 'key',
|
||||
ssh_public_key: 'ssh-ed25519 AAAA... user@example',
|
||||
},
|
||||
],
|
||||
},
|
||||
'POST /api/v1/batch-action': { action: 'restart', containers: [5], template_id: '' },
|
||||
'POST /api/v1/batch-action': {
|
||||
action: 'reinstall',
|
||||
containers: [5],
|
||||
template_id: 'debian-bookworm',
|
||||
ssh_auth_mode: 'keep',
|
||||
ssh_password: '',
|
||||
ssh_public_key: '',
|
||||
},
|
||||
'POST /api/v1/ssh-ticket': { container_name: 'example-vm' },
|
||||
'POST /api/v1/vnc-ticket': { container_name: 'kvm-demo' },
|
||||
'POST /api/v1/sub-user/create': { container_name: 'example-vm' },
|
||||
@@ -845,13 +914,30 @@ const responseSamples: Record<string, unknown> = {
|
||||
success: true,
|
||||
data: {
|
||||
nat4: { used: 62, remaining: '45474', total: '45536' },
|
||||
ipv4: { used: 1, remaining: '3', total: '4' },
|
||||
ipv6: { used: 31, remaining: 'large', total: 'large' },
|
||||
public_ipv4_addresses: [{ address: '203.0.113.10', interface: 'eth0', prefix_len: 32, gateway: '203.0.113.1' }],
|
||||
ipv4_assignments: [{ container_id: 5, container_name: 'example-vm', address: '203.0.113.10', interface: 'eth0', prefix_len: 32, gateway: '203.0.113.1' }],
|
||||
nat4_mappings: [
|
||||
{ container_id: 5, container_name: 'example-vm', status: 'running', ip: '10.0.0.10', host_port: 22004, container_port: 22, protocol: 'tcp' },
|
||||
],
|
||||
ipv6_assignments: [{ container_id: 5, container_name: 'example-vm', address: '2001:db8:100::1005', prefix_len: 64, interface: 'eth0' }],
|
||||
},
|
||||
},
|
||||
'PUT /api/v1/routing': {
|
||||
success: true,
|
||||
data: {
|
||||
ipv4: { used: 1, remaining: '3', total: '4' },
|
||||
public_ipv4_addresses: [{ address: '203.0.113.10', interface: 'eth0', prefix_len: 32, gateway: '203.0.113.1' }],
|
||||
ipv6_prefixes: [{ interface: 'eth0', address: '2001:db8:100::2', prefix: '2001:db8:100::/64', prefix_len: 64, gateway: '2001:db8:100::1' }],
|
||||
},
|
||||
},
|
||||
'POST /api/v1/routing/ipv4-scan': {
|
||||
success: true,
|
||||
data: [
|
||||
{ address: '203.0.113.10', interface: 'eth0', prefix_len: 32, gateway: '203.0.113.1', status: 'available', usable: true, reason: '' },
|
||||
],
|
||||
},
|
||||
'GET /api/v1/ipv6/status': {
|
||||
success: true,
|
||||
data: {
|
||||
@@ -960,6 +1046,31 @@ const responseSamples: Record<string, unknown> = {
|
||||
data: [{ container_port: 8081, host_port: 61320, protocol: 'tcp', description: 'HTTP' }],
|
||||
},
|
||||
'DELETE /api/v1/containers/{id}/port-mappings/{index}': { success: true, data: [] },
|
||||
'GET /api/v1/containers/{id}/firewall': {
|
||||
success: true,
|
||||
data: {
|
||||
enabled: true,
|
||||
default_action: 'DROP',
|
||||
rules: [
|
||||
{ id: 'a1b2c3d4', network: 'ipv4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv4/NAT4', enabled: true },
|
||||
{ id: 'e5f6g7h8', network: 'ipv6', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv6', enabled: true },
|
||||
{ id: 'i9j0k1l2', network: 'all', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow outbound TCP', enabled: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
'PUT /api/v1/containers/{id}/firewall': {
|
||||
success: true,
|
||||
message: 'Firewall updated',
|
||||
data: {
|
||||
enabled: true,
|
||||
default_action: 'DROP',
|
||||
rules: [
|
||||
{ id: 'a1b2c3d4', network: 'ipv4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv4/NAT4', enabled: true },
|
||||
{ id: 'e5f6g7h8', network: 'ipv6', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv6', enabled: true },
|
||||
{ id: 'i9j0k1l2', network: 'all', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow outbound TCP', enabled: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
'GET /api/v1/snapshots': { success: true, data: null },
|
||||
'GET /api/v1/containers/{id}/snapshots': {
|
||||
success: true,
|
||||
@@ -997,11 +1108,11 @@ const responseSamples: Record<string, unknown> = {
|
||||
'GET /api/v1/security/settings': { success: true, data: { auto_shutdown: false } },
|
||||
'PUT /api/v1/security/settings': { success: true, data: { auto_shutdown: false } },
|
||||
'GET /api/v1/swap': { success: true, data: { total_mb: 16383, used_mb: 0, free_mb: 16383, enabled: true, swap_file: '/swapfile' } },
|
||||
'POST /api/v1/swap': { success: true, message: 'SWAP 已调整为 16384 MB', data: { total_mb: 16383, used_mb: 0, free_mb: 16383, enabled: true, swap_file: '/swapfile' } },
|
||||
'POST /api/v1/swap': { success: true, message: 'SWAP adjusted to 16384 MB', data: { total_mb: 16383, used_mb: 0, free_mb: 16383, enabled: true, swap_file: '/swapfile' } },
|
||||
'POST /api/v1/batch-create': { success: true, data: ['task-12'] },
|
||||
'POST /api/v1/batch-action': { success: true, data: ['task-13'] },
|
||||
'POST /api/v1/ssh-ticket': { success: true, data: { ticket: '***60秒有效票据***' } },
|
||||
'POST /api/v1/vnc-ticket': { success: true, data: { ticket: '***60秒有效票据***' } },
|
||||
'POST /api/v1/ssh-ticket': { success: true, data: { ticket: '***60-second valid ticket***' } },
|
||||
'POST /api/v1/vnc-ticket': { success: true, data: { ticket: '***60-second valid ticket***' } },
|
||||
'POST /api/v1/sub-user/create': {
|
||||
success: true,
|
||||
message: 'Sub-user created',
|
||||
@@ -1064,10 +1175,36 @@ function examplePathFor(path: string) {
|
||||
}
|
||||
|
||||
function endpointNoteFor(key: string) {
|
||||
if (key.includes('/vnc-ticket')) return 'WebVNC 仅适用于 KVM 虚拟机;LXC 容器会返回 VNC console is only available for KVM VMs。'
|
||||
if (key.includes('/containers/{id}/delete') || key.includes('/batch-action')) return '该接口会进入任务队列,请随后调用 GET /api/v1/tasks 查看执行状态。'
|
||||
if (key.includes('/reset-password') || key.includes('/api-keys') || key.includes('/sub-user')) return '样例中的密钥、密码和票据已脱敏;创建类接口的完整密钥只在创建响应中出现一次。'
|
||||
return ''
|
||||
const notes: string[] = []
|
||||
if (key === 'POST /api/v1/containers') {
|
||||
notes.push('Linux container creation supports ssh_auth_mode=auto_password|password|key. Public IPv4, IPv6, and NAT can be configured with assign_nat, assign_ipv4, and assign_ipv6.')
|
||||
notes.push('Supports independent upload/download bandwidth limits and read/write I/O limits. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases. New integrations should use network_down_mbps, network_up_mbps, io_read_mbps, and io_write_mbps.')
|
||||
}
|
||||
if (key === 'POST /api/v1/containers/{id}/reinstall') {
|
||||
notes.push('Reinstall supports ssh_auth_mode=keep|auto_password|password|key. keep is only for reinstall requests; if SSH fields are omitted, the existing behavior is kept.')
|
||||
}
|
||||
if (key === 'POST /api/v1/batch-create') {
|
||||
notes.push('Each containers[] item in batch creation supports the same network and SSH authentication fields as POST /api/v1/containers.')
|
||||
}
|
||||
if (key === 'PUT /api/v1/containers/{id}/resource-limit') {
|
||||
notes.push('Supports independent download/upload bandwidth limits and read/write I/O limits. Omitted fields keep their current values, and explicitly passing 0 makes that direction unlimited. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases.')
|
||||
}
|
||||
if (key === 'PUT /api/v1/containers/{id}/firewall') {
|
||||
notes.push('Backward compatible: default_action is optional; if omitted, the existing policy is kept. rule.network is optional; if omitted, it is treated as ipv4. default_action: DROP=deny unmatched traffic, ACCEPT=allow unmatched traffic. network: ipv4=IPv4 NAT/public IPv4, ipv6=IPv6, all=apply to both IPv4 and IPv6. For NAT inbound rules, port is the container internal port, not the host public port.')
|
||||
}
|
||||
if (key === 'POST /api/v1/batch-action') {
|
||||
notes.push('When action=reinstall, you can include template_id, ssh_auth_mode, ssh_password, and ssh_public_key. Other actions ignore these reinstall fields.')
|
||||
}
|
||||
if (key === 'PUT /api/v1/routing') {
|
||||
notes.push('Updating public address pools requires routing:write. Addresses already assigned to containers cannot be removed from the pool.')
|
||||
}
|
||||
if (key === 'POST /api/v1/routing/ipv4-scan') {
|
||||
notes.push('Scanning public IPv4 prefixes requires routing:write. When verify=true, the API also attempts to check address availability.')
|
||||
}
|
||||
if (key.includes('/vnc-ticket')) notes.push('WebVNC only applies to KVM VMs; LXC containers return "VNC console is only available for KVM VMs".')
|
||||
if (key.includes('/containers/{id}/delete') || key.includes('/batch-action')) notes.push('This API enters the task queue. Call GET /api/v1/tasks afterward to check execution status.')
|
||||
if (key.includes('/reset-password') || key.includes('/api-keys') || key.includes('/sub-user')) notes.push('Keys, passwords, and tickets in examples are masked. Full secrets from create APIs appear only once in the creation response.')
|
||||
return notes.join(' ')
|
||||
}
|
||||
|
||||
function defaultResponseFor(method: HttpMethod) {
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Save,
|
||||
|
||||
Settings,
|
||||
Square,
|
||||
TerminalSquare,
|
||||
@@ -47,7 +46,9 @@ import {
|
||||
HostInfo,
|
||||
TrafficInfo,
|
||||
getEnabledImages,
|
||||
getFirewall,
|
||||
PortMapping,
|
||||
FirewallRule,
|
||||
reinstallContainer,
|
||||
resetSSHPassword,
|
||||
restartContainer,
|
||||
@@ -57,6 +58,7 @@ import {
|
||||
SnapshotSchedule,
|
||||
Template,
|
||||
updateContainerExpiry,
|
||||
updateFirewall,
|
||||
updateSnapshotQuota,
|
||||
updateSnapshotSchedule,
|
||||
restoreContainerSnapshot,
|
||||
@@ -147,7 +149,7 @@ export default function ContainerDetail() {
|
||||
const [trafficEdit, setTrafficEdit] = useState({ mode: 'total', monthly: 0, inGB: 0, outGB: 0 })
|
||||
const [savingTraffic, setSavingTraffic] = useState(false)
|
||||
const [showResourceEdit, setShowResourceEdit] = useState(false)
|
||||
const [resourceEdit, setResourceEdit] = useState({ vcpu: 1, ramMb: 512, ioMbps: 500, bwMbps: 100 })
|
||||
const [resourceEdit, setResourceEdit] = useState({ vcpu: 1, ramMb: 512, networkDownMbps: 0, networkUpMbps: 0, ioReadMbps: 0, ioWriteMbps: 0 })
|
||||
const [savingResource, setSavingResource] = useState(false)
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [showResetPassword, setShowResetPassword] = useState(false)
|
||||
@@ -163,6 +165,14 @@ export default function ContainerDetail() {
|
||||
const [snapshotBusy, setSnapshotBusy] = useState('')
|
||||
const [showSnapshotSchedule, setShowSnapshotSchedule] = useState(false)
|
||||
const [snapshotScheduleDraft, setSnapshotScheduleDraft] = useState({ intervalHours: 24, time: '03:00' })
|
||||
const [showFirewall, setShowFirewall] = useState(false)
|
||||
const [firewallEnabled, setFirewallEnabled] = useState(false)
|
||||
const [firewallDefaultAction, setFirewallDefaultAction] = useState<'ACCEPT' | 'DROP'>('DROP')
|
||||
const [firewallRules, setFirewallRules] = useState<FirewallRule[]>([])
|
||||
const [firewallSaving, setFirewallSaving] = useState(false)
|
||||
const [firewallMessage, setFirewallMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)
|
||||
const [editingFirewallRule, setEditingFirewallRule] = useState<FirewallRule | null>(null)
|
||||
const [showFirewallEditor, setShowFirewallEditor] = useState(false)
|
||||
|
||||
const fetchContainer = useCallback(async () => {
|
||||
if (!containerIdentifier) return
|
||||
@@ -385,8 +395,10 @@ export default function ContainerDetail() {
|
||||
setResourceEdit({
|
||||
vcpu: container.vcpu,
|
||||
ramMb: container.ram_mb,
|
||||
ioMbps: container.io_speed_mbps || 0,
|
||||
bwMbps: container.network_bw_mbps || 0,
|
||||
networkDownMbps: resourceLimitValue(container.network_down_mbps, container.network_bw_mbps),
|
||||
networkUpMbps: resourceLimitValue(container.network_up_mbps, container.network_bw_mbps),
|
||||
ioReadMbps: resourceLimitValue(container.io_read_mbps, container.io_speed_mbps),
|
||||
ioWriteMbps: resourceLimitValue(container.io_write_mbps, container.io_speed_mbps),
|
||||
})
|
||||
setShowResourceEdit(true)
|
||||
}
|
||||
@@ -398,8 +410,12 @@ export default function ContainerDetail() {
|
||||
await updateResourceLimit(container.id, {
|
||||
vcpu: resourceEdit.vcpu,
|
||||
ram_mb: resourceEdit.ramMb,
|
||||
io_speed_mbps: resourceEdit.ioMbps,
|
||||
network_bw_mbps: resourceEdit.bwMbps,
|
||||
network_down_mbps: resourceEdit.networkDownMbps,
|
||||
network_up_mbps: resourceEdit.networkUpMbps,
|
||||
network_bw_mbps: symmetricLimit(resourceEdit.networkDownMbps, resourceEdit.networkUpMbps),
|
||||
io_read_mbps: resourceEdit.ioReadMbps,
|
||||
io_write_mbps: resourceEdit.ioWriteMbps,
|
||||
io_speed_mbps: symmetricLimit(resourceEdit.ioReadMbps, resourceEdit.ioWriteMbps),
|
||||
})
|
||||
setShowResourceEdit(false)
|
||||
fetchContainer()
|
||||
@@ -410,6 +426,91 @@ export default function ContainerDetail() {
|
||||
}
|
||||
}
|
||||
|
||||
const syncFirewallState = (enabled: boolean, defaultAction: 'ACCEPT' | 'DROP', rules: FirewallRule[]) => {
|
||||
const nextRules = rules.map(r => ({ ...r }))
|
||||
setFirewallEnabled(enabled)
|
||||
setFirewallDefaultAction(defaultAction)
|
||||
setFirewallRules(nextRules)
|
||||
setContainer(prev => prev ? {
|
||||
...prev,
|
||||
firewall_enabled: enabled,
|
||||
firewall_default_action: defaultAction,
|
||||
firewall_rules: nextRules.map(r => ({ ...r })),
|
||||
} : prev)
|
||||
}
|
||||
|
||||
const openFirewall = async () => {
|
||||
if (!container) return
|
||||
syncFirewallState(container.firewall_enabled || false, container.firewall_default_action || 'DROP', container.firewall_rules || [])
|
||||
setFirewallMessage(null)
|
||||
setShowFirewall(true)
|
||||
try {
|
||||
const res = await getFirewall(container.id)
|
||||
const data = res.data.data
|
||||
if (data) syncFirewallState(data.enabled, data.default_action || 'DROP', data.rules || [])
|
||||
} catch (err) {
|
||||
console.error('Failed to load firewall:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const saveFirewall = async () => {
|
||||
if (!container) return
|
||||
setFirewallSaving(true)
|
||||
try {
|
||||
const res = await updateFirewall(container.id, { enabled: firewallEnabled, default_action: firewallDefaultAction, rules: firewallRules })
|
||||
const data = res.data.data
|
||||
if (data) {
|
||||
syncFirewallState(data.enabled, data.default_action || 'DROP', data.rules || [])
|
||||
}
|
||||
setFirewallMessage({ type: 'success', text: '防火墙设置已保存并应用' })
|
||||
fetchContainer()
|
||||
} catch (err: any) {
|
||||
const message = err?.response?.data?.message || '保存防火墙设置失败'
|
||||
setFirewallMessage({ type: 'error', text: message })
|
||||
dialog.alert('错误', message)
|
||||
} finally {
|
||||
setFirewallSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const addFirewallRule = () => {
|
||||
const hasIPv4Firewall = (container?.public_ipv4s?.length || 0) > 0 || Math.max(container?.port_mapping_limit || 0, container?.port_mappings?.length || 0) > 0
|
||||
const hasIPv6Firewall = !!container?.ipv6 || (container?.ipv6_addresses?.length || 0) > 0
|
||||
setEditingFirewallRule({
|
||||
id: '',
|
||||
network: hasIPv4Firewall ? 'ipv4' : hasIPv6Firewall ? 'ipv6' : 'ipv4',
|
||||
direction: 'in',
|
||||
protocol: 'tcp',
|
||||
port: '',
|
||||
source_ip: '',
|
||||
action: 'DROP',
|
||||
description: '',
|
||||
enabled: true,
|
||||
})
|
||||
setShowFirewallEditor(true)
|
||||
}
|
||||
|
||||
const saveFirewallRule = (rule: FirewallRule) => {
|
||||
if (rule.id) {
|
||||
// Update existing
|
||||
setFirewallRules(firewallRules.map(r => r.id === rule.id ? rule : r))
|
||||
} else {
|
||||
// Add new with temporary ID
|
||||
const newRule = { ...rule, id: `tmp-${Date.now()}` }
|
||||
setFirewallRules([...firewallRules, newRule])
|
||||
}
|
||||
setShowFirewallEditor(false)
|
||||
setEditingFirewallRule(null)
|
||||
}
|
||||
|
||||
const deleteFirewallRule = (ruleId: string) => {
|
||||
setFirewallRules(firewallRules.filter(r => r.id !== ruleId))
|
||||
}
|
||||
|
||||
const toggleFirewallRule = (ruleId: string) => {
|
||||
setFirewallRules(firewallRules.map(r => r.id === ruleId ? { ...r, enabled: !r.enabled } : r))
|
||||
}
|
||||
|
||||
const openReinstall = async () => {
|
||||
try {
|
||||
const res = await getEnabledImages(container?.virtualization || 'lxc')
|
||||
@@ -753,6 +854,7 @@ export default function ContainerDetail() {
|
||||
}
|
||||
|
||||
const isRunning = container.status === 'running'
|
||||
const isInitializing = container.status === 'initializing'
|
||||
const isKVM = (container.virtualization || 'lxc') === 'kvm'
|
||||
const isWindows = container.template?.includes('windows')
|
||||
const reinstallLinuxTemplate = !isWindowsTemplate(selectedTemplate)
|
||||
@@ -770,8 +872,29 @@ export default function ContainerDetail() {
|
||||
if (ipv6List.length === 0 && container.ipv6) ipv6List.push(container.ipv6)
|
||||
const maxVCPU = hostInfo?.cpu.cores || 64
|
||||
const maxRAMMB = hostInfo?.ram.total_mb ? Number(hostInfo.ram.total_mb) : undefined
|
||||
const publicEndpoint = container.ssh_port > 0 ? `${publicHost}:${container.ssh_port}` : '-'
|
||||
const sshCommand = container.ssh_port > 0 ? `ssh -p ${container.ssh_port} root@${publicHost}` : ''
|
||||
const hasIndependentIPv4 = assignedIPv4List.length > 0
|
||||
const hasIndependentIPv6 = ipv6List.length > 0
|
||||
const defaultConnPort = isWindows ? 3389 : 22
|
||||
|
||||
let publicEndpoint = '-'
|
||||
let sshCommand = ''
|
||||
|
||||
if (hasIndependentIPv4) {
|
||||
// Direct connection via independent IPv4 — all ports forwarded
|
||||
publicEndpoint = `${assignedIPv4List[0]}:${defaultConnPort}`
|
||||
if (!isWindows) {
|
||||
sshCommand = `ssh root@${assignedIPv4List[0]}`
|
||||
}
|
||||
} else if (hasIndependentIPv6) {
|
||||
publicEndpoint = `[${ipv6List[0]}]:${defaultConnPort}`
|
||||
if (!isWindows) {
|
||||
sshCommand = `ssh root@[${ipv6List[0]}]`
|
||||
}
|
||||
} else if (container.ssh_port > 0) {
|
||||
// NAT port mapping mode
|
||||
publicEndpoint = `${publicHost}:${container.ssh_port}`
|
||||
sshCommand = `ssh -p ${container.ssh_port} root@${publicHost}`
|
||||
}
|
||||
const editingSSH = draft.index !== null && !!container.port_mappings?.[draft.index] && (
|
||||
container.port_mappings[draft.index].description === 'SSH' || container.port_mappings[draft.index].container_port === 22 ||
|
||||
container.port_mappings[draft.index].description === 'RDP' || container.port_mappings[draft.index].container_port === 3389
|
||||
@@ -786,12 +909,37 @@ export default function ContainerDetail() {
|
||||
const diskPct = container.disk_gb > 0 ? clamp(((usage?.disk_usage_bytes || 0) / (container.disk_gb * 1024 * 1024 * 1024)) * 100) : 0
|
||||
const networkBps = (usage?.network_rx_bps || 0) + (usage?.network_tx_bps || 0)
|
||||
const rx = usage?.network_rx_bps || 0
|
||||
const netPct = Math.min(((usage?.network_rx_bps || 0) + (usage?.network_tx_bps || 0)) / (container.network_bw_mbps > 0 ? container.network_bw_mbps * 125000 : 125000000) * 100, 100)
|
||||
const networkDownLimit = resourceLimitValue(container.network_down_mbps, container.network_bw_mbps)
|
||||
const networkUpLimit = resourceLimitValue(container.network_up_mbps, container.network_bw_mbps)
|
||||
const netPct = Math.max(
|
||||
directionUsagePercent(usage?.network_rx_bps || 0, networkDownLimit, 125000, 125000000),
|
||||
directionUsagePercent(usage?.network_tx_bps || 0, networkUpLimit, 125000, 125000000),
|
||||
)
|
||||
const diskIOBps = (usage?.disk_read_bps || 0) + (usage?.disk_write_bps || 0)
|
||||
const ioReadLimit = resourceLimitValue(container.io_read_mbps, container.io_speed_mbps)
|
||||
const ioWriteLimit = resourceLimitValue(container.io_write_mbps, container.io_speed_mbps)
|
||||
const diskIOPct = Math.max(
|
||||
directionUsagePercent(usage?.disk_read_bps || 0, ioReadLimit, 1024 * 1024, 1024 * 1024 * 1024),
|
||||
directionUsagePercent(usage?.disk_write_bps || 0, ioWriteLimit, 1024 * 1024, 1024 * 1024 * 1024),
|
||||
)
|
||||
const mappingCount = container.port_mappings?.length || 0
|
||||
const mappingLimit = Math.max(container.port_mapping_limit || 0, mappingCount)
|
||||
const hasNATQuota = mappingLimit > 0
|
||||
const canAddMapping = hasNATQuota && mappingCount < mappingLimit && !isSubUserPolicyBlocked
|
||||
const hasFirewallIPv4 = hasIndependentIPv4 || hasNATQuota
|
||||
const firewallNetworkOptions: Array<{ value: NonNullable<FirewallRule['network']>; label: string }> = []
|
||||
if (hasFirewallIPv4) {
|
||||
firewallNetworkOptions.push({
|
||||
value: 'ipv4',
|
||||
label: hasIndependentIPv4 ? 'IPv4(公网 IPv4)' : 'IPv4(NAT)',
|
||||
})
|
||||
}
|
||||
if (hasIndependentIPv6) {
|
||||
firewallNetworkOptions.push({ value: 'ipv6', label: 'IPv6' })
|
||||
}
|
||||
if (hasFirewallIPv4 && hasIndependentIPv6) {
|
||||
firewallNetworkOptions.push({ value: 'all', label: '全部网络' })
|
||||
}
|
||||
const managementUrl = subUser?.access_code
|
||||
? `${window.location.origin}/login?code=${encodeURIComponent(subUser.access_code)}`
|
||||
: ''
|
||||
@@ -820,7 +968,7 @@ export default function ContainerDetail() {
|
||||
current: networkBps,
|
||||
points: toChartPoints(filtered, 'network'),
|
||||
formatValue: formatRate,
|
||||
detail: `入 ${formatRate(usage?.network_rx_bps || 0)} / 出 ${formatRate(usage?.network_tx_bps || 0)},累计 ${formatBytes((usage?.network_rx_bytes || 0) + (usage?.network_tx_bytes || 0))}`,
|
||||
detail: `入 ${formatRate(usage?.network_rx_bps || 0)} / 出 ${formatRate(usage?.network_tx_bps || 0)},限速占用 ${netPct.toFixed(1)}%,累计 ${formatBytes((usage?.network_rx_bytes || 0) + (usage?.network_tx_bytes || 0))}`,
|
||||
},
|
||||
{
|
||||
title: '磁盘IO',
|
||||
@@ -828,7 +976,7 @@ export default function ContainerDetail() {
|
||||
current: diskIOBps,
|
||||
points: toChartPoints(filtered, 'diskIO'),
|
||||
formatValue: formatRate,
|
||||
detail: `读 ${formatRate(usage?.disk_read_bps || 0)} / 写 ${formatRate(usage?.disk_write_bps || 0)},累计 ${formatBytes((usage?.disk_read_bytes || 0) + (usage?.disk_write_bytes || 0))},容量 ${diskPct.toFixed(1)}%`,
|
||||
detail: `读 ${formatRate(usage?.disk_read_bps || 0)} / 写 ${formatRate(usage?.disk_write_bps || 0)},限速占用 ${diskIOPct.toFixed(1)}%,累计 ${formatBytes((usage?.disk_read_bytes || 0) + (usage?.disk_write_bytes || 0))},容量 ${diskPct.toFixed(1)}%`,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -854,13 +1002,17 @@ export default function ContainerDetail() {
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h1 className="text-xl font-bold text-black">{container.name}</h1>
|
||||
<StatusBadge running={isRunning} />
|
||||
<StatusBadge running={isRunning} initializing={isInitializing} />
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap mt-2">
|
||||
<InfoTag color="blue">系统 {container.template}</InfoTag>
|
||||
<InfoTag color="slate">类型 {(container.virtualization || 'lxc').toUpperCase()}</InfoTag>
|
||||
<InfoTag color="emerald">内网 {container.ip || '-'}</InfoTag>
|
||||
<InfoTag color="amber">IPv4 NAT {hasNATQuota ? `${mappingCount} 条` : '未分配'}</InfoTag>
|
||||
{hasIndependentIPv4 ? (
|
||||
<InfoTag color="amber">独立 IPv4 {assignedIPv4List[0]}</InfoTag>
|
||||
) : (
|
||||
<InfoTag color="amber">IPv4 NAT {hasNATQuota ? `${mappingCount} 条` : '未分配'}</InfoTag>
|
||||
)}
|
||||
<InfoTag color="violet">{isWindows ? 'RDP' : 'SSH'} {publicEndpoint}</InfoTag>
|
||||
{isPolicyBlocked && <InfoTag color="red">策略封禁</InfoTag>}
|
||||
</div>
|
||||
@@ -903,22 +1055,24 @@ export default function ContainerDetail() {
|
||||
管理链接
|
||||
</ActionButton>
|
||||
)}
|
||||
<>
|
||||
{!hasIndependentIPv4 && hasNATQuota && (
|
||||
<ActionButton disabled={isSubUserPolicyBlocked} onClick={() => setShowNat(true)}>
|
||||
<Settings className="w-3.5 h-3.5" />
|
||||
IPv4 NAT 管理
|
||||
</ActionButton>
|
||||
</>
|
||||
)}
|
||||
<ActionButton onClick={openFirewall} disabled={isSubUserPolicyBlocked}>
|
||||
<FirewallIcon className="w-3.5 h-3.5" />
|
||||
防火墙
|
||||
</ActionButton>
|
||||
<ActionButton onClick={() => setShowSnapshots(true)} disabled={!!taskStatus || !!snapshotBusy || isSubUserPolicyBlocked}>
|
||||
<Camera className="w-3.5 h-3.5" />
|
||||
快照
|
||||
</ActionButton>
|
||||
{!isSubUser && (
|
||||
<ActionButton onClick={openReinstall} disabled={!!taskStatus || isExpired}>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
{isExpired ? '已到期' : taskStatus === 'reinstall' ? taskActionLabels['reinstall'] : '重装'}
|
||||
</ActionButton>
|
||||
)}
|
||||
<ActionButton onClick={openReinstall} disabled={!!taskStatus || isExpired || isSubUserPolicyBlocked}>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
{isExpired ? '已到期' : taskStatus === 'reinstall' ? taskActionLabels['reinstall'] : '重装'}
|
||||
</ActionButton>
|
||||
{!isSubUser && (
|
||||
<ActionButton disabled={!!taskStatus} onClick={() => handleAction('delete')}>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
@@ -942,7 +1096,7 @@ export default function ContainerDetail() {
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
|
||||
<Panel
|
||||
title="连接信息"
|
||||
extra={!isSubUser && !isWindows && !isSubUserPolicyBlocked ? (
|
||||
extra={!isWindows && !isSubUserPolicyBlocked ? (
|
||||
<button
|
||||
onClick={openResetPassword}
|
||||
className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs text-gray-600 hover:bg-gray-100 hover:text-black"
|
||||
@@ -1017,8 +1171,8 @@ export default function ContainerDetail() {
|
||||
<PlainRow label="vCPU" value={`${container.vcpu} 核`} />
|
||||
<PlainRow label="内存" value={`${container.ram_mb} MB`} />
|
||||
<PlainRow label="磁盘" value={`${container.disk_gb} GB`} />
|
||||
<PlainRow label="网络速率" value={container.network_bw_mbps > 0 ? `${container.network_bw_mbps} Mbps` : '不限制'} />
|
||||
<PlainRow label="IO 速度" value={container.io_speed_mbps > 0 ? `${container.io_speed_mbps} MB/s` : '不限制'} />
|
||||
<PlainRow label="网络速率" value={formatDirectionalLimit('下行', networkDownLimit, '上行', networkUpLimit, 'Mbps')} />
|
||||
<PlainRow label="IO 速度" value={formatDirectionalLimit('读取', ioReadLimit, '写入', ioWriteLimit, 'MB/s')} />
|
||||
</Panel>
|
||||
|
||||
<Panel title="实时状态">
|
||||
@@ -1418,7 +1572,242 @@ export default function ContainerDetail() {
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{showNat && (
|
||||
{showFirewall && (
|
||||
<Modal title="防火墙设置" onClose={() => { setShowFirewall(false); setShowFirewallEditor(false); setEditingFirewallRule(null) }} wide extra={
|
||||
!isSubUser && (
|
||||
<button
|
||||
onClick={addFirewallRule}
|
||||
disabled={firewallNetworkOptions.length === 0}
|
||||
title={firewallNetworkOptions.length === 0 ? '当前容器没有可配置的 NAT、公网 IPv4 或 IPv6' : undefined}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-black text-white rounded-md text-xs hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />添加规则
|
||||
</button>
|
||||
)
|
||||
}>
|
||||
<div className="space-y-5">
|
||||
{/* Global toggle */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-800">防火墙</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{firewallEnabled
|
||||
? (firewallDefaultAction === 'DROP' ? '已启用,未匹配规则的流量将被拒绝' : '已启用,未匹配规则的流量将被放行')
|
||||
: '未启用时不接管该容器流量'}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setFirewallEnabled(!firewallEnabled)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${firewallEnabled ? 'bg-emerald-500' : 'bg-gray-300'}`}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${firewallEnabled ? 'translate-x-6' : 'translate-x-1'}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-4 rounded-md border border-gray-200 px-3 py-2">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-800">默认动作</div>
|
||||
<div className="text-xs text-gray-500">没有命中下方规则时如何处理</div>
|
||||
</div>
|
||||
<select
|
||||
value={firewallDefaultAction}
|
||||
onChange={(e) => setFirewallDefaultAction(e.target.value as 'ACCEPT' | 'DROP')}
|
||||
disabled={isSubUser}
|
||||
className="rounded-md border border-gray-300 bg-white px-2.5 py-1.5 text-xs text-gray-800 focus:border-black focus:outline-none focus:ring-2 focus:ring-black disabled:opacity-60"
|
||||
>
|
||||
<option value="DROP">未匹配拒绝</option>
|
||||
<option value="ACCEPT">未匹配放行</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border border-blue-100 bg-blue-50 px-3 py-2 text-xs text-blue-800">
|
||||
<div className="font-medium text-blue-900">网络范围</div>
|
||||
<div className="mt-1">
|
||||
{firewallNetworkOptions.length > 0
|
||||
? `可配置:${firewallNetworkOptions.filter((option) => option.value !== 'all').map((option) => option.label).join('、')}。`
|
||||
: '当前容器未分配 IPv4 NAT、独立公网 IPv4 或 IPv6,暂无可配置网络。'}
|
||||
{hasFirewallIPv4 ? ` IPv4 规则覆盖${hasIndependentIPv4 ? '独立公网 IPv4' : 'IPv4 NAT 端口映射'}。` : ''}
|
||||
{hasNATQuota && !hasIndependentIPv4 ? ' NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。' : ''}
|
||||
{hasIndependentIPv6 ? ' IPv6 规则覆盖该容器已分配的 IPv6 地址。' : ''}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{firewallMessage && (
|
||||
<div className={`rounded-md px-3 py-2 text-xs ${firewallMessage.type === 'success' ? 'border border-emerald-100 bg-emerald-50 text-emerald-700' : 'border border-red-100 bg-red-50 text-red-700'}`}>
|
||||
{firewallMessage.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rules table */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="border-b border-gray-200 bg-gray-50 text-xs text-gray-500">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">状态</th>
|
||||
<th className="px-3 py-2 text-left font-medium">网络</th>
|
||||
<th className="px-3 py-2 text-left font-medium">方向</th>
|
||||
<th className="px-3 py-2 text-left font-medium">协议</th>
|
||||
<th className="px-3 py-2 text-left font-medium">端口</th>
|
||||
<th className="px-3 py-2 text-left font-medium">来源/目标 IP</th>
|
||||
<th className="px-3 py-2 text-left font-medium">动作</th>
|
||||
<th className="px-3 py-2 text-left font-medium">描述</th>
|
||||
{!isSubUser && <th className="px-3 py-2 text-right font-medium">操作</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{firewallRules.map((rule) => (
|
||||
<tr key={rule.id} className={!rule.enabled ? 'opacity-50' : ''}>
|
||||
<td className="px-3 py-2">
|
||||
<button onClick={() => toggleFirewallRule(rule.id)} className={`inline-flex h-4 w-7 items-center rounded-full transition-colors ${rule.enabled ? 'bg-emerald-500' : 'bg-gray-300'}`}>
|
||||
<span className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${rule.enabled ? 'translate-x-3.5' : 'translate-x-0.5'}`} />
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<span className="inline-flex rounded bg-gray-100 px-1.5 py-0.5 text-xs font-medium text-gray-700">
|
||||
{(rule.network || 'ipv4') === 'ipv6' ? 'IPv6' : (rule.network || 'ipv4') === 'all' ? '全部' : 'IPv4'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<span className={`inline-flex px-1.5 py-0.5 rounded text-xs font-medium ${rule.direction === 'in' ? 'bg-blue-50 text-blue-700' : 'bg-orange-50 text-orange-700'}`}>
|
||||
{rule.direction === 'in' ? '入站' : '出站'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 font-mono text-xs">{rule.protocol.toUpperCase()}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs">{rule.port || '全部'}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs">{rule.source_ip || '任意'}</td>
|
||||
<td className="px-3 py-2">
|
||||
<span className={`inline-flex px-1.5 py-0.5 rounded text-xs font-medium ${rule.action === 'ACCEPT' ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'}`}>
|
||||
{rule.action === 'ACCEPT' ? '放行' : '拒绝'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-600 max-w-32 truncate">{rule.description || '-'}</td>
|
||||
{!isSubUser && (
|
||||
<td className="px-3 py-2 text-right">
|
||||
<div className="inline-flex items-center gap-1">
|
||||
<button onClick={() => {
|
||||
const currentNetwork = (rule.network || 'ipv4') as NonNullable<FirewallRule['network']>
|
||||
const network = firewallNetworkOptions.some((option) => option.value === currentNetwork)
|
||||
? currentNetwork
|
||||
: (firewallNetworkOptions[0]?.value || currentNetwork)
|
||||
setEditingFirewallRule({ ...rule, network })
|
||||
setShowFirewallEditor(true)
|
||||
}} className="p-1.5 text-gray-400 hover:text-gray-700 rounded hover:bg-gray-100">
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button onClick={() => deleteFirewallRule(rule.id)} className="p-1.5 text-gray-400 hover:text-red-600 rounded hover:bg-red-50">
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
{firewallRules.length === 0 && (
|
||||
<tr><td colSpan={isSubUser ? 8 : 9} className="px-3 py-6 text-center text-xs text-gray-400">暂无防火墙规则</td></tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Save button */}
|
||||
{!isSubUser && (
|
||||
<div className="flex justify-end">
|
||||
<button onClick={saveFirewall} disabled={firewallSaving} className="inline-flex items-center gap-1.5 px-4 py-2 bg-black text-white rounded-md text-sm hover:bg-gray-800 disabled:opacity-50">
|
||||
<Save className="w-3.5 h-3.5" />
|
||||
{firewallSaving ? '保存中...' : '保存'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{showFirewallEditor && editingFirewallRule && (
|
||||
<Modal title={editingFirewallRule.id ? '编辑规则' : '添加规则'} onClose={() => { setShowFirewallEditor(false); setEditingFirewallRule(null) }}>
|
||||
<div className="space-y-4">
|
||||
<Field label="网络">
|
||||
{firewallNetworkOptions.length > 0 ? (
|
||||
<select value={editingFirewallRule.network || firewallNetworkOptions[0].value} onChange={(e) => setEditingFirewallRule({ ...editingFirewallRule, network: e.target.value as FirewallRule['network'] })} className={inputClass}>
|
||||
{firewallNetworkOptions.map((option) => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input value="当前容器没有可配置网络" disabled className={`${inputClass} bg-gray-100 text-gray-400`} />
|
||||
)}
|
||||
</Field>
|
||||
<Field label="方向">
|
||||
<select value={editingFirewallRule.direction} onChange={(e) => setEditingFirewallRule({ ...editingFirewallRule, direction: e.target.value as 'in' | 'out' })} className={inputClass}>
|
||||
<option value="in">入站 (Inbound)</option>
|
||||
<option value="out">出站 (Outbound)</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="协议">
|
||||
<select
|
||||
value={editingFirewallRule.protocol}
|
||||
onChange={(e) => {
|
||||
const protocol = e.target.value as FirewallRule['protocol']
|
||||
setEditingFirewallRule({
|
||||
...editingFirewallRule,
|
||||
protocol,
|
||||
port: protocol === 'tcp' || protocol === 'udp' ? editingFirewallRule.port : '',
|
||||
})
|
||||
}}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="tcp">TCP</option>
|
||||
<option value="udp">UDP</option>
|
||||
<option value="icmp">ICMP</option>
|
||||
<option value="all">全部</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="端口"
|
||||
hint={editingFirewallRule.protocol === 'tcp' || editingFirewallRule.protocol === 'udp'
|
||||
? (editingFirewallRule.direction === 'in'
|
||||
? ((editingFirewallRule.network || 'ipv4') === 'ipv4' && hasNATQuota && !hasIndependentIPv4
|
||||
? 'NAT 入站填容器内部端口,例如公网 22023 -> 容器 22,这里填 22'
|
||||
: '入站填容器服务端口;留空为全部端口,支持: 22 | 80,443 | 8000-9000')
|
||||
: '出站填远端目标端口;留空为全部端口,支持: 22 | 80,443 | 8000-9000')
|
||||
: '端口仅适用于 TCP/UDP'}
|
||||
>
|
||||
<input
|
||||
value={editingFirewallRule.port}
|
||||
onChange={(e) => setEditingFirewallRule({ ...editingFirewallRule, port: e.target.value })}
|
||||
placeholder={editingFirewallRule.protocol === 'tcp' || editingFirewallRule.protocol === 'udp' ? '如: 22 或 80,443 或 8000-9000' : '当前协议不使用端口'}
|
||||
disabled={editingFirewallRule.protocol !== 'tcp' && editingFirewallRule.protocol !== 'udp'}
|
||||
className={`${inputClass} disabled:bg-gray-100 disabled:text-gray-400`}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={editingFirewallRule.direction === 'in' ? '来源 IP' : '目标 IP'}
|
||||
hint={(editingFirewallRule.network || 'ipv4') === 'ipv6' ? '留空为任意 IPv6,支持 CIDR: 2001:db8::/64' : (editingFirewallRule.network || 'ipv4') === 'all' ? '留空为任意 IP,支持 IPv4/IPv6 CIDR' : '留空为任意 IPv4,支持 CIDR: 192.168.1.0/24'}
|
||||
>
|
||||
<input
|
||||
value={editingFirewallRule.source_ip}
|
||||
onChange={(e) => setEditingFirewallRule({ ...editingFirewallRule, source_ip: e.target.value })}
|
||||
placeholder={(editingFirewallRule.network || 'ipv4') === 'ipv6' ? '如: 2001:db8::/64' : (editingFirewallRule.network || 'ipv4') === 'all' ? '如: 192.168.1.0/24 或 2001:db8::/64' : '如: 192.168.1.0/24'}
|
||||
className={inputClass}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="动作">
|
||||
<select value={editingFirewallRule.action} onChange={(e) => setEditingFirewallRule({ ...editingFirewallRule, action: e.target.value as 'ACCEPT' | 'DROP' })} className={inputClass}>
|
||||
<option value="ACCEPT">放行 (ACCEPT)</option>
|
||||
<option value="DROP">拒绝 (DROP)</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="描述">
|
||||
<input value={editingFirewallRule.description} onChange={(e) => setEditingFirewallRule({ ...editingFirewallRule, description: e.target.value })} placeholder="规则描述" className={inputClass} />
|
||||
</Field>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button onClick={() => { setShowFirewallEditor(false); setEditingFirewallRule(null) }} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-md">取消</button>
|
||||
<button onClick={() => saveFirewallRule(editingFirewallRule)} className="px-4 py-2 text-sm bg-black text-white rounded-md hover:bg-gray-800">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{showNat && !hasIndependentIPv4 && (
|
||||
<Modal title="IPv4 NAT 端口管理" onClose={() => { setShowNat(false); setDraft(emptyDraft); setShowMappingEditor(false) }} wide extra={
|
||||
!isSubUser && canAddMapping && (
|
||||
<button onClick={openAddMapping} className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-black text-white rounded-md text-xs hover:bg-gray-800">
|
||||
@@ -1610,15 +1999,27 @@ export default function ContainerDetail() {
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">网络速率 (Mbps,0=不限制)</label>
|
||||
<input type="number" min={0} value={resourceEdit.bwMbps}
|
||||
onChange={(e) => setResourceEdit({ ...resourceEdit, bwMbps: Math.max(0, Number(e.target.value) || 0) })}
|
||||
<label className="block text-xs text-gray-500 mb-1">下行带宽 (Mbps,0=不限制)</label>
|
||||
<input type="number" min={0} value={resourceEdit.networkDownMbps}
|
||||
onChange={(e) => setResourceEdit({ ...resourceEdit, networkDownMbps: Math.max(0, Number(e.target.value) || 0) })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">IO 速度 (MB/s,0=不限制)</label>
|
||||
<input type="number" min={0} value={resourceEdit.ioMbps}
|
||||
onChange={(e) => setResourceEdit({ ...resourceEdit, ioMbps: Math.max(0, Number(e.target.value) || 0) })}
|
||||
<label className="block text-xs text-gray-500 mb-1">上行带宽 (Mbps,0=不限制)</label>
|
||||
<input type="number" min={0} value={resourceEdit.networkUpMbps}
|
||||
onChange={(e) => setResourceEdit({ ...resourceEdit, networkUpMbps: Math.max(0, Number(e.target.value) || 0) })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">读取 IO (MB/s,0=不限制)</label>
|
||||
<input type="number" min={0} value={resourceEdit.ioReadMbps}
|
||||
onChange={(e) => setResourceEdit({ ...resourceEdit, ioReadMbps: Math.max(0, Number(e.target.value) || 0) })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">写入 IO (MB/s,0=不限制)</label>
|
||||
<input type="number" min={0} value={resourceEdit.ioWriteMbps}
|
||||
onChange={(e) => setResourceEdit({ ...resourceEdit, ioWriteMbps: Math.max(0, Number(e.target.value) || 0) })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -1652,7 +2053,23 @@ function RangeSwitch({ value, onChange }: { value: StatsRangeKey; onChange: (val
|
||||
)
|
||||
}
|
||||
|
||||
function StatusBadge({ running }: { running: boolean }) {
|
||||
function FirewallIcon({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 1024 1024" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M979.989543 469.308394H757.450516c4.519899-21.887511 7.247838-45.094992 7.247838-69.798441 0-137.428929-116.773391-270.417958-121.72528-276.001833a21.415521 21.415521 0 0 0-21.887511-6.319858 21.287524 21.287524 0 0 0-15.103663 16.98362l-12.583719 75.438315C571.854663 148.115571 533.535519 69.229333 467.241 5.910748A21.46352 21.46352 0 0 0 441.585573 2.982813a21.295524 21.295524 0 0 0-9.727782 23.935466c15.703649 58.366696-2.815937 152.996581-22.911488 226.978928-5.591875-35.7912-15.615651-66.214521-32.935264-76.414293a21.351523 21.351523 0 0 0-32.167282 18.399589c0 31.359299-15.999643 60.278653-34.519228 93.813904-24.703448 44.759-52.734822 95.525866-52.734822 167.972247 0 4.055909 0.599987 7.727827 0.767983 11.64774H41.346516A21.343523 21.343523 0 0 0 20.010993 490.651917v511.98856a21.343523 21.343523 0 0 0 21.335523 21.335524H979.989543a21.343523 21.343523 0 0 0 21.335524-21.335524v-511.98856A21.343523 21.343523 0 0 0 979.989543 469.308394z m-149.332663 42.663047v127.99714H660.380685c33.879243-29.183348 65.878528-72.702376 85.334093-127.99714h84.942102zM346.699693 310.255948c7.559831-13.599696 14.895667-26.919399 21.167527-40.399098 3.495922 28.543362 5.503877 64.510559 5.071887 100.26176a21.311524 21.311524 0 0 0 17.367612 21.199526 21.255525 21.255525 0 0 0 23.935465-13.351701c3.071931-8.191817 63.918572-169.980202 65.958527-293.241448 78.462247 104.493665 96.429845 228.906885 96.63784 230.354853a21.279525 21.279525 0 0 0 20.823535 18.431588c9.85578-0.255994 19.631561-7.383835 21.335523-17.791602L640.077138 189.29865c32.895265 46.422963 81.958169 129.277111 81.958169 210.219303 0 157.772475-113.837456 240.458627-153.212577 240.458628H455.241268c-19.023575-5.247883-155.940516-47.742933-155.940516-182.347926 0-61.486626 24.111461-105.133651 47.398941-147.372707zM659.996693 682.647627v127.99714H361.339366v-127.99714H659.996693zM190.67118 511.971441h72.750374c15.311658 60.974638 54.910773 101.717727 93.693907 127.99714H190.67118v-127.99714z m-127.99714 0H148.008133v127.99714H62.67404v-127.99714z m0 170.668186h255.99428v127.99714h-255.99428v-127.99714zM148.008133 981.296954H62.67404v-127.99714H148.008133v127.99714z m341.328373 0H190.67118v-127.99714h298.665326v127.99714z m341.320374 0H531.999553v-127.99714h298.657327v127.99714z m127.99714 0h-85.326093v-127.99714h85.326093v127.99714z m0-170.660187h-255.99428v-127.99714h255.99428v127.99714z m0-170.668186h-85.326093v-127.99714h85.326093v127.99714z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function StatusBadge({ running, initializing }: { running: boolean; initializing?: boolean }) {
|
||||
if (initializing) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium whitespace-nowrap bg-amber-50 text-amber-700">
|
||||
<span className="w-1.5 h-1.5 rounded-full flex-shrink-0 bg-amber-500 animate-pulse"></span>
|
||||
正在初始化
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium whitespace-nowrap ${running ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'}`}>
|
||||
<span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${running ? 'bg-emerald-500' : 'bg-rose-500'}`}></span>
|
||||
@@ -2005,11 +2422,12 @@ function TableHead({ children }: { children: ReactNode }) {
|
||||
return <th className="text-left px-3 py-2 text-xs font-medium text-gray-500">{children}</th>
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||
function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: string }) {
|
||||
return (
|
||||
<label className="block">
|
||||
<span className="block text-xs font-medium text-gray-600 mb-1.5">{label}</span>
|
||||
{children}
|
||||
{hint && <span className="block text-[11px] text-gray-400 mt-1">{hint}</span>}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -2070,6 +2488,32 @@ function clampResourceInt(value: number, min: number, max?: number, fallback = m
|
||||
return Math.min(Math.max(next, min), max ?? next)
|
||||
}
|
||||
|
||||
function resourceLimitValue(value?: number, fallback?: number) {
|
||||
return Math.max(0, Number(value || fallback || 0))
|
||||
}
|
||||
|
||||
function symmetricLimit(a: number, b: number) {
|
||||
const left = resourceLimitValue(a)
|
||||
const right = resourceLimitValue(b)
|
||||
if (left === right) return left
|
||||
if (left === 0) return right
|
||||
if (right === 0) return left
|
||||
return Math.min(left, right)
|
||||
}
|
||||
|
||||
function directionUsagePercent(bytesPerSecond: number, limit: number, bytesPerLimitUnit: number, fallbackBytesPerSecond: number) {
|
||||
const denominator = limit > 0 ? limit * bytesPerLimitUnit : fallbackBytesPerSecond
|
||||
return denominator > 0 ? clamp((bytesPerSecond / denominator) * 100) : 0
|
||||
}
|
||||
|
||||
function formatLimit(value: number, unit: string) {
|
||||
return value > 0 ? `${value} ${unit}` : '不限制'
|
||||
}
|
||||
|
||||
function formatDirectionalLimit(firstLabel: string, firstValue: number, secondLabel: string, secondValue: number, unit: string) {
|
||||
return `${firstLabel} ${formatLimit(firstValue, unit)} / ${secondLabel} ${formatLimit(secondValue, unit)}`
|
||||
}
|
||||
|
||||
function toChartPoints<T extends keyof Omit<MetricPoint, 'ts'>>(history: MetricPoint[], key: T): ChartPoint[] {
|
||||
return history.map((point) => ({ ts: point.ts, value: Number(point[key]) || 0 }))
|
||||
}
|
||||
|
||||
@@ -390,6 +390,7 @@ export default function Containers() {
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{pageContainers.map((container) => {
|
||||
const isRunning = container.status === 'running'
|
||||
const isInitializing = container.status === 'initializing'
|
||||
const task = (container.id > 0 ? taskStatusMap[container.id] : taskNameMap[container.name]) || container.createTask
|
||||
const isPlaceholder = !!container.isPlaceholder
|
||||
const isPolicyBlocked = !!container.policy_blocked
|
||||
@@ -437,7 +438,7 @@ export default function Containers() {
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2.5 py-2 align-top">
|
||||
<StatusBadge running={isRunning} task={task} placeholder={isPlaceholder} policyBlocked={isPolicyBlocked} />
|
||||
<StatusBadge running={isRunning} initializing={isInitializing} task={task} placeholder={isPlaceholder} policyBlocked={isPolicyBlocked} />
|
||||
</td>
|
||||
<td className="px-2.5 py-2 align-top text-xs text-gray-600 whitespace-nowrap">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
@@ -483,7 +484,7 @@ export default function Containers() {
|
||||
try {
|
||||
const { default: api } = await import('../services/api')
|
||||
await api.delete(`/tasks/${task.id}`)
|
||||
fetchData()
|
||||
await Promise.all([fetchData(), fetchTasks()])
|
||||
} catch { /* ignore */ }
|
||||
}}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded-md border border-red-200 text-[11px] text-red-600 hover:bg-red-50 transition-colors whitespace-nowrap"
|
||||
@@ -581,7 +582,7 @@ type DisplayContainer = Container & {
|
||||
createTask?: Task
|
||||
}
|
||||
|
||||
function StatusBadge({ running, task, placeholder, policyBlocked }: { running: boolean; task?: Task; placeholder?: boolean; policyBlocked?: boolean }) {
|
||||
function StatusBadge({ running, initializing, task, placeholder, policyBlocked }: { running: boolean; initializing?: boolean; task?: Task; placeholder?: boolean; policyBlocked?: boolean }) {
|
||||
const baseClass = "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium whitespace-nowrap"
|
||||
if (policyBlocked) {
|
||||
return (
|
||||
@@ -640,6 +641,15 @@ function StatusBadge({ running, task, placeholder, policyBlocked }: { running: b
|
||||
)
|
||||
}
|
||||
|
||||
if (initializing) {
|
||||
return (
|
||||
<span className={`${baseClass} bg-amber-50 text-amber-700`}>
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span>
|
||||
正在初始化
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={`${baseClass} ${running ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-600'}`}>
|
||||
<span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${running ? 'bg-green-500' : 'bg-red-500'}`}></span>
|
||||
@@ -694,6 +704,8 @@ function toPlaceholder(cfg: CreateContainerRequest): DisplayContainer {
|
||||
ram_mb: cfg.ram_mb,
|
||||
disk_gb: cfg.disk_gb,
|
||||
network_bw_mbps: cfg.network_bw_mbps,
|
||||
network_down_mbps: cfg.network_down_mbps,
|
||||
network_up_mbps: cfg.network_up_mbps,
|
||||
monthly_traffic_gb: cfg.monthly_traffic_gb,
|
||||
traffic_mode: cfg.traffic_mode || 'total',
|
||||
traffic_in_gb: cfg.traffic_in_gb || 0,
|
||||
@@ -702,6 +714,8 @@ function toPlaceholder(cfg: CreateContainerRequest): DisplayContainer {
|
||||
traffic_used_tx: 0,
|
||||
traffic_reset_date: '',
|
||||
io_speed_mbps: cfg.io_speed_mbps,
|
||||
io_read_mbps: cfg.io_read_mbps,
|
||||
io_write_mbps: cfg.io_write_mbps,
|
||||
status: 'creating',
|
||||
ip: '',
|
||||
public_ipv4s: [],
|
||||
@@ -714,6 +728,9 @@ function toPlaceholder(cfg: CreateContainerRequest): DisplayContainer {
|
||||
ssh_password: '',
|
||||
port_mappings: [],
|
||||
port_mapping_limit: cfg.assign_nat === false ? 0 : (cfg.port_mapping_count || 0),
|
||||
firewall_enabled: false,
|
||||
firewall_default_action: 'DROP',
|
||||
firewall_rules: [],
|
||||
snapshot_limit: cfg.snapshot_limit || 3,
|
||||
created_at: '',
|
||||
expires_at: cfg.expires_at,
|
||||
|
||||
@@ -66,7 +66,7 @@ export default function Login() {
|
||||
<AppIcon className="w-10 h-10" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-gray-950">CLICD</h1>
|
||||
<p className="text-gray-500 mt-1 text-sm">{isAccessCodeLogin ? '容器管理登录' : 'LXC Container Manager'}</p>
|
||||
<p className="text-gray-500 mt-1 text-sm">{isAccessCodeLogin ? '容器管理登录' : 'Container Manager'}</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
@@ -128,7 +128,7 @@ export default function Login() {
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-xs text-gray-400 mt-6">CLICD v1.1.12</p>
|
||||
<p className="text-center text-xs text-gray-400 mt-6">CLICD v1.1.19</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { Globe2, Network, Pencil, Plus, RefreshCw, Router, Save, Search, Server, Trash2, X } from 'lucide-react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useLanguage, type Language } from '../contexts/LanguageContext'
|
||||
@@ -23,7 +23,8 @@ export default function Routing() {
|
||||
const [ipv4EditMode, setIPv4EditMode] = useState<'pool' | 'address'>('pool')
|
||||
const [editingIPv4Address, setEditingIPv4Address] = useState('')
|
||||
const [savingIPv4, setSavingIPv4] = useState(false)
|
||||
const [ipv4Draft, setIPv4Draft] = useState<PublicIPv4Info[]>([])
|
||||
const [ipv4Draft, setIPv4Draft] = useState<(PublicIPv4Info & { _id: number })[]>([])
|
||||
const nextDraftId = useRef(0)
|
||||
const [nat4Page, setNat4Page] = useState(1)
|
||||
const [ipv6Page, setIPv6Page] = useState(1)
|
||||
const [nat4Search, setNat4Search] = useState('')
|
||||
@@ -54,7 +55,7 @@ export default function Routing() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!editingIPv4) {
|
||||
setIPv4Draft(publicIPv4s.map((ip) => ({ ...ip })))
|
||||
setIPv4Draft(publicIPv4s.map((ip) => ({ ...ip, _id: nextDraftId.current++ })))
|
||||
}
|
||||
}, [editingIPv4, publicIPv4s])
|
||||
|
||||
@@ -65,14 +66,14 @@ export default function Routing() {
|
||||
}, [ipv4Assignments])
|
||||
|
||||
const startEditIPv4 = () => {
|
||||
setIPv4Draft(publicIPv4s.map((ip) => ({ ...ip })))
|
||||
setIPv4Draft(publicIPv4s.map((ip) => ({ ...ip, _id: nextDraftId.current++ })))
|
||||
setIPv4EditMode('pool')
|
||||
setEditingIPv4Address('')
|
||||
setEditingIPv4(true)
|
||||
}
|
||||
|
||||
const startEditIPv4Address = (ip: PublicIPv4Info) => {
|
||||
setIPv4Draft([{ ...ip }])
|
||||
setIPv4Draft([{ ...ip, _id: nextDraftId.current++ }])
|
||||
setIPv4EditMode('address')
|
||||
setEditingIPv4Address(ip.address)
|
||||
setEditingIPv4(true)
|
||||
@@ -82,13 +83,14 @@ export default function Routing() {
|
||||
setEditingIPv4(false)
|
||||
setIPv4EditMode('pool')
|
||||
setEditingIPv4Address('')
|
||||
setIPv4Draft(publicIPv4s.map((ip) => ({ ...ip })))
|
||||
setIPv4Draft([])
|
||||
}
|
||||
|
||||
const addIPv4Row = () => {
|
||||
setIPv4Draft((items) => [
|
||||
...items,
|
||||
{
|
||||
_id: nextDraftId.current++,
|
||||
address: '',
|
||||
interface: defaultIPv4Interface,
|
||||
prefix: '',
|
||||
@@ -108,7 +110,7 @@ export default function Routing() {
|
||||
setSavingIPv4(true)
|
||||
try {
|
||||
const draftItems = ipv4Draft
|
||||
.map((item) => ({
|
||||
.map(({ _id, ...item }) => ({
|
||||
...item,
|
||||
address: (item.address || '').trim(),
|
||||
interface: (item.interface || defaultIPv4Interface).trim(),
|
||||
@@ -187,9 +189,9 @@ export default function Routing() {
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<CapacityCard title={text.nat4Ports} icon={<Network className="h-5 w-5" />} remaining={routing?.nat4.remaining || '0'} total={routing?.nat4.total || '0'} used={routing?.nat4.used || 0} label={text.remainingTotal} usedLabel={text.used} />
|
||||
<CapacityCard title={text.publicIPv4} icon={<Globe2 className="h-5 w-5" />} remaining={routing?.ipv4.remaining || '0'} total={routing?.ipv4.total || '0'} used={routing?.ipv4.used || 0} label={formatPoolCount(publicIPv4s.length, language)} usedLabel={text.used} />
|
||||
<CapacityCard title="IPv6" icon={<Router className="h-5 w-5" />} remaining={formatCapacity(routing?.ipv6.remaining || '0', language)} total={formatCapacity(routing?.ipv6.total || '0', language)} used={routing?.ipv6.used || 0} label={formatDetectedPrefixCount(ipv6Prefixes.length, language)} usedLabel={text.used} />
|
||||
<CapacityCard title={text.nat4Ports} watermark="NAT4" remaining={routing?.nat4.remaining || '0'} total={routing?.nat4.total || '0'} used={routing?.nat4.used || 0} label={text.remainingTotal} usedLabel={text.used} />
|
||||
<CapacityCard title={text.publicIPv4} watermark="IPv4" remaining={routing?.ipv4.remaining || '0'} total={routing?.ipv4.total || '0'} used={routing?.ipv4.used || 0} label={formatPoolCount(publicIPv4s.length, language)} usedLabel={text.used} />
|
||||
<CapacityCard title="IPv6" watermark="IPv6" remaining={formatCapacity(routing?.ipv6.remaining || '0', language)} total={formatCapacity(routing?.ipv6.total || '0', language)} used={routing?.ipv6.used || 0} label={formatDetectedPrefixCount(ipv6Prefixes.length, language)} usedLabel={text.used} />
|
||||
</div>
|
||||
|
||||
<Panel
|
||||
@@ -285,7 +287,7 @@ export default function Routing() {
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{ipv4Draft.map((item, index) => (
|
||||
<tr key={`${item.address}-${index}`}>
|
||||
<tr key={item._id}>
|
||||
<td className="px-3 py-2"><input value={item.address || ''} onChange={(e) => updateIPv4Draft(index, { address: e.target.value })} placeholder={text.ipv4CIDR} className={smallInputClass} /></td>
|
||||
<td className="px-3 py-2"><input value={item.gateway || ''} onChange={(e) => updateIPv4Draft(index, { gateway: e.target.value })} placeholder={defaultIPv4Gateway || text.gateway} className={smallInputClass} /></td>
|
||||
<td className="px-3 py-2"><input value={item.interface || ''} onChange={(e) => updateIPv4Draft(index, { interface: e.target.value })} placeholder={defaultIPv4Interface} className={smallInputClass} /></td>
|
||||
@@ -525,9 +527,9 @@ function Pagination({ page, totalPages, totalItems, pageSize, onPageChange, lang
|
||||
)
|
||||
}
|
||||
|
||||
function CapacityCard({ title, icon, remaining, total, used, label, usedLabel }: {
|
||||
function CapacityCard({ title, watermark, remaining, total, used, label, usedLabel }: {
|
||||
title: string
|
||||
icon: ReactNode
|
||||
watermark: string
|
||||
remaining: string
|
||||
total: string
|
||||
used: number
|
||||
@@ -535,8 +537,11 @@ function CapacityCard({ title, icon, remaining, total, used, label, usedLabel }:
|
||||
usedLabel: string
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-lg border border-gray-200 bg-white p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4">
|
||||
<div className="pointer-events-none absolute bottom-1 right-3 select-none bg-gradient-to-br from-black via-gray-600 to-gray-300 bg-clip-text text-[44px] font-black italic tracking-wide text-transparent opacity-25 -skew-x-12">
|
||||
{watermark}
|
||||
</div>
|
||||
<div className="relative z-10">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-700">{title}</div>
|
||||
<div className="mt-2 flex items-end gap-2">
|
||||
@@ -544,10 +549,9 @@ function CapacityCard({ title, icon, remaining, total, used, label, usedLabel }:
|
||||
<span className="pb-1 text-sm text-gray-400">/ {total}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-md bg-gray-100 text-gray-700">{icon}</div>
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-gray-500">{label}</div>
|
||||
<div className="mt-1 text-xs text-gray-400">{usedLabel} {used}</div>
|
||||
<div className="relative z-10 mt-3 text-xs text-gray-500">{label}</div>
|
||||
<div className="relative z-10 mt-1 text-xs text-gray-400">{usedLabel} {used}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -45,6 +45,18 @@ export interface PortMapping {
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface FirewallRule {
|
||||
id: string
|
||||
network?: 'ipv4' | 'ipv6' | 'all'
|
||||
direction: 'in' | 'out'
|
||||
protocol: 'tcp' | 'udp' | 'icmp' | 'all'
|
||||
port: string
|
||||
source_ip: string
|
||||
action: 'ACCEPT' | 'DROP'
|
||||
description: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export interface PublicIPv4Assignment {
|
||||
address: string
|
||||
interface?: string
|
||||
@@ -68,6 +80,8 @@ export interface Container {
|
||||
ram_mb: number
|
||||
disk_gb: number
|
||||
network_bw_mbps: number
|
||||
network_down_mbps: number
|
||||
network_up_mbps: number
|
||||
monthly_traffic_gb: number
|
||||
traffic_mode: string
|
||||
traffic_in_gb: number
|
||||
@@ -76,6 +90,8 @@ export interface Container {
|
||||
traffic_used_tx: number
|
||||
traffic_reset_date: string
|
||||
io_speed_mbps: number
|
||||
io_read_mbps: number
|
||||
io_write_mbps: number
|
||||
status: string
|
||||
ip: string
|
||||
public_ipv4s?: PublicIPv4Assignment[]
|
||||
@@ -88,6 +104,9 @@ export interface Container {
|
||||
ssh_password: string
|
||||
port_mappings: PortMapping[]
|
||||
port_mapping_limit: number
|
||||
firewall_enabled: boolean
|
||||
firewall_default_action: 'ACCEPT' | 'DROP'
|
||||
firewall_rules: FirewallRule[]
|
||||
snapshot_limit: number
|
||||
created_at: string
|
||||
expires_at: string
|
||||
@@ -123,11 +142,15 @@ export interface CreateContainerRequest {
|
||||
ram_mb: number
|
||||
disk_gb: number
|
||||
network_bw_mbps: number
|
||||
network_down_mbps: number
|
||||
network_up_mbps: number
|
||||
monthly_traffic_gb: number
|
||||
traffic_mode: string
|
||||
traffic_in_gb: number
|
||||
traffic_out_gb: number
|
||||
io_speed_mbps: number
|
||||
io_read_mbps: number
|
||||
io_write_mbps: number
|
||||
extra_ports: number[]
|
||||
port_mapping_count: number
|
||||
assign_nat?: boolean
|
||||
@@ -473,8 +496,12 @@ export const updateTrafficLimit = (id: ContainerIdentifier, data: {
|
||||
export const updateResourceLimit = (id: ContainerIdentifier, data: {
|
||||
vcpu: number
|
||||
ram_mb: number
|
||||
io_speed_mbps: number
|
||||
network_bw_mbps: number
|
||||
io_speed_mbps?: number
|
||||
io_read_mbps?: number
|
||||
io_write_mbps?: number
|
||||
network_bw_mbps?: number
|
||||
network_down_mbps?: number
|
||||
network_up_mbps?: number
|
||||
}) =>
|
||||
api.put<APIResponse>(`/containers/${id}/resource-limit`, data)
|
||||
|
||||
@@ -487,6 +514,12 @@ export const updatePortMapping = (id: ContainerIdentifier, index: number, data:
|
||||
export const deletePortMapping = (id: ContainerIdentifier, index: number) =>
|
||||
api.delete<APIResponse<PortMapping[]>>(`/containers/${id}/port-mappings/${index}`)
|
||||
|
||||
export const getFirewall = (id: ContainerIdentifier) =>
|
||||
api.get<APIResponse<{ enabled: boolean; default_action: 'ACCEPT' | 'DROP'; rules: FirewallRule[] }>>(`/containers/${id}/firewall`)
|
||||
|
||||
export const updateFirewall = (id: ContainerIdentifier, data: { enabled?: boolean; default_action?: 'ACCEPT' | 'DROP'; rules?: FirewallRule[] }) =>
|
||||
api.put<APIResponse<{ enabled: boolean; default_action: 'ACCEPT' | 'DROP'; rules: FirewallRule[] }>>(`/containers/${id}/firewall`, data)
|
||||
|
||||
export const updateContainerExpiry = (id: ContainerIdentifier, expiresAt: string) =>
|
||||
api.put<APIResponse>(`/containers/${id}/expiry`, { expires_at: expiresAt })
|
||||
|
||||
|
||||
@@ -92,6 +92,22 @@ const exact: Record<string, string> = {
|
||||
'创建时间': 'Created At',
|
||||
'网络速率': 'Network Speed',
|
||||
'IO 速度': 'IO Speed',
|
||||
'下行带宽': 'Download Bandwidth',
|
||||
'上行带宽': 'Upload Bandwidth',
|
||||
'读取 IO': 'Read IO',
|
||||
'写入 IO': 'Write IO',
|
||||
'下行带宽 (Mbps)': 'Download Bandwidth (Mbps)',
|
||||
'上行带宽 (Mbps)': 'Upload Bandwidth (Mbps)',
|
||||
'读取 IO (MB/s)': 'Read IO (MB/s)',
|
||||
'写入 IO (MB/s)': 'Write IO (MB/s)',
|
||||
'下行带宽 (Mbps,0=不限制)': 'Download Bandwidth (Mbps, 0=unlimited)',
|
||||
'上行带宽 (Mbps,0=不限制)': 'Upload Bandwidth (Mbps, 0=unlimited)',
|
||||
'读取 IO (MB/s,0=不限制)': 'Read IO (MB/s, 0=unlimited)',
|
||||
'写入 IO (MB/s,0=不限制)': 'Write IO (MB/s, 0=unlimited)',
|
||||
'限速占用': 'Limit Usage',
|
||||
'支持独立限制上行/下行带宽和读/写 I/O 操作。': 'Supports independent upload/download bandwidth limits and read/write I/O limits.',
|
||||
'支持独立限制上行/下行带宽和读/写 I/O 操作。network_bw_mbps 与 io_speed_mbps 为旧版对称限制兼容别名,建议新对接使用 network_down_mbps、network_up_mbps、io_read_mbps、io_write_mbps。': 'Supports independent upload/download bandwidth limits and read/write I/O limits. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases. New integrations should use network_down_mbps, network_up_mbps, io_read_mbps, and io_write_mbps.',
|
||||
'支持独立限制下行/上行带宽和读取/写入 I/O。未传字段保持原值,显式传 0 表示该方向不限速;network_bw_mbps 与 io_speed_mbps 为旧版对称限制兼容别名。': 'Supports independent download/upload bandwidth limits and read/write I/O limits. Omitted fields keep their current values, and explicitly passing 0 makes that direction unlimited. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases.',
|
||||
'月流量': 'Monthly Traffic',
|
||||
'统计信息': 'Statistics',
|
||||
'CPU 使用率': 'CPU Usage',
|
||||
@@ -578,7 +594,11 @@ const exact: Record<string, string> = {
|
||||
'更新 Key': 'Update Key',
|
||||
'删除 Key': 'Delete Key',
|
||||
'总览': 'Overview',
|
||||
'NAT/IPv4/IPv6 路由': 'NAT / IPv4 / IPv6 Routing',
|
||||
'NAT/IPv6 路由': 'NAT / IPv6 Routing',
|
||||
'更新公网 IPv4/IPv6 池': 'Update Public IPv4 / IPv6 Pools',
|
||||
'扫描公网 IPv4 段': 'Scan Public IPv4 Prefixes',
|
||||
'公网 IPv4/IPv6 池': 'Public IPv4 / IPv6 Pools',
|
||||
'任务队列': 'Task Queue',
|
||||
'任务列表': 'Task List',
|
||||
'操作记录': 'audit records',
|
||||
@@ -588,6 +608,7 @@ const exact: Record<string, string> = {
|
||||
'管理员接口': 'Admin API',
|
||||
'控制面板统计': 'Dashboard Stats',
|
||||
'立即安全检查': 'Run Security Check',
|
||||
'路由配置': 'Routing Configuration',
|
||||
'返回响应样例': 'Response Example',
|
||||
'请求参数': 'Request Parameters',
|
||||
'响应字段': 'Response Fields',
|
||||
@@ -616,11 +637,14 @@ const exact: Record<string, string> = {
|
||||
'添加端口映射': 'Add Port Mapping',
|
||||
'更新端口映射': 'Update Port Mapping',
|
||||
'删除端口映射': 'Delete Port Mapping',
|
||||
'获取防火墙设置': 'Get Firewall Settings',
|
||||
'更新防火墙设置': 'Update Firewall Settings',
|
||||
'快照总览': 'Snapshot Overview',
|
||||
'容器快照': 'Container Snapshots',
|
||||
'计划快照': 'Scheduled Snapshots',
|
||||
'快照配额': 'Snapshot Quota',
|
||||
'模板列表': 'Template List',
|
||||
'镜像管理列表': 'Image Management List',
|
||||
'取消镜像下载': 'Cancel Image Download',
|
||||
'启用/禁用镜像': 'Enable / Disable Image',
|
||||
'安全连接日志': 'Security Connection Logs',
|
||||
@@ -648,9 +672,8 @@ const exact: Record<string, string> = {
|
||||
'删除容器': 'Delete Container',
|
||||
'WebSSH 票据': 'WebSSH Ticket',
|
||||
'WebVNC 票据': 'WebVNC Ticket',
|
||||
'容器列表(兼容旧接口)': 'Container List (legacy-compatible API)',
|
||||
'容器列表(兼容 POST 写法)': 'Container List (compatible POST form)',
|
||||
'调整到期时间': 'Adjust Expiration Time',
|
||||
'镜像管理列表': 'Image Management List',
|
||||
'批量创建容器': 'Batch Create Containers',
|
||||
'创建 WebSSH 票据': 'Create WebSSH Ticket',
|
||||
'创建 WebVNC 票据': 'Create WebVNC Ticket',
|
||||
@@ -677,6 +700,12 @@ const exact: Record<string, string> = {
|
||||
'CI/CD、计费系统、自动化脚本': 'CI/CD, billing systems, automation scripts',
|
||||
'SWAP 已调整为 16384 MB': 'SWAP adjusted to 16384 MB',
|
||||
'***60秒有效票据***': '***60-second valid ticket***',
|
||||
'Linux 创建支持 ssh_auth_mode=auto_password|password|key;公网 IPv4、IPv6 与 NAT 可通过 assign_nat、assign_ipv4、assign_ipv6 组合使用。': 'Linux container creation supports ssh_auth_mode=auto_password|password|key. Public IPv4, IPv6, and NAT can be configured with assign_nat, assign_ipv4, and assign_ipv6.',
|
||||
'重装支持 ssh_auth_mode=keep|auto_password|password|key;keep 仅用于重装,未传 SSH 字段时保持原有行为。': 'Reinstall supports ssh_auth_mode=keep|auto_password|password|key. keep is only for reinstall requests; if SSH fields are omitted, the existing behavior is kept.',
|
||||
'批量创建的单个 containers[] 项支持与 POST /api/v1/containers 相同的网络和 SSH 认证字段。': 'Each containers[] item in batch creation supports the same network and SSH authentication fields as POST /api/v1/containers.',
|
||||
'action=reinstall 时可追加 template_id、ssh_auth_mode、ssh_password、ssh_public_key;其他 action 会忽略这些重装字段。': 'When action=reinstall, you can include template_id, ssh_auth_mode, ssh_password, and ssh_public_key. Other actions ignore these reinstall fields.',
|
||||
'更新公网地址池需要 routing:write;已分配给容器的地址不能从池中移除。': 'Updating public address pools requires routing:write. Addresses already assigned to containers cannot be removed from the pool.',
|
||||
'扫描公网 IPv4 段需要 routing:write;verify=true 时会尝试校验地址可用性。': 'Scanning public IPv4 prefixes requires routing:write. When verify=true, the API also attempts to check address availability.',
|
||||
'WebVNC 仅适用于 KVM 虚拟机;LXC 容器会返回 VNC console is only available for KVM VMs。': 'WebVNC only applies to KVM VMs; LXC containers return "VNC console is only available for KVM VMs".',
|
||||
'该接口会进入任务队列,请随后调用 GET /api/v1/tasks 查看执行状态。': 'This API enters the task queue. Call GET /api/v1/tasks afterward to check execution status.',
|
||||
'样例中的密钥、密码和票据已脱敏;创建类接口的完整密钥只在创建响应中出现一次。': 'Keys, passwords, and tickets in examples are masked. Full secrets from create APIs appear only once in the creation response.',
|
||||
@@ -788,6 +817,75 @@ const exact: Record<string, string> = {
|
||||
'50 / 页': '50 / page',
|
||||
'全局快照列表,共': 'Global snapshot list, total',
|
||||
'容器分配的子用户列表,共': 'Sub-user list assigned to containers, total',
|
||||
'防火墙': 'Firewall',
|
||||
'防火墙设置': 'Firewall Settings',
|
||||
'独立 IPv4': 'Dedicated IPv4',
|
||||
'添加规则': 'Add Rule',
|
||||
'启用后默认拒绝所有入站和出站流量,仅放行下方规则': 'When enabled, all inbound and outbound traffic is blocked by default. Only the rules below are allowed.',
|
||||
'已启用,未匹配规则的流量将被拒绝': 'Enabled. Traffic that does not match a rule will be denied.',
|
||||
'已启用,未匹配规则的流量将被放行': 'Enabled. Traffic that does not match a rule will be allowed.',
|
||||
'未启用时不接管该容器流量': 'Disabled. Container traffic is not managed by this firewall.',
|
||||
'默认动作': 'Default Action',
|
||||
'没有命中下方规则时如何处理': 'How to handle traffic that does not match the rules below',
|
||||
'未匹配拒绝': 'Deny unmatched',
|
||||
'未匹配放行': 'Allow unmatched',
|
||||
'网络范围': 'Network Scope',
|
||||
'可配置:': 'Configurable: ',
|
||||
'可配置:IPv4(公网 IPv4)。 IPv4 规则覆盖独立公网 IPv4。': 'Configurable: IPv4 (Public IPv4). IPv4 rules apply to the dedicated public IPv4.',
|
||||
'可配置:IPv4(NAT)。 IPv4 规则覆盖IPv4 NAT 端口映射。 NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。': 'Configurable: IPv4 (NAT). IPv4 rules apply to IPv4 NAT port mappings. NAT inbound ports are matched by the container internal port, not the host public port.',
|
||||
'可配置:IPv6。 IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'Configurable: IPv6. IPv6 rules apply to the IPv6 addresses assigned to this container.',
|
||||
'可配置:IPv4(公网 IPv4)、IPv6。 IPv4 规则覆盖独立公网 IPv4。 IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'Configurable: IPv4 (Public IPv4), IPv6. IPv4 rules apply to the dedicated public IPv4. IPv6 rules apply to the IPv6 addresses assigned to this container.',
|
||||
'可配置:IPv4(NAT)、IPv6。 IPv4 规则覆盖IPv4 NAT 端口映射。 NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。 IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'Configurable: IPv4 (NAT), IPv6. IPv4 rules apply to IPv4 NAT port mappings. NAT inbound ports are matched by the container internal port, not the host public port. IPv6 rules apply to the IPv6 addresses assigned to this container.',
|
||||
'当前容器未分配 IPv4 NAT、独立公网 IPv4 或 IPv6,暂无可配置网络。': 'This container has no IPv4 NAT, dedicated public IPv4, or IPv6 assigned, so no firewall network can be configured.',
|
||||
'当前容器没有可配置的 NAT、公网 IPv4 或 IPv6': 'This container has no configurable NAT, public IPv4, or IPv6',
|
||||
'当前容器没有可配置网络': 'This container has no configurable network',
|
||||
'IPv4 规则覆盖独立公网 IPv4。': 'IPv4 rules apply to the dedicated public IPv4.',
|
||||
'IPv4 规则覆盖IPv4 NAT 端口映射。': 'IPv4 rules apply to IPv4 NAT port mappings.',
|
||||
'NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。': 'NAT inbound ports are matched by the container internal port, not the host public port.',
|
||||
'IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'IPv6 rules apply to the IPv6 addresses assigned to this container.',
|
||||
'IPv4(公网 IPv4)': 'IPv4 (Public IPv4)',
|
||||
'IPv4(NAT)': 'IPv4 (NAT)',
|
||||
'全部网络': 'All Networks',
|
||||
'方向': 'Direction',
|
||||
'网络': 'Network',
|
||||
'来源/目标 IP': 'Source / Destination IP',
|
||||
'动作': 'Action',
|
||||
'入站': 'Inbound',
|
||||
'出站': 'Outbound',
|
||||
'任意': 'Any',
|
||||
'放行': 'Allow',
|
||||
'拒绝': 'Deny',
|
||||
'暂无防火墙规则': 'No firewall rules',
|
||||
'防火墙设置已保存并应用': 'Firewall settings saved and applied',
|
||||
'保存防火墙设置失败': 'Failed to save firewall settings',
|
||||
'编辑规则': 'Edit Rule',
|
||||
'入站 (Inbound)': 'Inbound',
|
||||
'出站 (Outbound)': 'Outbound',
|
||||
'留空为全部端口,支持: 22 | 80,443 | 8000-9000': 'Leave empty for all ports. Supports: 22 | 80,443 | 8000-9000',
|
||||
'入站填容器服务端口;留空为全部端口,支持: 22 | 80,443 | 8000-9000': 'For inbound rules, enter the container service port. Leave empty for all ports. Supports: 22 | 80,443 | 8000-9000',
|
||||
'出站填远端目标端口;留空为全部端口,支持: 22 | 80,443 | 8000-9000': 'For outbound rules, enter the remote destination port. Leave empty for all ports. Supports: 22 | 80,443 | 8000-9000',
|
||||
'NAT 入站填容器内部端口,例如公网 22023 -> 容器 22,这里填 22': 'For NAT inbound rules, enter the container internal port. For example, public 22023 -> container 22 means enter 22 here.',
|
||||
'端口仅适用于 TCP/UDP': 'Ports only apply to TCP/UDP',
|
||||
'如: 22 或 80,443 或 8000-9000': 'e.g. 22 or 80,443 or 8000-9000',
|
||||
'当前协议不使用端口': 'This protocol does not use ports',
|
||||
'来源 IP': 'Source IP',
|
||||
'目标 IP': 'Destination IP',
|
||||
'留空为任意 IP,支持 CIDR: 192.168.1.0/24': 'Leave empty for any IP. Supports CIDR: 192.168.1.0/24',
|
||||
'留空为任意 IPv4,支持 CIDR: 192.168.1.0/24': 'Leave empty for any IPv4. Supports CIDR: 192.168.1.0/24',
|
||||
'留空为任意 IPv6,支持 CIDR: 2001:db8::/64': 'Leave empty for any IPv6. Supports CIDR: 2001:db8::/64',
|
||||
'留空为任意 IP,支持 IPv4/IPv6 CIDR': 'Leave empty for any IP. Supports IPv4/IPv6 CIDR',
|
||||
'如: 192.168.1.0/24': 'e.g. 192.168.1.0/24',
|
||||
'如: 2001:db8::/64': 'e.g. 2001:db8::/64',
|
||||
'如: 192.168.1.0/24 或 2001:db8::/64': 'e.g. 192.168.1.0/24 or 2001:db8::/64',
|
||||
'放行 (ACCEPT)': 'Allow (ACCEPT)',
|
||||
'拒绝 (DROP)': 'Deny (DROP)',
|
||||
'规则描述': 'Rule description',
|
||||
'兼容旧请求:default_action 可不传,不传时保留现有策略;rule.network 可不传,不传按 ipv4 处理。default_action: DROP=未命中规则时拒绝, ACCEPT=未命中规则时放行。network: ipv4=IPv4 NAT/公网 IPv4, ipv6=IPv6, all=同时应用到 IPv4 和 IPv6。NAT 入站规则的 port 填容器内端口,不是宿主机公网端口。': 'Backward compatible: default_action is optional; if omitted, the existing policy is kept. rule.network is optional; if omitted, it is treated as ipv4. default_action: DROP=deny unmatched traffic, ACCEPT=allow unmatched traffic. network: ipv4=IPv4 NAT/public IPv4, ipv6=IPv6, all=apply to both IPv4 and IPv6. For NAT inbound rules, port is the container internal port, not the host public port.',
|
||||
'登录方式': 'SSH Auth Method',
|
||||
'保留当前密码': 'Keep current password',
|
||||
'生成新密码': 'Generate new password',
|
||||
'自定义密码': 'Custom password',
|
||||
'生成密码': 'Generate password',
|
||||
}
|
||||
|
||||
const artifactPatterns: RegExp[] = [
|
||||
@@ -829,7 +927,6 @@ const replacements: Array<[RegExp, string]> = [
|
||||
[/拍摄快照需要先关机,完成后会自动重启容器\s*(.+?)。是否继续?/g, 'Taking a snapshot requires shutdown first. Container $1 will restart automatically afterward. Continue?'],
|
||||
[/确定删除\s*(.+?)\s*的快照吗?/g, 'Delete snapshot $1?'],
|
||||
[/确定恢复到\s*(.+?)\s*的快照吗?当前容器数据会被覆盖。/g, 'Restore to snapshot $1? Current container data will be overwritten.'],
|
||||
[/旧版\s*\/api\/containers\/list\s*已兼容,但新接入请使用\s*GET\s*\/api\/v1\/containers/g, 'Legacy /api/containers/list remains compatible, but new integrations should use GET /api/v1/containers'],
|
||||
[/到期\s*(.+)$/g, 'Expires $1'],
|
||||
[/支持\s*\((.+?)\)/g, 'Supported ($1)'],
|
||||
[/下载中\s*(.+)$/g, 'Downloading $1'],
|
||||
@@ -854,6 +951,7 @@ const replacements: Array<[RegExp, string]> = [
|
||||
[/搜索\s*"([^"]+)"\s*结果\s*(\d+)\s*个地址/g, 'Search "$1" returned $2 addresses, '],
|
||||
[/(\d+)\s*个/g, '$1 items'],
|
||||
[/(\d+)\s*条/g, '$1 records'],
|
||||
[/1\s*核\b/g, '1 core'],
|
||||
[/(\d+)\s*核/g, '$1 cores'],
|
||||
[/(\d+)\s*线程/g, '$1 threads'],
|
||||
[/已用/g, 'used'],
|
||||
@@ -874,7 +972,12 @@ const replacements: Array<[RegExp, string]> = [
|
||||
[/当前证书:/g, 'Current certificate: '],
|
||||
[/第\s*(\d+)\s*页/g, 'Page $1'],
|
||||
[/入\s*([^/,]+)\s*\/\s*出\s*([^,]+),累计\s*(.+)$/g, 'In $1 / Out $2, total $3'],
|
||||
[/入\s*([^/,]+)\s*\/\s*出\s*([^,]+),限速占用\s*([^,]+),累计\s*(.+)$/g, 'In $1 / Out $2, limit usage $3, total $4'],
|
||||
[/下\s*([^/]+)\s*\/\s*上\s*(.+)$/g, 'Down $1 / Up $2'],
|
||||
[/下行\s*([^/]+)\s*\/\s*上行\s*(.+)$/g, 'Download $1 / Upload $2'],
|
||||
[/读取\s*([^/]+)\s*\/\s*写入\s*(.+)$/g, 'Read $1 / Write $2'],
|
||||
[/读\s*([^/,]+)\s*\/\s*写\s*([^,]+),累计\s*([^,]+),容量\s*(.+)$/g, 'Read $1 / Write $2, total $3, capacity $4'],
|
||||
[/读\s*([^/,]+)\s*\/\s*写\s*([^,]+),限速占用\s*([^,]+),累计\s*([^,]+),容量\s*(.+)$/g, 'Read $1 / Write $2, limit usage $3, total $4, capacity $5'],
|
||||
[/(.+?),筛选后\s*(\d+)\s*items/g, '$1, filtered $2 items'],
|
||||
[/(.+?),已选\s*(\d+)\s*items/g, '$1, selected $2 items'],
|
||||
[/将创建\s*(\d+)\s*个容器:(.+?)\s*至\s*(.+)$/g, 'Will create $1 containers: $2 to $3'],
|
||||
|
||||
|
Before Width: | Height: | Size: 130 KiB After Width: | Height: | Size: 179 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 110 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 159 KiB |