Compare commits

..
57 Commits
Author SHA1 Message Date
Akizon 5278803fb1 Merge pull request #36 from komari-monitor/dev
移除mmdb下载地址代理,增加版本号信息
2025-06-04 13:26:51 +08:00
Akizon 662a3033f7 Merge branch 'main' into dev 2025-06-04 13:26:43 +08:00
Akizon77 4c55e52374 feat: 添加版本信息API接口,支持获取当前版本和哈希 2025-06-03 23:25:50 +08:00
Akizon77 864b91fad1 ci/cd: 版本信息构建 2025-06-03 23:21:57 +08:00
Akizon77 8ed2e5a774 cd: 使用完整前端 2025-06-03 23:07:26 +08:00
Akizon77 907419ec73 cd: 工作流处理文件已存在 2025-05-30 16:53:12 +08:00
Akizon77 dc05937331 fix: 移除geoip下载地址代理 2025-05-30 16:44:21 +08:00
Akizon77 3169ec687b feat: 添加开发环境工作流,支持多平台构建和生产部署 2025-05-30 15:47:17 +08:00
Akizon 9160c1eef7 Merge pull request #35 from komari-monitor/dev
refactor: Client优化模型
2025-05-29 18:08:36 +08:00
Akizon77 7b95e270b5 fix: 修复EditClient函数中UUID的处理逻辑 2025-05-29 18:07:03 +08:00
Akizon77 95cf1d78d0 feat: 添加SSO相关信息返回 2025-05-29 17:51:04 +08:00
Akizon77 fefdcee60d refactor: 更新Client相关逻辑,迁移旧版ClientInfo数据并优化模型 2025-05-29 17:29:02 +08:00
Akizon 1f7bdf60c2 Merge pull request #34 from komari-monitor/dev
fix: 数据库charset=utf8mb4
2025-05-27 23:00:16 +08:00
Akizon77 554caf7a37 fix: 数据库charset=utf8mb4 2025-05-27 22:12:52 +08:00
Akizon 61277a8fc8 Merge pull request #33 from komari-monitor/dev
refactor: 默认服务端配置的创建
2025-05-27 17:19:29 +08:00
Akizon b178ceb62f Update docker-publish.yml 2025-05-27 17:18:28 +08:00
Akizon77 793852f7dc refactor: 优化Get函数,移除重复的默认配置创建逻辑 2025-05-27 17:17:35 +08:00
Akizon77 276feae7f6 feat: 在Update函数中添加默认配置创建逻辑 2025-05-27 17:13:43 +08:00
Akizon 3f6073cab4 Merge pull request #32 from komari-monitor/dev
fix: 修复Session表的索引冲突并优化数据库清理逻辑
2025-05-27 16:23:25 +08:00
Akizon77 a9f2c7658d fix: 修复Session表的索引冲突并优化数据库清理逻辑 2025-05-27 16:21:56 +08:00
Akizon da6eaddf3f Merge pull request #31 from komari-monitor/dev
refactor: 更新UploadBasicInfo函数以使用SaveClientInfo,移除UpdateOrInsertBasicI…
2025-05-27 15:50:07 +08:00
Akizon77 e0175e3b6c refactor: 更新UploadBasicInfo函数以使用SaveClientInfo,移除UpdateOrInsertBasicInfo的依赖 2025-05-27 15:46:43 +08:00
Akizon bd2d9117d9 Merge pull request #30 from komari-monitor/dev
feat: 添加mysql支持,新增部分公开字段
2025-05-26 20:26:29 +08:00
Akizon77 cde3a55451 feat: 添加billing_cycle 2025-05-26 19:32:17 +08:00
Akizon77 d3ad29439a feat: 添加虚拟化 2025-05-26 19:29:37 +08:00
Akizon77 fb80e48010 feat: 添加数据库配置,支持MySQL,修改uuid类型为varchar(36),移除默认时间字段 2025-05-25 18:50:33 +08:00
Akizon77 513e59dbff feat: 添加终端连接功能和会话管理 2025-05-16 22:04:44 +08:00
Akizon 7d79825345 Update README.md 2025-05-16 18:24:58 +08:00
Akizon77 735a08ad75 fix: 添加public_remark字段 2025-05-15 21:07:59 +08:00
Akizon77 874b272f55 fix: 确保发给前端的数据中有cpu usage 2025-05-15 20:59:25 +08:00
Akizon 4d86cb3632 Merge pull request #29 from komari-monitor/dev
fix: #28 修改Settings时如果不包含全部信息会导致丢失数据
fix: 修改Config结构体中的字段名称以提高一致性
feat: 添加中间件以禁用API请求的缓存
fix: 统一Record结构体字段名称以提高一致性
fix: 修复AddClient和EditClient函数中的JSON绑定和字段更新逻辑
feat: 添加获取客户端最近记录的API接口
2025-05-15 20:54:02 +08:00
Akizon77 5316a4d3b2 feat: 添加获取客户端最近记录的API接口 2025-05-15 20:49:12 +08:00
Akizon77 5d386a18e4 fix: 修复AddClient和EditClient函数中的JSON绑定和字段更新逻辑 2025-05-15 20:43:13 +08:00
Akizon77 6e65706a23 fix: 统一Record结构体字段名称以提高一致性 2025-05-15 20:33:11 +08:00
Akizon 55e48ee8f1 Update README.md 2025-05-13 00:35:33 +08:00
Akizon caf330265a Update LICENSE 2025-05-12 20:18:02 +08:00
Akizon 9e86118683 Update LICENSE 2025-05-12 20:15:44 +08:00
Akizon e5d7c2f89c Update README.md 2025-05-12 20:12:08 +08:00
Akizon77 803251fbc1 wip: 添加价格、过期时间 2025-05-12 19:33:15 +08:00
Akizon77 b6b75c9aa2 feat: 添加中间件以禁用API请求的缓存 2025-05-12 17:06:14 +08:00
Akizon77 07ff3c1cfe fix: 修改Config结构体中的字段名称以提高一致性 2025-05-12 16:57:47 +08:00
Akizon77 544aada3b9 fix: #28 修改Settings时如果不包含全部信息会导致丢失数据 2025-05-12 16:41:34 +08:00
Akizon 64683bc50a Merge pull request #27 from komari-monitor/dev
feat: #25 添加批量修改weight权重的接口
feat: #24 添加logout登出
feat: 添加OAuth功能及相关API接口
2025-05-12 16:23:11 +08:00
Akizon77 62b0dff1f4 feat: #25 添加批量修改weight权重的接口
fix: #24 logout 接口
2025-05-12 16:21:31 +08:00
Akizon77 5accc9d258 feat: #24 添加logout登出 2025-05-12 16:12:20 +08:00
Akizon77 8535b4ba7a fix: # 26add client 可以指定名称
fix: 修改日志记录方式,避免在读取index.html失败时导致程序崩溃
2025-05-12 16:09:47 +08:00
Akizon77 cc3cda12cf 改回来了www 2025-05-08 23:02:19 +08:00
Akizon77 4ecf1fccd7 npm -> pnpm 2025-05-08 23:00:54 +08:00
Akizon77 74b9b8f9c8 fix: 修复OAuth回调中cookie设置逻辑,确保状态验证后正确清除cookie 2025-05-08 20:41:42 +08:00
Akizon77 9b2a33824a fix: 修复OAuth未启用时的HTTP状态码返回 2025-05-08 20:28:53 +08:00
Akizon77 2c3b5f7a47 feat: 添加OAuth功能及相关API接口
修改API路径
2025-05-08 20:13:31 +08:00
Akizon d81ec0eee6 非常抱歉!!漏了一个 '\' 2025-05-08 16:56:57 +08:00
Akizon 0ccda568ed Update README.md 2025-05-08 16:52:08 +08:00
Akizon 2cf38a729a Merge pull request #23 from komari-monitor/dev
feat: 添加获取公共设置的API接口
2025-05-08 16:21:16 +08:00
Akizon77 77aa490696 feat: 添加获取公共设置的API接口 2025-05-08 16:20:44 +08:00
Akizon77 2e524fda42 fix: 修复配置保存时的时间戳和ID设置逻辑 2025-05-08 16:07:26 +08:00
Akizon77 9a6b2b8a35 feat: #19 1分钟的历史记录 2025-05-07 23:19:08 +08:00
43 changed files with 1530 additions and 253 deletions

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
name: Development Environment
on:
push:
branches:
- dev
workflow_dispatch:
jobs:
build-binaries:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
#- name: Create dummy index.html
# run: |
# mkdir -p public/dist
# echo "<html><body><h1>This is komari development server.</h1></body></html>" > public/dist/index.html
- name: Clone and build frontend
run: |
git clone https://github.com/komari-monitor/komari-web web
cd web
npm install
npm run build
cd ..
mkdir -p public/dist
cp -r web/dist/* public/dist/
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Build application
env:
GOOS: linux
GOARCH: amd64
run: |
VERSION_SHA="${{ github.sha }}"
go build -ldflags "-X github.com/komari-monitor/komari/utils.CurrentVersion=dev -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_SHA}" -o komari .
- name: Upload binary as artifact
uses: actions/upload-artifact@v4
with:
name: komari
path: komari
deploy-to-production:
needs: build-binaries
runs-on: ubuntu-latest
env:
PRODUCTION_SERVER: ${{ vars.PRODUCTION_SERVER }}
if: github.ref == 'refs/heads/dev'
steps:
- name: Download binary
uses: actions/download-artifact@v4
with:
name: komari
- name: Setup SSH Key
uses: webfactory/ssh-agent@v0.8.0
with:
ssh-private-key: ${{ secrets.PRODUCTION_SSH_KEY }}
- name: Add host to known hosts
run: |
mkdir -p ~/.ssh
ssh-keyscan -H ${{ env.PRODUCTION_SERVER }} >> ~/.ssh/known_hosts
- name: Deploy to production
run: |
chmod +x komari
ssh root@${{ env.PRODUCTION_SERVER }} 'mkdir -p /opt/komari/'
ssh root@${{ env.PRODUCTION_SERVER }} 'systemctl stop komari.service || true'
ssh root@${{ env.PRODUCTION_SERVER }} 'rm -f /opt/komari/komari.old'
ssh root@${{ env.PRODUCTION_SERVER }} 'mv /opt/komari/komari /opt/komari/komari.old || true'
scp komari root@${{ env.PRODUCTION_SERVER }}:/opt/komari/komari
ssh root@${{ env.PRODUCTION_SERVER }} 'systemctl start komari.service'
+3 -1
View File
@@ -3,7 +3,6 @@ name: Docker Build and Publish
on:
push:
branches:
- dev
- main
workflow_dispatch:
@@ -45,3 +44,6 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ github.ref_name }}
VERSION_HASH=${{ github.sha }}
+7 -2
View File
@@ -55,7 +55,9 @@ jobs:
if [ "${{ matrix.goos }}" = "windows" ]; then
BINARY_NAME=${BINARY_NAME}.exe
fi
go build -trimpath -ldflags="-s -w" -o $BINARY_NAME
VERSION="${{ github.event.release.tag_name }}"
VERSION_HASH="${{ github.sha }}"
go build -trimpath -ldflags="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o $BINARY_NAME
- name: Upload binary to release
env:
@@ -97,4 +99,7 @@ jobs:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ github.event.release.tag_name }}
VERSION_HASH=${{ github.sha }}
+15 -2
View File
@@ -16,8 +16,10 @@ COPY . .
COPY --from=frontend /web/dist ./public/dist
ENV CGO_ENABLED=1
ARG VERSION=unknown
ARG VERSION_HASH=unknown
# RUN CC=musl-gcc go build -trimpath -ldflags="-s -w -linkmode external -extldflags -static" -o komari .
RUN go build -trimpath -ldflags="-s -w -linkmode external -extldflags -static" -o komari .
RUN go build -trimpath -ldflags="-s -w -linkmode external -extldflags -static -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o komari .
# FROM scratch
FROM alpine:3.21
@@ -26,6 +28,17 @@ WORKDIR /app
COPY --from=builder /app/komari .
ENV GIN_MODE=release
# 数据库配置环境变量(可以在运行时覆盖)
ENV KOMARI_DB_TYPE=sqlite
ENV KOMARI_DB_FILE=/app/data/komari.db
ENV KOMARI_DB_HOST=localhost
ENV KOMARI_DB_PORT=3306
ENV KOMARI_DB_USER=root
ENV KOMARI_DB_PASS=
ENV KOMARI_DB_NAME=komari
ENV KOMARI_LISTEN=0.0.0.0:25774
EXPOSE 25774
CMD ["/app/komari","server", "-l", "0.0.0.0:25774","-d", "/app/data/komari.db"]
# 使用环境变量启动服务
CMD ["/app/komari","server"]
+122 -1
View File
@@ -1 +1,122 @@
# komari
# Komari
Komari 是一款轻量级的自托管服务器监控工具,旨在提供简单、高效的服务器性能监控解决方案。它支持通过 Web 界面查看服务器状态,并通过轻量级 Agent 收集数据。
[文档](https://komari-monitor.github.io/komari-document/)
## 特性
- **轻量高效**:低资源占用,适合各种规模的服务器。
- **自托管**:完全掌控数据隐私,部署简单。
- **Web 界面**:直观的监控仪表盘,易于使用。
## 快速开始
### 依赖
- Docker(快速部署)
- 或者 Go 1.18+ 和 Node.js 20+(手工构建)
### Docker 部署
1. 创建数据目录:
```bash
mkdir -p ./data
```
2. 运行 Docker 容器:
```bash
docker run -d \
-p 25774:25774 \
-v $(pwd)/data:/app/data \
--name komari \
ghcr.io/komari-monitor/komari:latest
```
3. 查看默认账号和密码:
```bash
docker logs komari
```
4. 在浏览器中访问 `http://<your_server_ip>:25774`。
> [!NOTE]
> 你也可以通过环境变量 `ADMIN_USERNAME` 和 `ADMIN_PASSWORD` 自定义初始用户名和密码。
### 二进制文件部署
1. 访问 Komari 的 [GitHub Release 页面](https://github.com/komari-monitor/komari/releases) 下载适用于你操作系统的最新二进制文件。
2. 运行 Komari:
```bash
./komari server -l 0.0.0.0:25774
```
3. 在浏览器中访问 `http://<your_server_ip>:25774`,默认监听 `25774` 端口。
4. 默认账号和密码可在启动日志中查看,或通过环境变量 `ADMIN_USERNAME` 和 `ADMIN_PASSWORD` 设置。
> [!NOTE]
> 确保二进制文件具有可执行权限(`chmod +x komari`)。数据将保存在运行目录下的 `data` 文件夹中。
### 手工构建
1. 构建前端静态文件:
```bash
git clone https://github.com/komari-monitor/komari-web
cd komari-web
npm install
npm run build
```
2. 构建后端:
```bash
git clone https://github.com/komari-monitor/komari
cd komari
```
将步骤1中生成的静态文件复制到 `komari` 项目根目录下的 `/public/dist` 文件夹。
```bash
go build -o komari
```
4. 运行:
```bash
./komari server -l 0.0.0.0:25774
```
默认监听 `25774` 端口,访问 `http://localhost:25774`。
## 前端开发指南
这个坑晚点再填吧 ヽ( ̄ω ̄( ̄ω ̄〃)ゝ
## 客户端 Agent 开发指南
这个坑晚点再填吧 (o゜▽゜)o☆
## 贡献
欢迎提交 Issue 或 Pull Request!
## 鸣谢
- 感谢 [Alice Networks LTD](https://app.alice.ws/) 提供的免费服务器
## 引用
- [gorm.io](https://gorm.io/)
- [spf13/cobra](https://github.com/spf13/cobra)
- [oschwald/maxminddb-golang](https://github.com/oschwald/maxminddb-golang)
- [gorilla/websocket](https://github.com/gorilla/websocket)
- [google/uuid](https://github.com/google/uuid)
- [gin-gonic/gin](https://github.com/gin-gonic/gin)
- [UserExistsError/conpty](https://github.com/UserExistsError/conpty)
- [creack/pty](https://github.com/creack/pty)
- [rhysd/go-github-selfupdate](https://github.com/rhysd/go-github-selfupdate)
- [shirou/gopsutil](https://github.com/shirou/gopsutil)
## 许可证
[MIT License](LICENSE)
## 碎碎念
### 我为什么做Komari?
起因: [求推荐系统监控软件](https://www.nodeseek.com/post-133745-1)
> @古xx斯
> 哪吒?
> > 数据至少保存15天
> @sxxu
> 怕不是做梦的预算
> @Vxxn
> prometheus加grafana
> > 部署太麻烦
没有合适的,最近刚好时间稍微多了一些,就搓了 komari.
+53
View File
@@ -0,0 +1,53 @@
package api
import (
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/utils"
)
var (
Records map[string][]common.Report = make(map[string][]common.Report)
)
type TerminalSession struct {
UUID string
Browser *websocket.Conn
Agent *websocket.Conn
}
var TerminalSessionsMutex = &sync.Mutex{}
var TerminalSessions = make(map[string]*TerminalSession)
func SaveClientReportToDB() error {
lastMinute := time.Now().Add(-time.Minute * 1).Unix()
record := []models.Record{}
// 遍历所有的客户端记录
for uuid, reports := range Records {
// 删除一分钟前的记录
filtered := reports[:0]
for _, r := range reports {
if r.UpdatedAt.Unix() >= lastMinute {
filtered = append(filtered, r)
}
}
Records[uuid] = filtered
r := utils.AverageReport(uuid, time.Now(), filtered)
record = append(record, r)
db := dbcore.GetDBInstance()
err := db.Model(&models.Record{}).Where("client = ?", uuid).Create(record).Error
if err != nil {
return err
}
}
return nil
}
+31 -51
View File
@@ -2,80 +2,57 @@ package admin
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/database/records"
)
func AddClient(c *gin.Context) {
uuid, token, err := clients.CreateClient()
var req struct {
Name string `json:"name"`
}
if err := c.ShouldBindJSON(&req); err != nil || req.Name == "" {
uuid, token, err := clients.CreateClient()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "uuid": uuid, "token": token})
return
}
uuid, token, err := clients.CreateClientWithName(req.Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "uuid": uuid, "token": token})
}
func EditClient(c *gin.Context) {
var req struct {
UUID string `json:"uuid" binding:"required"`
ClientName string `json:"name,omitempty"`
Token string `json:"token,omitempty"`
Weigth int `json:"weight,omitempty"`
}
var req = make(map[string]interface{})
uuid := c.Param("uuid")
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": err.Error()})
return
}
db := dbcore.GetDBInstance()
var err error
if req.ClientName != "" {
err = db.Model(&common.ClientInfo{}).Where("uuid = ?", req.UUID).
Updates(map[string]interface{}{"name": req.ClientName, "updated_at": time.Now()}).Error
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
if uuid == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Invalid or missing UUID"})
return
}
if req.Token != "" {
err = db.Model(&models.Client{}).Where("uuid = ?", req.UUID).
Updates(map[string]interface{}{"token": req.Token, "updated_at": time.Now()}).Error
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
}
if req.Weigth != 0 {
err = db.Model(&common.ClientInfo{}).Where("uuid = ?", req.UUID).
Updates(map[string]interface{}{"weigth": req.Weigth, "updated_at": time.Now()}).Error
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
req["uuid"] = uuid
err := clients.SaveClient(req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func RemoveClient(c *gin.Context) {
var req struct {
UUID string `json:"uuid" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing UUID",
})
}
err := clients.DeleteClient(req.UUID)
uuid := c.Param("uuid")
err := clients.DeleteClient(uuid)
if err != nil {
c.JSON(500, gin.H{
"status": "error",
@@ -98,7 +75,7 @@ func ClearRecord(c *gin.Context) {
}
func GetClient(c *gin.Context) {
uuid := c.Query("uuid")
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(400, gin.H{
"status": "error",
@@ -109,7 +86,10 @@ func GetClient(c *gin.Context) {
result, err := clients.GetClientByUUID(uuid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{
"status": "error",
"error": err.Error(),
})
return
}
@@ -127,7 +107,7 @@ func ListClients(c *gin.Context) {
}
func GetClientToken(c *gin.Context) {
uuid := c.Query("uuid")
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(400, gin.H{
"status": "error",
+33
View File
@@ -0,0 +1,33 @@
package admin
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
)
func OrderWeight(c *gin.Context) {
var req = make(map[string]int)
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing request body",
})
return
}
db := dbcore.GetDBInstance()
for uuid, weight := range req {
err := db.Model(&models.Client{}).Where("uuid = ?", uuid).Update("weight", weight).Error
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to update client weight",
})
return
}
}
c.JSON(200, gin.H{
"status": "success",
"message": "Client weight updated successfully",
})
}
+34
View File
@@ -0,0 +1,34 @@
package admin
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/accounts"
)
func BindingExternalAccount(c *gin.Context) {
session, _ := c.Cookie("session_token")
user, err := accounts.GetUserBySession(session)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "No user found"})
return
}
c.SetCookie("binding_external_account", user.UUID, 3600, "/", "", false, true)
c.Redirect(302, "/api/oauth")
}
func UnbindExternalAccount(c *gin.Context) {
session, _ := c.Cookie("session_token")
user, err := accounts.GetUserBySession(session)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "No user found"})
return
}
err = accounts.UnbindExternalAccount(user.UUID)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "Failed to unbind external account"})
return
}
c.JSON(200, gin.H{"status": "success", "message": "External account unbound"})
}
+19 -1
View File
@@ -16,7 +16,8 @@ func GetSessions(c *gin.Context) {
})
return
}
c.JSON(200, ss)
current, _ := c.Cookie("session_token")
c.JSON(200, gin.H{"status": "success", "current": current, "data": ss})
}
func DeleteSession(c *gin.Context) {
@@ -44,3 +45,20 @@ func DeleteSession(c *gin.Context) {
"message": "Session deleted successfully",
})
}
func DeleteAllSession(c *gin.Context) {
err := accounts.DeleteAllSessions()
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Failed to delete session",
})
return
}
c.JSON(200, gin.H{
"status": "success",
"message": "Session deleted successfully",
})
}
+3 -4
View File
@@ -30,9 +30,8 @@ func GetSettings(c *gin.Context) {
}
// EditSettings 更新自定义配置
// 务必传全数据
func EditSettings(c *gin.Context) {
cfg := models.Config{}
cfg := make(map[string]interface{})
if err := c.ShouldBindJSON(&cfg); err != nil {
c.JSON(400, gin.H{
"status": "error",
@@ -41,8 +40,8 @@ func EditSettings(c *gin.Context) {
return
}
cfg.ID = 1 // Only one record
if err := config.Save(cfg); err != nil {
cfg["id"] = 1 // Only one record
if err := config.Update(cfg); err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Internal Server Error: " + err.Error(),
+18 -5
View File
@@ -12,6 +12,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/api"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/ws"
@@ -38,13 +39,14 @@ func UploadReport(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
return
}
err = clients.SaveClientReport(report.UUID, report)
report.UpdatedAt = time.Now()
err = SaveClientReport(report.UUID, report)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("%v", err)})
return
}
// Update report with method and token
report.UpdatedAt = time.Now()
ws.LatestReport[report.UUID] = &report
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) // Restore the body for further use
@@ -124,13 +126,24 @@ func WebSocketReport(c *gin.Context) {
if err != nil {
break
}
err = clients.SaveClientReport(uuid, report)
report.UpdatedAt = time.Now()
err = SaveClientReport(uuid, report)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": fmt.Sprintf("%v", err)})
}
report.UpdatedAt = time.Now()
ws.LatestReport[uuid] = &report
}
}
func SaveClientReport(uuid string, report common.Report) error {
if api.Records[uuid] == nil {
api.Records[uuid] = []common.Report{}
}
if report.CPU.Usage < 0.01 {
report.CPU.Usage = 0.01
}
api.Records[uuid] = append(api.Records[uuid], report)
return nil
}
+48
View File
@@ -0,0 +1,48 @@
package client
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/api"
)
func EstablishConnection(c *gin.Context) {
session_id := c.Query("id")
session, exists := api.TerminalSessions[session_id]
if !exists || session == nil || session.Browser == nil {
c.JSON(404, gin.H{"status": "error", "error": "Session not found"})
return
}
// Upgrade the connection to WebSocket
if !websocket.IsWebSocketUpgrade(c.Request) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"})
return
}
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // TODO: 检查源站
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
api.TerminalSessionsMutex.Lock()
if session.Browser != nil {
session.Browser.Close()
}
delete(api.TerminalSessions, session_id)
api.TerminalSessionsMutex.Unlock()
return
}
session.Agent = conn
conn.SetCloseHandler(func(code int, text string) error {
delete(api.TerminalSessions, session_id)
// 通知 Browser 关闭终端连接
if session.Browser != nil {
session.Browser.Close()
}
return nil
})
go api.ForwardTerminal(session_id)
}
+9 -10
View File
@@ -3,7 +3,6 @@ package client
import (
"net"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/utils/geoip"
@@ -12,7 +11,7 @@ import (
)
func UploadBasicInfo(c *gin.Context) {
var cbi = common.ClientInfo{}
var cbi = map[string]interface{}{}
if err := c.ShouldBindJSON(&cbi); err != nil {
c.JSON(400, gin.H{"status": "error", "error": "Invalid or missing data"})
return
@@ -25,25 +24,25 @@ func UploadBasicInfo(c *gin.Context) {
return
}
cbi.UUID = uuid
cbi["uuid"] = uuid
if cfg, err := config.Get(); err == nil && cfg.GeoIpEnabled {
if cbi.IPv4 != "" {
ip4 := net.ParseIP(cbi.IPv4)
if ipv4, ok := cbi["ipv4"].(string); ok && ipv4 != "" {
ip4 := net.ParseIP(ipv4)
ip4_record, _ := geoip.GetGeoIpInfo(ip4)
if ip4_record != nil {
cbi.Region = geoip.GetRegionUnicodeEmoji(ip4_record.Country.ISOCode)
cbi["region"] = geoip.GetRegionUnicodeEmoji(ip4_record.Country.ISOCode)
}
} else if cbi.IPv6 != "" {
ip6 := net.ParseIP(cbi.IPv6)
} else if ipv6, ok := cbi["ipv6"].(string); ok && ipv6 != "" {
ip6 := net.ParseIP(ipv6)
ip6_record, _ := geoip.GetGeoIpInfo(ip6)
if ip6_record != nil {
cbi.Region = geoip.GetRegionUnicodeEmoji(ip6_record.Country.ISOCode)
cbi["region"] = geoip.GetRegionUnicodeEmoji(ip6_record.Country.ISOCode)
}
}
}
if err := clients.UpdateOrInsertBasicInfo(cbi); err != nil {
if err := clients.SaveClientInfo(cbi); err != nil {
c.JSON(500, gin.H{"status": "error", "error": err})
return
}
+17
View File
@@ -0,0 +1,17 @@
package api
import (
"github.com/gin-gonic/gin"
)
func GetClientRecentRecords(c *gin.Context) {
uuid := c.Param("uuid")
if uuid == "" {
c.JSON(400, gin.H{
"status": "error",
"error": "Invalid or missing UUID",
})
return
}
c.JSON(200, Records[uuid])
}
-1
View File
@@ -16,7 +16,6 @@ type LoginRequest struct {
}
func Login(c *gin.Context) {
// TODO: Settings -> Disable password login when using OAuth
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Invalid request body"})
+13
View File
@@ -0,0 +1,13 @@
package api
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/accounts"
)
func Logout(c *gin.Context) {
session, _ := c.Cookie("session_token")
accounts.DeleteSession(session)
c.SetCookie("session_token", "", -1, "/", "", false, true)
c.Redirect(302, "/")
}
+1 -1
View File
@@ -22,6 +22,6 @@ func GetMe(c *gin.Context) {
c.JSON(200, gin.H{"username": "Guest", "logged_in": false})
return
}
c.JSON(200, gin.H{"username": user.Username, "logged_in": true, "uuid": user.UUID})
c.JSON(200, gin.H{"username": user.Username, "logged_in": true, "uuid": user.UUID, "sso_type": user.SSOType, "sso_id": user.SSOID})
}
+4 -1
View File
@@ -13,10 +13,13 @@ func GetNodesInformation(c *gin.Context) {
}
count := len(clientList)
// 公开信息不展示IP地址
// 公开信息不展示IP地址,私有备注不展示
for i := 0; i < count; i++ {
clientList[i].IPv4 = ""
clientList[i].IPv6 = ""
clientList[i].Remark = ""
clientList[i].Version = ""
clientList[i].Token = ""
}
c.JSON(200, gin.H{"status": "success", "data": clientList})
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/utils/oauth"
)
// /api/oauth
func OAuth(c *gin.Context) {
cfg, _ := config.Get()
if !cfg.OAuthEnabled {
c.JSON(403, gin.H{"status": "error", "error": "OAuth is not enabled"})
return
}
authURL, state := oauth.GetOAuthUrl()
c.SetCookie("oauth_state", state, 3600, "/", "", false, true)
c.Redirect(302, authURL)
}
// /api/oauth_callback
func OAuthCallback(c *gin.Context) {
// 验证state防止CSRF攻击
state, _ := c.Cookie("oauth_state")
c.SetCookie("oauth_state", "", -1, "/", "", false, true)
if state == "" || state != c.Query("state") {
c.JSON(400, gin.H{"status": "error", "error": "Invalid state"})
return
}
// 获取code
code := c.Query("code")
if code == "" {
c.JSON(400, gin.H{"status": "error", "error": "No code provided"})
return
}
githubUser, err := oauth.OAuthCallback(code, state)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "Failed to get user info: " + err.Error()})
return
}
// 使用GitHub ID作为SSO ID
sso_id := fmt.Sprintf("github_%d", githubUser.ID)
// 如果cookie中有binding_external_account,说明是绑定外部账号
// 否则是登录
uuid, _ := c.Cookie("binding_external_account")
c.SetCookie("binding_external_account", "", -1, "/", "", false, true)
if uuid != "" {
// 绑定外部账号
session, _ := c.Cookie("session_token")
user, err := accounts.GetUserBySession(session)
if err != nil || user.UUID != uuid {
c.JSON(500, gin.H{"status": "error", "error": "Binding failed"})
return
}
err = accounts.BindingExternalAccount(user.UUID, sso_id)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": "Binding failed"})
return
}
c.Redirect(302, "/")
return
}
// 尝试获取用户
user, err := accounts.GetUserBySSO(sso_id)
if err != nil {
c.JSON(401, gin.H{
"status": "error",
"error": "please log in and bind your GitHub account first.",
})
return
}
// 创建会话
session, err := accounts.CreateSession(user.UUID, 2592000)
if err != nil {
c.JSON(500, gin.H{"status": "error", "error": err.Error()})
return
}
// 设置cookie并返回
c.SetCookie("session_token", session, 2592000, "/", "", false, true)
c.Redirect(302, "/")
}
+27
View File
@@ -0,0 +1,27 @@
package api
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/database/config"
)
func GetPublicSettings(c *gin.Context) {
cst, err := config.Get()
if err != nil {
c.JSON(500, gin.H{
"status": "error",
"error": "Internal Server Error: " + err.Error(),
})
return
}
c.JSON(200, gin.H{
"status": "success",
"data": gin.H{
"sitename": cst.Sitename,
"desc": cst.Description,
"custom_head": cst.CustomHead,
"oauth_enable": cst.OAuthEnabled,
"allow_cros": cst.AllowCros,
},
})
}
+158
View File
@@ -0,0 +1,158 @@
package api
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/utils"
"github.com/komari-monitor/komari/ws"
)
func RequestTerminal(c *gin.Context) {
uuid := c.Param("uuid")
_, err := clients.GetClientByUUID(uuid)
if err != nil {
c.JSON(400, gin.H{
"error": "Client not found",
})
return
}
// 建立ws
if !websocket.IsWebSocketUpgrade(c.Request) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"})
return
}
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // TODO: 检查源站
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
// 新建一个终端连接
id := utils.GenerateRandomString(32)
session := &TerminalSession{
UUID: uuid,
Browser: conn,
Agent: nil,
}
TerminalSessionsMutex.Lock()
TerminalSessions[id] = session
TerminalSessionsMutex.Unlock()
conn.SetCloseHandler(func(code int, text string) error {
log.Println("Terminal connection closed:", code, text)
TerminalSessionsMutex.Lock()
delete(TerminalSessions, id)
TerminalSessionsMutex.Unlock()
// 通知 Agent 关闭终端连接
if session.Agent != nil {
session.Agent.Close()
}
return nil
})
if ws.ConnectedClients[uuid] == nil {
conn.WriteMessage(1, []byte("Client offline!"))
conn.Close()
TerminalSessionsMutex.Lock()
delete(TerminalSessions, id)
TerminalSessionsMutex.Unlock()
return
}
err = ws.ConnectedClients[uuid].WriteJSON(gin.H{
"message": "terminal",
"request_id": id,
})
if err != nil {
conn.Close()
TerminalSessionsMutex.Lock()
delete(TerminalSessions, id)
TerminalSessionsMutex.Unlock()
return
}
conn.WriteMessage(1, []byte("waiting for agent..."))
// 如果没有连接上,则关闭连接
time.AfterFunc(30*time.Second, func() {
TerminalSessionsMutex.Lock()
if session.Agent == nil {
if session.Browser != nil {
session.Browser.WriteMessage(1, []byte("timeout"))
session.Browser.Close()
}
conn.Close()
delete(TerminalSessions, id)
}
TerminalSessionsMutex.Unlock()
})
}
func ForwardTerminal(id string) {
session, exists := TerminalSessions[id]
if !exists || session == nil || session.Agent == nil || session.Browser == nil {
return
}
errChan := make(chan error, 1)
go func() {
for {
messageType, data, err := session.Browser.ReadMessage()
if err != nil {
errChan <- err
return
}
if messageType == websocket.TextMessage {
if session.Agent != nil && string(data[0:1]) == "{" {
err = session.Agent.WriteMessage(websocket.TextMessage, data)
} else if session.Agent != nil {
err = session.Agent.WriteMessage(websocket.BinaryMessage, data)
}
} else if session.Agent != nil {
// 二进制消息,原样传递
err = session.Agent.WriteMessage(websocket.BinaryMessage, data)
}
if err != nil {
errChan <- err
return
}
}
}()
go func() {
for {
_, data, err := session.Agent.ReadMessage()
if err != nil {
errChan <- err
return
}
if session.Browser != nil {
err = session.Browser.WriteMessage(websocket.BinaryMessage, data)
if err != nil {
errChan <- err
return
}
}
}
}()
// 等待错误或主动关闭
<-errChan
// 关闭连接
if session.Agent != nil {
session.Agent.Close()
}
if session.Browser != nil {
session.Browser.Close()
}
TerminalSessionsMutex.Lock()
delete(TerminalSessions, id)
TerminalSessionsMutex.Unlock()
}
+14
View File
@@ -0,0 +1,14 @@
package api
import (
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/utils"
)
func GetVersion(c *gin.Context) {
c.JSON(200, gin.H{
"version": utils.CurrentVersion,
"hash": utils.VersionHash,
"status": "success",
})
}
+10 -2
View File
@@ -1,6 +1,14 @@
package flags
var (
DatabaseFile string
Listen string
// 数据库配置
DatabaseType string // 数据库类型:sqlite, mysql
DatabaseFile string // SQLite数据库文件路径
DatabaseHost string // MySQL/其他数据库主机地址
DatabasePort string // MySQL/其他数据库端口
DatabaseUser string // MySQL/其他数据库用户名
DatabasePass string // MySQL/其他数据库密码
DatabaseName string // MySQL/其他数据库名称
Listen string
)
+27 -1
View File
@@ -9,6 +9,25 @@ import (
"github.com/spf13/cobra"
)
func getEnv(key, defaultValue string) string {
value := os.Getenv(key)
if value == "" {
return defaultValue
}
return value
}
// 从环境变量获取默认值
var (
dbTypeEnv = getEnv("KOMARI_DB_TYPE", "sqlite")
dbFileEnv = getEnv("KOMARI_DB_FILE", "./data/komari.db")
dbHostEnv = getEnv("KOMARI_DB_HOST", "localhost")
dbPortEnv = getEnv("KOMARI_DB_PORT", "3306")
dbUserEnv = getEnv("KOMARI_DB_USER", "root")
dbPassEnv = getEnv("KOMARI_DB_PASS", "")
dbNameEnv = getEnv("KOMARI_DB_NAME", "komari")
)
var RootCmd = &cobra.Command{
Use: "Komari",
Short: "Komari is a simple server monitoring tool",
@@ -28,5 +47,12 @@ func Execute() {
}
func init() {
RootCmd.PersistentFlags().StringVarP(&flags.DatabaseFile, "database", "d", "./data/komari.db", "Database file")
// 设置命令行参数,提供环境变量作为默认值
RootCmd.PersistentFlags().StringVarP(&flags.DatabaseType, "db-type", "t", dbTypeEnv, "Database type (sqlite, mysql) [env: KOMARI_DB_TYPE]")
RootCmd.PersistentFlags().StringVarP(&flags.DatabaseFile, "database", "d", dbFileEnv, "SQLite database file path [env: KOMARI_DB_FILE]")
RootCmd.PersistentFlags().StringVar(&flags.DatabaseHost, "db-host", dbHostEnv, "MySQL/Other database host address [env: KOMARI_DB_HOST]")
RootCmd.PersistentFlags().StringVar(&flags.DatabasePort, "db-port", dbPortEnv, "MySQL/Other database port [env: KOMARI_DB_PORT]")
RootCmd.PersistentFlags().StringVar(&flags.DatabaseUser, "db-user", dbUserEnv, "MySQL/Other database username [env: KOMARI_DB_USER]")
RootCmd.PersistentFlags().StringVar(&flags.DatabasePass, "db-pass", dbPassEnv, "MySQL/Other database password [env: KOMARI_DB_PASS]")
RootCmd.PersistentFlags().StringVar(&flags.DatabaseName, "db-name", dbNameEnv, "MySQL/Other database name [env: KOMARI_DB_NAME]")
}
+74 -13
View File
@@ -11,6 +11,7 @@ import (
"github.com/komari-monitor/komari/database/accounts"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/database/records"
"github.com/komari-monitor/komari/public"
"github.com/komari-monitor/komari/utils/geoip"
@@ -57,6 +58,13 @@ var ServerCmd = &cobra.Command{
}()
}
r.Use(func(c *gin.Context) {
if len(c.Request.URL.Path) >= 4 && c.Request.URL.Path[:4] == "/api" {
c.Header("Cache-Control", "no-store")
}
c.Next()
})
r.Any("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
@@ -65,28 +73,57 @@ var ServerCmd = &cobra.Command{
r.GET("/api/me", api.GetMe)
r.GET("/api/clients", ws.GetClients)
r.GET("/api/nodes", api.GetNodesInformation)
r.GET("/api/public", api.GetPublicSettings)
r.GET("/api/oauth", api.OAuth)
r.GET("/api/oauth_callback", api.OAuthCallback)
r.GET("/api/logout", api.Logout)
r.GET("/api/version", api.GetVersion)
r.GET("/api/recent/:uuid", api.GetClientRecentRecords)
tokenAuthrized := r.Group("/api/clients", api.TokenAuthMiddleware())
{
tokenAuthrized.GET("/report", client.WebSocketReport) // websocket
tokenAuthrized.POST("/uploadBasicInfo", client.UploadBasicInfo)
tokenAuthrized.POST("/report", client.UploadReport)
tokenAuthrized.GET("/terminal", client.EstablishConnection)
}
adminAuthrized := r.Group("/api/admin", api.AdminAuthMiddleware())
{
// clients
adminAuthrized.POST("/addClient", admin.AddClient)
adminAuthrized.POST("/editClient", admin.EditClient)
adminAuthrized.GET("/listClients", admin.ListClients)
adminAuthrized.GET("/getClient", admin.GetClient)
adminAuthrized.POST("/clearRecord", admin.ClearRecord)
adminAuthrized.POST("/removeClient", admin.RemoveClient)
adminAuthrized.GET("/clientToken", admin.GetClientToken)
// settings
adminAuthrized.GET("/settings", admin.GetSettings)
adminAuthrized.POST("/settings", admin.EditSettings)
// clients
clientGroup := adminAuthrized.Group("/client")
{
clientGroup.POST("/add", admin.AddClient)
clientGroup.GET("/list", admin.ListClients)
clientGroup.GET("/:uuid", admin.GetClient)
clientGroup.POST("/:uuid/edit", admin.EditClient)
clientGroup.POST("/:uuid/remove", admin.RemoveClient)
clientGroup.GET("/:uuid/token", admin.GetClientToken)
clientGroup.POST("/order", admin.OrderWeight)
// client terminal
clientGroup.GET("/:uuid/terminal", api.RequestTerminal)
}
// records
recordGroup := adminAuthrized.Group("/record")
{
recordGroup.POST("/clear", admin.ClearRecord)
}
// oauth2
oauth2Group := adminAuthrized.Group("/oauth2")
{
oauth2Group.GET("/bind", admin.BindingExternalAccount)
oauth2Group.POST("/unbind", admin.UnbindExternalAccount)
}
sessionGroup := adminAuthrized.Group("/session")
{
sessionGroup.GET("/get", admin.GetSessions)
sessionGroup.POST("/remove", admin.DeleteSession)
sessionGroup.POST("/remove/all", admin.DeleteAllSession)
}
}
public.Static(r.Group("/"), func(handlers ...gin.HandlerFunc) {
@@ -107,12 +144,27 @@ var ServerCmd = &cobra.Command{
}
func init() {
ServerCmd.PersistentFlags().StringVarP(&flags.Listen, "listen", "l", "0.0.0.0:25774", "Listen address")
// 从环境变量获取监听地址
listenAddr := getEnv("KOMARI_LISTEN", "0.0.0.0:25774")
ServerCmd.PersistentFlags().StringVarP(&flags.Listen, "listen", "l", listenAddr, "监听地址 [env: KOMARI_LISTEN]")
RootCmd.AddCommand(ServerCmd)
}
func InitDatabase() {
if !dbcore.InitDatabase() {
// // 打印数据库类型和连接信息
// if flags.DatabaseType == "mysql" {
// log.Printf("使用 MySQL 数据库连接: %s@%s:%s/%s",
// flags.DatabaseUser, flags.DatabaseHost, flags.DatabasePort, flags.DatabaseName)
// log.Printf("环境变量配置: [KOMARI_DB_TYPE=%s] [KOMARI_DB_HOST=%s] [KOMARI_DB_PORT=%s] [KOMARI_DB_USER=%s] [KOMARI_DB_NAME=%s]",
// os.Getenv("KOMARI_DB_TYPE"), os.Getenv("KOMARI_DB_HOST"), os.Getenv("KOMARI_DB_PORT"),
// os.Getenv("KOMARI_DB_USER"), os.Getenv("KOMARI_DB_NAME"))
// } else {
// log.Printf("使用 SQLite 数据库文件: %s", flags.DatabaseFile)
// log.Printf("环境变量配置: [KOMARI_DB_TYPE=%s] [KOMARI_DB_FILE=%s]",
// os.Getenv("KOMARI_DB_TYPE"), os.Getenv("KOMARI_DB_FILE"))
// }
var count int64 = 0
if dbcore.GetDBInstance().Model(&models.User{}).Count(&count); count == 0 {
user, passwd, err := accounts.CreateDefaultAdminAccount()
if err != nil {
panic(err)
@@ -123,10 +175,19 @@ func InitDatabase() {
func DoRecordsWork() {
ticker := time.NewTicker(time.Minute * 30)
ticker1 := time.NewTicker(60 * time.Second)
records.DeleteRecordBefore(time.Now().Add(-time.Hour * 24 * 30))
records.CompactRecord()
for range ticker.C {
records.DeleteRecordBefore(time.Now().Add(-time.Hour * 24 * 30))
records.CompactRecord()
for {
select {
case <-ticker.C:
records.DeleteRecordBefore(time.Now().Add(-time.Hour * 24 * 30))
records.CompactRecord()
break
case <-ticker1.C:
api.SaveClientReportToDB()
break
}
}
}
+24 -18
View File
@@ -29,25 +29,31 @@ type ClientConfig struct {
}
// ClientInfo stores static client information
// Deprecated: Use models.Client instead.
type ClientInfo struct {
UUID string `json:"uuid,omitempty" gorm:"type:uuid;primaryKey;foreignKey:ClientUUID;references:UUID;constraint:OnDelete:CASCADE"`
Name string `json:"name" gorm:"type:varchar(100);not null"`
CpuName string `json:"cpu_name" gorm:"type:varchar(100)"`
Arch string `json:"arch" gorm:"type:varchar(50)"`
CpuCores int `json:"cpu_cores" gorm:"type:int"`
OS string `json:"os" gorm:"type:varchar(100)"`
GpuName string `json:"gpu_name" gorm:"type:varchar(100)"`
IPv4 string `json:"ipv4,omitempty" gorm:"type:varchar(100)"`
IPv6 string `json:"ipv6,omitempty" gorm:"type:varchar(100)"`
Region string `json:"region" gorm:"type:varchar(100)"`
Remark string `json:"remark,omitempty" gorm:"type:longtext"`
MemTotal int64 `json:"mem_total" gorm:"type:bigint"`
SwapTotal int64 `json:"swap_total" gorm:"type:bigint"`
DiskTotal int64 `json:"disk_total" gorm:"type:bigint"`
Version string `json:"version" gorm:"type:varchar(100)"`
Weigth int `json:"weigth" gorm:"type:int"`
CreatedAt time.Time
UpdatedAt time.Time
UUID string `json:"uuid,omitempty" gorm:"type:varchar(36);primaryKey;foreignKey:ClientUUID;references:UUID;constraint:OnDelete:CASCADE"`
Name string `json:"name" gorm:"type:varchar(100);not null"`
CpuName string `json:"cpu_name" gorm:"type:varchar(100)"`
Virtualization string `json:"virtualization" gorm:"type:varchar(50)"`
Arch string `json:"arch" gorm:"type:varchar(50)"`
CpuCores int `json:"cpu_cores" gorm:"type:int"`
OS string `json:"os" gorm:"type:varchar(100)"`
GpuName string `json:"gpu_name" gorm:"type:varchar(100)"`
IPv4 string `json:"ipv4,omitempty" gorm:"type:varchar(100)"`
IPv6 string `json:"ipv6,omitempty" gorm:"type:varchar(100)"`
Region string `json:"region" gorm:"type:varchar(100)"`
Remark string `json:"remark,omitempty" gorm:"type:longtext"`
PublicRemark string `json:"public_remark,omitempty" gorm:"type:longtext"`
MemTotal int64 `json:"mem_total" gorm:"type:bigint"`
SwapTotal int64 `json:"swap_total" gorm:"type:bigint"`
DiskTotal int64 `json:"disk_total" gorm:"type:bigint"`
Version string `json:"version,omitempty" gorm:"type:varchar(100)"`
Weight int `json:"weight" gorm:"type:int"`
Price float64 `json:"price"`
BillingCycle int `json:"billing_cycle"`
ExpiredAt time.Time `json:"expired_at" gorm:"type:timestamp"`
CreatedAt time.Time
UpdatedAt time.Time
}
type IPAddress struct {
+21 -2
View File
@@ -122,7 +122,7 @@ func GetUserByUUID(uuid string) (user models.User, err error) {
}
// 通过 SSO 信息获取用户
func GetUserBySSO(ssoID, username string) (user models.User, err error) {
func GetUserBySSO(ssoID string) (user models.User, err error) {
db := dbcore.GetDBInstance()
// 首先尝试查找已存在的用户
@@ -131,5 +131,24 @@ func GetUserBySSO(ssoID, username string) (user models.User, err error) {
return user, nil
}
return user, nil
// 如果找不到用户,返回明确的错误信息
return models.User{}, fmt.Errorf("用户不存在:%s", ssoID)
}
func BindingExternalAccount(uuid string, sso_id string) error {
db := dbcore.GetDBInstance()
err := db.Model(&models.User{}).Where("uuid = ?", uuid).Update("sso_id", sso_id).Error
if err != nil {
return err
}
return nil
}
func UnbindExternalAccount(uuid string) error {
db := dbcore.GetDBInstance()
err := db.Model(&models.User{}).Where("uuid = ?", uuid).Update("sso_id", "").Error
if err != nil {
return err
}
return nil
}
+96 -16
View File
@@ -7,8 +7,11 @@ import (
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/utils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"fmt"
"github.com/google/uuid"
)
@@ -27,14 +30,10 @@ func DeleteClient(clientUuid string) error {
if err != nil {
return err
}
err = db.Delete(&common.ClientInfo{}, "uuid = ?", clientUuid).Error
if err != nil {
return err
}
return nil
}
// 更新或插入客户端基本信息
// Deprecated: UpdateOrInsertBasicInfo is deprecated and will be removed in a future release. Use SaveClientInfo instead.
func UpdateOrInsertBasicInfo(cbi common.ClientInfo) error {
db := dbcore.GetDBInstance()
updates := make(map[string]interface{})
@@ -75,10 +74,53 @@ func UpdateOrInsertBasicInfo(cbi common.ClientInfo) error {
updates["version"] = cbi.Version
updates["updated_at"] = time.Now()
err := db.Clauses(clause.OnConflict{
// 转换为更新Client表
client := models.Client{
UUID: cbi.UUID,
}
err := db.Model(&client).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "uuid"}},
DoUpdates: clause.Assignments(updates),
}).Create(&cbi).Error
}).Create(map[string]interface{}{
"uuid": cbi.UUID,
"name": cbi.Name,
"cpu_name": cbi.CpuName,
"arch": cbi.Arch,
"cpu_cores": cbi.CpuCores,
"os": cbi.OS,
"gpu_name": cbi.GpuName,
"ipv4": cbi.IPv4,
"ipv6": cbi.IPv6,
"region": cbi.Region,
"remark": cbi.Remark,
"mem_total": cbi.MemTotal,
"swap_total": cbi.SwapTotal,
"disk_total": cbi.DiskTotal,
"version": cbi.Version,
"updated_at": time.Now(),
}).Error
if err != nil {
return err
}
return nil
}
func SaveClientInfo(update map[string]interface{}) error {
db := dbcore.GetDBInstance()
clientUUID, ok := update["uuid"].(string)
if !ok || clientUUID == "" {
return fmt.Errorf("invalid client UUID")
}
// 确保更新的字段不为空
if len(update) == 0 {
return fmt.Errorf("no fields to update")
}
update["updated_at"] = time.Now()
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Updates(update).Error
if err != nil {
return err
}
@@ -97,7 +139,7 @@ func UpdateClientConfig(config common.ClientConfig) error {
func EditClientName(clientUUID, clientName string) error {
db := dbcore.GetDBInstance()
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Update("client_name", clientName).Error
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Update("name", clientName).Error
if err != nil {
return err
}
@@ -137,6 +179,7 @@ func CreateClient() (clientUUID, token string, err error) {
client := models.Client{
UUID: clientUUID,
Token: token,
Name: "client_" + clientUUID[0:8],
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
@@ -145,11 +188,25 @@ func CreateClient() (clientUUID, token string, err error) {
if err != nil {
return "", "", err
}
clientInfo := common.ClientInfo{
UUID: clientUUID,
Name: "client_" + clientUUID[0:8],
return clientUUID, token, nil
}
func CreateClientWithName(name string) (clientUUID, token string, err error) {
if name == "" {
return CreateClient()
}
err = db.Create(&clientInfo).Error
db := dbcore.GetDBInstance()
token = utils.GenerateToken()
clientUUID = uuid.New().String()
client := models.Client{
UUID: clientUUID,
Token: token,
Name: name,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
err = db.Create(&client).Error
if err != nil {
return "", "", err
}
@@ -178,13 +235,15 @@ func GetClientByUUID(uuid string) (client models.Client, err error) {
}
// GetClientBasicInfo 获取指定 UUID 的客户端基本信息
func GetClientBasicInfo(uuid string) (client common.ClientInfo, err error) {
func GetClientBasicInfo(uuid string) (client models.Client, err error) {
db := dbcore.GetDBInstance()
err = db.Where("uuid = ?", uuid).First(&client).Error
if err != nil {
return client, err
if err == gorm.ErrRecordNotFound {
return models.Client{}, fmt.Errorf("客户端不存在: %s", uuid)
}
return models.Client{}, err
}
return client, nil
}
@@ -198,7 +257,7 @@ func GetClientTokenByUUID(uuid string) (token string, err error) {
return client.Token, nil
}
func GetAllClientBasicInfo() (clients []common.ClientInfo, err error) {
func GetAllClientBasicInfo() (clients []models.Client, err error) {
db := dbcore.GetDBInstance()
err = db.Find(&clients).Error
if err != nil {
@@ -206,3 +265,24 @@ func GetAllClientBasicInfo() (clients []common.ClientInfo, err error) {
}
return clients, nil
}
func SaveClient(updates map[string]interface{}) error {
db := dbcore.GetDBInstance()
clientUUID, ok := updates["uuid"].(string)
if !ok || clientUUID == "" {
return fmt.Errorf("invalid client UUID")
}
// 确保更新的字段不为空
if len(updates) == 0 {
return fmt.Errorf("no fields to update")
}
updates["updated_at"] = time.Now()
err := db.Model(&models.Client{}).Where("uuid = ?", clientUUID).Updates(updates).Error
if err != nil {
return err
}
return nil
}
+16 -16
View File
@@ -58,23 +58,23 @@ func SaveClientReport(clientUUID string, report common.Report) (err error) {
Record := models.Record{
Client: clientUUID,
Time: time.Now(),
CPU: float32(report.CPU.Usage),
GPU: 0, // Report 未提供 GPU Usage,设为 0(与原 nil 行为类似)
RAM: report.Ram.Used,
RAMTotal: report.Ram.Total,
SWAP: report.Swap.Used,
SWAPTotal: report.Swap.Total,
LOAD: float32(report.Load.Load1), // 使用 Load1 作为主要负载指标
TEMP: 0, // Report 未提供 TEMP,设为 0(与原 nil 行为类似)
DISK: report.Disk.Used,
DISKTotal: report.Disk.Total,
NETIn: report.Network.Down,
NETOut: report.Network.Up,
NETTotalUp: report.Network.TotalUp,
NETTotalDown: report.Network.TotalDown,
PROCESS: report.Process,
Cpu: float32(report.CPU.Usage),
Gpu: 0, // Report 未提供 GPU Usage,设为 0(与原 nil 行为类似)
Ram: report.Ram.Used,
RamTotal: report.Ram.Total,
Swap: report.Swap.Used,
SwapTotal: report.Swap.Total,
Load: float32(report.Load.Load1), // 使用 Load1 作为主要负载指标
Temp: 0, // Report 未提供 TEMP,设为 0(与原 nil 行为类似)
Disk: report.Disk.Used,
DiskTotal: report.Disk.Total,
NetIn: report.Network.Down,
NetOut: report.Network.Up,
NetTotalUp: report.Network.TotalUp,
NetTotalDown: report.Network.TotalDown,
Process: report.Process,
Connections: report.Connections.TCP,
ConnectionsUDP: report.Connections.UDP,
ConnectionsUdp: report.Connections.UDP,
}
// 使用事务确保 Record 和 ClientsInfo 一致性
+44 -7
View File
@@ -1,9 +1,11 @@
package config
import (
"log"
"time"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/public"
"gorm.io/gorm"
)
@@ -13,9 +15,19 @@ func Get() (models.Config, error) {
if err := db.First(&config).Error; err != nil {
if err == gorm.ErrRecordNotFound {
config = models.Config{
ID: 1,
ID: 1,
Sitename: "Komari",
Description: "Komari Monitor, a simple server monitoring tool.",
AllowCros: false,
OAuthEnabled: false,
GeoIpEnabled: true,
GeoIpProvider: "mmdb",
UpdatedAt: time.Now(),
CreatedAt: time.Now(),
}
if err := db.Create(&config).Error; err != nil {
log.Fatal("Failed to create default config:", err)
}
Save(config)
return config, nil
}
return config, err
@@ -25,12 +37,37 @@ func Get() (models.Config, error) {
func Save(cst models.Config) error {
db := dbcore.GetDBInstance()
var config models.Config
// Only one records
config.ID = 1
if err := db.Save(&config).Error; err != nil {
cst.ID = 1
cst.UpdatedAt = time.Now()
// Do not update CreatedAt
if err := db.Model(&models.Config{}).Where("id = ?", cst.ID).
Select("sitename",
"description",
"allow_cros",
"geo_ip_enabled",
"geo_ip_provider",
"o_auth_client_id",
"o_auth_client_secret",
"o_auth_enabled",
"custom_head",
"updated_at").
Updates(cst).Error; err != nil {
return err
}
return nil
}
func Update(cst map[string]interface{}) error {
db := dbcore.GetDBInstance()
// Proceed with update
cst["id"] = 1
cst["updated_at"] = time.Now()
delete(cst, "created_at")
delete(cst, "CreatedAt")
if err := db.Model(&models.Config{}).Where("id = ?", 1).Updates(cst).Error; err != nil {
return err
}
go public.UpdateIndex(config)
return nil
}
+136 -24
View File
@@ -1,6 +1,7 @@
package dbcore
import (
"fmt"
"log"
"os"
"path/filepath"
@@ -9,59 +10,170 @@ import (
"github.com/komari-monitor/komari/cmd/flags"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/models"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// migrateClientData 将旧版ClientInfo数据迁移到新版Client表
func migrateClientData(db *gorm.DB) {
log.Println("正在迁移旧版ClientInfo数据到新版Client表...")
// 读取所有ClientInfo记录
var clientInfos []common.ClientInfo
if err := db.Find(&clientInfos).Error; err != nil {
log.Printf("读取ClientInfo表失败: %v", err)
return
}
// 遍历每条记录并更新到Client表
for _, info := range clientInfos {
// 查找对应的Client记录
var client models.Client
if err := db.Where("uuid = ?", info.UUID).First(&client).Error; err != nil {
log.Printf("找不到UUID为%s的Client记录: %v", info.UUID, err)
continue
}
// 更新Client记录
client.Name = info.Name
client.CpuName = info.CpuName
client.Virtualization = info.Virtualization
client.Arch = info.Arch
client.CpuCores = info.CpuCores
client.OS = info.OS
client.GpuName = info.GpuName
client.IPv4 = info.IPv4
client.IPv6 = info.IPv6
client.Region = info.Region
client.Remark = info.Remark
client.PublicRemark = info.PublicRemark
client.MemTotal = info.MemTotal
client.SwapTotal = info.SwapTotal
client.DiskTotal = info.DiskTotal
client.Version = info.Version
client.Weight = info.Weight
client.Price = info.Price
client.BillingCycle = info.BillingCycle
client.ExpiredAt = info.ExpiredAt
// 保存更新后的Client记录
if err := db.Save(&client).Error; err != nil {
log.Printf("更新Client记录失败: %v", err)
continue
}
}
// 数据迁移完成后,备份并删除旧表
if err := db.Migrator().RenameTable("client_infos", "client_infos_backup"); err != nil {
log.Printf("备份ClientInfo表失败: %v", err)
return
}
log.Println("数据迁移完成,旧表已备份为client_infos_backup")
}
var (
instance *gorm.DB
once sync.Once
)
// true if database file exists
//
// false if database file does not exist
// 初始化数据库
// 对于 SQLite:true 如果数据库文件存在,false 如果数据库文件不存在并被创建
// 对于 MySQL/其他数据库:总是返回 true
func InitDatabase() bool {
if _, err := os.Stat(flags.DatabaseFile); os.IsNotExist(err) {
log.Printf("Database file %q does not exist, creating...", flags.DatabaseFile)
dbDir := filepath.Dir(flags.DatabaseFile)
if dbDir != "" {
if err := os.MkdirAll(dbDir, 0755); err != nil {
log.Fatalf("Failed to create directory %q for database file: %v", dbDir, err)
// 默认使用 SQLite 如果未指定类型
if flags.DatabaseType == "" || flags.DatabaseType == "sqlite" {
if _, err := os.Stat(flags.DatabaseFile); os.IsNotExist(err) {
log.Printf("SQLite database file %q does not exist, creating...", flags.DatabaseFile)
dbDir := filepath.Dir(flags.DatabaseFile)
if dbDir != "" {
if err := os.MkdirAll(dbDir, 0755); err != nil {
log.Fatalf("Failed to create database file directory %q: %v", dbDir, err)
}
}
file, err := os.Create(flags.DatabaseFile)
if err != nil {
log.Fatalf("Failed to create SQLite database file %q: %v", flags.DatabaseFile, err)
}
if err := file.Close(); err != nil {
log.Fatalf("Failed to close database file %q: %v", flags.DatabaseFile, err)
}
return false
} else if err != nil {
log.Fatalf("Failed to check database file %q: %v", flags.DatabaseFile, err)
}
file, err := os.Create(flags.DatabaseFile)
if err != nil {
log.Fatalf("Failed to create SQLite3 database file %q: %v", flags.DatabaseFile, err)
}
if err := file.Close(); err != nil {
log.Fatalf("Failed to close database file %q: %v", flags.DatabaseFile, err)
}
return true
} else if flags.DatabaseType == "mysql" {
// 对于 MySQL,我们不需要创建文件,只需检查连接信息是否有效
log.Printf("Using MySQL database: %s@%s:%s/%s",
flags.DatabaseUser, flags.DatabaseHost, flags.DatabasePort, flags.DatabaseName)
return true
} else {
log.Fatalf("Unsupported database type: %s", flags.DatabaseType)
return false
} else if err != nil {
log.Fatalf("Failed to check database file %q: %v", flags.DatabaseFile, err)
}
return true
}
func GetDBInstance() *gorm.DB {
once.Do(func() {
var err error
instance, err = gorm.Open(sqlite.Open(flags.DatabaseFile), &gorm.Config{})
if err != nil {
log.Fatalf("Failed to connect to SQLite3 database: %v", err)
logConfig := &gorm.Config{
//Logger: logger.Default.LogMode(logger.Silent),
}
// 根据数据库类型选择不同的连接方式
switch flags.DatabaseType {
case "sqlite", "":
// SQLite 连接
instance, err = gorm.Open(sqlite.Open(flags.DatabaseFile), logConfig)
if err != nil {
log.Fatalf("Failed to connect to SQLite3 database: %v", err)
}
log.Printf("Using SQLite database file: %s", flags.DatabaseFile)
case "mysql":
// MySQL 连接
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local",
flags.DatabaseUser,
flags.DatabasePass,
flags.DatabaseHost,
flags.DatabasePort,
flags.DatabaseName)
instance, err = gorm.Open(mysql.Open(dsn), logConfig)
if err != nil {
log.Fatalf("Failed to connect to MySQL database: %v", err)
}
log.Printf("Using MySQL database: %s@%s:%s/%s", flags.DatabaseUser, flags.DatabaseHost, flags.DatabasePort, flags.DatabaseName)
default:
log.Fatalf("Unsupported database type: %s", flags.DatabaseType)
}
// 检查是否存在旧版ClientInfo表
hasOldClientInfoTable := instance.Migrator().HasTable(&common.ClientInfo{})
// 自动迁移模型
err = instance.AutoMigrate(
&models.User{},
&models.Client{},
&models.Session{},
&models.Record{},
&common.ClientInfo{},
&models.Config{},
)
if err != nil {
log.Fatalf("Failed to create tables: %v", err)
}
err = instance.AutoMigrate(
&models.Session{},
)
if err != nil {
log.Printf("Failed to create Session table, it may already exist: %v", err)
}
// 如果存在旧表,执行数据迁移
if hasOldClientInfoTable {
migrateClientData(instance)
}
})
return instance
}
+52 -32
View File
@@ -6,15 +6,35 @@ import (
// Client represents a registered client device
type Client struct {
UUID string `json:"uuid,omitempty" gorm:"type:uuid;primaryKey"`
Token string `json:"token,omitempty" gorm:"type:varchar(255);unique;not null"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UUID string `json:"uuid,omitempty" gorm:"type:varchar(36);primaryKey"`
Token string `json:"token,omitempty" gorm:"type:varchar(255);unique;not null"`
Name string `json:"name" gorm:"type:varchar(100)"`
CpuName string `json:"cpu_name" gorm:"type:varchar(100)"`
Virtualization string `json:"virtualization" gorm:"type:varchar(50)"`
Arch string `json:"arch" gorm:"type:varchar(50)"`
CpuCores int `json:"cpu_cores" gorm:"type:int"`
OS string `json:"os" gorm:"type:varchar(100)"`
GpuName string `json:"gpu_name" gorm:"type:varchar(100)"`
IPv4 string `json:"ipv4,omitempty" gorm:"type:varchar(100)"`
IPv6 string `json:"ipv6,omitempty" gorm:"type:varchar(100)"`
Region string `json:"region" gorm:"type:varchar(100)"`
Remark string `json:"remark,omitempty" gorm:"type:longtext"`
PublicRemark string `json:"public_remark,omitempty" gorm:"type:longtext"`
MemTotal int64 `json:"mem_total" gorm:"type:bigint"`
SwapTotal int64 `json:"swap_total" gorm:"type:bigint"`
DiskTotal int64 `json:"disk_total" gorm:"type:bigint"`
Version string `json:"version,omitempty" gorm:"type:varchar(100)"`
Weight int `json:"weight" gorm:"type:int"`
Price float64 `json:"price"`
BillingCycle int `json:"billing_cycle"`
ExpiredAt time.Time `json:"expired_at" gorm:"type:timestamp"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// User represents an authenticated user
type User struct {
UUID string `json:"uuid,omitempty" gorm:"type:uuid;primaryKey"`
UUID string `json:"uuid,omitempty" gorm:"type:varchar(36);primaryKey"`
Username string `json:"username" gorm:"type:varchar(50);unique;not null"`
Passwd string `json:"passwd,omitempty" gorm:"type:varchar(255);not null"` // Hashed password
SSOType string `json:"sso_type" gorm:"type:varchar(20)"` // e.g., "github", "google"
@@ -25,48 +45,48 @@ type User struct {
// Session manages user sessions
type Session struct {
UUID string `gorm:"type:uuid;foreignKey:UserUUID;references:UUID;constraint:OnDelete:CASCADE"`
Session string `gorm:"type:varchar(255);unique;not null"`
UUID string `gorm:"type:varchar(36);foreignKey:UserUUID;references:UUID;constraint:OnDelete:CASCADE"`
Session string `gorm:"type:varchar(255);uniqueIndex:idx_sessions_session;not null"`
Expires time.Time `gorm:"not null"`
CreatedAt time.Time
}
// Record logs client metrics over time
type Record struct {
Client string `gorm:"type:uuid;index;foreignKey:ClientUUID;references:UUID;constraint:OnDelete:CASCADE"`
Time time.Time `gorm:"index;default:CURRENT_TIMESTAMP"`
CPU float32 `gorm:"type:decimal(5,2)"` // e.g., 75.50%
GPU float32 `gorm:"type:decimal(5,2)"`
RAM int64 `gorm:"type:bigint"`
RAMTotal int64 `gorm:"type:bigint"`
SWAP int64 `gorm:"type:bigint"`
SWAPTotal int64 `gorm:"type:bigint"`
LOAD float32 `gorm:"type:decimal(5,2)"`
TEMP float32 `gorm:"type:decimal(5,2)"`
DISK int64 `gorm:"type:bigint"`
DISKTotal int64 `gorm:"type:bigint"`
NETIn int64 `gorm:"type:bigint"`
NETOut int64 `gorm:"type:bigint"`
NETTotalUp int64 `gorm:"type:bigint"`
NETTotalDown int64 `gorm:"type:bigint"`
PROCESS int
Connections int
ConnectionsUDP int
Client string `json:"client" gorm:"type:varchar(36);index;foreignKey:ClientUUID;references:UUID;constraint:OnDelete:CASCADE"`
Time time.Time `json:"time" gorm:"index"`
Cpu float32 `json:"cpu" gorm:"type:decimal(5,2)"` // e.g., 75.50%
Gpu float32 `json:"gpu" gorm:"type:decimal(5,2)"`
Ram int64 `json:"ram" gorm:"type:bigint"`
RamTotal int64 `json:"ram_total" gorm:"type:bigint"`
Swap int64 `json:"swap" gorm:"type:bigint"`
SwapTotal int64 `json:"swap_total" gorm:"type:bigint"`
Load float32 `json:"load" gorm:"type:decimal(5,2)"`
Temp float32 `json:"temp" gorm:"type:decimal(5,2)"`
Disk int64 `json:"disk" gorm:"type:bigint"`
DiskTotal int64 `json:"disk_total" gorm:"type:bigint"`
NetIn int64 `json:"net_in" gorm:"type:bigint"`
NetOut int64 `json:"net_out" gorm:"type:bigint"`
NetTotalUp int64 `json:"net_total_up" gorm:"type:bigint"`
NetTotalDown int64 `json:"net_total_down" gorm:"type:bigint"`
Process int `json:"process"`
Connections int `json:"connections"`
ConnectionsUdp int `json:"connections_udp"`
}
// Config stores site-wide settings
type Config struct {
ID uint `json:"id,omitempty" gorm:"primaryKey;autoIncrement"`
Sitename string `json:"sitename" gorm:"type:varchar(100);not null"`
Description string `json:"desc" gorm:"type:text"`
Description string `json:"description" gorm:"type:text"`
AllowCros bool `json:"allow_cros" gorm:"default:false"`
// GeoIP 配置
GeoIpEnabled bool `json:"geoip_enable" gorm:"default:true"`
GeoIpProvider string `json:"geoip_provider" gorm:"type:varchar(20);default:'mmdb'"` // mmdb, bilibili, ip-api. 暂时只实现了mmdb
GeoIpEnabled bool `json:"geo_ip_enabled" gorm:"default:true"`
GeoIpProvider string `json:"geo_ip_provider" gorm:"type:varchar(20);default:'mmdb'"` // mmdb, bilibili, ip-api. 暂时只实现了mmdb
// OAuth 配置
OAuthClientID string `json:"oauth_id" gorm:"type:varchar(255);not null"`
OAuthClientSecret string `json:"oauth_secret" gorm:"type:varchar(255);not null"`
OAuthEnabled bool `json:"oauth_enable" gorm:"default:false"`
OAuthClientID string `json:"o_auth_client_id" gorm:"type:varchar(255);not null"`
OAuthClientSecret string `json:"o_auth_client_secret" gorm:"type:varchar(255);not null"`
OAuthEnabled bool `json:"o_auth_enabled" gorm:"default:false"`
// 自定义美化
CustomHead string `json:"custom_head" gorm:"type:longtext"`
CreatedAt time.Time
+41 -33
View File
@@ -6,6 +6,7 @@ import (
"gorm.io/gorm"
"github.com/komari-monitor/komari/cmd/flags"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
)
@@ -100,7 +101,9 @@ func CompactRecord() error {
continue
}
}
if flags.DatabaseType != "sqlite" {
return nil // Only vacuum for SQLite
}
if err := db.Exec("VACUUM").Error; err != nil {
log.Printf("Error vacuuming the database: %v", err)
}
@@ -176,46 +179,46 @@ func processTimeRange(db *gorm.DB, clientUUID string, start, end time.Time, inte
count := len(agg.Records)
for _, r := range agg.Records {
sumCPU += r.CPU
sumGPU += r.GPU
sumLOAD += r.LOAD
sumTEMP += r.TEMP
sumRAM += r.RAM
sumRAMTotal += r.RAMTotal
sumSWAP += r.SWAP
sumSWAPTotal += r.SWAPTotal
sumDISK += r.DISK
sumDISKTotal += r.DISKTotal
sumNETIn += r.NETIn
sumNETOut += r.NETOut
sumNETTotalUp += r.NETTotalUp
sumNETTotalDown += r.NETTotalDown
sumPROCESS += r.PROCESS
sumCPU += r.Cpu
sumGPU += r.Gpu
sumLOAD += r.Load
sumTEMP += r.Temp
sumRAM += r.Ram
sumRAMTotal += r.RamTotal
sumSWAP += r.Swap
sumSWAPTotal += r.SwapTotal
sumDISK += r.Disk
sumDISKTotal += r.DiskTotal
sumNETIn += r.NetIn
sumNETOut += r.NetOut
sumNETTotalUp += r.NetTotalUp
sumNETTotalDown += r.NetTotalDown
sumPROCESS += r.Process
sumConnections += r.Connections
sumConnectionsUDP += r.ConnectionsUDP
sumConnectionsUDP += r.ConnectionsUdp
}
// Create new aggregated record
newRecord := models.Record{
Client: clientUUID,
Time: agg.StartTime,
CPU: sumCPU / float32(count),
GPU: sumGPU / float32(count),
RAM: sumRAM / int64(count),
RAMTotal: sumRAMTotal / int64(count),
SWAP: sumSWAP / int64(count),
SWAPTotal: sumSWAPTotal / int64(count),
LOAD: sumLOAD / float32(count),
TEMP: sumTEMP / float32(count),
DISK: sumDISK / int64(count),
DISKTotal: sumDISKTotal / int64(count),
NETIn: sumNETIn / int64(count),
NETOut: sumNETOut / int64(count),
NETTotalUp: sumNETTotalUp / int64(count),
NETTotalDown: sumNETTotalDown / int64(count),
PROCESS: sumPROCESS / count,
Cpu: sumCPU / float32(count),
Gpu: sumGPU / float32(count),
Ram: sumRAM / int64(count),
RamTotal: sumRAMTotal / int64(count),
Swap: sumSWAP / int64(count),
SwapTotal: sumSWAPTotal / int64(count),
Load: sumLOAD / float32(count),
Temp: sumTEMP / float32(count),
Disk: sumDISK / int64(count),
DiskTotal: sumDISKTotal / int64(count),
NetIn: sumNETIn / int64(count),
NetOut: sumNETOut / int64(count),
NetTotalUp: sumNETTotalUp / int64(count),
NetTotalDown: sumNETTotalDown / int64(count),
Process: sumPROCESS / count,
Connections: sumConnections / count,
ConnectionsUDP: sumConnectionsUDP / count,
ConnectionsUdp: sumConnectionsUDP / count,
}
if err := tx.Create(&newRecord).Error; err != nil {
@@ -226,3 +229,8 @@ func processTimeRange(db *gorm.DB, clientUUID string, start, end time.Time, inte
return tx.Commit().Error
}
func Save(rec models.Record) error {
db := dbcore.GetDBInstance()
return db.Create(&rec).Error
}
+5 -2
View File
@@ -10,8 +10,9 @@ require (
github.com/oschwald/maxminddb-golang v1.13.1
github.com/spf13/cobra v1.9.1
github.com/stretchr/testify v1.10.0
gorm.io/driver/mysql v1.5.7
gorm.io/driver/sqlite v1.5.7
gorm.io/gorm v1.25.12
gorm.io/gorm v1.26.1
)
@@ -24,6 +25,7 @@ require golang.org/x/crypto v0.37.0 // indirect
require golang.org/x/net v0.39.0 // indirect
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/sonic v1.13.2 // indirect
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
@@ -33,6 +35,7 @@ require (
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.26.0 // indirect
github.com/go-sql-driver/mysql v1.9.2 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
@@ -53,7 +56,7 @@ require (
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.15.0 // indirect
golang.org/x/sys v0.32.0 // indirect
golang.org/x/text v0.24.0 // indirect
golang.org/x/text v0.25.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+12 -4
View File
@@ -1,3 +1,5 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
@@ -27,6 +29,9 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
@@ -101,8 +106,8 @@ golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -111,8 +116,11 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I=
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.26.1 h1:ghB2gUI9FkS46luZtn6DLZ0f6ooBJ5IbVej2ENFDjRw=
gorm.io/gorm v1.26.1/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
+4
View File
@@ -1,9 +1,13 @@
package main
import (
"log"
"github.com/komari-monitor/komari/cmd"
"github.com/komari-monitor/komari/utils"
)
func main() {
log.Printf("Komari Monitor %s (hash: %s)", utils.CurrentVersion, utils.VersionHash)
cmd.Execute()
}
+1 -1
View File
@@ -41,7 +41,7 @@ func initIndex() {
}()
index, err := io.ReadAll(indexFile)
if err != nil {
log.Fatalln("Failed to read index.html:", err)
log.Println("Failed to read index.html:", err)
}
RawIndexFile = string(index)
}
+1 -1
View File
@@ -4,7 +4,7 @@
- [ ] 低带宽模式
- [ ] Web终端
- [x] Web终端
- [ ] 一键部署脚本
+1 -1
View File
@@ -15,7 +15,7 @@ import (
)
var (
GeoIpUrl = "https://gh-proxy.com/raw.githubusercontent.com/Loyalsoldier/geoip/release/GeoLite2-Country.mmdb"
GeoIpUrl = "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/GeoLite2-Country.mmdb"
GeoIpFilePath = "./data/GeoLite2-Country.mmdb"
geoIpDb *maxminddb.Reader = nil
lock = &sync.RWMutex{}
+95
View File
@@ -0,0 +1,95 @@
package oauth
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/utils"
)
type GitHubUser struct {
ID int `json:"id"`
Login string `json:"login"`
Email string `json:"email"`
}
// 获取OAuth的URL、state !!请务必验证state防止CSRF攻击
func GetOAuthUrl() (string, string) {
cfg, _ := config.Get()
state := utils.GenerateRandomString(16)
// 构建GitHub OAuth授权URL
authURL := fmt.Sprintf(
"https://github.com/login/oauth/authorize?client_id=%s&state=%s&scope=user:email",
url.QueryEscape(cfg.OAuthClientID),
url.QueryEscape(state),
)
return authURL, state
}
func OAuthCallback(code, state string) (GitHubUser, error) {
cfg, _ := config.Get()
// 验证state防止CSRF攻击
// state, _ := c.Cookie("oauth_state")
if state == "" {
return GitHubUser{}, fmt.Errorf("invalid state")
}
// 获取code
//code := c.Query("code")
if code == "" {
return GitHubUser{}, fmt.Errorf("no code provided")
}
// 获取访问令牌
tokenURL := "https://github.com/login/oauth/access_token"
data := url.Values{
"client_id": {cfg.OAuthClientID},
"client_secret": {cfg.OAuthClientSecret},
"code": {code},
}
req, _ := http.NewRequest("POST", tokenURL, nil)
req.URL.RawQuery = data.Encode()
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return GitHubUser{}, fmt.Errorf("failed to get access token: %v", err)
}
defer resp.Body.Close()
var tokenResp struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
}
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return GitHubUser{}, fmt.Errorf("failed to parse access token response: %v", err)
}
// 获取用户信息
userReq, _ := http.NewRequest("GET", "https://api.github.com/user", nil)
userReq.Header.Set("Authorization", "Bearer "+tokenResp.AccessToken)
userReq.Header.Set("Accept", "application/json")
userResp, err := http.DefaultClient.Do(userReq)
if err != nil {
return GitHubUser{}, fmt.Errorf("failed to get user info: %v", err)
}
defer userResp.Body.Close()
var githubUser GitHubUser
if err := json.NewDecoder(userResp.Body).Decode(&githubUser); err != nil {
return GitHubUser{}, fmt.Errorf("failed to parse user info response: %v", err)
}
return githubUser, nil
}
+59
View File
@@ -0,0 +1,59 @@
package utils
import (
"time"
"github.com/komari-monitor/komari/common"
"github.com/komari-monitor/komari/database/models"
)
func AverageReport(uuid string, time time.Time, records []common.Report) models.Record {
var sumCPU, sumGPU, sumLOAD, sumTEMP float32
var sumRAM, sumRAMTotal, sumSWAP, sumSWAPTotal, sumDISK, sumDISKTotal int64
var sumNETIn, sumNETOut, sumNETTotalUp, sumNETTotalDown int64
var sumPROCESS, sumConnections, sumConnectionsUDP int
count := len(records)
if count == 0 {
return models.Record{}
}
for _, r := range records {
sumCPU += float32(r.CPU.Usage)
sumGPU += 0
sumLOAD += float32(r.Load.Load1)
sumTEMP += 0
sumRAM += r.Ram.Used
sumSWAP += r.Swap.Used
sumDISK += r.Disk.Used
sumNETIn += r.Network.Down
sumNETOut += r.Network.Up
sumNETTotalUp += r.Network.TotalUp
sumNETTotalDown += r.Network.TotalDown
sumPROCESS += r.Process
sumConnections += r.Connections.TCP
sumConnectionsUDP += r.Connections.UDP
}
// Create new aggregated record
newRecord := models.Record{
Client: uuid,
Time: time,
Cpu: sumCPU / float32(count),
Gpu: sumGPU / float32(count),
Ram: sumRAM / int64(count),
RamTotal: sumRAMTotal / int64(count),
Swap: sumSWAP / int64(count),
SwapTotal: sumSWAPTotal / int64(count),
Load: sumLOAD / float32(count),
Temp: sumTEMP / float32(count),
Disk: sumDISK / int64(count),
DiskTotal: sumDISKTotal / int64(count),
NetIn: sumNETIn / int64(count),
NetOut: sumNETOut / int64(count),
NetTotalUp: sumNETTotalUp / int64(count),
NetTotalDown: sumNETTotalDown / int64(count),
Process: sumPROCESS / count,
Connections: sumConnections / count,
ConnectionsUdp: sumConnectionsUDP / count,
}
return newRecord
}
+6
View File
@@ -0,0 +1,6 @@
package utils
var (
CurrentVersion = "0.0.1"
VersionHash = "unknown"
)