飞牛docker容器管理增强版 v3:应用看板 / 优化建议 / 未启动应用 / 一键安装
This commit is contained in:
commit
aeb7f91502
11 files changed
+2404
No files matched your search
@@ -0,0 +1,4 @@
|
||||
data/
|
||||
node_modules/
|
||||
.env
|
||||
*.log
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
# 更新日志
|
||||
|
||||
## 2026-10-26 → 🐛 左侧「停止的容器」计数补上未启动应用
|
||||
|
||||
- 🐛 菜单徽章原来只统计「已停止的容器」,全都跑着时显示 0,明明页面上有 14 个未启动应用 → 现在徽章 = 已停止容器 + 有镜像未启动的应用
|
||||
- ✨ 徽章加悬停说明:`已停止容器 0 个 · 有镜像未启动的应用 14 个`,一眼看清来源
|
||||
- 🔧 `/api/host` 增加 `pending` 字段(沿用 20 秒扫描缓存,不额外压 Docker)
|
||||
|
||||
## 2026-10-26 → ✨ 停止的容器页显示「有镜像但未启动的应用」
|
||||
|
||||
- ✨ 新增扫描:遍历 `COMPOSE_ROOT`(默认 `/vol1/1000/HD1/docker`)下的 compose 文件,找出**一个容器都没有、但本地已有镜像**的项目
|
||||
- ✨ 停止的容器页顶部新增「有镜像但未启动的应用」卡片网格:项目名、服务数、compose 相对路径、镜像就绪情况(缺哪些、启动时自动拉取)
|
||||
- ✨ **一键启动**:直接执行 `docker compose -f <file> up -d`,完成后项目自动从该列表消失并出现在容器页
|
||||
- ✨ 「命令」按钮可看到对应的宿主机命令,方便自己排查
|
||||
- 🔧 容器存在性判断同时看 compose 项目标签和容器名,避免同名单容器项目被重复列出
|
||||
- 🔧 容器镜像里加了 `docker-cli` + `docker-cli-compose`,并把 docker 根目录**同路径**挂载进容器,保证 compose 里的 `./data` 之类相对路径与宿主机一致
|
||||
- 🐛 项目名不合法(如以下划线开头)时 compose 会报 `invalid project name`,改为仅在名称合法时才设置 `COMPOSE_PROJECT_NAME`
|
||||
- 🐛 启动接口会强制重扫,避免新建项目被 20 秒缓存挡掉而报「未找到该项目」
|
||||
|
||||
## 2026-10-26 → ✨ 显示每个应用的运行时长
|
||||
|
||||
- ✨ 应用卡片底部新增「已运行 1 天 3 小时 / 刚刚启动 / 未运行」
|
||||
- ✨ 应用详情页统计条新增「运行时长」
|
||||
- ✨ 容器表格的运行时长统一格式(如 `2 天 5 小时`、`38 分钟`),原来只显示粗略的「x 天前」
|
||||
- 🔧 应用运行时长取该应用**最早启动的运行中容器**(不是最晚),停止的容器不参与计算,避免旧容器把时长算长
|
||||
- 🔧 卡片高度保持一致,实测 50 张卡片均为 206px,时长文本无溢出
|
||||
|
||||
## 2026-10-26 → ✨ 首页「优化建议」(自动分析 + 一键处理)
|
||||
|
||||
- ✨ 首页统计条下新增**优化建议**面板,按当前真实运行状态自动生成,标注高 / 中 / 低并统计条数
|
||||
- ✨ 规则集(10 类):
|
||||
- 高:特权容器(privileged)、容器反复重启(≥3 次)、磁盘可用低于 10%
|
||||
- 中:挂载 docker.sock、内存接近上限(>85%)、CPU 偏高(>60%)、内存无上限且合计 >1GB、悬空镜像 >1GB、构建缓存 >5GB、应用已停止
|
||||
- 低:对外容器无健康检查、使用 latest 镜像、未纳入 Compose 管理
|
||||
- ✨ 汇总类问题合并成单条(如「31 个应用使用 latest 镜像」并列出涉及的应用),避免刷屏:本机实测 57 条压缩为 **10 条**
|
||||
- ✨ 一键处理:清理悬空镜像、清理构建缓存、启动已停止应用;其余条目可直接「查看」跳到对应应用
|
||||
- ✨ 超过 4 条折叠,点「展开全部 N 条建议」展开;展开状态在轮询刷新中保持
|
||||
- 🔧 每条建议加左侧风险色条、8px 圆点,扫读更快
|
||||
- 🐛 新增容器级对外端口数字段(健康检查规则原先因缺失该字段而永不触发)
|
||||
|
||||
## 2026-10-26 → 🔧 顶栏控件重叠修复 + 刷新间隔可设置
|
||||
|
||||
- 🔧 排序下拉的展开箭头与「↓」按钮贴在一起(视觉上像重叠):下拉改为自绘箭头并留右边距,升降序按钮拆成独立的「降序 ↓ / 升序 ↑」文字按钮,间距从 6px 增加到 17px
|
||||
- ✨ 新增**刷新间隔**设置(1/2/3/5/10/30 秒,默认 3 秒),保存在浏览器本地,切换后立即生效
|
||||
- 🐛 顶栏控件在 1280 / 1100 / 900 三种宽度下逐一检测,无任何元素重叠
|
||||
- 🔧 容器页页脚改为显示当前实际刷新间隔
|
||||
|
||||
## 2026-10-26 → 🚀 v2:面向多应用用户的健康看板与告警
|
||||
|
||||
- ✨ **应用聚合**:按 Compose 项目把容器合成「应用」(61 容器 → 50 应用),单容器自成应用
|
||||
- ✨ **应用健康看板**(默认首屏):应用总数/异常/注意/资源/运行容器统计条;筛选(全部/有问题/已停止/高占用)
|
||||
- ✨ **异常优先排序**:默认按「异常 → 注意 → 资源占用」排序,坏的应用永远在最前面
|
||||
- ✨ **健康判定**:部分容器未运行(红)、健康检查失败(红)、应用整体停止(黄)、健康检查中(黄)、CPU/内存超阈值(黄)、重启次数增加(事件)
|
||||
- ✨ **应用详情页**:应用级指标 + 全部容器表格 + 三个标签页(容器 / 聚合日志 / 事件),支持整应用启停重启
|
||||
- ✨ **聚合日志**:一个应用下所有容器日志按容器名加前缀合并展示
|
||||
- ✨ **事件时间线**:状态变化、重启、恢复都记录,保留 400 条
|
||||
- ✨ **可用率统计**:每分钟采样,卡片显示 24 小时窗口可用率
|
||||
- ✨ **告警推送**:可配置 CPU/内存阈值、Webhook、推送间隔,支持测试推送;同一应用按间隔去重
|
||||
- ✨ **告警设置页**:阈值、Webhook、开关、测试、事件查看
|
||||
- ✨ 端口徽章:应用卡片上直接点端口打开对应 Web UI
|
||||
|
||||
### 🐛 修复
|
||||
|
||||
- 🐛 应用详情页被 4 秒轮询覆盖回看板(详情改为独立视图状态 `app-detail`)
|
||||
- 🐛 「一上线就异常」的应用不产生事件(首次发现异常时补记一条)
|
||||
|
||||
## 2026-10-26 → 🔧 去掉 Compose,改为「停止的容器」独立页
|
||||
|
||||
- 🔧 移除 Compose 页面(导航项与 `/api/compose` 接口一并删除)
|
||||
- ✨ 新增「停止的容器」导航页,单独列出已停止/退出的容器,导航带数量角标
|
||||
- 🔧 容器页只显示运行中容器,移除「显示已停止」勾选框
|
||||
- 🎨 停止的容器行隐藏 CPU/内存进度条、图标底色变灰,操作按钮只保留「启动 / 删除 / 详情」
|
||||
|
||||
## 2026-10-26 → 🎨 更名为「飞牛docker容器管理增强版」
|
||||
|
||||
- 🎨 应用显示名改为「飞牛docker容器管理增强版」(浏览器标题 + 侧栏品牌)
|
||||
- 🎨 侧栏宽度 208→226px、品牌字号 12.5px 并锁单行,避免长名称把「增强版」拆到第二行
|
||||
- 🐛 布局修复:超长容器名/项目名曾横向溢出压到 CPU、内存数值,改为名称行省略号截断(悬停看全名),状态文字并入名称行第二行
|
||||
- 🐛 布局修复:带「打开端口」图标的那几行状态文字被截断;现所有行固定 70px 高、CPU 列 x 坐标完全一致(实测 61 行无位移)
|
||||
|
||||
## 2026-10-26 → ✨ 首发
|
||||
|
||||
- ✨ 仿飞牛 Docker 面板的容器管理应用(Node 22 + Express + dockerode),端口 7030
|
||||
- ✨ 容器列表按卡片行展示:状态点、名称、Compose 项目、CPU、内存、网络 ↑↓、磁盘 IO、运行状态
|
||||
- ✨ 资源排序:CPU / 内存 / 网络速率 / 磁盘 IO / 进程数 / 名称,默认 **CPU 降序(占用高的在最前)**,可一键切换升降序
|
||||
- ✨ 搜索(容器名 / 镜像 / 项目)与「显示已停止」开关
|
||||
- ✨ 容器详情抽屉:CPU、内存(含上限与占比)、网络速率与累计、磁盘读写与累计、进程数、重启策略、健康状态
|
||||
- ✨ 三条实时曲线(CPU / 内存 / 网络,约 12 分钟窗口,每 3 秒采样)
|
||||
- ✨ 日志查看:tail 拉取 + SSE 实时跟随,支持自定义行数
|
||||
- ✨ 环境变量、挂载、网络详情
|
||||
- ✨ 容器操作:启动 / 停止 / 重启 / 暂停 / 恢复 / 删除(不删卷)/ 一键打开映射端口
|
||||
- ✨ 新建容器:镜像、名称、端口映射、环境变量、挂载、重启策略(自动拉取镜像)
|
||||
- ✨ 概览页:CPU 负载、内存、Swap、/vol1 磁盘、容器数,以及 CPU/内存占用 TOP 8
|
||||
- ✨ Compose 页:按项目归组,显示合计 CPU/内存,支持整组启动/重启/停止
|
||||
- ✨ 本地镜像页:按大小排序、删除、清理悬空镜像
|
||||
- ✨ 镜像仓库页:流式输出拉取进度
|
||||
- ✨ 网络页:名称/驱动/子网/网关/容器数
|
||||
|
||||
### 🐛 修复
|
||||
|
||||
- 🐛 排序方向错误:`desc` 实际按升序返回(最高占用排到最后),改为比较器统一降序 + `dir` 取反
|
||||
- 🐛 日志接口 120 秒超时:Docker 日志多路复用流用 `demuxStream` 解不出内容,改手动按 8 字节头解帧
|
||||
- 🐛 CPU 进度条刻度错误:原按单核百分比绘制,6 核机器几乎不可见,改为按整机核数归一
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
FROM node:22-alpine
|
||||
RUN apk add --no-cache tzdata docker-cli docker-cli-compose
|
||||
WORKDIR /app
|
||||
COPY package.json ./
|
||||
RUN npm install --omit=dev --registry=https://registry.npmmirror.com && npm cache clean --force
|
||||
COPY server ./server
|
||||
COPY public ./public
|
||||
ENV TZ=Asia/Shanghai PORT=7030
|
||||
EXPOSE 7030
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD wget -qO- http://127.0.0.1:7030/api/health || exit 1
|
||||
CMD ["node", "server/index.js"]
|
||||
@@ -0,0 +1,135 @@
|
||||
# 飞牛docker容器管理增强版(docker-center)
|
||||
|
||||
面向**多应用用户**的 Docker 管理与监控面板。核心不是「一堆容器」,而是把容器按 **应用(Compose 项目 / 单容器)** 聚合:一眼看哪个应用坏了、占用多少、怎么一键恢复。
|
||||
|
||||
- 地址:http://192.168.68.19:7030
|
||||
- 目录:`/vol1/1000/HD1/docker/docker-center`
|
||||
- 端口:7030,`restart: always`,内存上限 384MB(实测 ~40MB)
|
||||
|
||||
## 安装(新用户)
|
||||
|
||||
前置:Linux/飞牛 NAS 上已装 Docker 与 compose 插件(`docker compose version` 能跑)、有 `git`。
|
||||
|
||||
```bash
|
||||
curl -fsSL http://192.168.68.19:3200/jinghui/docker-center/raw/branch/main/install.sh | bash
|
||||
```
|
||||
|
||||
脚本做的事:检查环境 → 自动探测 docker 目录 → 拉源码到安装目录 → 写 `.env` → `docker compose up -d --build` → 等健康检查通过 → 打印访问地址。
|
||||
|
||||
可覆盖参数(写在 `curl` 前面):
|
||||
|
||||
```bash
|
||||
PORT=8080 \
|
||||
COMPOSE_ROOT=/你的/docker目录 \
|
||||
INSTALL_DIR=/opt/docker-center \
|
||||
bash install.sh
|
||||
```
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `PORT` | `7030` | 面板访问端口 |
|
||||
| `COMPOSE_ROOT` | 自动探测(飞牛 `/vol1/1000/HD1/docker`,其次 `~/docker`) | 扫描 compose 文件、判断「未启动应用」的根目录 |
|
||||
| `INSTALL_DIR` | `/vol1/1000/HD1/docker/docker-center` | 源码与数据目录 |
|
||||
| `CONTAINER_NAME` | `docker-center` | 容器名 |
|
||||
| `REPO_URL` | 本机 Gitea 仓库地址 | 换源时用 |
|
||||
|
||||
升级:再跑一次同一条命令即可(检测到已有仓库会 `fetch` + `reset --hard` 后重建)。
|
||||
|
||||
卸载:`cd <安装目录> && docker compose down -v && cd .. && rm -rf <安装目录>`。
|
||||
|
||||
> 安全提示:面板挂载了 `/var/run/docker.sock`(等同宿主 root),**不要直接暴露公网**,放在内网或前面套一层带鉴权的反代。
|
||||
|
||||
## 为什么按「应用」而不是「容器」管
|
||||
|
||||
61 个容器里其实只有 50 个应用(app + db + redis 属于同一个项目)。按容器管要逐个点,按应用管只需看:
|
||||
|
||||
- 这个应用**整体**是否健康(部分容器挂了会标红,而不是淹没在列表里)
|
||||
- 它总共吃多少 CPU/内存、占了哪些端口
|
||||
- 一键启动/停止/重启**整个应用**
|
||||
- 出问题时有一条事件、一份合并日志
|
||||
|
||||
## 页面
|
||||
|
||||
| 页面 | 内容 |
|
||||
|---|---|
|
||||
| 应用(默认) | 健康看板:应用总数/异常/注意/资源/运行容器;筛选(全部·有问题·已停止·高占用);应用卡片(状态胶囊、CPU 占整机、内存、网络、端口、**已运行时长**、可用率、重启次数、问题摘要);卡片内直接启停重启;底部最近事件时间线。**排序默认「异常优先」**,其次按资源占用 |
|
||||
| 应用详情 | 应用级指标 + 全部容器表格(状态/健康/CPU/内存/网络/重启/运行时长/单容器操作)+ 三个标签页:容器、聚合日志(多容器合并、按容器名加前缀)、事件;顶部可整应用启停重启 |
|
||||
| 容器 | 只列运行中容器,可排序(CPU/内存/网络/磁盘IO/进程数/名称)、搜索;行内启停/重启/删除/详情/打开端口 |
|
||||
| 停止的容器 | 两个部分:**有镜像但未启动的应用**(compose 项目存在、本地有镜像、但一个容器都没有,可一键 `docker compose up -d`)+ 已停止/退出的容器(只保留启动/删除/详情) |
|
||||
| 本地镜像 | 按大小排序、删除、清理悬空镜像 |
|
||||
| 镜像仓库 | 拉取镜像(流式进度) |
|
||||
| 网络 | 名称/驱动/子网/网关/容器数 |
|
||||
| 告警设置 | CPU/内存阈值、推送间隔、Webhook、开关、测试推送、查看事件 |
|
||||
|
||||
顶栏工具条:搜索、排序字段、升/降序切换、**刷新间隔(1/2/3/5/10/30 秒,默认 3 秒,存浏览器本地)**、手动刷新、添加容器。后端采样固定 3 秒,所以设成 1~2 秒只是更勤地读缓存,不会更快拿到新数据。
|
||||
|
||||
## 首页优化建议
|
||||
|
||||
首页统计条下面是一块**优化建议**:服务端根据当前真实状态(容器配置 + 实时占用 + Docker 磁盘)生成,按 高 / 中 / 低 排序,超过 4 条自动折叠。
|
||||
|
||||
| 级别 | 规则 |
|
||||
|---|---|
|
||||
| 高 | 特权容器(privileged);容器重启 ≥3 次;磁盘可用 <10% |
|
||||
| 中 | 挂载 docker.sock;内存占用接近上限(>85%);单容器 CPU >60%;容器未设内存上限且合计 >1GB;悬空镜像 >1GB;构建缓存 >5GB;应用整体已停止 |
|
||||
| 低 | 对外容器没有 HEALTHCHECK;使用 latest 镜像;单容器应用未纳入 Compose |
|
||||
|
||||
- 同类问题会**合并成一条**(例如「31 个应用使用 latest 镜像,涉及 …」),不会一个应用刷一条。
|
||||
- 可一键处理的直接给按钮:**清理悬空镜像**、**清理构建缓存**(都不影响运行中的容器)、**启动已停止应用**;其余给「查看」跳到应用详情自己改 compose。
|
||||
- 建议每次刷新(3 秒)重新计算,但 Docker 磁盘统计缓存 60 秒,避免频繁扫描镜像层。
|
||||
|
||||
## 健康判定规则
|
||||
|
||||
| 级别 | 触发条件 |
|
||||
|---|---|
|
||||
| 异常(红) | 应用里**部分容器未运行**(其余在跑);任一容器健康检查 `unhealthy` |
|
||||
| 注意(黄) | 应用整体已停止;健康检查 `starting`;CPU 占整机超阈值;容器内存占上限超阈值;容器重启次数增加(单独一条事件) |
|
||||
| 正常(绿) | 以上都不满足 |
|
||||
|
||||
- 状态从正常→异常/注意、异常→恢复都会写一条事件;「一上线就异常」的应用首次发现也会补记一条。
|
||||
- 可用率:每分钟记录一次应用是否正常,保留 24 小时,卡片显示窗口内可用率。
|
||||
- 事件保留最近 400 条(内存),重启服务后清空。
|
||||
|
||||
## 告警推送(Webhook)
|
||||
|
||||
在「告警设置」填 Webhook 地址,收到的是 POST JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "[异常] my-app",
|
||||
"level": "critical",
|
||||
"app": "my-app",
|
||||
"detail": "1 个容器未运行(my-app-db)",
|
||||
"time": "2026/10/26 16:43:46",
|
||||
"host": "gzFNos2"
|
||||
}
|
||||
```
|
||||
|
||||
注意两点:
|
||||
1. **容器内的 `127.0.0.1` 是容器自己**,要推给宿主机上的服务请用宿主 LAN IP(如 `http://192.168.68.19:端口/hook`)或 `http://host.docker.internal:端口/hook`(compose 已加 `host-gateway`)。
|
||||
2. 同一应用在 `debounceMinutes`(默认 10 分钟)内只推一条,避免刷屏。
|
||||
|
||||
## 运维
|
||||
|
||||
```bash
|
||||
cd /vol1/1000/HD1/docker/docker-center
|
||||
docker compose up -d --build # 改动后重建
|
||||
docker compose logs -f # 看日志
|
||||
docker compose restart # 重启
|
||||
```
|
||||
|
||||
- 配置持久化:`data/settings.json`(阈值、webhook、开关)
|
||||
- 环境变量:`PORT`、`SAMPLE_MS`(3000)、`INSPECT_MS`(15000)、`DISK_PATH`、`SETTINGS_PATH`
|
||||
|
||||
## 实现要点 / 坑
|
||||
|
||||
- 采样:每 3 秒并行拉一次所有运行中容器的 `stats`;CPU% 用 `cpu_stats`/`precpu_stats` 差值 × 核数;内存扣 `inactive_file`;网络与块设备速率靠相邻采样差分。
|
||||
- 重启次数/健康状态来自 `inspect`,每 15 秒才刷一遍(每 3 秒 inspect 61 个容器太重)。
|
||||
- 日志是 Docker 的 8 字节头多路复用流,用 `demuxLogs` 手动解帧;`modem.demuxStream` 在 follow=false 时会挂住请求。
|
||||
- 排序比较器统一按「降序」写,`order=asc` 时取反,否则会出现 desc 变升序。
|
||||
- 详情页是独立视图状态(`app-detail`),轮询刷新时必须保住它,否则每 4 秒会被看板覆盖。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 曲线与可用率都在内存里,重启服务后重新累积(可用率保留 24 小时窗口)。
|
||||
- 不提供在线改容器配置,改配置请用 Compose 或重建容器。
|
||||
- 应用归属依赖 `com.docker.compose.project` 标签;手工 `docker run` 的容器各自算一个「单容器应用」。
|
||||
@@ -0,0 +1,25 @@
|
||||
services:
|
||||
docker-center:
|
||||
build: .
|
||||
image: docker-center:1.0
|
||||
container_name: ${CONTAINER_NAME:-docker-center}
|
||||
restart: always
|
||||
ports:
|
||||
- "${PORT:-7030}:7030"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- /:/host:ro
|
||||
# 同路径挂载:compose 里的相对路径(./data 等)才能被宿主正确解析
|
||||
- ${COMPOSE_ROOT:-/vol1/1000/HD1/docker}:${COMPOSE_ROOT:-/vol1/1000/HD1/docker}
|
||||
- ./data:/data
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
- PORT=7030
|
||||
- DISK_PATH=/host/vol1
|
||||
- COMPOSE_ROOT=${COMPOSE_ROOT:-/vol1/1000/HD1/docker}
|
||||
- SAMPLE_MS=3000
|
||||
- INSPECT_MS=15000
|
||||
- SETTINGS_PATH=/data/settings.json
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
mem_limit: 384m
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env bash
|
||||
# 飞牛docker容器管理增强版 — 一键安装 / 升级脚本
|
||||
# 用法:
|
||||
# curl -fsSL http://192.168.68.19:3200/jinghui/docker-center/raw/branch/main/install.sh | bash
|
||||
# 可覆盖的环境变量:
|
||||
# PORT=7030 访问端口
|
||||
# COMPOSE_ROOT=... 扫描 compose 文件的 docker 根目录(默认自动探测)
|
||||
# INSTALL_DIR=... 安装目录(默认 /vol1/1000/HD1/docker/docker-center)
|
||||
# CONTAINER_NAME=... 容器名(默认 docker-center)
|
||||
# REPO_URL=... 源码仓库(默认本机 Gitea)
|
||||
set -euo pipefail
|
||||
|
||||
REPO_URL="${REPO_URL:-http://192.168.68.19:3200/jinghui/docker-center}"
|
||||
BRANCH="${BRANCH:-main}"
|
||||
PORT="${PORT:-7030}"
|
||||
CONTAINER_NAME="${CONTAINER_NAME:-docker-center}"
|
||||
INSTALL_DIR="${INSTALL_DIR:-/vol1/1000/HD1/docker/docker-center}"
|
||||
|
||||
say() { printf '\033[36m%s\033[0m\n' "$*"; }
|
||||
ok() { printf '\033[32m%s\033[0m\n' "$*"; }
|
||||
die() { printf '\033[31m%s\033[0m\n' "$*" >&2; exit 1; }
|
||||
|
||||
# ---------- 环境检查 ----------
|
||||
command -v docker >/dev/null 2>&1 || die "未检测到 docker。飞牛 NAS:应用中心 → 安装 Docker;其他系统:https://docs.docker.com/engine/install/"
|
||||
docker compose version >/dev/null 2>&1 || die "缺少 compose 插件(docker compose version 执行失败)。Debian/Ubuntu:apt install docker-compose-plugin"
|
||||
command -v git >/dev/null 2>&1 || die "缺少 git,请先安装:apt install git"
|
||||
|
||||
# ---------- 自动探测 compose 根目录 ----------
|
||||
if [ -z "${COMPOSE_ROOT:-}" ]; then
|
||||
if [ -d /vol1/1000/HD1/docker ]; then
|
||||
COMPOSE_ROOT=/vol1/1000/HD1/docker # 飞牛默认数据盘路径
|
||||
elif [ -d "$HOME/docker" ]; then
|
||||
COMPOSE_ROOT="$HOME/docker"
|
||||
else
|
||||
COMPOSE_ROOT="$(dirname "$INSTALL_DIR")"
|
||||
fi
|
||||
fi
|
||||
[ -d "$COMPOSE_ROOT" ] || die "compose 根目录不存在:$COMPOSE_ROOT(用 COMPOSE_ROOT=/你的/docker目录 指定)"
|
||||
|
||||
say "安装目录 :$INSTALL_DIR"
|
||||
say "compose 根 :$COMPOSE_ROOT"
|
||||
say "端口 :$PORT"
|
||||
say "容器名 :$CONTAINER_NAME"
|
||||
|
||||
# ---------- 拉取 / 更新源码 ----------
|
||||
if [ -d "$INSTALL_DIR/.git" ]; then
|
||||
say "检测到已有安装,更新源码…"
|
||||
git -C "$INSTALL_DIR" fetch --all -q
|
||||
git -C "$INSTALL_DIR" reset --hard "origin/$BRANCH" -q
|
||||
else
|
||||
say "拉取源码…"
|
||||
mkdir -p "$(dirname "$INSTALL_DIR")"
|
||||
git clone -q -b "$BRANCH" "${REPO_URL}.git" "$INSTALL_DIR"
|
||||
fi
|
||||
|
||||
cd "$INSTALL_DIR"
|
||||
mkdir -p data
|
||||
|
||||
# ---------- 写入运行参数 ----------
|
||||
cat > .env <<EOF
|
||||
PORT=$PORT
|
||||
COMPOSE_ROOT=$COMPOSE_ROOT
|
||||
CONTAINER_NAME=$CONTAINER_NAME
|
||||
EOF
|
||||
|
||||
# ---------- 构建并启动 ----------
|
||||
say "构建镜像并启动(首次 1~2 分钟)…"
|
||||
docker compose up -d --build
|
||||
|
||||
say "等待健康检查…"
|
||||
code=""
|
||||
for _ in $(seq 1 60); do
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/api/health" || true)
|
||||
[ "$code" = "200" ] && break
|
||||
sleep 2
|
||||
done
|
||||
[ "$code" = "200" ] || die "健康检查未通过,查看日志:docker logs ${CONTAINER_NAME}"
|
||||
|
||||
IP=$(hostname -I 2>/dev/null | awk '{print $1}')
|
||||
ok "安装完成 → http://${IP:-127.0.0.1}:${PORT}"
|
||||
say "提示:本面板挂载了 docker.sock(等同 root 权限),请勿直接暴露到公网,建议放在内网或加反代鉴权。"
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "docker-center",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "飞牛风格 Docker 容器管理面板(资源占用可排序 + 逐容器详情)",
|
||||
"main": "server/index.js",
|
||||
"scripts": {
|
||||
"start": "node server/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"dockerode": "^4.0.2",
|
||||
"express": "^4.21.2"
|
||||
}
|
||||
}
|
||||
+772
@@ -0,0 +1,772 @@
|
||||
'use strict';
|
||||
|
||||
/* ---------------- 基础 ---------------- */
|
||||
const $ = (s, r = document) => r.querySelector(s);
|
||||
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
|
||||
const state = { view: 'apps', filter: 'all', sort: 'severity', order: 'desc', q: '', timer: null, current: null, currentApp: null, tab: 'stat', appTab: 'containers', insightOpen: false };
|
||||
const REFRESH_KEY = 'dc.refreshMs';
|
||||
state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000));
|
||||
|
||||
const ICONS = {
|
||||
grid: '<path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z"/>',
|
||||
box: '<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z"/><path d="M4 7.5l8 4.5 8-4.5M12 12v9"/>',
|
||||
pause: '<rect x="8" y="5" width="3" height="14" rx="1"/><rect x="13" y="5" width="3" height="14" rx="1"/>',
|
||||
disc: '<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="2.5"/>',
|
||||
repo: '<path d="M4 20V7a3 3 0 013-3h10v16H7a3 3 0 00-3 3z"/><path d="M4 20h13"/>',
|
||||
globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14 0 18"/>',
|
||||
bell: '<path d="M18 9a6 6 0 10-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M10.5 20a2 2 0 003 0"/>',
|
||||
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/>',
|
||||
refresh: '<path d="M20 11a8 8 0 10-2.5 5.7"/><path d="M20 5v6h-6"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
power: '<path d="M12 3v9"/><path d="M7 6a7 7 0 1010 0"/>',
|
||||
restart: '<path d="M4 12a8 8 0 018-8 8 8 0 017 4"/><path d="M20 3v5h-5"/><path d="M20 12a8 8 0 01-8 8 8 8 0 01-7-4"/><path d="M4 21v-5h5"/>',
|
||||
link: '<path d="M10 13a5 5 0 007 0l2-2a5 5 0 00-7-7l-1 1"/><path d="M14 11a5 5 0 00-7 0l-2 2a5 5 0 007 7l1-1"/>',
|
||||
more: '<circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/>',
|
||||
trash: '<path d="M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"/>',
|
||||
back: '<path d="M15 6l-6 6 6 6"/>',
|
||||
};
|
||||
const icon = (n) => `<svg viewBox="0 0 24 24">${ICONS[n] || ''}</svg>`;
|
||||
function paintIcons(root = document) { $$('i[data-ico]', root).forEach(el => { el.outerHTML = icon(el.dataset.ico); }); }
|
||||
|
||||
const fmtBytes = (b) => {
|
||||
if (b === undefined || b === null) return '-';
|
||||
const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0, n = Math.abs(b);
|
||||
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
|
||||
return `${n < 10 && i > 0 ? n.toFixed(2) : Math.round(n * 10) / 10} ${u[i]}`;
|
||||
};
|
||||
const fmtRate = (b) => (b > 0 ? fmtBytes(b) + '/s' : '0 B/s');
|
||||
const fmtPct = (n) => (n >= 10 ? n.toFixed(1) : (n || 0).toFixed(2)) + '%';
|
||||
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const fmtDur = (ms) => {
|
||||
if (ms === null || ms === undefined || !isFinite(ms) || ms < 0) return '—';
|
||||
const s = Math.floor(ms / 1000);
|
||||
const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
|
||||
if (d > 0) return `${d} 天${h ? ' ' + h + ' 小时' : ''}`;
|
||||
if (h > 0) return `${h} 小时${m ? ' ' + m + ' 分' : ''}`;
|
||||
if (m > 0) return `${m} 分钟`;
|
||||
return '不到 1 分钟';
|
||||
};
|
||||
const ago = (iso) => {
|
||||
if (!iso) return '-';
|
||||
const d = (Date.now() - new Date(iso).getTime()) / 1000;
|
||||
if (!isFinite(d) || d < 0) return '-';
|
||||
if (d < 60) return `${Math.round(d)} 秒`;
|
||||
if (d < 3600) return `${Math.round(d / 60)} 分钟`;
|
||||
if (d < 86400) return `${(d / 3600).toFixed(1)} 小时`;
|
||||
return `${Math.floor(d / 86400)} 天`;
|
||||
};
|
||||
const timeStr = (t) => new Date(t).toLocaleString('zh-CN', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||||
|
||||
async function api(url, opts) {
|
||||
const r = await fetch(url, opts);
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(j.error || r.statusText);
|
||||
return j;
|
||||
}
|
||||
function toast(msg, err) {
|
||||
const t = $('#toast'); t.textContent = msg; t.className = 'toast' + (err ? ' err' : '');
|
||||
clearTimeout(t._h); t._h = setTimeout(() => t.classList.add('hidden'), 2600);
|
||||
}
|
||||
|
||||
/* ---------------- 路由 ---------------- */
|
||||
const TITLES = { apps: '应用', containers: '运行的容器', stopped: '停止的容器', images: '本地镜像', registry: '镜像仓库', networks: '网络', settings: '告警设置' };
|
||||
const SORTS = {
|
||||
apps: [['severity', '异常优先'], ['cpu', 'CPU 占用'], ['mem', '内存占用'], ['containers', '容器数'], ['name', '名称']],
|
||||
containers: [['cpu', 'CPU 占用'], ['mem', '内存占用'], ['net', '网络速率'], ['io', '磁盘 IO'], ['pids', '进程数'], ['name', '名称']],
|
||||
stopped: [['name', '名称'], ['mem', '内存占用']],
|
||||
};
|
||||
function go(view) {
|
||||
state.view = view;
|
||||
state.currentApp = null;
|
||||
$$('#nav a').forEach(a => a.classList.toggle('active', a.dataset.view === view));
|
||||
$('#pageTitle').textContent = TITLES[view] || view;
|
||||
const isList = ['apps', 'containers', 'stopped'].includes(view);
|
||||
$('#search').style.display = isList || view === 'images' ? '' : 'none';
|
||||
$('#sortbox').style.display = isList ? '' : 'none';
|
||||
const opts = SORTS[view] || SORTS.containers;
|
||||
if (state.sort && !opts.some(o => o[0] === state.sort)) state.sort = opts[0][0];
|
||||
$('#sort').innerHTML = opts.map(([v, t]) => `<option value="${v}">${t}</option>`).join('');
|
||||
$('#sort').value = state.sort;
|
||||
$('#addBtn').textContent = view === 'registry' ? '拉取镜像' : view === 'images' ? '清理悬空镜像' : '添加容器';
|
||||
clearInterval(state.timer);
|
||||
if ($('#refreshSel')) $('#refreshSel').value = String(state.refreshMs);
|
||||
render();
|
||||
state.timer = setInterval(() => {
|
||||
if (!document.hidden && (state.view === view || state.view === 'app-detail')) render(true);
|
||||
}, state.refreshMs);
|
||||
}
|
||||
|
||||
async function render(silent) {
|
||||
try {
|
||||
if (state.view === 'app-detail') {
|
||||
if (state.appTab === 'containers' && state.currentApp) return openApp(state.currentApp);
|
||||
return;
|
||||
}
|
||||
if (state.view === 'apps') return renderApps(silent);
|
||||
if (state.view === 'containers') return renderContainers(silent, 'running');
|
||||
if (state.view === 'stopped') return renderContainers(silent, 'stopped');
|
||||
if (state.view === 'images') return renderImages();
|
||||
if (state.view === 'registry') return renderRegistry();
|
||||
if (state.view === 'networks') return renderNetworks();
|
||||
if (state.view === 'settings') return renderSettings();
|
||||
} catch (e) { if (!silent) $('#view').innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; }
|
||||
}
|
||||
|
||||
/* ---------------- 主机信息 ---------------- */
|
||||
async function refreshHost() {
|
||||
const h = await api('/api/host');
|
||||
$('#hostMini').innerHTML = `<b>${esc(h.hostname)}</b><br/>${h.cpus} 核 · 内存 ${fmtBytes(h.memTotal)}<br/>运行 ${h.running} / 共 ${h.containers} 容器`;
|
||||
$('#navRunning').textContent = h.running;
|
||||
$('#navStopped').textContent = (h.stopped || 0) + (h.pending || 0);
|
||||
$('#navStopped').title = `已停止容器 ${h.stopped || 0} 个 · 有镜像未启动的应用 ${h.pending || 0} 个`;
|
||||
return h;
|
||||
}
|
||||
|
||||
/* ---------------- 应用看板 ---------------- */
|
||||
const AVATAR_COLORS = ['#1a73e8', '#7a5af8', '#12b76a', '#f79009', '#e5484d', '#0ba5ec', '#9e77ed', '#099250'];
|
||||
function avatar(name) {
|
||||
const s = String(name || '?');
|
||||
const code = [...s].reduce((a, c) => a + c.codePointAt(0), 0);
|
||||
const color = AVATAR_COLORS[code % AVATAR_COLORS.length];
|
||||
const label = /^[a-zA-Z]/.test(s) ? s.slice(0, 2).toUpperCase() : [...s].slice(0, 1).join('');
|
||||
return `<span class="avatar" style="background:${color}">${esc(label)}</span>`;
|
||||
}
|
||||
|
||||
async function renderApps(silent) {
|
||||
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
|
||||
const [data, h, ev, ins] = await Promise.all([
|
||||
api(`/api/apps?filter=${state.filter}&sort=${state.sort}&order=${state.order}${q}`),
|
||||
refreshHost(),
|
||||
api('/api/events?limit=8'),
|
||||
api('/api/insights').catch(() => null),
|
||||
]);
|
||||
const s = data.summary;
|
||||
$('#navIssues').textContent = s.critical + s.warning;
|
||||
$('#navIssues').className = 'nav-badge' + (s.critical ? ' alert' : s.warning ? ' warn' : '');
|
||||
const disk = h.disk;
|
||||
const pill = (a) => `<span class="pill ${a.severity === 2 ? 'bad' : a.severity === 1 ? 'warn' : 'ok'}">${a.statusText}</span>`;
|
||||
const chips = [['all', '全部', s.total], ['issues', '有问题', s.critical + s.warning], ['stopped', '已停止', s.stopped], ['high', '高占用', '']];
|
||||
|
||||
const cards = data.items.map(a => `
|
||||
<div class="app-card ${a.severity === 2 ? 'sev2' : a.severity === 1 ? 'sev1' : ''}" data-app="${esc(a.key)}">
|
||||
<div class="app-head">
|
||||
${avatar(a.name)}
|
||||
<div class="app-title">
|
||||
<div class="app-name" title="${esc(a.name)}">${esc(a.name)}</div>
|
||||
<div class="app-sub">${a.type === 'compose' ? `Compose · ${a.total} 个容器` : '单容器'} · ${a.running}/${a.total} 运行</div>
|
||||
</div>
|
||||
${pill(a)}
|
||||
</div>
|
||||
<div class="app-metrics">
|
||||
<div><div class="k">CPU</div><div class="v">${fmtPct(a.cpuPctOfMachine)}</div><div class="bar ${a.cpuPctOfMachine > 50 ? 'hot' : a.cpuPctOfMachine > 20 ? 'warn' : ''}"><i style="width:${Math.min(100, a.cpuPctOfMachine)}%"></i></div></div>
|
||||
<div><div class="k">内存</div><div class="v">${fmtBytes(a.mem)}</div><div class="bar mem"><i style="width:${Math.min(100, a.memPctMax)}%"></i></div></div>
|
||||
<div><div class="k">网络</div><div class="v" style="font-size:12px">↑${fmtRate(a.txBps)}<br/>↓${fmtRate(a.rxBps)}</div></div>
|
||||
</div>
|
||||
${a.issues.length ? `<div class="app-issues">${a.issues.slice(0, 2).map(i => `<div class="issue ${i.level}">${esc(i.text)}</div>`).join('')}${a.issues.length > 2 ? `<div class="issue more">还有 ${a.issues.length - 2} 条</div>` : ''}</div>` : ''}
|
||||
<div class="app-foot">
|
||||
<div class="app-ports">${a.ports.slice(0, 3).map(p => `<span class="port" data-port="${p.public}" title="打开 :${p.public}">:${p.public}</span>`).join('') || '<span class="muted">无对外端口</span>'}</div>
|
||||
<div class="app-meta"><span title="自最早启动的运行中容器算起">${a.runMs === null ? '未运行' : a.runMs < 60000 ? '刚刚启动' : `已运行 ${fmtDur(a.runMs)}`}</span> · ${a.uptime !== null ? `可用率 ${a.uptime}%` : '采样中'}${a.restarts ? ` · 重启 ${a.restarts}` : ''}</div>
|
||||
</div>
|
||||
<div class="app-acts">
|
||||
<button class="mini" data-app-act="start">启动</button>
|
||||
<button class="mini" data-app-act="restart">重启</button>
|
||||
<button class="mini danger" data-app-act="stop">停止</button>
|
||||
<button class="mini primary" data-app-act="detail">详情</button>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
|
||||
const insItems = (ins && ins.items) || [];
|
||||
const shownIns = state.insightOpen ? insItems : insItems.slice(0, 4);
|
||||
const insHtml = insItems.length ? `
|
||||
<div class="insight-box">
|
||||
<div class="insight-head">
|
||||
<div class="insight-title"><span class="ic-dot"></span><b>优化建议</b><span class="muted">根据当前运行状态自动分析</span></div>
|
||||
<div class="insight-counts">
|
||||
${ins.counts.high ? `<span class="ic high">高 ${ins.counts.high}</span>` : ''}
|
||||
${ins.counts.mid ? `<span class="ic mid">中 ${ins.counts.mid}</span>` : ''}
|
||||
${ins.counts.low ? `<span class="ic low">低 ${ins.counts.low}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="insight-list">
|
||||
${shownIns.map(i => `
|
||||
<div class="insight ${i.sev}">
|
||||
<span class="dot"></span>
|
||||
<div class="it">
|
||||
<div class="it-t">${esc(i.title)}<span class="app-tag${i.appName ? '' : ' sys'}">${esc(i.appName || '系统')}</span></div>
|
||||
<div class="it-d">${esc(i.detail)}</div>
|
||||
</div>
|
||||
${i.action
|
||||
? `<button class="mini ${i.action.type.startsWith('prune') ? 'primary' : ''}" data-insight="${i.action.type}" data-key="${esc(i.appKey || '')}">${esc(i.action.label)}</button>`
|
||||
: (i.appKey ? `<button class="mini ghost" data-insight="openApp" data-key="${esc(i.appKey)}">查看</button>` : '')}
|
||||
</div>`).join('')}
|
||||
</div>
|
||||
${insItems.length > 4 ? `<button class="insight-more" id="insightMore">${state.insightOpen ? '收起' : `展开全部 ${insItems.length} 条建议`}</button>` : ''}
|
||||
</div>` : `
|
||||
<div class="insight-box none">
|
||||
<div class="insight-head">
|
||||
<div class="insight-title"><span class="ic-dot ok"></span><b>优化建议</b><span class="muted">当前没有需要优化的项,配置状态良好</span></div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
$('#view').innerHTML = `
|
||||
<div class="stat-strip">
|
||||
<div class="s-card"><div class="k">应用总数</div><div class="v">${s.total}</div><div class="s">${s.containers} 个容器</div></div>
|
||||
<div class="s-card ${s.critical ? 'bad' : ''}"><div class="k">异常</div><div class="v">${s.critical}</div><div class="s">需要立即处理</div></div>
|
||||
<div class="s-card ${s.warning ? 'warn' : ''}"><div class="k">注意</div><div class="v">${s.warning}</div><div class="s">建议关注</div></div>
|
||||
<div class="s-card"><div class="k">资源占用</div><div class="v">${fmtBytes(s.mem)}</div><div class="s">CPU ${fmtPct(s.cpu / h.cpus)} · 磁盘可用 ${disk ? fmtBytes(disk.free) : '-'}</div></div>
|
||||
<div class="s-card"><div class="k">运行容器</div><div class="v">${h.running}<span class="muted" style="font-size:12px">/${h.containers}</span></div><div class="s">镜像 ${h.images} 个</div></div>
|
||||
</div>
|
||||
|
||||
${insHtml}
|
||||
|
||||
<div class="filters">
|
||||
${chips.map(([k, t, n]) => `<button class="chip ${state.filter === k ? 'on' : ''}" data-filter="${k}">${t}${n !== '' ? ` <b>${n}</b>` : ''}</button>`).join('')}
|
||||
<span class="muted" style="margin-left:auto">按状态异常优先、其次资源占用排序</span>
|
||||
</div>
|
||||
|
||||
<div class="app-grid">${cards || '<div class="empty">没有匹配的应用</div>'}</div>
|
||||
|
||||
<div class="section-title"><h2>最近事件</h2><span class="muted">状态变化与重启记录</span></div>
|
||||
<div class="timeline">
|
||||
${ev.items.length ? ev.items.map(e => `<div class="ev ${e.level}"><span class="t">${timeStr(e.t)}</span><span class="dotmark"></span><div><b>${esc(e.title)}</b><div class="muted">${esc(e.detail || '')}</div></div></div>`).join('') : '<div class="muted">暂无事件</div>'}
|
||||
</div>`;
|
||||
|
||||
$$('#view .chip').forEach(b => b.onclick = () => { state.filter = b.dataset.filter; render(); });
|
||||
const moreBtn = $('#insightMore');
|
||||
if (moreBtn) moreBtn.onclick = () => { state.insightOpen = !state.insightOpen; render(); };
|
||||
$$('#view [data-insight]').forEach(b => b.onclick = async (e) => {
|
||||
e.stopPropagation();
|
||||
const type = b.dataset.insight, key = b.dataset.key;
|
||||
if (type === 'openApp') return openApp(key);
|
||||
b.disabled = true;
|
||||
try {
|
||||
if (type === 'startApp') {
|
||||
const r = await api(`/api/apps/${encodeURIComponent(key)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'start' }) });
|
||||
toast(`启动完成(${r.results.filter(x => x.ok).length}/${r.results.length})`);
|
||||
} else if (type === 'pruneImages') {
|
||||
const r = await api('/api/maintenance/prune', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ what: 'images' }) });
|
||||
toast(`清理完成,释放 ${fmtBytes(r.reclaimed)}(${r.deleted} 个镜像)`);
|
||||
} else if (type === 'pruneBuildCache') {
|
||||
const r = await api('/api/maintenance/prune', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ what: 'buildCache' }) });
|
||||
toast(`构建缓存已清理,释放 ${fmtBytes(r.reclaimed)}`);
|
||||
}
|
||||
setTimeout(render, 900);
|
||||
} catch (err) { toast(err.message, true); }
|
||||
b.disabled = false;
|
||||
});
|
||||
$$('#view .app-card').forEach(card => {
|
||||
card.addEventListener('click', async (e) => {
|
||||
const port = e.target.closest('.port');
|
||||
if (port) { e.stopPropagation(); window.open(`http://${location.hostname}:${port.dataset.port}`, '_blank'); return; }
|
||||
const b = e.target.closest('[data-app-act]');
|
||||
if (!b) return openApp(card.dataset.app);
|
||||
e.stopPropagation();
|
||||
const act = b.dataset.appAct;
|
||||
if (act === 'detail') return openApp(card.dataset.app);
|
||||
if (act === 'stop' && !confirm('确定停止该应用的全部容器?')) return;
|
||||
b.disabled = true;
|
||||
try {
|
||||
const r = await api(`/api/apps/${encodeURIComponent(card.dataset.app)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act }) });
|
||||
const ok = r.results.filter(x => x.ok).length;
|
||||
toast(`${act === 'start' ? '启动' : act === 'restart' ? '重启' : '停止'}完成(${ok}/${r.results.length})`);
|
||||
setTimeout(render, 900);
|
||||
} catch (err) { toast(err.message, true); }
|
||||
b.disabled = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------- 应用详情 ---------------- */
|
||||
async function openApp(key) {
|
||||
if (state.currentApp !== key) state.appTab = 'containers';
|
||||
state.currentApp = key;
|
||||
state.view = 'app-detail';
|
||||
$$('#nav a').forEach(a => a.classList.remove('active'));
|
||||
const a = await api(`/api/apps/${encodeURIComponent(key)}`);
|
||||
$('#pageTitle').textContent = '应用详情';
|
||||
const disk = null;
|
||||
const conts = a.containers.map(c => `
|
||||
<tr>
|
||||
<td><b>${esc(c.name)}</b><div class="muted">${esc(c.service || c.image)}</div></td>
|
||||
<td><span class="pill ${c.state === 'running' ? (c.health === 'unhealthy' ? 'bad' : 'ok') : 'stop'}">${c.state === 'running' ? (c.health === 'unhealthy' ? '异常' : '运行中') : '已停止'}</span></td>
|
||||
<td class="num">${fmtPct(c.stats.cpu)}</td>
|
||||
<td class="num">${fmtBytes(c.stats.mem)}</td>
|
||||
<td class="num">↑${fmtRate(c.stats.txBps)} ↓${fmtRate(c.stats.rxBps)}</td>
|
||||
<td class="num">${c.restarts || 0}</td>
|
||||
<td class="muted">${c.state === 'running' ? fmtDur(c.runMs !== null && c.runMs !== undefined ? c.runMs : Date.now() - Date.parse(c.startedAt)) : '—'}</td>
|
||||
<td class="num">
|
||||
<button class="mini" data-c-act="toggle" data-id="${c.id}">${c.state === 'running' ? '停止' : '启动'}</button>
|
||||
<button class="mini" data-c-act="restart" data-id="${c.id}" ${c.state === 'running' ? '' : 'disabled'}>重启</button>
|
||||
<button class="mini" data-c-act="detail" data-id="${c.id}">详情</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
|
||||
$('#view').innerHTML = `
|
||||
<div class="detail-head">
|
||||
<button class="btn ghost" id="backBtn">${icon('back')} 返回</button>
|
||||
<div class="detail-title">${avatar(a.name)}<div><h2>${esc(a.name)}</h2><div class="muted">${a.type === 'compose' ? 'Compose 应用' : '单容器'} · ${a.running}/${a.total} 运行 · ${a.key}</div></div></div>
|
||||
<span class="pill ${a.severity === 2 ? 'bad' : a.severity === 1 ? 'warn' : 'ok'}">${a.statusText}</span>
|
||||
<div class="detail-acts">
|
||||
<button class="btn ghost" data-app-act="start">全部启动</button>
|
||||
<button class="btn ghost" data-app-act="restart">全部重启</button>
|
||||
<button class="btn danger" data-app-act="stop">全部停止</button>
|
||||
</div>
|
||||
</div>
|
||||
${a.issues.length ? `<div class="issue-box">${a.issues.map(i => `<div class="issue ${i.level}">${esc(i.text)}</div>`).join('')}</div>` : ''}
|
||||
<div class="stat-strip small">
|
||||
<div class="s-card"><div class="k">CPU 占整机</div><div class="v">${fmtPct(a.cpuPctOfMachine)}</div></div>
|
||||
<div class="s-card"><div class="k">内存合计</div><div class="v">${fmtBytes(a.mem)}</div></div>
|
||||
<div class="s-card"><div class="k">网络</div><div class="v" style="font-size:14px">↑${fmtRate(a.txBps)} ↓${fmtRate(a.rxBps)}</div></div>
|
||||
<div class="s-card"><div class="k">重启总数</div><div class="v">${a.restarts}</div></div>
|
||||
<div class="s-card"><div class="k">运行时长</div><div class="v" style="font-size:15px">${a.runMs === null ? '已停止' : a.runMs < 60000 ? '1 分钟内' : fmtDur(a.runMs)}</div></div>
|
||||
<div class="s-card"><div class="k">可用率</div><div class="v">${a.uptime !== null ? a.uptime + '%' : '采样中'}</div></div>
|
||||
<div class="s-card"><div class="k">端口</div><div class="v" style="font-size:13px">${a.ports.map(p => `<span class="port" data-port="${p.public}">:${p.public}</span>`).join(' ') || '无'}</div></div>
|
||||
</div>
|
||||
<div class="tabs inline" id="appTabs">
|
||||
<button data-atab="containers" class="active">容器 (${a.total})</button>
|
||||
<button data-atab="logs">聚合日志</button>
|
||||
<button data-atab="events">事件 (${a.events.length})</button>
|
||||
</div>
|
||||
<div id="appTabBody"></div>`;
|
||||
|
||||
$('#backBtn').onclick = () => { $('#pageTitle').textContent = '应用'; go('apps'); };
|
||||
$$('#view [data-app-act]').forEach(b => b.onclick = async () => {
|
||||
const act = b.dataset.appAct;
|
||||
if (act === 'stop' && !confirm('确定停止该应用的全部容器?')) return;
|
||||
b.disabled = true;
|
||||
try {
|
||||
const r = await api(`/api/apps/${encodeURIComponent(key)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act }) });
|
||||
toast(`完成(${r.results.filter(x => x.ok).length}/${r.results.length})`);
|
||||
setTimeout(() => openApp(key), 1000);
|
||||
} catch (e) { toast(e.message, true); b.disabled = false; }
|
||||
});
|
||||
$$('#view .port').forEach(p => p.onclick = () => window.open(`http://${location.hostname}:${p.dataset.port}`, '_blank'));
|
||||
|
||||
const body = $('#appTabBody');
|
||||
const drawTab = async () => {
|
||||
$$('#appTabs button').forEach(b => b.classList.toggle('active', b.dataset.atab === state.appTab));
|
||||
if (state.appTab === 'containers') {
|
||||
body.innerHTML = `<table class="tb"><thead><tr><th>容器</th><th>状态</th><th class="num">CPU</th><th class="num">内存</th><th class="num">网络</th><th class="num">重启</th><th>运行时长</th><th class="num">操作</th></tr></thead><tbody>${conts}</tbody></table>`;
|
||||
$$('#appTabBody [data-c-act]').forEach(b => b.onclick = async () => {
|
||||
const act = b.dataset.cAct, id = b.dataset.id;
|
||||
if (act === 'detail') return openDrawer(id);
|
||||
const running = b.textContent.includes('停止');
|
||||
try {
|
||||
await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act === 'restart' ? 'restart' : (running ? 'stop' : 'start') }) });
|
||||
toast('已执行'); setTimeout(() => openApp(key), 900);
|
||||
} catch (e) { toast(e.message, true); }
|
||||
});
|
||||
} else if (state.appTab === 'logs') {
|
||||
body.innerHTML = `<div style="display:flex;gap:8px;margin-bottom:10px;align-items:center">
|
||||
<button class="btn ghost" id="appLogReload">刷新</button>
|
||||
<label class="chk">每个容器行数 <input type="number" id="appLogTail" value="60" style="width:76px;padding:3px 6px;border:1px solid var(--line);border-radius:6px"/></label>
|
||||
<span class="muted">按容器名加前缀合并显示</span></div>
|
||||
<div class="code" id="appLogBox">加载中…</div>`;
|
||||
const load = async () => {
|
||||
const r = await api(`/api/apps/${encodeURIComponent(key)}/logs?tail=${$('#appLogTail').value || 60}`);
|
||||
$('#appLogBox').textContent = r.logs || '(无日志)';
|
||||
};
|
||||
$('#appLogReload').onclick = load;
|
||||
await load();
|
||||
} else {
|
||||
body.innerHTML = `<div class="timeline">${a.events.length ? a.events.map(e => `<div class="ev ${e.level}"><span class="t">${timeStr(e.t)}</span><span class="dotmark"></span><div><b>${esc(e.title)}</b><div class="muted">${esc(e.detail || '')}</div></div></div>`).join('') : '<div class="muted">该应用暂无事件</div>'}</div>`;
|
||||
}
|
||||
};
|
||||
$$('#appTabs button').forEach(b => b.onclick = () => { state.appTab = b.dataset.atab; drawTab(); });
|
||||
await drawTab();
|
||||
}
|
||||
|
||||
/* ---------------- 容器列表 ---------------- */
|
||||
async function renderContainers(silent, mode = 'running') {
|
||||
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
|
||||
const filter = mode === 'stopped' ? '&all=1&state=stopped' : '&all=0';
|
||||
const [data, h, pend] = await Promise.all([
|
||||
api(`/api/containers?sort=${state.sort}&order=${state.order}${filter}${q}`),
|
||||
refreshHost(),
|
||||
mode === 'stopped' ? api('/api/pending-apps').catch(() => null) : Promise.resolve(null),
|
||||
]);
|
||||
const html = data.items.map(c => {
|
||||
const s = c.stats;
|
||||
const cpuCls = s.cpu > 80 ? 'hot' : s.cpu > 40 ? 'warn' : '';
|
||||
const memCls = s.memPct > 80 ? 'hot' : s.memPct > 50 ? 'warn' : '';
|
||||
const ports = c.ports.filter(p => p.public).slice(0, 2);
|
||||
const linkBtn = ports.length ? `<span class="ico-btn" title="打开端口 ${ports.map(p => p.public).join(', ')}" data-act="open" data-ports="${esc(ports.map(p => p.public).join(','))}">${icon('link')}</span>` : '';
|
||||
return `<div class="row${c.state === 'running' ? '' : ' off'}" data-id="${c.id}">
|
||||
<div class="wicon">${icon('box')}<span class="dot ${c.state === 'running' ? 'up' : ''}"></span></div>
|
||||
<div class="ident" title="${esc(c.name)}"><div class="nm">${esc(c.name)}</div>
|
||||
<div class="pj" title="${esc((c.project ? '项目: ' + c.project : c.image) + ' · ' + c.status)}">${c.project ? '项目: ' + esc(c.project) : esc(c.image.split('/').pop())} · ${esc(c.status)}${c.restarts ? ` · 重启${c.restarts}` : ''}</div></div>
|
||||
<div class="metrics">
|
||||
<div class="metric"><div class="k">CPU</div><div class="v">${fmtPct(s.cpu)}</div>
|
||||
<div class="bar ${cpuCls}"><i style="width:${Math.min(100, s.cpu / Math.max(1, h.cpus))}%"></i></div></div>
|
||||
<div class="metric"><div class="k">内存</div><div class="v">${fmtBytes(s.mem)} <small>${s.memPct ? s.memPct.toFixed(1) + '%' : ''}</small></div>
|
||||
<div class="bar mem ${memCls}"><i style="width:${Math.min(100, s.memPct)}%"></i></div></div>
|
||||
<div class="metric"><div class="k">网络</div><div class="net"><span class="up">↑${fmtRate(s.txBps)}</span> <span class="dn">↓${fmtRate(s.rxBps)}</span></div></div>
|
||||
<div class="metric"><div class="k">磁盘 IO</div><div class="net">R ${fmtRate(s.rdBps)} / W ${fmtRate(s.wrBps)}</div></div>
|
||||
</div>
|
||||
<div class="acts">
|
||||
${linkBtn}
|
||||
<span class="ico-btn" title="${c.state === 'running' ? '停止' : '启动'}" data-act="toggle">${icon('power')}</span>
|
||||
${c.state === 'running' ? `<span class="ico-btn" title="重启" data-act="restart">${icon('restart')}</span>` : ''}
|
||||
<span class="ico-btn" title="删除" data-act="rm">${icon('trash')}</span>
|
||||
<span class="ico-btn" title="详情" data-act="detail">${icon('more')}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
const pendHtml = (mode === 'stopped' && pend && pend.items.length) ? `
|
||||
<div class="sec-head"><b>有镜像但未启动的应用</b><span class="muted">${pend.items.length} 个 · 扫描 ${esc((pend.root || '').replace(/^.*\/docker$/, '.../docker'))}</span></div>
|
||||
<div class="pend-grid">
|
||||
${pend.items.map(p => `
|
||||
<div class="pend-card">
|
||||
<div class="pend-top"><b title="${esc(p.name)}">${esc(p.name)}</b><span class="tag">${p.services} 个服务</span></div>
|
||||
<div class="pend-sub" title="${esc(p.dir)}">${esc(p.file.replace((pend.root || '') + '/', ''))}</div>
|
||||
<div class="pend-img">${p.images.missing.length
|
||||
? `<span class="warn-txt" title="缺:${esc(p.images.missing.join('、'))}(启动时会自动拉取)">缺 ${p.images.missing.length} 个镜像 · 自动拉取</span>`
|
||||
: `<span class="ok-txt">镜像就绪 ${p.images.present}/${p.images.total}</span>`}</div>
|
||||
<div class="pend-acts">
|
||||
<button class="mini primary" data-pend="${esc(p.name)}" data-file="${esc(p.file)}">启动</button>
|
||||
<button class="mini" data-pend-cmd="${esc(p.file)}">命令</button>
|
||||
</div>
|
||||
</div>`).join('')}
|
||||
</div>
|
||||
<div class="sec-head sub"><b>已停止的容器</b><span class="muted">${data.total} 个</span></div>` : '';
|
||||
|
||||
const label = mode === 'stopped' ? '已停止' : '运行中';
|
||||
$('#view').innerHTML = `${pendHtml}${html || `<div class="empty">${mode === 'stopped' ? '没有已停止的容器' : '没有正在运行的容器'}</div>`}
|
||||
<div class="foot">共 ${data.total} 个${label}容器 · 排序:${({ cpu: 'CPU', mem: '内存', net: '网络', io: '磁盘IO', pids: '进程数', name: '名称' })[state.sort] || state.sort} ${state.order === 'desc' ? '降序' : '升序'} · 每 ${state.refreshMs / 1000} 秒刷新${h.disk ? ` · /vol1 可用 ${fmtBytes(h.disk.free)}` : ''}</div>`;
|
||||
|
||||
$$('#view [data-pend-cmd]').forEach(b => b.onclick = () => {
|
||||
alert(`在宿主机执行:\n\ndocker compose -f ${b.dataset.pendCmd} up -d`);
|
||||
});
|
||||
$$('#view [data-pend]').forEach(b => b.onclick = async () => {
|
||||
const name = b.dataset.pend;
|
||||
if (!confirm(`启动应用「${name}」?\n\n将执行 docker compose up -d,会创建并运行该项目下的容器。`)) return;
|
||||
b.disabled = true; b.textContent = '启动中…';
|
||||
try {
|
||||
const r = await api('/api/pending-apps/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
|
||||
if (r.ok) { toast(`「${name}」已启动`); setTimeout(() => render(), 1500); }
|
||||
else { alert(`启动失败:\n\n${r.output || '未知错误'}`); b.disabled = false; b.textContent = '启动'; }
|
||||
} catch (e) { toast(e.message, true); b.disabled = false; b.textContent = '启动'; }
|
||||
});
|
||||
|
||||
$$('#view .row').forEach(row => {
|
||||
row.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('[data-act]'); const id = row.dataset.id;
|
||||
if (!btn) return openDrawer(id);
|
||||
e.stopPropagation();
|
||||
const act = btn.dataset.act;
|
||||
if (act === 'detail') return openDrawer(id);
|
||||
if (act === 'open') { window.open(`http://${location.hostname}:${btn.dataset.ports.split(',')[0]}`, '_blank'); return; }
|
||||
if (act === 'rm') {
|
||||
if (!confirm('确定删除这个容器?(不会删除数据卷)')) return;
|
||||
try { await api(`/api/containers/${id}?force=1`, { method: 'DELETE' }); toast('已删除'); render(); } catch (err) { toast(err.message, true); }
|
||||
return;
|
||||
}
|
||||
const running = row.querySelector('.dot').classList.contains('up');
|
||||
try {
|
||||
await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act === 'restart' ? 'restart' : (running ? 'stop' : 'start') }) });
|
||||
toast('已执行'); setTimeout(render, 700);
|
||||
} catch (err) { toast(err.message, true); }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------- 容器详情抽屉 ---------------- */
|
||||
async function openDrawer(id) {
|
||||
state.current = id; state.tab = 'stat';
|
||||
$('#drawer').classList.remove('hidden');
|
||||
$('#drawerBody').innerHTML = '<div class="empty">加载中…</div>';
|
||||
const d = await api(`/api/containers/${id}`);
|
||||
$('#drawerName').textContent = d.info.Name.replace(/^\//, '');
|
||||
$('#drawerSub').innerHTML = `${esc(d.info.Config.Image)} · ${esc(d.info.State.Status)} · ${esc(d.info.Id.slice(0, 12))}`;
|
||||
const running = d.info.State.Running;
|
||||
$('#drawerActions').innerHTML = `
|
||||
<button class="btn ${running ? 'danger' : 'primary'}" data-d="toggle">${running ? '停止' : '启动'}</button>
|
||||
<button class="btn" data-d="restart">重启</button>
|
||||
<button class="btn" data-d="${running ? 'pause' : 'unpause'}" ${running ? '' : 'disabled'}>${running ? '暂停' : '恢复'}</button>
|
||||
<button class="btn danger" data-d="rm">删除</button>`;
|
||||
$$('#drawerActions [data-d]').forEach(b => b.onclick = async () => {
|
||||
const a = b.dataset.d;
|
||||
try {
|
||||
if (a === 'rm') { if (!confirm('确定删除该容器?')) return; await api(`/api/containers/${id}?force=1`, { method: 'DELETE' }); closeDrawer(); render(); toast('已删除'); return; }
|
||||
await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: a === 'toggle' ? (running ? 'stop' : 'start') : a }) });
|
||||
toast('操作成功'); openDrawer(id); render();
|
||||
} catch (e) { toast(e.message, true); }
|
||||
});
|
||||
drawTab(d);
|
||||
}
|
||||
|
||||
async function drawTab(d) {
|
||||
const tab = state.tab;
|
||||
$$('#drawerTabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
|
||||
const body = $('#drawerBody');
|
||||
const s = d.stats || {};
|
||||
if (tab === 'stat') {
|
||||
body.innerHTML = `
|
||||
<div class="stat-grid">
|
||||
<div class="stat"><div class="k">CPU</div><div class="v">${fmtPct(s.cpu || 0)}</div></div>
|
||||
<div class="stat"><div class="k">内存</div><div class="v">${fmtBytes(s.mem || 0)}</div><div class="muted">上限 ${fmtBytes(s.memLimit || 0)} · ${(s.memPct || 0).toFixed(1)}%</div></div>
|
||||
<div class="stat"><div class="k">网络</div><div class="v" style="font-size:13px">↑ ${fmtRate(s.txBps || 0)}<br/>↓ ${fmtRate(s.rxBps || 0)}</div><div class="muted">累计 ↑${fmtBytes(s.tx || 0)} ↓${fmtBytes(s.rx || 0)}</div></div>
|
||||
<div class="stat"><div class="k">磁盘 IO</div><div class="v" style="font-size:13px">读 ${fmtRate(s.rdBps || 0)}<br/>写 ${fmtRate(s.wrBps || 0)}</div><div class="muted">累计读 ${fmtBytes(s.rd || 0)} / 写 ${fmtBytes(s.wr || 0)}</div></div>
|
||||
<div class="stat"><div class="k">进程数</div><div class="v">${s.pids || 0}</div></div>
|
||||
<div class="stat"><div class="k">重启策略</div><div class="v" style="font-size:13px">${esc(d.restartPolicy)}</div><div class="muted">退出码 ${d.exitCode ?? 0}${d.health ? ' · ' + esc(d.health) : ''}</div></div>
|
||||
</div>
|
||||
<div class="section-title"><h2>CPU 曲线(约 12 分钟)</h2><span class="muted">当前 ${fmtPct(s.cpu || 0)}</span></div>
|
||||
<canvas class="spark" data-chart="cpu"></canvas>
|
||||
<div class="section-title"><h2>内存曲线</h2><span class="muted">当前 ${fmtBytes(s.mem || 0)}</span></div>
|
||||
<canvas class="spark" data-chart="mem"></canvas>
|
||||
<div class="section-title"><h2>网络速率</h2></div>
|
||||
<canvas class="spark" data-chart="net"></canvas>
|
||||
<div class="section-title"><h2>基本信息</h2></div>
|
||||
<div class="kv">
|
||||
<div class="k">启动时间</div><div>${esc(d.startedAt || '-')}</div>
|
||||
<div class="k">镜像</div><div>${esc(d.info.Config.Image)}</div>
|
||||
<div class="k">命令</div><div class="muted">${esc([].concat(d.entrypoint || [], d.cmd || []).join(' ') || '-')}</div>
|
||||
<div class="k">端口</div><div>${Object.entries(d.ports || {}).map(([p, b]) => `${p} → ${(b || []).map(x => x.HostPort).join(',') || '-'}`).join('<br/>') || '-'}</div>
|
||||
<div class="k">容器 ID</div><div class="muted">${esc(d.info.Id)}</div>
|
||||
</div>`;
|
||||
const hist = d.history || [];
|
||||
drawChart(body, 'cpu', hist.map(x => x.c), v => v.toFixed(1) + '%', '#1a73e8');
|
||||
drawChart(body, 'mem', hist.map(x => x.m / 1048576), v => v.toFixed(0) + ' MB', '#7a5af8');
|
||||
drawChart(body, 'net', hist.map(x => (x.rx || 0) + (x.tx || 0)), v => fmtRate(v), '#12b76a');
|
||||
} else if (tab === 'logs') {
|
||||
body.innerHTML = `<div style="display:flex;gap:8px;margin-bottom:10px;align-items:center">
|
||||
<button class="btn ghost" id="logReload">刷新日志</button>
|
||||
<label class="chk"><input type="checkbox" id="logLive" checked /> 实时跟随</label>
|
||||
<label class="chk">行数 <input type="number" id="logTail" value="200" style="width:70px;padding:3px 6px;border:1px solid var(--line);border-radius:6px"/></label>
|
||||
</div><div class="code" id="logBox">加载中…</div>`;
|
||||
let es = null;
|
||||
const startStream = () => {
|
||||
if (es) es.close();
|
||||
es = new EventSource(`/api/containers/${state.current}/logs/stream?tail=${$('#logTail').value || 200}`);
|
||||
es.onmessage = (ev) => {
|
||||
const box = $('#logBox'); if (!box) return;
|
||||
try { box.textContent += JSON.parse(ev.data); } catch (e) {}
|
||||
box.scrollTop = box.scrollHeight;
|
||||
};
|
||||
};
|
||||
$('#logReload').onclick = async () => {
|
||||
if (es) { es.close(); es = null; }
|
||||
const r = await api(`/api/containers/${state.current}/logs?tail=${$('#logTail').value || 200}`);
|
||||
$('#logBox').textContent = r.logs || '(无日志)';
|
||||
if ($('#logLive').checked) startStream();
|
||||
};
|
||||
$('#logLive').onchange = (e) => { if (e.target.checked) startStream(); else if (es) { es.close(); es = null; } };
|
||||
const r = await api(`/api/containers/${state.current}/logs?tail=${$('#logTail').value || 200}`);
|
||||
$('#logBox').textContent = r.logs || '(无日志)';
|
||||
if ($('#logLive').checked) startStream();
|
||||
} else if (tab === 'env') {
|
||||
body.innerHTML = `<div class="kv"><div class="k">环境变量</div><div></div>${(d.env || []).map(e => `<div class="k" style="word-break:break-all">${esc(e.split('=')[0])}</div><div class="muted" style="word-break:break-all">${esc(e.split('=').slice(1).join('='))}</div>`).join('') || '<div>-</div><div>-</div>'}</div>`;
|
||||
} else {
|
||||
body.innerHTML = `
|
||||
<div class="section-title"><h2>挂载</h2></div>
|
||||
<table class="tb"><thead><tr><th>宿主机路径 / 卷</th><th>容器路径</th><th>模式</th></tr></thead><tbody>
|
||||
${(d.mounts || []).map(m => `<tr><td>${esc(m.Source || m.Name || '')}</td><td>${esc(m.Destination)}</td><td>${m.RW ? '读写' : '只读'}</td></tr>`).join('') || '<tr><td colspan="3" class="muted">无挂载</td></tr>'}
|
||||
</tbody></table>
|
||||
<div class="section-title"><h2>网络</h2></div>
|
||||
<table class="tb"><thead><tr><th>网络</th><th>IP</th><th>网关</th></tr></thead><tbody>
|
||||
${Object.entries(d.networks || {}).map(([n, v]) => `<tr><td>${esc(n)}</td><td>${esc(v.IPAddress || '-')}</td><td>${esc(v.Gateway || '-')}</td></tr>`).join('') || '<tr><td colspan="3" class="muted">无网络</td></tr>'}
|
||||
</tbody></table>`;
|
||||
}
|
||||
}
|
||||
|
||||
function drawChart(root, which, values, fmt, color) {
|
||||
const cv = root.querySelector(`canvas[data-chart="${which}"]`);
|
||||
if (!cv) return;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const w = cv.clientWidth || 600, hgt = cv.clientHeight || 90;
|
||||
cv.width = w * dpr; cv.height = hgt * dpr;
|
||||
const ctx = cv.getContext('2d'); ctx.scale(dpr, dpr);
|
||||
ctx.clearRect(0, 0, w, hgt);
|
||||
if (!values || values.length < 2) { ctx.fillStyle = '#98a2b3'; ctx.font = '12px sans-serif'; ctx.fillText('采集中…', 12, hgt / 2); return; }
|
||||
const max = Math.max(...values, 1) * 1.15, pad = 8;
|
||||
const x = i => pad + (w - pad * 2) * i / (values.length - 1);
|
||||
const y = v => hgt - pad - (hgt - pad * 2) * (v / max);
|
||||
ctx.beginPath(); ctx.moveTo(x(0), y(values[0]));
|
||||
values.forEach((v, i) => ctx.lineTo(x(i), y(v)));
|
||||
ctx.strokeStyle = color; ctx.lineWidth = 1.8; ctx.lineJoin = 'round'; ctx.stroke();
|
||||
ctx.lineTo(x(values.length - 1), hgt - pad); ctx.lineTo(x(0), hgt - pad); ctx.closePath();
|
||||
const g = ctx.createLinearGradient(0, 0, 0, hgt); g.addColorStop(0, color + '33'); g.addColorStop(1, color + '05');
|
||||
ctx.fillStyle = g; ctx.fill();
|
||||
ctx.fillStyle = '#98a2b3'; ctx.font = '11px sans-serif';
|
||||
ctx.fillText(fmt(max / 1.15), 10, 14);
|
||||
ctx.fillText(fmt(values[values.length - 1]), Math.max(10, w - 70), hgt - 10);
|
||||
}
|
||||
|
||||
/* ---------------- 镜像 / 仓库 / 网络 / 设置 ---------------- */
|
||||
async function renderImages() {
|
||||
const imgs = await api('/api/images');
|
||||
const total = imgs.reduce((a, b) => a + b.size, 0);
|
||||
$('#view').innerHTML = `<table class="tb"><thead><tr><th>镜像</th><th>ID</th><th class="num">大小</th><th>创建</th><th></th></tr></thead><tbody>
|
||||
${imgs.map(i => `<tr><td>${(i.tags.length ? i.tags : ['<none>:<none>']).map(t => `<span class="tag blue">${esc(t)}</span>`).join(' ')}</td>
|
||||
<td class="muted">${esc(i.shortId)}</td><td class="num">${fmtBytes(i.size)}</td>
|
||||
<td class="muted">${new Date(i.created * 1000).toLocaleDateString('zh-CN')}</td>
|
||||
<td><button class="btn danger" data-img="${esc(i.id)}">删除</button></td></tr>`).join('')}
|
||||
</tbody></table><div class="foot">共 ${imgs.length} 个镜像 · 合计 ${fmtBytes(total)}</div>`;
|
||||
$$('#view [data-img]').forEach(b => b.onclick = async () => {
|
||||
if (!confirm('确定删除该镜像?')) return;
|
||||
try { await api(`/api/images/${encodeURIComponent(b.dataset.img)}?force=1`, { method: 'DELETE' }); toast('已删除'); render(); }
|
||||
catch (e) { toast(e.message, true); }
|
||||
});
|
||||
}
|
||||
|
||||
async function renderRegistry() {
|
||||
$('#view').innerHTML = `
|
||||
<div class="card" style="max-width:760px">
|
||||
<h3>拉取镜像</h3>
|
||||
<div style="display:flex;gap:8px;margin-top:8px">
|
||||
<input id="pullName" placeholder="例如 nginx:latest / jellyfin/jellyfin" style="flex:1;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font-size:13px"/>
|
||||
<button class="btn primary" id="pullBtn">开始拉取</button>
|
||||
</div>
|
||||
<div class="muted" style="margin-top:8px">国内建议用加速前缀:<code>docker.1ms.run/library/nginx:latest</code></div>
|
||||
<div class="code" id="pullLog" style="margin-top:12px;min-height:120px;max-height:320px">等待操作…</div>
|
||||
</div>
|
||||
<div class="section-title"><h2>常用镜像</h2></div>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap">
|
||||
${['nginx:latest', 'redis:7-alpine', 'postgres:17', 'mysql:8', 'mongo:8', 'louislam/uptime-kuma:2', 'jellyfin/jellyfin:latest'].map(t => `<button class="btn" data-pull="${t}">${t}</button>`).join('')}
|
||||
</div>`;
|
||||
const doPull = (name) => {
|
||||
const box = $('#pullLog'); box.textContent = '';
|
||||
fetch('/api/images/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: name }) })
|
||||
.then(async (resp) => {
|
||||
const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf = '';
|
||||
while (true) {
|
||||
const { done, value } = await reader.read(); if (done) break;
|
||||
buf += dec.decode(value, { stream: true });
|
||||
const parts = buf.split('\n\n'); buf = parts.pop();
|
||||
for (const p of parts) {
|
||||
const line = p.replace(/^data: /, ''); if (!line) continue;
|
||||
try {
|
||||
const j = JSON.parse(line);
|
||||
if (j.error) box.textContent += `\n❌ ${j.error}`;
|
||||
else if (j.status) box.textContent += `\n${j.status}${j.progress ? ' ' + j.progress : ''}`;
|
||||
if (j.done) box.textContent += '\n✅ 完成';
|
||||
} catch (e) {}
|
||||
}
|
||||
box.scrollTop = box.scrollHeight;
|
||||
}
|
||||
}).catch(e => box.textContent += `\n❌ ${e.message}`);
|
||||
};
|
||||
$('#pullBtn').onclick = () => { const n = $('#pullName').value.trim(); if (n) doPull(n); };
|
||||
$$('#view [data-pull]').forEach(b => b.onclick = () => { $('#pullName').value = b.dataset.pull; doPull(b.dataset.pull); });
|
||||
}
|
||||
|
||||
async function renderNetworks() {
|
||||
const nets = await api('/api/networks');
|
||||
$('#view').innerHTML = `<table class="tb"><thead><tr><th>网络名</th><th>驱动</th><th>子网</th><th>网关</th><th class="num">容器数</th><th>范围</th></tr></thead><tbody>
|
||||
${nets.map(n => `<tr><td><b>${esc(n.name)}</b>${n.internal ? ' <span class="tag">内部</span>' : ''}</td><td>${esc(n.driver)}</td>
|
||||
<td class="muted">${n.subnet.map(esc).join('<br/>') || '-'}</td><td class="muted">${n.gateway.map(esc).join('<br/>') || '-'}</td>
|
||||
<td class="num">${n.containers}</td><td class="muted">${esc(n.scope)}</td></tr>`).join('')}
|
||||
</tbody></table><div class="foot">共 ${nets.length} 个网络</div>`;
|
||||
}
|
||||
|
||||
async function renderSettings() {
|
||||
const s = await api('/api/settings');
|
||||
$('#view').innerHTML = `
|
||||
<div class="card" style="max-width:720px">
|
||||
<h3>告警规则</h3>
|
||||
<div class="form-row"><label>CPU 占整机超过</label><input id="th_cpu" type="number" value="${s.thresholds.cpu}" /> %</div>
|
||||
<div class="form-row"><label>内存占容器上限超过</label><input id="th_mem" type="number" value="${s.thresholds.mem}" /> %</div>
|
||||
<div class="form-row"><label>同一应用推送间隔</label><input id="th_debounce" type="number" value="${s.debounceMinutes}" /> 分钟</div>
|
||||
<div class="form-row"><label>Webhook 地址</label><input id="th_webhook" placeholder="https://..." value="${esc(s.webhook)}" style="flex:1" /></div>
|
||||
<div class="form-row"><label>启用推送</label><input id="th_notify" type="checkbox" ${s.notify ? 'checked' : ''} style="width:auto" /></div>
|
||||
<div class="muted" style="margin-top:10px">容器未运行、健康检查失败、重启次数增加、超过资源阈值时产生事件;「异常」级事件按上面的间隔去重后推送到 webhook(POST JSON:title / level / app / detail / time / host)。</div>
|
||||
<div style="display:flex;gap:8px;margin-top:14px">
|
||||
<button class="btn primary" id="saveBtn">保存</button>
|
||||
<button class="btn ghost" id="testBtn">发送测试推送</button>
|
||||
<button class="btn ghost" id="eventBtn">查看事件</button>
|
||||
</div>
|
||||
<div class="code" id="setLog" style="margin-top:12px;max-height:260px">—</div>
|
||||
</div>`;
|
||||
$('#saveBtn').onclick = async () => {
|
||||
try {
|
||||
await api('/api/settings', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
thresholds: { cpu: Number($('#th_cpu').value), mem: Number($('#th_mem').value) },
|
||||
debounceMinutes: Number($('#th_debounce').value),
|
||||
webhook: $('#th_webhook').value,
|
||||
notify: $('#th_notify').checked,
|
||||
}),
|
||||
});
|
||||
toast('已保存');
|
||||
} catch (e) { toast(e.message, true); }
|
||||
};
|
||||
$('#testBtn').onclick = async () => {
|
||||
try { await api('/api/settings/test', { method: 'POST' }); $('#setLog').textContent = '测试推送已发送'; toast('已发送'); }
|
||||
catch (e) { $('#setLog').textContent = '推送失败:' + e.message; toast(e.message, true); }
|
||||
};
|
||||
$('#eventBtn').onclick = async () => {
|
||||
const ev = await api('/api/events?limit=50');
|
||||
$('#setLog').textContent = ev.items.length ? ev.items.map(e => `${timeStr(e.t)} [${e.level}] ${e.title} — ${e.detail}`).join('\n') : '暂无事件';
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------------- 添加容器 ---------------- */
|
||||
function openAddModal() {
|
||||
if (state.view === 'registry') { go('registry'); return; }
|
||||
if (state.view === 'images') return pruneImages();
|
||||
$('#modalTitle').textContent = '添加容器';
|
||||
$('#modalBody').innerHTML = `
|
||||
<label>镜像</label><input id="f_image" placeholder="nginx:latest 或 docker.1ms.run/library/nginx:latest" />
|
||||
<label>容器名(可选)</label><input id="f_name" placeholder="my-nginx" />
|
||||
<label>端口映射(宿主机:容器,每行一个)</label><textarea id="f_ports" rows="2" placeholder="8080:80"></textarea>
|
||||
<label>环境变量(每行 KEY=VALUE)</label><textarea id="f_env" rows="2" placeholder="TZ=Asia/Shanghai"></textarea>
|
||||
<label>挂载(每行 宿主路径:容器路径)</label><textarea id="f_vol" rows="2" placeholder="/vol1/1000/HD1/docker/app/data:/data"></textarea>
|
||||
<label>重启策略</label><input id="f_restart" value="always" />`;
|
||||
$('#modal').classList.remove('hidden');
|
||||
$('#modalOk').onclick = async () => {
|
||||
const image = $('#f_image').value.trim(); if (!image) return toast('请填写镜像', true);
|
||||
const ports = $('#f_ports').value.split('\n').map(l => l.trim()).filter(Boolean).map(l => {
|
||||
const [host, cont] = l.split(':');
|
||||
return { host: Number(host), container: Number(cont || host) };
|
||||
});
|
||||
const body = {
|
||||
image, name: $('#f_name').value.trim() || undefined, ports,
|
||||
env: $('#f_env').value.split('\n').map(s => s.trim()).filter(Boolean),
|
||||
volumes: $('#f_vol').value.split('\n').map(s => s.trim()).filter(Boolean),
|
||||
restart: $('#f_restart').value.trim() || 'always',
|
||||
};
|
||||
$('#modalOk').disabled = true; $('#modalOk').textContent = '创建中…';
|
||||
try { await api('/api/containers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); toast('创建成功'); $('#modal').classList.add('hidden'); render(); }
|
||||
catch (e) { toast(e.message, true); }
|
||||
$('#modalOk').disabled = false; $('#modalOk').textContent = '确定';
|
||||
};
|
||||
}
|
||||
async function pruneImages() {
|
||||
if (!confirm('清理未被使用的悬空镜像?')) return;
|
||||
try { const r = await api('/api/images/prune', { method: 'POST' }); toast(`已清理,释放 ${fmtBytes(r.SpaceReclaimed || 0)}`); render(); }
|
||||
catch (e) { toast(e.message, true); }
|
||||
}
|
||||
|
||||
/* ---------------- 事件绑定 ---------------- */
|
||||
$('#nav').addEventListener('click', e => { const a = e.target.closest('a'); if (a) go(a.dataset.view); });
|
||||
let qTimer = null;
|
||||
$('#search').addEventListener('input', e => { state.q = e.target.value; clearTimeout(qTimer); qTimer = setTimeout(() => { if (state.currentApp) return; render(); }, 250); });
|
||||
$('#sort').addEventListener('change', e => { state.sort = e.target.value; render(); });
|
||||
$('#orderBtn').addEventListener('click', () => { state.order = state.order === 'desc' ? 'asc' : 'desc'; $('#orderBtn').textContent = state.order === 'desc' ? '降序 ↓' : '升序 ↑'; render(); });
|
||||
$('#refreshBtn').addEventListener('click', () => render());
|
||||
$('#refreshSel').addEventListener('change', (e) => {
|
||||
state.refreshMs = Math.min(30000, Math.max(1000, Number(e.target.value) || 3000));
|
||||
localStorage.setItem(REFRESH_KEY, state.refreshMs);
|
||||
clearInterval(state.timer);
|
||||
const view = state.view;
|
||||
state.timer = setInterval(() => {
|
||||
if (!document.hidden && (state.view === view || state.view === 'app-detail')) render(true);
|
||||
}, state.refreshMs);
|
||||
toast(`刷新间隔已设为 ${state.refreshMs / 1000} 秒`);
|
||||
});
|
||||
$('#addBtn').addEventListener('click', openAddModal);
|
||||
$('#drawerClose').onclick = () => $('#drawer').classList.add('hidden');
|
||||
$('#drawerMask').onclick = () => $('#drawer').classList.add('hidden');
|
||||
$('#drawerTabs').addEventListener('click', async e => {
|
||||
const b = e.target.closest('button'); if (!b) return;
|
||||
state.tab = b.dataset.tab;
|
||||
if (state.current) drawTab(await api(`/api/containers/${state.current}`));
|
||||
});
|
||||
$('#modalCancel').onclick = () => $('#modal').classList.add('hidden');
|
||||
$('#modalMask').onclick = () => $('#modal').classList.add('hidden');
|
||||
document.addEventListener('keydown', e => { if (e.key === 'Escape') { $('#modal').classList.add('hidden'); $('#drawer').classList.add('hidden'); } });
|
||||
|
||||
paintIcons();
|
||||
go('apps');
|
||||
@@ -0,0 +1,107 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>飞牛docker容器管理增强版</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<aside class="nav">
|
||||
<div class="brand">
|
||||
<span class="brand-icon">
|
||||
<svg viewBox="0 0 24 24" width="20" height="20"><path fill="#fff" d="M22 11.5c-.6-.4-1.9-.6-2.9-.4-.1-1.1-.6-2-1.5-2.8l-.5-.4-.4.5c-.5.7-.7 1.7-.6 2.6.1.4.2.9.5 1.2-.3.2-.9.4-1.7.4H2.1l-.1.5c-.2 1.6.2 3.3 1.2 4.6 1 1.3 2.7 2 4.9 2 4.7 0 8.2-2.2 9.8-6.1 1.1 0 2.2-.3 2.8-1.2l.3-.4-.5-.5zM6.5 9.5H4.2v2.3h2.3V9.5zm2.9 0H7.1v2.3h2.3V9.5zm2.9 0h-2.3v2.3h2.3V9.5zm2.9 0h-2.3v2.3h2.3V9.5zm-8.7-2.9H4.2v2.3h2.3V6.6zm2.9 0H7.1v2.3h2.3V6.6zm2.9 0h-2.3v2.3h2.3V6.6zm0-2.9h-2.3v2.3h2.3V3.7z"/></svg>
|
||||
</span>
|
||||
<span class="brand-text">飞牛docker容器管理增强版</span>
|
||||
</div>
|
||||
<nav id="nav">
|
||||
<a data-view="apps" class="active"><i data-ico="grid"></i>应用<span class="nav-badge alert" id="navIssues">-</span></a>
|
||||
<a data-view="containers"><i data-ico="box"></i>运行的容器<span class="nav-badge" id="navRunning">-</span></a>
|
||||
<a data-view="stopped"><i data-ico="pause"></i>停止的容器<span class="nav-badge" id="navStopped">-</span></a>
|
||||
<a data-view="images"><i data-ico="disc"></i>本地镜像</a>
|
||||
<a data-view="registry"><i data-ico="repo"></i>镜像仓库</a>
|
||||
<a data-view="networks"><i data-ico="globe"></i>网络</a>
|
||||
<a data-view="settings"><i data-ico="bell"></i>告警设置</a>
|
||||
</nav>
|
||||
<div class="nav-foot">
|
||||
<div id="hostMini" class="host-mini">连接中…</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<header class="topbar">
|
||||
<h1 id="pageTitle">应用</h1>
|
||||
<div class="topbar-right">
|
||||
<div class="search">
|
||||
<i data-ico="search"></i>
|
||||
<input id="search" placeholder="搜索应用 / 容器 / 镜像" autocomplete="off" />
|
||||
</div>
|
||||
<div class="sortbox" id="sortbox">
|
||||
<label>排序</label>
|
||||
<select id="sort">
|
||||
<option value="severity">异常优先</option>
|
||||
<option value="cpu">CPU 占用</option>
|
||||
<option value="mem">内存占用</option>
|
||||
<option value="containers">容器数</option>
|
||||
<option value="name">名称</option>
|
||||
</select>
|
||||
</div>
|
||||
<button id="orderBtn" class="btn ghost" title="切换升序 / 降序">降序 ↓</button>
|
||||
<div class="sortbox refreshbox">
|
||||
<label>刷新</label>
|
||||
<select id="refreshSel">
|
||||
<option value="1000">1 秒</option>
|
||||
<option value="2000">2 秒</option>
|
||||
<option value="3000">3 秒</option>
|
||||
<option value="5000">5 秒</option>
|
||||
<option value="10000">10 秒</option>
|
||||
<option value="30000">30 秒</option>
|
||||
</select>
|
||||
</div>
|
||||
<button id="refreshBtn" class="btn ghost"><i data-ico="refresh"></i>刷新</button>
|
||||
<button id="addBtn" class="btn primary"><i data-ico="plus"></i>添加容器</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section id="view" class="view"></section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<div id="drawer" class="drawer hidden">
|
||||
<div class="drawer-mask" id="drawerMask"></div>
|
||||
<div class="drawer-panel">
|
||||
<div class="drawer-head">
|
||||
<div>
|
||||
<h2 id="drawerName">容器</h2>
|
||||
<div id="drawerSub" class="muted"></div>
|
||||
</div>
|
||||
<button class="ico-btn" id="drawerClose">✕</button>
|
||||
</div>
|
||||
<div class="drawer-actions" id="drawerActions"></div>
|
||||
<div class="tabs" id="drawerTabs">
|
||||
<button data-tab="stat" class="active">资源</button>
|
||||
<button data-tab="logs">日志</button>
|
||||
<button data-tab="env">配置</button>
|
||||
<button data-tab="mount">挂载 / 网络</button>
|
||||
</div>
|
||||
<div class="drawer-body" id="drawerBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="modal" class="modal hidden">
|
||||
<div class="modal-mask" id="modalMask"></div>
|
||||
<div class="modal-box">
|
||||
<h2 id="modalTitle">添加容器</h2>
|
||||
<div id="modalBody"></div>
|
||||
<div class="modal-foot">
|
||||
<button class="btn ghost" id="modalCancel">取消</button>
|
||||
<button class="btn primary" id="modalOk">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast hidden"></div>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,270 @@
|
||||
:root{
|
||||
--bg:#f4f6f9; --panel:#fff; --line:#e8ecf2; --text:#1f2733; --muted:#7b8798;
|
||||
--blue:#1a73e8; --blue-soft:#e8f1fe; --green:#12b76a; --red:#e5484d; --amber:#f79009;
|
||||
--radius:10px; --shadow:0 1px 2px rgba(16,24,40,.04), 0 1px 3px rgba(16,24,40,.06);
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;height:100%}
|
||||
body{background:var(--bg);color:var(--text);font:14px/1.5 -apple-system,"PingFang SC","Microsoft YaHei",Segoe UI,Roboto,sans-serif}
|
||||
.app{display:flex;height:100vh;overflow:hidden}
|
||||
a{color:var(--blue);text-decoration:none;cursor:pointer}
|
||||
.muted{color:var(--muted);font-size:12px}
|
||||
|
||||
/* 左侧导航 */
|
||||
.nav{width:226px;background:#fbfcfe;border-right:1px solid var(--line);display:flex;flex-direction:column;flex-shrink:0}
|
||||
.brand{display:flex;align-items:center;gap:9px;padding:16px 12px 12px}
|
||||
.brand-icon{width:28px;height:28px;border-radius:8px;background:var(--blue);display:grid;place-items:center;flex-shrink:0;box-shadow:0 2px 6px rgba(26,115,232,.35)}
|
||||
.brand-text{font-weight:600;font-size:12.5px;line-height:1.3;letter-spacing:0;white-space:nowrap}
|
||||
.nav nav{display:flex;flex-direction:column;padding:6px 10px;gap:2px}
|
||||
.nav nav a{display:flex;align-items:center;gap:10px;padding:9px 12px;border-radius:8px;color:#3d4859;font-size:14px;user-select:none}
|
||||
.nav nav a:hover{background:#eef3fa}
|
||||
.nav nav a.active{background:var(--blue-soft);color:var(--blue);font-weight:600}
|
||||
.nav nav a svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:1.8}
|
||||
.nav-badge{margin-left:auto;background:#e6ebf3;color:#5b6676;border-radius:20px;padding:0 7px;font-size:11px;line-height:18px}
|
||||
.nav-foot{margin-top:auto;padding:12px 14px;border-top:1px solid var(--line)}
|
||||
.host-mini{font-size:11px;color:var(--muted);line-height:1.6}
|
||||
.host-mini b{color:#3d4859;font-weight:600}
|
||||
|
||||
/* 主区 */
|
||||
.main{flex:1;display:flex;flex-direction:column;min-width:0}
|
||||
.topbar{display:flex;align-items:center;gap:12px;padding:14px 20px;border-bottom:1px solid var(--line);background:#fff}
|
||||
.topbar h1{font-size:17px;margin:0;font-weight:600;white-space:nowrap}
|
||||
.topbar-right{margin-left:auto;display:flex;align-items:center;gap:8px;flex-wrap:wrap;justify-content:flex-end;min-width:0}
|
||||
.search{position:relative;display:flex;align-items:center}
|
||||
.search svg{position:absolute;left:10px;width:14px;height:14px;stroke:#97a2b2;fill:none;stroke-width:2}
|
||||
.search input{width:210px;padding:7px 10px 7px 30px;border:1px solid var(--line);border-radius:8px;background:#fbfcfe;font-size:13px;outline:none}
|
||||
.search input:focus{border-color:#bcd4f7;background:#fff}
|
||||
.sortbox{display:flex;align-items:center;gap:8px;background:#fbfcfe;border:1px solid var(--line);border-radius:8px;padding:3px 8px;flex-shrink:0}
|
||||
.sortbox label{font-size:12px;color:var(--muted);white-space:nowrap}
|
||||
/* 原生下拉箭头会贴住右侧按钮,改成自绘箭头并留出内边距 */
|
||||
.sortbox select{
|
||||
appearance:none;-webkit-appearance:none;border:0;background:transparent;font-size:13px;color:#3d4859;
|
||||
outline:none;padding:3px 18px 3px 2px;cursor:pointer;flex-shrink:0;
|
||||
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path d='M1 1l4 4 4-4' fill='none' stroke='%238b95a5' stroke-width='1.6' stroke-linecap='round'/></svg>");
|
||||
background-repeat:no-repeat;background-position:right 3px center;
|
||||
}
|
||||
.refreshbox select{padding-right:18px;width:56px}
|
||||
.chk{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);user-select:none}
|
||||
.btn{display:inline-flex;align-items:center;gap:6px;border-radius:8px;border:1px solid var(--line);background:#fff;color:#3d4859;padding:7px 12px;font-size:13px;cursor:pointer;white-space:nowrap}
|
||||
.btn:hover{background:#f6f8fb}
|
||||
.btn.primary{background:var(--blue);border-color:var(--blue);color:#fff}
|
||||
.btn.primary:hover{background:#1668d0}
|
||||
.btn.danger{color:var(--red);border-color:#f6d5d6}
|
||||
.btn svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:2}
|
||||
.ico-btn{border:0;background:transparent;color:#8b95a5;cursor:pointer;font-size:13px;padding:4px 6px;border-radius:6px}
|
||||
.ico-btn:hover{background:#eef2f8;color:#3d4859}
|
||||
|
||||
.view{padding:16px 20px 40px;overflow:auto;flex:1}
|
||||
|
||||
/* 卡片行 */
|
||||
.row{display:flex;align-items:center;gap:16px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:12px 14px;margin-bottom:8px;box-shadow:var(--shadow);transition:.15s}
|
||||
.row:hover{border-color:#cfe0f8;box-shadow:0 2px 10px rgba(26,115,232,.08)}
|
||||
.row.off{background:#fcfcfd}
|
||||
.row.off .bar{display:none}
|
||||
.row.off .wicon{background:#f2f4f7}
|
||||
.row.off .dot{background:#c3cad6}
|
||||
.wicon{width:34px;height:34px;border-radius:9px;background:#eef4fe;display:grid;place-items:center;position:relative;flex-shrink:0}
|
||||
.wicon svg{width:20px;height:20px}
|
||||
.dot{position:absolute;right:-2px;bottom:-2px;width:9px;height:9px;border-radius:50%;border:2px solid #fff;background:#c3cad6}
|
||||
.dot.up{background:var(--blue)}
|
||||
.dot.err{background:var(--red)}
|
||||
.ident{min-width:170px;flex:0 0 200px;overflow:hidden}
|
||||
.ident .nm{font-weight:600;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.ident .pj{font-size:12px;color:var(--muted);margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.metrics{display:flex;gap:16px;flex:1;flex-wrap:nowrap;align-items:center;overflow:hidden;min-width:0}
|
||||
.metric{min-width:88px;flex:0 0 auto;max-width:150px;overflow:hidden}
|
||||
.metric .net{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.metric .k{font-size:11px;color:var(--muted)}
|
||||
.metric .v{font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}
|
||||
.metric .v small{font-weight:400;color:var(--muted);font-size:11px}
|
||||
.bar{height:4px;border-radius:3px;background:#eef1f6;margin-top:4px;overflow:hidden;width:96px}
|
||||
.bar i{display:block;height:100%;background:var(--blue);border-radius:3px}
|
||||
.bar.mem i{background:#7a5af8}
|
||||
.bar.warn i{background:var(--amber)}
|
||||
.bar.hot i{background:var(--red)}
|
||||
.net{font-variant-numeric:tabular-nums;font-size:12px}
|
||||
.net .up{color:#1a73e8}
|
||||
.net .dn{color:#12b76a}
|
||||
.acts{display:flex;align-items:center;gap:4px;margin-left:auto;flex-shrink:0}
|
||||
.acts .ico-btn{display:grid;place-items:center;width:30px;height:30px;border-radius:8px;background:#f6f8fb;color:#5b6676}
|
||||
.acts .ico-btn:hover{background:#e9f1fe;color:var(--blue)}
|
||||
.acts .ico-btn svg{width:15px;height:15px;stroke:currentColor;fill:none;stroke-width:1.9}
|
||||
.acts .ico-btn.danger:hover{background:#fdeaea;color:var(--red)}
|
||||
|
||||
/* 概览 */
|
||||
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-bottom:16px}
|
||||
.card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;box-shadow:var(--shadow)}
|
||||
.card h3{margin:0 0 8px;font-size:12px;color:var(--muted);font-weight:500}
|
||||
.card .big{font-size:22px;font-weight:600;font-variant-numeric:tabular-nums}
|
||||
.card .sub{font-size:12px;color:var(--muted);margin-top:4px}
|
||||
.section-title{display:flex;align-items:center;gap:10px;margin:20px 0 10px}
|
||||
.section-title h2{font-size:14px;margin:0;font-weight:600}
|
||||
table.tb{width:100%;border-collapse:collapse;background:#fff;border:1px solid var(--line);border-radius:var(--radius);overflow:hidden}
|
||||
table.tb th,table.tb td{padding:10px 12px;text-align:left;font-size:13px;border-bottom:1px solid var(--line)}
|
||||
table.tb th{background:#fafbfd;color:var(--muted);font-weight:500;font-size:12px;cursor:pointer;user-select:none}
|
||||
table.tb tr:last-child td{border-bottom:0}
|
||||
table.tb td.num{text-align:right;font-variant-numeric:tabular-nums}
|
||||
table.tb th.num{text-align:right}
|
||||
.tag{display:inline-block;padding:1px 7px;border-radius:20px;font-size:11px;background:#eef2f8;color:#5b6676}
|
||||
.tag.blue{background:var(--blue-soft);color:var(--blue)}
|
||||
.tag.green{background:#e6f7ee;color:#0f9d58}
|
||||
|
||||
/* 抽屉 */
|
||||
.drawer{position:fixed;inset:0;z-index:40}
|
||||
.drawer.hidden{display:none}
|
||||
.drawer-mask{position:absolute;inset:0;background:rgba(16,24,40,.32)}
|
||||
.drawer-panel{position:absolute;right:0;top:0;bottom:0;width:min(760px,92vw);background:#fff;display:flex;flex-direction:column;box-shadow:-8px 0 30px rgba(16,24,40,.14);animation:slide .18s ease}
|
||||
@keyframes slide{from{transform:translateX(24px);opacity:.6}to{transform:none;opacity:1}}
|
||||
.drawer-head{display:flex;align-items:flex-start;justify-content:space-between;padding:16px 18px;border-bottom:1px solid var(--line)}
|
||||
.drawer-head h2{margin:0;font-size:16px}
|
||||
.drawer-actions{display:flex;gap:8px;padding:10px 18px;border-bottom:1px solid var(--line);flex-wrap:wrap}
|
||||
.tabs{display:flex;gap:6px;padding:10px 18px 0;border-bottom:1px solid var(--line)}
|
||||
.tabs button{border:0;background:transparent;padding:8px 12px;font-size:13px;color:var(--muted);cursor:pointer;border-bottom:2px solid transparent}
|
||||
.tabs button.active{color:var(--blue);border-bottom-color:var(--blue);font-weight:600}
|
||||
.drawer-body{padding:16px 18px 40px;overflow:auto;flex:1}
|
||||
.stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px}
|
||||
.stat{background:#fafbfd;border:1px solid var(--line);border-radius:9px;padding:10px 12px}
|
||||
.stat .k{font-size:11px;color:var(--muted)}
|
||||
.stat .v{font-size:16px;font-weight:600;font-variant-numeric:tabular-nums;margin-top:2px}
|
||||
.spark{width:100%;height:90px;background:#fafbfd;border:1px solid var(--line);border-radius:9px;display:block}
|
||||
.code{background:#0f172a;color:#d6e2f5;border-radius:9px;padding:12px;font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-all;max-height:420px;overflow:auto}
|
||||
.kv{display:grid;grid-template-columns:150px 1fr;gap:6px 12px;font-size:13px}
|
||||
.kv .k{color:var(--muted)}
|
||||
.empty{text-align:center;color:var(--muted);padding:60px 0;font-size:13px}
|
||||
|
||||
/* 弹窗 */
|
||||
.modal{position:fixed;inset:0;z-index:50;display:grid;place-items:center}
|
||||
.modal.hidden{display:none}
|
||||
.modal-mask{position:absolute;inset:0;background:rgba(16,24,40,.32)}
|
||||
.modal-box{position:relative;background:#fff;border-radius:12px;width:min(560px,94vw);max-height:88vh;overflow:auto;padding:18px 20px;box-shadow:0 20px 50px rgba(16,24,40,.2)}
|
||||
.modal-box h2{margin:0 0 14px;font-size:16px}
|
||||
.modal-box label{display:block;font-size:12px;color:var(--muted);margin:10px 0 4px}
|
||||
.modal-box input,.modal-box textarea{width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font-size:13px;outline:none;font-family:inherit}
|
||||
.modal-box input:focus,.modal-box textarea:focus{border-color:#bcd4f7}
|
||||
.modal-foot{display:flex;justify-content:flex-end;gap:8px;margin-top:16px}
|
||||
.ports-row{display:flex;gap:6px;align-items:center;margin-bottom:6px}
|
||||
.ports-row input{width:110px}
|
||||
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#101828;color:#fff;padding:10px 16px;border-radius:9px;font-size:13px;z-index:60;box-shadow:0 8px 24px rgba(16,24,40,.24)}
|
||||
.toast.hidden{display:none}
|
||||
.toast.err{background:#b42318}
|
||||
.foot{color:var(--muted);font-size:12px;padding:14px 2px}
|
||||
|
||||
/* ================= 应用看板 v2 ================= */
|
||||
.nav-badge.alert{background:#fdeaea;color:#b42318}
|
||||
.nav-badge.warn{background:#fff4e5;color:#b54708}
|
||||
.stat-strip{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px;margin-bottom:14px}
|
||||
.stat-strip.small .s-card{padding:10px 12px}
|
||||
.s-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:12px 14px;box-shadow:var(--shadow)}
|
||||
.s-card .k{font-size:12px;color:var(--muted)}
|
||||
.s-card .v{font-size:22px;font-weight:600;font-variant-numeric:tabular-nums;margin-top:2px}
|
||||
.stat-strip.small .s-card .v{font-size:17px}
|
||||
.s-card .s{font-size:11px;color:var(--muted);margin-top:2px}
|
||||
.s-card.bad{border-color:#fbd5d5;background:#fffafa}
|
||||
.s-card.bad .v{color:var(--red)}
|
||||
.s-card.warn{border-color:#fce7c6;background:#fffcf7}
|
||||
.s-card.warn .v{color:var(--amber)}
|
||||
.filters{display:flex;gap:8px;align-items:center;margin-bottom:12px;flex-wrap:wrap}
|
||||
.chip{border:1px solid var(--line);background:#fff;border-radius:20px;padding:5px 12px;font-size:13px;cursor:pointer;color:#3d4859}
|
||||
.chip b{font-weight:600;color:var(--muted);margin-left:2px}
|
||||
.chip.on{background:var(--blue-soft);border-color:#bcd4f7;color:var(--blue);font-weight:600}
|
||||
.chip.on b{color:var(--blue)}
|
||||
.app-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(330px,1fr));gap:12px}
|
||||
.app-card{background:#fff;border:1px solid var(--line);border-radius:12px;padding:14px;box-shadow:var(--shadow);cursor:pointer;transition:.15s;display:flex;flex-direction:column;gap:10px}
|
||||
.app-card:hover{border-color:#cfe0f8;box-shadow:0 4px 16px rgba(26,115,232,.1);transform:translateY(-1px)}
|
||||
.app-card.sev2{border-left:3px solid var(--red)}
|
||||
.app-card.sev1{border-left:3px solid var(--amber)}
|
||||
.app-head{display:flex;align-items:center;gap:10px}
|
||||
.avatar{width:34px;height:34px;border-radius:9px;color:#fff;display:grid;place-items:center;font-size:13px;font-weight:700;flex-shrink:0}
|
||||
.app-title{min-width:0;flex:1}
|
||||
.app-name{font-weight:600;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.app-sub{font-size:11.5px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.pill{font-size:11px;padding:2px 9px;border-radius:20px;white-space:nowrap;flex-shrink:0}
|
||||
.pill.ok{background:#e6f7ee;color:#0f9d58}
|
||||
.pill.warn{background:#fff4e5;color:#b54708}
|
||||
.pill.bad{background:#fdeaea;color:#b42318}
|
||||
.pill.stop{background:#eef1f6;color:#5b6676}
|
||||
.app-metrics{display:grid;grid-template-columns:1fr 1fr 1.15fr;gap:12px}
|
||||
.app-metrics .k{font-size:11px;color:var(--muted)}
|
||||
.app-metrics .v{font-size:13.5px;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:clip;padding-right:2px}
|
||||
.app-issues{display:flex;flex-direction:column;gap:4px}
|
||||
.issue{font-size:11.5px;padding:4px 8px;border-radius:6px;line-height:1.4}
|
||||
.issue.critical{background:#fdeaea;color:#b42318}
|
||||
.issue.warning{background:#fff4e5;color:#b54708}
|
||||
.issue.more{background:#f2f4f7;color:#5b6676}
|
||||
.issue-box{display:flex;flex-direction:column;gap:5px;margin:0 0 12px}
|
||||
.app-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;border-top:1px solid var(--line);padding-top:9px;margin-top:auto}
|
||||
.app-ports{display:flex;gap:4px;flex-wrap:wrap}
|
||||
.port{font-size:11px;background:#eef4fe;color:#1a73e8;border-radius:6px;padding:1px 7px;cursor:pointer;font-variant-numeric:tabular-nums}
|
||||
.port:hover{background:#dbe9fd}
|
||||
.app-meta{font-size:11px;color:var(--muted);white-space:nowrap}
|
||||
.app-acts{display:flex;gap:6px}
|
||||
.mini{border:1px solid var(--line);background:#fff;border-radius:7px;padding:4px 9px;font-size:12px;cursor:pointer;color:#3d4859}
|
||||
.mini:hover{background:#f6f8fb}
|
||||
.mini.primary{background:var(--blue);border-color:var(--blue);color:#fff}
|
||||
.mini.primary:hover{background:#1668d0}
|
||||
.mini.danger:hover{background:#fdeaea;color:var(--red);border-color:#f6d5d6}
|
||||
.mini:disabled{opacity:.45;cursor:not-allowed}
|
||||
.timeline{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:10px 14px;display:flex;flex-direction:column;gap:8px}
|
||||
.ev{display:flex;gap:10px;align-items:flex-start;font-size:13px}
|
||||
.ev .t{color:var(--muted);font-size:11.5px;width:92px;flex-shrink:0;font-variant-numeric:tabular-nums}
|
||||
.ev .dotmark{width:7px;height:7px;border-radius:50%;background:#98a2b3;margin-top:6px;flex-shrink:0}
|
||||
.ev.critical .dotmark{background:var(--red)}
|
||||
.ev.warning .dotmark{background:var(--amber)}
|
||||
.ev.info .dotmark{background:var(--green)}
|
||||
.detail-head{display:flex;align-items:center;gap:12px;margin-bottom:12px;flex-wrap:wrap}
|
||||
.detail-title{display:flex;align-items:center;gap:10px;flex:1;min-width:0}
|
||||
.detail-title h2{margin:0;font-size:16px}
|
||||
.detail-acts{display:flex;gap:6px;margin-left:auto}
|
||||
.tabs.inline{padding:0 0 0;border-bottom:1px solid var(--line);margin:14px 0 12px}
|
||||
.form-row{display:flex;align-items:center;gap:10px;margin:10px 0;font-size:13px}
|
||||
.form-row label{width:180px;color:var(--muted);flex-shrink:0}
|
||||
.form-row input[type=number],.form-row input[type=text],.form-row input:not([type]){width:120px;padding:6px 9px;border:1px solid var(--line);border-radius:7px;font-size:13px;outline:none}
|
||||
.form-row input:focus{border-color:#bcd4f7}
|
||||
@media (max-width:1100px){.app-grid{grid-template-columns:1fr}}
|
||||
|
||||
/* 优化建议 */
|
||||
.insight-box{background:var(--panel);border:1px solid var(--line);border-radius:12px;margin-bottom:14px;overflow:hidden;box-shadow:var(--shadow)}
|
||||
.insight-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:11px 14px;border-bottom:1px solid var(--line);background:#fcfdff}
|
||||
.insight-box.none .insight-head{border-bottom:0}
|
||||
.insight-title{display:flex;align-items:center;gap:8px;font-size:13.5px;min-width:0}
|
||||
.insight-title b{font-weight:650;color:#26303f}
|
||||
.ic-dot{width:8px;height:8px;border-radius:50%;background:var(--amber);box-shadow:0 0 0 3px rgba(247,144,9,.15);flex-shrink:0}
|
||||
.ic-dot.ok{background:var(--green);box-shadow:0 0 0 3px rgba(18,183,106,.15)}
|
||||
.insight-counts{display:flex;gap:6px;font-size:11.5px;flex-shrink:0}
|
||||
.insight-counts .ic{padding:2px 8px;border-radius:20px;background:#f3f5f9;color:#6b7688}
|
||||
.insight-counts .ic.high{background:#fdecec;color:#cf3b3b}
|
||||
.insight-counts .ic.mid{background:#fff5e6;color:#b57209}
|
||||
.insight-counts .ic.low{background:#eef4ff;color:#3a6fbf}
|
||||
.insight-list{display:flex;flex-direction:column}
|
||||
.insight{display:flex;align-items:flex-start;gap:10px;padding:10px 14px 10px 13px;border-top:1px solid #eef2f7;border-left:3px solid transparent}
|
||||
.insight:first-child{border-top:0}
|
||||
.insight .dot{width:8px;height:8px;border-radius:50%;margin-top:5px;flex-shrink:0;background:#c3cbd8}
|
||||
.insight.high{border-left-color:var(--red)}
|
||||
.insight.high .dot{background:var(--red)}
|
||||
.insight.mid{border-left-color:var(--amber)}
|
||||
.insight.mid .dot{background:var(--amber)}
|
||||
.insight.low{border-left-color:#7a9ed6}
|
||||
.insight.low .dot{background:#7a9ed6}
|
||||
.insight .it{flex:1;min-width:0}
|
||||
.insight .it-t{font-size:13px;color:#26303f;font-weight:560;display:flex;align-items:center;gap:7px;flex-wrap:wrap}
|
||||
.insight .it-d{font-size:12px;color:var(--muted);margin-top:2px;line-height:1.55}
|
||||
.app-tag{font-size:11px;padding:1px 6px;border-radius:5px;background:#eef2f9;color:#5b6a85;font-weight:500;white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis}
|
||||
.app-tag.sys{background:#f3f0fb;color:#6f5bb5}
|
||||
.insight .mini{flex-shrink:0;margin-top:1px}
|
||||
.insight-more{width:100%;border:0;border-top:1px solid #f1f4f8;background:#fafbfd;color:#4a72bd;font-size:12px;padding:8px;cursor:pointer;font-family:inherit}
|
||||
.insight-more:hover{background:#f2f6fd}
|
||||
|
||||
/* 有镜像但未启动的应用 */
|
||||
.sec-head{display:flex;align-items:baseline;gap:10px;margin:14px 0 10px;font-size:13.5px;color:#26303f}
|
||||
.sec-head.sub{margin-top:22px}
|
||||
.sec-head .muted{font-size:12px}
|
||||
.pend-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(238px,1fr));gap:10px}
|
||||
.pend-card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:11px 12px;box-shadow:var(--shadow);display:flex;flex-direction:column;gap:6px}
|
||||
.pend-top{display:flex;align-items:center;gap:8px;min-width:0}
|
||||
.pend-top b{font-size:13.5px;color:#26303f;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.pend-top .tag{font-size:11px;color:#5b6a85;background:#eef2f9;border-radius:5px;padding:1px 6px;white-space:nowrap;flex-shrink:0}
|
||||
.pend-sub{font-size:11.5px;color:#6b7688;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.pend-img{font-size:11.5px;min-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.warn-txt{color:#b57209}
|
||||
.ok-txt{color:#12a15f}
|
||||
.pend-acts{display:flex;gap:6px;margin-top:2px}
|
||||
+882
@@ -0,0 +1,882 @@
|
||||
'use strict';
|
||||
/* 飞牛docker容器管理增强版 — 面向多应用用户的管理与监控 */
|
||||
const express = require('express');
|
||||
const Docker = require('dockerode');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs/promises');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { PassThrough } = require('stream');
|
||||
const { execFile } = require('child_process');
|
||||
|
||||
const docker = new Docker({ socketPath: process.env.DOCKER_SOCK || '/var/run/docker.sock' });
|
||||
const app = express();
|
||||
const PORT = Number(process.env.PORT || 7030);
|
||||
const SAMPLE_MS = Number(process.env.SAMPLE_MS || 3000);
|
||||
const INSPECT_MS = Number(process.env.INSPECT_MS || 15000);
|
||||
const UPTIME_MS = Number(process.env.UPTIME_MS || 60000);
|
||||
const HISTORY_MAX = 240;
|
||||
const UPTIME_MAX = 1440;
|
||||
const EVENT_MAX = 400;
|
||||
const SETTINGS_PATH = process.env.SETTINGS_PATH || '/data/settings.json';
|
||||
const COMPOSE_ROOT = process.env.COMPOSE_ROOT || '/host/vol1/1000/HD1/docker';
|
||||
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
app.use(express.static(path.join(__dirname, '..', 'public')));
|
||||
|
||||
/* ---------------- 设置 ---------------- */
|
||||
const DEFAULT_SETTINGS = {
|
||||
thresholds: { cpu: 85, mem: 90, diskFreePct: 10 }, // cpu 为占整机核数比(%), mem 为容器内存上限占比(%)
|
||||
webhook: '',
|
||||
notify: true,
|
||||
debounceMinutes: 10,
|
||||
};
|
||||
let settings = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
|
||||
try {
|
||||
if (fs.existsSync(SETTINGS_PATH)) {
|
||||
const saved = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8'));
|
||||
settings = { ...settings, ...saved, thresholds: { ...settings.thresholds, ...(saved.thresholds || {}) } };
|
||||
}
|
||||
} catch (e) { console.error('[settings] 读取失败', e.message); }
|
||||
function saveSettings() {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(SETTINGS_PATH), { recursive: true });
|
||||
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2));
|
||||
} catch (e) { console.error('[settings] 写入失败', e.message); }
|
||||
}
|
||||
|
||||
/* ---------------- 内存状态 ---------------- */
|
||||
const stats = new Map(); // containerId -> 采样
|
||||
const history = new Map(); // containerId -> [{t,c,m,rx,tx}]
|
||||
const meta = new Map(); // containerId -> {state,health,restarts,startedAt,exitCode,restartPolicy,memLimitCfg,privileged,user,healthcheck,dockerSock,inspected}
|
||||
const events = []; // {t,level,appKey,title,detail}
|
||||
const appState = new Map(); // appKey -> {severity,uptime[],lastNotifyAt,since}
|
||||
const restartsSeen = new Map();
|
||||
let lastError = '';
|
||||
let dfCache = { at: 0, data: null };
|
||||
|
||||
/* ---------------- 工具 ---------------- */
|
||||
const strip = (n) => (n || '').replace(/^\//, '');
|
||||
// 容器内的 os.hostname() 是容器 ID,推送里要用真实宿主机名
|
||||
function hostName() {
|
||||
try {
|
||||
const h = fs.readFileSync('/host/etc/hostname', 'utf8').trim();
|
||||
if (h) return h;
|
||||
} catch (e) {}
|
||||
return os.hostname();
|
||||
}
|
||||
function demuxLogs(buf) {
|
||||
if (!Buffer.isBuffer(buf)) return String(buf || '');
|
||||
const mux = buf.length > 8 && buf[0] <= 2 && buf[1] === 0 && buf[2] === 0 && buf[3] === 0;
|
||||
if (!mux) return buf.toString('utf8');
|
||||
const parts = [];
|
||||
let i = 0;
|
||||
while (i + 8 <= buf.length) {
|
||||
const size = buf.readUInt32BE(i + 4);
|
||||
const start = i + 8;
|
||||
if (start + size > buf.length) { parts.push(buf.slice(start)); break; }
|
||||
parts.push(buf.slice(start, start + size));
|
||||
i = start + size;
|
||||
}
|
||||
return Buffer.concat(parts).toString('utf8');
|
||||
}
|
||||
const projectOf = (labels) => (labels && labels['com.docker.compose.project']) || '';
|
||||
const svcOf = (labels) => (labels && labels['com.docker.compose.service']) || '';
|
||||
const appKeyOf = (c) => {
|
||||
const p = projectOf(c.Labels);
|
||||
return p ? `compose:${p}` : `solo:${strip((c.Names || [])[0])}`;
|
||||
};
|
||||
|
||||
/* ---------------- 采样 ---------------- */
|
||||
function computeUsage(id, s) {
|
||||
const prev = stats.get(id);
|
||||
const now = Date.now();
|
||||
const c = s.cpu_stats || {}, pc = s.precpu_stats || {};
|
||||
const cpuDelta = (c.cpu_usage?.total_usage || 0) - (pc.cpu_usage?.total_usage || 0);
|
||||
const sysDelta = (c.system_cpu_usage || 0) - (pc.system_cpu_usage || 0);
|
||||
const cores = c.online_cpus || os.cpus().length || 1;
|
||||
let cpu = 0;
|
||||
if (cpuDelta > 0 && sysDelta > 0) cpu = (cpuDelta / sysDelta) * cores * 100;
|
||||
const ms = s.memory_stats || {};
|
||||
const cache = ms.stats?.inactive_file ?? ms.stats?.cache ?? 0;
|
||||
const mem = Math.max(0, (ms.usage || 0) - cache);
|
||||
const memLimit = ms.limit && ms.limit < 9e15 ? ms.limit : os.totalmem();
|
||||
let rx = 0, tx = 0;
|
||||
for (const n of Object.values(s.networks || {})) { rx += n.rx_bytes || 0; tx += n.tx_bytes || 0; }
|
||||
let rd = 0, wr = 0;
|
||||
for (const b of (s.blkio_stats?.io_service_bytes_recursive || [])) {
|
||||
if (b.op === 'read') rd += b.value; else if (b.op === 'write') wr += b.value;
|
||||
}
|
||||
const dt = prev ? Math.max(0.5, (now - prev.ts) / 1000) : 0;
|
||||
const rate = (cur, old) => (prev && dt > 0 ? Math.max(0, (cur - (old || 0)) / dt) : 0);
|
||||
const out = {
|
||||
ts: now, cpu: +cpu.toFixed(2), mem, memLimit, memPct: memLimit ? +(mem / memLimit * 100).toFixed(2) : 0,
|
||||
rx, tx, rxBps: rate(rx, prev?.rx), txBps: rate(tx, prev?.tx),
|
||||
rd, wr, rdBps: rate(rd, prev?.rd), wrBps: rate(wr, prev?.wr),
|
||||
pids: s.pids_stats?.current || 0,
|
||||
};
|
||||
stats.set(id, out);
|
||||
let h = history.get(id); if (!h) { h = []; history.set(id, h); }
|
||||
h.push({ t: out.ts, c: out.cpu, m: out.mem, rx: out.rxBps, tx: out.txBps });
|
||||
if (h.length > HISTORY_MAX) h.shift();
|
||||
return out;
|
||||
}
|
||||
|
||||
async function sampleOnce() {
|
||||
try {
|
||||
const list = await docker.listContainers({ all: false });
|
||||
const alive = new Set(list.map(c => c.Id));
|
||||
for (const id of [...stats.keys()]) if (!alive.has(id)) { stats.delete(id); history.delete(id); }
|
||||
await Promise.all(list.map(async c => {
|
||||
try { computeUsage(c.Id, await docker.getContainer(c.Id).stats({ stream: false })); } catch (e) {}
|
||||
}));
|
||||
lastError = '';
|
||||
} catch (e) { lastError = e.message; }
|
||||
}
|
||||
|
||||
/* 重启次数 / 健康状态:15 秒刷一次,避免每次采样都 inspect */
|
||||
async function inspectAll() {
|
||||
try {
|
||||
const list = await docker.listContainers({ all: true });
|
||||
for (const c of list) {
|
||||
const old = meta.get(c.Id) || {};
|
||||
const next = {
|
||||
state: c.State, restarts: old.restarts || 0, health: old.health || '',
|
||||
startedAt: old.startedAt || '', exitCode: old.exitCode ?? 0,
|
||||
restartPolicy: old.restartPolicy || '', memLimitCfg: old.memLimitCfg || 0,
|
||||
privileged: !!old.privileged, user: old.user || '', healthcheck: !!old.healthcheck,
|
||||
dockerSock: !!old.dockerSock, inspected: !!old.inspected,
|
||||
};
|
||||
meta.set(c.Id, next);
|
||||
const changed = old.state !== c.State;
|
||||
if (c.State === 'running' || changed || !old.inspected) {
|
||||
try {
|
||||
const d = await docker.getContainer(c.Id).inspect();
|
||||
next.restarts = d.RestartCount || 0;
|
||||
next.health = d.State?.Health?.Status || '';
|
||||
next.startedAt = d.State?.StartedAt || '';
|
||||
next.exitCode = d.State?.ExitCode ?? 0;
|
||||
next.restartPolicy = d.HostConfig?.RestartPolicy?.Name || 'no';
|
||||
next.memLimitCfg = d.HostConfig?.Memory || 0;
|
||||
next.privileged = !!d.HostConfig?.Privileged;
|
||||
next.user = d.Config?.User || '';
|
||||
next.healthcheck = !!(d.Config?.Healthcheck && (d.Config.Healthcheck.Test || []).length);
|
||||
next.dockerSock = (d.Mounts || []).some(m => String(m.Source || '').includes('docker.sock'));
|
||||
next.inspected = true;
|
||||
const seen = restartsSeen.get(c.Id);
|
||||
if (seen !== undefined && next.restarts > seen) {
|
||||
pushEvent('warning', appKeyOf(c), `${strip((c.Names || [])[0])} 发生重启`, `重启次数 ${seen} → ${next.restarts}`);
|
||||
}
|
||||
restartsSeen.set(c.Id, next.restarts);
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
} catch (e) { lastError = e.message; }
|
||||
}
|
||||
|
||||
/* ---------------- 应用聚合与健康 ---------------- */
|
||||
function buildApps(containers) {
|
||||
const map = new Map();
|
||||
for (const c of containers) {
|
||||
const key = appKeyOf(c);
|
||||
if (!map.has(key)) {
|
||||
map.set(key, {
|
||||
key, name: projectOf(c.Labels) || strip((c.Names || [])[0]),
|
||||
type: projectOf(c.Labels) ? 'compose' : 'solo',
|
||||
containers: [], cpu: 0, mem: 0, rxBps: 0, txBps: 0, memPctMax: 0,
|
||||
running: 0, total: 0, ports: [], issues: [], restarts: 0, startedAt: null,
|
||||
});
|
||||
}
|
||||
const a = map.get(key);
|
||||
const st = stats.get(c.Id) || {};
|
||||
const m = meta.get(c.Id) || {};
|
||||
a.containers.push({
|
||||
id: c.Id, name: strip((c.Names || [])[0]), service: svcOf(c.Labels),
|
||||
image: c.Image, state: c.State, status: c.Status,
|
||||
health: m.health || '', restarts: m.restarts || 0, startedAt: m.startedAt || '', exitCode: m.exitCode ?? 0,
|
||||
restartPolicy: m.restartPolicy || '', memLimitCfg: m.memLimitCfg || 0,
|
||||
privileged: !!m.privileged, healthcheck: !!m.healthcheck, dockerSock: !!m.dockerSock,
|
||||
ports: (c.Ports || []).filter(pp => pp.PublicPort).length,
|
||||
runMs: c.State === 'running' && m.startedAt ? Math.max(0, Date.now() - Date.parse(m.startedAt)) : null,
|
||||
stats: {
|
||||
cpu: st.cpu ?? 0, mem: st.mem ?? 0, memPct: st.memPct ?? 0,
|
||||
rxBps: st.rxBps ?? 0, txBps: st.txBps ?? 0, rdBps: st.rdBps ?? 0, wrBps: st.wrBps ?? 0, pids: st.pids ?? 0,
|
||||
},
|
||||
});
|
||||
a.total++;
|
||||
if (c.State === 'running') a.running++;
|
||||
a.cpu += st.cpu || 0;
|
||||
a.mem += st.mem || 0;
|
||||
a.rxBps += st.rxBps || 0;
|
||||
a.txBps += st.txBps || 0;
|
||||
a.memPctMax = Math.max(a.memPctMax, st.memPct || 0);
|
||||
a.restarts += m.restarts || 0;
|
||||
for (const p of (c.Ports || [])) if (p.PublicPort) a.ports.push({ public: p.PublicPort, private: p.PrivatePort, type: p.Type });
|
||||
if (c.State === 'running' && m.startedAt && (!a.startedAt || m.startedAt < a.startedAt)) a.startedAt = m.startedAt;
|
||||
}
|
||||
|
||||
const cores = os.cpus().length || 1;
|
||||
const cpuLimit = settings.thresholds.cpu || 85;
|
||||
const memLimit = settings.thresholds.mem || 90;
|
||||
|
||||
for (const a of map.values()) {
|
||||
a.ports = [...new Map(a.ports.map(p => [p.public, p])).values()].sort((x, y) => x.public - y.public);
|
||||
const down = a.containers.filter(c => c.state !== 'running');
|
||||
if (down.length && a.running > 0) {
|
||||
a.issues.push({ level: 'critical', code: 'partial_down', text: `${down.length} 个容器未运行(${down.map(c => c.name).join('、')})` });
|
||||
} else if (down.length && a.running === 0) {
|
||||
a.issues.push({ level: 'warning', code: 'stopped', text: '应用已停止' });
|
||||
}
|
||||
for (const c of a.containers) {
|
||||
if (c.health === 'unhealthy') a.issues.push({ level: 'critical', code: 'unhealthy', text: `${c.name} 健康检查失败` });
|
||||
else if (c.health === 'starting') a.issues.push({ level: 'warning', code: 'health_starting', text: `${c.name} 健康检查中` });
|
||||
}
|
||||
const cpuPctOfMachine = a.cpu / cores;
|
||||
if (cpuPctOfMachine > cpuLimit) a.issues.push({ level: 'warning', code: 'cpu', text: `CPU 占整机 ${cpuPctOfMachine.toFixed(1)}%(阈值 ${cpuLimit}%)` });
|
||||
if (a.memPctMax > memLimit) a.issues.push({ level: 'warning', code: 'mem', text: `内存占上限 ${a.memPctMax.toFixed(1)}%(阈值 ${memLimit}%)` });
|
||||
a.cpuPctOfMachine = +cpuPctOfMachine.toFixed(2);
|
||||
a.severity = a.issues.some(i => i.level === 'critical') ? 2 : (a.issues.length ? 1 : 0);
|
||||
a.statusText = a.severity === 2 ? '异常' : a.severity === 1 ? '注意' : '正常';
|
||||
const st = appState.get(a.key);
|
||||
a.uptime = computeUptime(st?.uptime);
|
||||
a.runMs = a.running > 0 && a.startedAt ? Math.max(0, Date.now() - Date.parse(a.startedAt)) : null;
|
||||
a.since = st?.since || null;
|
||||
delete a.containers_meta;
|
||||
}
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
function computeUptime(points) {
|
||||
if (!points || !points.length) return null;
|
||||
const ok = points.filter(p => p.ok).length;
|
||||
return +(ok / points.length * 100).toFixed(2);
|
||||
}
|
||||
|
||||
function pushEvent(level, appKey, title, detail) {
|
||||
const ev = { t: Date.now(), level, appKey, title, detail };
|
||||
events.unshift(ev);
|
||||
if (events.length > EVENT_MAX) events.pop();
|
||||
return ev;
|
||||
}
|
||||
|
||||
async function tickApps() {
|
||||
try {
|
||||
const apps = buildApps(await docker.listContainers({ all: true }));
|
||||
for (const a of apps) {
|
||||
let st = appState.get(a.key);
|
||||
if (!st) {
|
||||
st = { severity: a.severity, uptime: [], since: Date.now(), lastNotifyAt: 0 };
|
||||
appState.set(a.key, st);
|
||||
// 首次发现就已异常,也要留一条事件,否则「一上线就坏」的应用没有任何记录
|
||||
if (a.severity > 0) {
|
||||
const ev = pushEvent(a.severity === 2 ? 'critical' : 'warning', a.key,
|
||||
`${a.name} ${a.severity === 2 ? '异常' : '注意'}`, a.issues.map(i => i.text).join(';'));
|
||||
notify(ev, a, st).catch(() => {});
|
||||
}
|
||||
}
|
||||
const prev = st.severity;
|
||||
if (a.severity > prev) {
|
||||
const ev = pushEvent(a.severity === 2 ? 'critical' : 'warning', a.key,
|
||||
`${a.name} ${a.severity === 2 ? '异常' : '注意'}`, a.issues.map(i => i.text).join(';'));
|
||||
notify(ev, a, st).catch(() => {});
|
||||
} else if (a.severity < prev && prev > 0) {
|
||||
pushEvent('info', a.key, `${a.name} 已恢复`, '所有容器恢复正常');
|
||||
}
|
||||
st.severity = a.severity;
|
||||
}
|
||||
const keys = new Set(apps.map(a => a.key));
|
||||
for (const k of [...appState.keys()]) if (!keys.has(k)) appState.delete(k);
|
||||
} catch (e) { lastError = e.message; }
|
||||
}
|
||||
|
||||
function tickUptime() {
|
||||
const now = Date.now();
|
||||
for (const [, st] of appState) {
|
||||
st.uptime.push({ t: now, ok: st.severity === 0 });
|
||||
if (st.uptime.length > UPTIME_MAX) st.uptime.shift();
|
||||
}
|
||||
}
|
||||
|
||||
async function notify(ev, appInfo, st) {
|
||||
if (!settings.notify || !settings.webhook) return;
|
||||
const now = Date.now();
|
||||
if (st && now - (st.lastNotifyAt || 0) < (settings.debounceMinutes || 10) * 60000) return;
|
||||
if (st) st.lastNotifyAt = now;
|
||||
try {
|
||||
await fetch(settings.webhook, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: `[${appInfo.statusText}] ${appInfo.name}`, level: ev.level, app: appInfo.name,
|
||||
detail: ev.detail, time: new Date(ev.t).toLocaleString('zh-CN', { hour12: false }), host: hostName(),
|
||||
}),
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
} catch (e) { console.error('[notify] 推送失败', e.message); }
|
||||
}
|
||||
|
||||
/* ---------------- 接口:主机 ---------------- */
|
||||
app.get('/api/health', (req, res) => res.json({ ok: true, lastError }));
|
||||
|
||||
app.get('/api/host', async (req, res) => {
|
||||
try {
|
||||
const info = await docker.info();
|
||||
const ver = await docker.version();
|
||||
let memTotal = os.totalmem(), memFree = os.freemem(), swapTotal = 0, swapFree = 0;
|
||||
try {
|
||||
const mi = fs.readFileSync('/proc/meminfo', 'utf8');
|
||||
const g = (k) => Number((mi.match(new RegExp(k + ':\\s+(\\d+)')) || [])[1] || 0) * 1024;
|
||||
memTotal = g('MemTotal'); memFree = g('MemAvailable'); swapTotal = g('SwapTotal'); swapFree = g('SwapFree');
|
||||
} catch (e) {}
|
||||
let disk = null;
|
||||
try {
|
||||
const st = fs.statfsSync(process.env.DISK_PATH || '/host/vol1');
|
||||
disk = { total: st.blocks * st.bsize, free: st.bavail * st.bsize };
|
||||
} catch (e) {}
|
||||
let pending = 0;
|
||||
try { pending = (await scanPending()).length; } catch (e) {}
|
||||
res.json({
|
||||
hostname: info.Name, os: info.OperatingSystem, kernel: info.KernelVersion,
|
||||
dockerVersion: ver.Version, cpus: info.NCPU, cpuModel: os.cpus()[0]?.model,
|
||||
loadavg: os.loadavg(), memTotal, memFree, swapTotal, swapFree, disk,
|
||||
containers: info.Containers, running: info.ContainersRunning,
|
||||
paused: info.ContainersPaused, stopped: info.ContainersStopped, pending,
|
||||
images: info.Images, driver: info.Driver, lastError,
|
||||
});
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- 接口:应用 ---------------- */
|
||||
app.get('/api/apps', async (req, res) => {
|
||||
try {
|
||||
let apps = buildApps(await docker.listContainers({ all: true }));
|
||||
const q = (req.query.q || '').trim().toLowerCase();
|
||||
if (q) apps = apps.filter(a => a.name.toLowerCase().includes(q) || a.containers.some(c => c.name.toLowerCase().includes(q)));
|
||||
const f = req.query.filter;
|
||||
if (f === 'issues') apps = apps.filter(a => a.severity > 0);
|
||||
else if (f === 'stopped') apps = apps.filter(a => a.running === 0);
|
||||
else if (f === 'high') apps = apps.filter(a => a.cpuPctOfMachine > 20 || a.memPctMax > 50);
|
||||
const cmp = {
|
||||
severity: (a, b) => (b.severity - a.severity) || (b.cpu - a.cpu),
|
||||
cpu: (a, b) => b.cpu - a.cpu,
|
||||
mem: (a, b) => b.mem - a.mem,
|
||||
name: (a, b) => b.name.localeCompare(a.name, 'zh'),
|
||||
containers: (a, b) => b.total - a.total,
|
||||
}[req.query.sort] || ((a, b) => (b.severity - a.severity) || (b.cpu - a.cpu));
|
||||
const dir = req.query.order === 'asc' ? -1 : 1;
|
||||
apps.sort((a, b) => dir * cmp(a, b));
|
||||
res.json({
|
||||
summary: {
|
||||
total: apps.length,
|
||||
critical: apps.filter(a => a.severity === 2).length,
|
||||
warning: apps.filter(a => a.severity === 1).length,
|
||||
stopped: apps.filter(a => a.running === 0).length,
|
||||
running: apps.filter(a => a.running > 0).length,
|
||||
cpu: +apps.reduce((s, a) => s + a.cpu, 0).toFixed(2),
|
||||
mem: apps.reduce((s, a) => s + a.mem, 0),
|
||||
containers: apps.reduce((s, a) => s + a.total, 0),
|
||||
},
|
||||
items: apps,
|
||||
});
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.get('/api/apps/:key', async (req, res) => {
|
||||
try {
|
||||
const key = decodeURIComponent(req.params.key);
|
||||
const a = buildApps(await docker.listContainers({ all: true })).find(x => x.key === key);
|
||||
if (!a) return res.status(404).json({ error: '应用不存在' });
|
||||
const st = appState.get(key);
|
||||
a.uptimeHistory = (st?.uptime || []).slice(-120);
|
||||
a.events = events.filter(e => e.appKey === key).slice(0, 15);
|
||||
a.cpuPctOfMachine = a.cpuPctOfMachine || 0;
|
||||
res.json(a);
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/apps/:key/action', async (req, res) => {
|
||||
const { action } = req.body || {};
|
||||
try {
|
||||
const key = decodeURIComponent(req.params.key);
|
||||
const a = buildApps(await docker.listContainers({ all: true })).find(x => x.key === key);
|
||||
if (!a) return res.status(404).json({ error: '应用不存在' });
|
||||
if (!['start', 'stop', 'restart'].includes(action)) return res.status(400).json({ error: '未知操作' });
|
||||
const results = [];
|
||||
for (const c of a.containers) {
|
||||
try {
|
||||
const ct = docker.getContainer(c.id);
|
||||
if (action === 'start') { if (c.state !== 'running') await ct.start(); }
|
||||
else if (action === 'stop') { if (c.state === 'running') await ct.stop({ t: 10 }); }
|
||||
else { if (c.state === 'running') await ct.restart({ t: 10 }); else await ct.start(); }
|
||||
results.push({ name: c.name, ok: true });
|
||||
} catch (e) { results.push({ name: c.name, ok: false, error: e.message }); }
|
||||
}
|
||||
res.json({ ok: true, results });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.get('/api/apps/:key/logs', async (req, res) => {
|
||||
try {
|
||||
const key = decodeURIComponent(req.params.key);
|
||||
const a = buildApps(await docker.listContainers({ all: true })).find(x => x.key === key);
|
||||
if (!a) return res.status(404).json({ error: '应用不存在' });
|
||||
const tail = Math.min(Number(req.query.tail || 120), 2000);
|
||||
const parts = [];
|
||||
for (const c of a.containers) {
|
||||
try {
|
||||
const text = demuxLogs(await docker.getContainer(c.id).logs({ stdout: true, stderr: true, timestamps: true, tail, follow: false }));
|
||||
if (text.trim()) parts.push(text.split('\n').filter(Boolean).map(l => `[${c.name}] ${l}`).join('\n'));
|
||||
} catch (e) { parts.push(`[${c.name}] 日志读取失败:${e.message}`); }
|
||||
}
|
||||
res.json({ logs: parts.join('\n') });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.get('/api/events', (req, res) => {
|
||||
const limit = Math.min(Number(req.query.limit || 30), 200);
|
||||
res.json({ items: events.slice(0, limit) });
|
||||
});
|
||||
|
||||
/* ---------------- 接口:有镜像但未启动的应用 ---------------- */
|
||||
let pendingCache = { at: 0, items: [] };
|
||||
const normRef = (r) => {
|
||||
const s = String(r).split('@')[0];
|
||||
return s.split('/').pop().includes(':') ? s : `${s}:latest`;
|
||||
};
|
||||
const shortRef = (r) => normRef(r).split('/').pop();
|
||||
|
||||
async function scanPending(force) {
|
||||
if (!force && pendingCache.items.length && Date.now() - pendingCache.at < 20000) return pendingCache.items;
|
||||
const [conts, imgs] = await Promise.all([
|
||||
docker.listContainers({ all: true }),
|
||||
docker.listImages(),
|
||||
]);
|
||||
const busy = new Set();
|
||||
for (const c of conts) {
|
||||
const p = (c.Labels || {})['com.docker.compose.project'];
|
||||
if (p) busy.add(String(p).toLowerCase());
|
||||
// 单容器也可能是这目录起的,用容器名兜底
|
||||
for (const n of (c.Names || [])) busy.add(strip(n).toLowerCase());
|
||||
}
|
||||
const local = new Set();
|
||||
for (const im of imgs) for (const t of (im.RepoTags || [])) { local.add(normRef(t)); local.add(shortRef(t)); }
|
||||
|
||||
const CAND = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];
|
||||
let dirs = [];
|
||||
try { dirs = await fsp.readdir(COMPOSE_ROOT, { withFileTypes: true }); } catch (e) { return []; }
|
||||
const items = [];
|
||||
for (const d of dirs) {
|
||||
if (!d.isDirectory() || d.name.startsWith('.')) continue;
|
||||
let file = null;
|
||||
for (const fn of CAND) {
|
||||
const p = path.join(COMPOSE_ROOT, d.name, fn);
|
||||
try { await fsp.access(p); file = p; break; } catch (e) {}
|
||||
}
|
||||
if (!file) continue;
|
||||
if (busy.has(d.name.toLowerCase())) continue;
|
||||
let txt = '';
|
||||
try { txt = await fsp.readFile(file, 'utf8'); } catch (e) { continue; }
|
||||
const refs = [...new Set([...txt.matchAll(/^\s*image:\s*["']?([^\s"'#]+)/gm)].map(m => m[1]))];
|
||||
const svcBlock = txt.split(/^services:\s*$/m)[1] || '';
|
||||
const services = [...new Set([...svcBlock.matchAll(/^ ([A-Za-z0-9._-]+):\s*$/gm)].map(m => m[1]))];
|
||||
const hasBuild = /^\s*build:/m.test(txt);
|
||||
const present = refs.filter(r => local.has(normRef(r)) || local.has(shortRef(r)));
|
||||
const missing = refs.filter(r => !(local.has(normRef(r)) || local.has(shortRef(r))));
|
||||
if (!present.length) continue; // 只要“有镜像”的
|
||||
items.push({
|
||||
key: `dir:${d.name}`, name: d.name, dir: path.join(COMPOSE_ROOT, d.name), file,
|
||||
services: services.length || refs.length, hasBuild,
|
||||
images: { total: refs.length, present: present.length, missing: missing.slice(0, 4) },
|
||||
mtime: (await fsp.stat(file).catch(() => ({ mtimeMs: 0 }))).mtimeMs,
|
||||
});
|
||||
}
|
||||
items.sort((a, b) => b.mtime - a.mtime || a.name.localeCompare(b.name));
|
||||
pendingCache = { at: Date.now(), items };
|
||||
return items;
|
||||
}
|
||||
|
||||
app.get('/api/pending-apps', async (req, res) => {
|
||||
try {
|
||||
const items = await scanPending(req.query.refresh === '1');
|
||||
res.json({ items, total: items.length, root: COMPOSE_ROOT });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/pending-apps/start', async (req, res) => {
|
||||
const name = String((req.body && req.body.name) || '');
|
||||
try {
|
||||
const items = await scanPending(true);
|
||||
const target = items.find(i => i.name === name);
|
||||
if (!target) return res.status(404).json({ error: '未找到该项目(可能已经有容器在内)' });
|
||||
const projName = target.name.toLowerCase().replace(/[^a-z0-9_-]/g, '');
|
||||
const env = { ...process.env };
|
||||
if (/^[a-z0-9][a-z0-9_-]*$/.test(projName)) env.COMPOSE_PROJECT_NAME = projName;
|
||||
const out = await new Promise((resolve) => {
|
||||
execFile('docker', ['compose', '-f', target.file, 'up', '-d'], {
|
||||
cwd: target.dir, timeout: 240000, maxBuffer: 2 * 1024 * 1024, env,
|
||||
}, (err, stdout, stderr) => resolve({
|
||||
ok: !err, code: err ? (err.code || 1) : 0,
|
||||
output: `${stdout || ''}${stderr || ''}`.trim().split('\n').slice(-14).join('\n'),
|
||||
}));
|
||||
});
|
||||
pendingCache.at = 0;
|
||||
inspectAll().catch(() => {});
|
||||
res.json(out);
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- 接口:优化建议 ---------------- */
|
||||
async function getDf(force) {
|
||||
if (!force && dfCache.data && Date.now() - dfCache.at < 60000) return dfCache.data;
|
||||
const d = await docker.df();
|
||||
dfCache = { at: Date.now(), data: d };
|
||||
return d;
|
||||
}
|
||||
|
||||
app.get('/api/insights', async (req, res) => {
|
||||
try {
|
||||
const apps = buildApps(await docker.listContainers({ all: true }));
|
||||
const items = [];
|
||||
const add = (sev, app, title, detail, action) => items.push({
|
||||
sev, appKey: app ? app.key : null, appName: app ? app.name : null, title, detail, action: action || null,
|
||||
});
|
||||
const mb = (n) => `${(n / 1048576).toFixed(0)} MB`;
|
||||
const gb = (n) => `${(n / 1073741824).toFixed(1)} GB`;
|
||||
const agg = { latest: [], solo: [], noHealth: [], noLimit: [] };
|
||||
|
||||
for (const a of apps) {
|
||||
const c = a.containers;
|
||||
const running = c.filter(x => x.state === 'running');
|
||||
|
||||
// 停止的应用:确认不用就删,要用就起来
|
||||
if (a.running === 0) {
|
||||
add('mid', a, '应用已停止', '确认不再需要就删掉,需要就启动;停着的应用仍占镜像和磁盘',
|
||||
{ type: 'startApp', label: '启动应用' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const flappy = c.filter(x => (x.restarts || 0) >= 3).sort((x, y) => y.restarts - x.restarts);
|
||||
if (flappy.length) {
|
||||
add('high', a, `${flappy.slice(0, 2).map(x => x.name).join('、')} 反复重启(${flappy[0].restarts} 次)`,
|
||||
'连续重启通常是配置错误、依赖服务不可用或健康检查失败,先看该容器日志',
|
||||
{ type: 'openApp', label: '查看日志' });
|
||||
}
|
||||
|
||||
const near = running.filter(x => (x.stats.memPct || 0) > 85);
|
||||
if (near.length) {
|
||||
add('mid', a, `${near[0].name} 内存接近上限(${(near[0].stats.memPct || 0).toFixed(0)}%)`,
|
||||
'持续贴近上限会频繁 GC 或被杀,建议提高上限或排查内存泄漏',
|
||||
{ type: 'openApp', label: '查看应用' });
|
||||
}
|
||||
|
||||
const hot = running.filter(x => (x.stats.cpu || 0) > 60);
|
||||
if (hot.length) {
|
||||
add('mid', a, `${hot[0].name} CPU 偏高(${(hot[0].stats.cpu || 0).toFixed(0)}%)`,
|
||||
'持续高 CPU 会挤压其他应用,建议限流(cpus)或排查死循环/高频任务',
|
||||
{ type: 'openApp', label: '查看应用' });
|
||||
}
|
||||
|
||||
if (c.some(x => x.privileged)) {
|
||||
add('high', a, '存在特权容器(privileged)', '特权容器几乎等同宿主 root,非必要请去掉 privileged', null);
|
||||
}
|
||||
if (c.some(x => x.dockerSock)) {
|
||||
add('mid', a, '容器挂载了 docker.sock', '挂载 Docker socket 的容器可以控制整台机器的容器(等同 root),确认是本人设计再用', null);
|
||||
}
|
||||
|
||||
// 汇总类问题
|
||||
const latest = c.filter(x => /:latest$/.test(x.image) || !x.image.split('/').pop().includes(':'));
|
||||
if (latest.length) agg.latest.push(a.name);
|
||||
if (a.type === 'solo') agg.solo.push(a.name);
|
||||
for (const x of running) {
|
||||
if (!x.healthcheck && (x.ports || 0) > 0) agg.noHealth.push(a.name);
|
||||
if (!x.memLimitCfg && (x.stats.mem || 0) > 0) agg.noLimit.push([a.name, x.name, x.stats.mem]);
|
||||
}
|
||||
}
|
||||
|
||||
const list = (arr, n = 3) => {
|
||||
const uniq = [...new Set(arr)];
|
||||
return uniq.slice(0, n).join('、') + (uniq.length > n ? ` 等 ${uniq.length} 个` : '');
|
||||
};
|
||||
|
||||
if (agg.noLimit.length) {
|
||||
const total = agg.noLimit.reduce((s, x) => s + x[2], 0);
|
||||
const top = agg.noLimit.sort((a, b) => b[2] - a[2])[0];
|
||||
if (total > 1073741824) {
|
||||
add('mid', null, `${agg.noLimit.length} 个容器未设内存上限(合计 ${gb(total)})`,
|
||||
`占用最高的是 ${top[1]}(${mb(top[2])})。没有 mem_limit 时单个容器可能吃满整机内存并触发 OOM,建议在 compose 里加 mem_limit(例:512m)`, null);
|
||||
}
|
||||
}
|
||||
if (agg.noHealth.length) {
|
||||
add('low', null, `${agg.noHealth.length} 个对外容器没有健康检查`,
|
||||
`涉及 ${list(agg.noHealth)}。没有 HEALTHCHECK 时「进程还在但服务已挂」无法被发现,建议补上健康检查`, null);
|
||||
}
|
||||
if (agg.latest.length) {
|
||||
add('low', null, `${agg.latest.length} 个应用使用 latest 镜像`,
|
||||
`涉及 ${list(agg.latest)}。latest 随上游变动,更新不可控也不便回滚,建议固定版本号`, null);
|
||||
}
|
||||
if (agg.solo.length) {
|
||||
add('low', null, `${agg.solo.length} 个应用未纳入 Compose`,
|
||||
`涉及 ${list(agg.solo)}。手工 docker run 的容器不便备份、迁移和版本化,建议写成 compose 文件`, null);
|
||||
}
|
||||
|
||||
let disk = null;
|
||||
try {
|
||||
const df = await getDf();
|
||||
const imgs = df.Images || [];
|
||||
const dangling = imgs.filter(i => !i.RepoTags || !i.RepoTags.length);
|
||||
const danglingSize = dangling.reduce((s, i) => s + (i.Size || 0), 0);
|
||||
const buildCache = (df.BuildCache || []).reduce((s, b) => s + (b.Size || 0), 0);
|
||||
disk = { danglingCount: dangling.length, danglingSize, buildCache, layersSize: df.LayersSize || 0 };
|
||||
if (danglingSize > 1073741824) {
|
||||
add('mid', null, `悬空镜像占用 ${gb(danglingSize)}`,
|
||||
`${dangling.length} 个无标签镜像没有任何容器在用,可以安全清理`, { type: 'pruneImages', label: '清理悬空镜像' });
|
||||
}
|
||||
if (buildCache > 5 * 1073741824) {
|
||||
add('mid', null, `构建缓存占用 ${gb(buildCache)}`,
|
||||
'docker build 留下的中间层,清理后下次构建会重新生成(不影响已在运行的容器)', { type: 'pruneBuildCache', label: '清理构建缓存' });
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
try {
|
||||
const st = await fsp.statfs(process.env.DISK_PATH || '/host/vol1');
|
||||
const free = st.bavail * st.bsize, size = st.blocks * st.bsize;
|
||||
const pct = size ? (free / size) * 100 : 100;
|
||||
disk = { ...(disk || {}), free, size };
|
||||
if (pct < 10) {
|
||||
add('high', null, `磁盘可用仅剩 ${gb(free)}(${pct.toFixed(0)}%)`,
|
||||
'磁盘写满会导致容器崩溃、数据库损坏,建议先清理悬空镜像与构建缓存,再处理大日志', null);
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
const order = { high: 0, mid: 1, low: 2 };
|
||||
items.sort((x, y) => order[x.sev] - order[y.sev]);
|
||||
const counts = { high: 0, mid: 0, low: 0 };
|
||||
for (const i of items) counts[i.sev]++;
|
||||
res.json({ items, counts, total: items.length, disk });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/maintenance/prune', async (req, res) => {
|
||||
const what = (req.body && req.body.what) || 'images';
|
||||
try {
|
||||
let out = { ok: true, what };
|
||||
if (what === 'buildCache') {
|
||||
const r = await docker.pruneBuilder({}).catch(async () => ({ SpaceReclaimed: 0 }));
|
||||
out.reclaimed = r.SpaceReclaimed || 0;
|
||||
} else {
|
||||
const r = await docker.pruneImages({ filters: { dangling: ['true'] } });
|
||||
out.reclaimed = r.SpaceReclaimed || 0;
|
||||
out.deleted = (r.ImagesDeleted || []).length;
|
||||
}
|
||||
await getDf(true);
|
||||
res.json(out);
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- 接口:设置 ---------------- */
|
||||
app.get('/api/settings', (req, res) => res.json(settings));
|
||||
app.post('/api/settings', (req, res) => {
|
||||
const b = req.body || {};
|
||||
settings = {
|
||||
...settings,
|
||||
thresholds: { ...settings.thresholds, ...(b.thresholds || {}) },
|
||||
webhook: b.webhook !== undefined ? String(b.webhook).trim() : settings.webhook,
|
||||
notify: b.notify !== undefined ? !!b.notify : settings.notify,
|
||||
debounceMinutes: b.debounceMinutes !== undefined ? (Number(b.debounceMinutes) || 10) : settings.debounceMinutes,
|
||||
};
|
||||
saveSettings();
|
||||
res.json(settings);
|
||||
});
|
||||
app.post('/api/settings/test', async (req, res) => {
|
||||
if (!settings.webhook) return res.status(400).json({ error: '未配置 webhook' });
|
||||
try {
|
||||
await fetch(settings.webhook, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '[测试] 飞牛docker容器管理增强版', level: 'info', app: '-', detail: '这是一条测试推送', time: new Date().toLocaleString('zh-CN', { hour12: false }), host: hostName() }),
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
res.json({ ok: true });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- 接口:容器 ---------------- */
|
||||
const SORTERS = {
|
||||
cpu: (a, b) => b.stats.cpu - a.stats.cpu,
|
||||
mem: (a, b) => b.stats.mem - a.stats.mem,
|
||||
net: (a, b) => (b.stats.rxBps + b.stats.txBps) - (a.stats.rxBps + a.stats.txBps),
|
||||
io: (a, b) => (b.stats.rdBps + b.stats.wrBps) - (a.stats.rdBps + a.stats.wrBps),
|
||||
name: (a, b) => b.name.localeCompare(a.name, 'zh'),
|
||||
pids: (a, b) => b.stats.pids - a.stats.pids,
|
||||
};
|
||||
|
||||
app.get('/api/containers', async (req, res) => {
|
||||
try {
|
||||
const all = req.query.all !== '0';
|
||||
const raw = await docker.listContainers({ all });
|
||||
let list = raw.map(c => {
|
||||
const st = stats.get(c.Id) || {};
|
||||
const m = meta.get(c.Id) || {};
|
||||
return {
|
||||
id: c.Id, shortId: c.Id.slice(0, 12), name: strip((c.Names || [])[0]),
|
||||
image: c.Image, state: c.State, status: c.Status, created: c.Created,
|
||||
project: projectOf(c.Labels), service: svcOf(c.Labels),
|
||||
health: m.health || '', restarts: m.restarts || 0,
|
||||
ports: (c.Ports || []).map(p => ({ ip: p.IP, private: p.PrivatePort, public: p.PublicPort, type: p.Type })),
|
||||
stats: {
|
||||
cpu: st.cpu ?? 0, mem: st.mem ?? 0, memLimit: st.memLimit ?? 0, memPct: st.memPct ?? 0,
|
||||
rxBps: st.rxBps ?? 0, txBps: st.txBps ?? 0, rdBps: st.rdBps ?? 0, wrBps: st.wrBps ?? 0,
|
||||
pids: st.pids ?? 0, hasData: !!st.ts,
|
||||
},
|
||||
};
|
||||
});
|
||||
const q = (req.query.q || '').trim().toLowerCase();
|
||||
if (q) list = list.filter(c => c.name.toLowerCase().includes(q) || c.image.toLowerCase().includes(q) || c.project.toLowerCase().includes(q));
|
||||
if (req.query.state === 'running') list = list.filter(c => c.state === 'running');
|
||||
else if (req.query.state === 'stopped') list = list.filter(c => c.state !== 'running');
|
||||
const sort = SORTERS[req.query.sort] ? req.query.sort : 'cpu';
|
||||
const dir = req.query.order === 'asc' ? -1 : 1;
|
||||
list.sort((a, b) => dir * SORTERS[sort](a, b));
|
||||
res.json({ total: list.length, sort, order: dir === 1 ? 'desc' : 'asc', items: list });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.get('/api/containers/:id', async (req, res) => {
|
||||
try {
|
||||
const info = await docker.getContainer(req.params.id).inspect();
|
||||
res.json({
|
||||
info, stats: stats.get(info.Id) || null, history: history.get(info.Id) || [],
|
||||
cmd: info.Config?.Cmd, entrypoint: info.Config?.Entrypoint,
|
||||
env: info.Config?.Env || [], mounts: info.Mounts || [],
|
||||
networks: info.NetworkSettings?.Networks || {}, ports: info.NetworkSettings?.Ports || {},
|
||||
restartPolicy: info.HostConfig?.RestartPolicy?.Name || 'no',
|
||||
startedAt: info.State?.StartedAt, finishedAt: info.State?.FinishedAt,
|
||||
exitCode: info.State?.ExitCode, health: info.State?.Health?.Status || '',
|
||||
});
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.get('/api/containers/:id/logs', async (req, res) => {
|
||||
try {
|
||||
const tail = Math.min(Number(req.query.tail || 300), 5000);
|
||||
const buf = await docker.getContainer(req.params.id).logs({ stdout: true, stderr: true, timestamps: true, tail, follow: false });
|
||||
res.json({ logs: demuxLogs(buf) });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.get('/api/containers/:id/logs/stream', async (req, res) => {
|
||||
try {
|
||||
const ct = docker.getContainer(req.params.id);
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
|
||||
const stream = await ct.logs({ stdout: true, stderr: true, timestamps: true, tail: Number(req.query.tail || 100), follow: true });
|
||||
const out = new PassThrough();
|
||||
docker.modem.demuxStream(stream, out, out);
|
||||
out.on('data', d => res.write(`data: ${JSON.stringify(d.toString('utf8'))}\n\n`));
|
||||
req.on('close', () => { try { stream.destroy(); } catch (e) {} });
|
||||
} catch (e) { res.status(500).end(); }
|
||||
});
|
||||
|
||||
app.post('/api/containers/:id/action', async (req, res) => {
|
||||
const { action } = req.body || {};
|
||||
try {
|
||||
const ct = docker.getContainer(req.params.id);
|
||||
if (action === 'start') await ct.start();
|
||||
else if (action === 'stop') await ct.stop({ t: 10 });
|
||||
else if (action === 'restart') await ct.restart({ t: 10 });
|
||||
else if (action === 'pause') await ct.pause();
|
||||
else if (action === 'unpause') await ct.unpause();
|
||||
else if (action === 'kill') await ct.kill();
|
||||
else return res.status(400).json({ error: '未知操作' });
|
||||
res.json({ ok: true });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.delete('/api/containers/:id', async (req, res) => {
|
||||
try {
|
||||
await docker.getContainer(req.params.id).remove({ force: req.query.force === '1', v: req.query.volumes === '1' });
|
||||
res.json({ ok: true });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/containers', async (req, res) => {
|
||||
const { image, name, ports = [], env = [], volumes = [], restart = 'always', cmd } = req.body || {};
|
||||
if (!image) return res.status(400).json({ error: '缺少镜像名' });
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
docker.pull(image, (err, stream) => {
|
||||
if (err) return reject(err);
|
||||
docker.modem.followProgress(stream, (e) => (e ? reject(e) : resolve()), () => {});
|
||||
});
|
||||
});
|
||||
const ExposedPorts = {}, PortBindings = {};
|
||||
for (const p of ports) {
|
||||
if (!p.container) continue;
|
||||
const proto = p.protocol || 'tcp';
|
||||
ExposedPorts[`${p.container}/${proto}`] = {};
|
||||
PortBindings[`${p.container}/${proto}`] = [{ HostPort: String(p.host || p.container) }];
|
||||
}
|
||||
const c = await docker.createContainer({
|
||||
Image: image, name: name || undefined, Cmd: cmd ? cmd.split(' ') : undefined,
|
||||
Env: env.filter(Boolean), ExposedPorts,
|
||||
HostConfig: { PortBindings, Binds: volumes.filter(Boolean), RestartPolicy: { Name: restart } },
|
||||
});
|
||||
await c.start();
|
||||
res.json({ ok: true, id: c.id });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- 接口:镜像 / 网络 ---------------- */
|
||||
app.get('/api/images', async (req, res) => {
|
||||
try {
|
||||
const imgs = await docker.listImages({ all: false });
|
||||
res.json(imgs.map(i => ({
|
||||
id: i.Id, shortId: i.Id.replace('sha256:', '').slice(0, 12), tags: i.RepoTags || [],
|
||||
size: i.Size, created: i.Created, containers: i.Containers || 0,
|
||||
})).sort((a, b) => b.size - a.size));
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.delete('/api/images/:id', async (req, res) => {
|
||||
try { await docker.getImage(req.params.id).remove({ force: req.query.force === '1' }); res.json({ ok: true }); }
|
||||
catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/images/prune', async (req, res) => {
|
||||
try { const r = await docker.pruneImages(); res.json({ ok: true, ...r }); }
|
||||
catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/images/pull', async (req, res) => {
|
||||
const { image } = req.body || {};
|
||||
if (!image) return res.status(400).json({ error: '缺少镜像名' });
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
|
||||
docker.pull(image, (err, stream) => {
|
||||
if (err) { res.write(`data: ${JSON.stringify({ error: err.message })}\n\n`); return res.end(); }
|
||||
let last = '';
|
||||
docker.modem.followProgress(stream,
|
||||
(e) => { res.write(`data: ${JSON.stringify({ done: !e, error: e ? String(e) : null })}\n\n`); res.end(); },
|
||||
(ev) => {
|
||||
const line = ev.status + (ev.progress ? ' ' + ev.progress : '');
|
||||
if (line !== last) { last = line; res.write(`data: ${JSON.stringify({ status: ev.status, progress: ev.progress })}\n\n`); }
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/networks', async (req, res) => {
|
||||
try {
|
||||
const nets = await docker.listNetworks();
|
||||
res.json(nets.map(n => ({
|
||||
id: n.Id, name: n.Name, driver: n.Driver, scope: n.Scope,
|
||||
subnet: (n.IPAM?.Config || []).map(c => c.Subnet).filter(Boolean),
|
||||
gateway: (n.IPAM?.Config || []).map(c => c.Gateway).filter(Boolean),
|
||||
containers: Object.keys(n.Containers || {}).length, internal: !!n.Internal,
|
||||
})));
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- 启动 ---------------- */
|
||||
setInterval(sampleOnce, SAMPLE_MS);
|
||||
setInterval(tickApps, SAMPLE_MS);
|
||||
setInterval(inspectAll, INSPECT_MS);
|
||||
setInterval(tickUptime, UPTIME_MS);
|
||||
setTimeout(() => { sampleOnce(); inspectAll(); tickApps(); }, 300);
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => console.log(`[docker-center] http://0.0.0.0:${PORT} sample=${SAMPLE_MS}ms inspect=${INSPECT_MS}ms`));
|
||||
Reference in new issue
Block a user