From 215fdc822c165b2edccb7c86c839b982dfe607ce Mon Sep 17 00:00:00 2001 From: Akizon77 Date: Tue, 24 Jun 2025 14:36:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BD=BF=E7=94=A8go-cache=E6=9B=BF?= =?UTF-8?q?=E4=BB=A3=E5=AE=89=E5=85=A8=E6=98=A0=E5=B0=84=20ci:=20main?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=8F=91=E5=B8=83=E9=99=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 98 ++++++++++++++++++++++++++ .github/workflows/cleanup-packages.yml | 35 +++------ api/Common.go | 54 ++++++++------ api/client/report.go | 5 +- go.mod | 1 + go.sum | 2 + 6 files changed, 147 insertions(+), 48 deletions(-) create mode 100644 .github/workflows/build.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..1f9f968 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,98 @@ +name: Build Binaries on Main Push + +on: + push: + branches: + - main + +jobs: + build-binaries: + runs-on: ubuntu-latest + + strategy: + matrix: + goos: [windows, linux] + goarch: [amd64, arm64] + include: + - goos: windows + goarch: amd64 + gcc: x86_64-w64-mingw32-gcc + CGO_CFLAGS: '' + CGO_LDFLAGS: '' + - goos: linux + goarch: amd64 + gcc: gcc + CGO_CFLAGS: '' + CGO_LDFLAGS: '' + - goos: linux + goarch: arm64 + gcc: aarch64-linux-gnu-gcc + CGO_CFLAGS: '-pthread' + CGO_LDFLAGS: '-pthread' + exclude: + - goos: windows + goarch: arm64 + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "23" + + - 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: Install cross-compiler + run: | + sudo apt-get update + if [ "${{ matrix.goarch }}" = "arm64" ] && [ "${{ matrix.goos }}" = "linux" ]; then + sudo apt-get install gcc-aarch64-linux-gnu + fi + if [ "${{ matrix.goarch }}" = "amd64" ] && [ "${{ matrix.goos }}" = "windows" ]; then + sudo apt-get install mingw-w64 + fi + if [ "${{ matrix.goarch }}" = "arm64" ] && [ "${{ matrix.goos }}" = "windows" ]; then + sudo apt-get install wget xz-utils + mkdir -p /tmp/mingw64 + wget https://github.com/mstorsjo/llvm-mingw/releases/download/20250613/llvm-mingw-20250613-ucrt-ubuntu-22.04-aarch64.tar.xz -O /tmp/mingw64.tar.xz + tar -xf /tmp/mingw64.tar.xz -C /tmp/mingw64 --strip-components=1 + fi + + - name: Build binary + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + CGO_ENABLED: 1 + CC: ${{ matrix.gcc }} + CGO_CFLAGS: ${{ matrix.CGO_CFLAGS }} + CGO_LDFLAGS: ${{ matrix.CGO_LDFLAGS }} + GIN_MODE: release + run: | + BINARY_NAME=komari-${{ matrix.goos }}-${{ matrix.goarch }} + if [ "${{ matrix.goos }}" = "windows" ]; then + BINARY_NAME=${BINARY_NAME}.exe + fi + VERSION="${{ github.sha }}" + 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 as artifact + uses: actions/upload-artifact@v4 + with: + name: komari-${{ matrix.goos }}-${{ matrix.goarch }} + path: komari-${{ matrix.goos }}-${{ matrix.goarch }}* \ No newline at end of file diff --git a/.github/workflows/cleanup-packages.yml b/.github/workflows/cleanup-packages.yml index b526974..cb11221 100644 --- a/.github/workflows/cleanup-packages.yml +++ b/.github/workflows/cleanup-packages.yml @@ -25,35 +25,18 @@ jobs: package_name: process.env.GITHUB_REPOSITORY.split('/')[1] }); - // Keep packages with 'dev' or 'latest' tags, plus the 10 most recent non-dev, non-latest versions - const keepVersions = [ - // Keep packages with 'dev' tag - ...packages.filter(pkg => pkg.metadata.container.tags.includes('dev')), - // Keep packages with 'latest' tag, excluding those already included with 'dev' - ...packages.filter( - pkg => - pkg.metadata.container.tags.includes('latest') && - !pkg.metadata.container.tags.includes('dev') - ), - // Keep the 10 most recent non-dev, non-latest packages - ...packages - .filter( - pkg => - !pkg.metadata.container.tags.includes('dev') && - !pkg.metadata.container.tags.includes('latest') - ) - .slice(0, 10), - ]; + // Identify versions with only a single SHA tag (format: sha-<7 hexadecimal characters>) + const shaOnlyVersions = packages.filter(pkg => { + const tags = pkg.metadata.container.tags; + return tags.length === 1 && tags[0].match(/^sha-[0-9a-f]{7}$/); + }); - // Identify versions to delete (not in keepVersions) - const deleteVersions = packages.filter(pkg => !keepVersions.includes(pkg)); - - // Delete the versions - for (const version of deleteVersions) { + // Delete the SHA-only versions + for (const version of shaOnlyVersions) { await github.rest.packages.deletePackageVersionForAuthenticatedUser({ package_type: 'container', package_name: process.env.GITHUB_REPOSITORY.split('/')[1], package_version_id: version.id }); - console.log(`Deleted package version ${version.id}`); - } + console.log(`Deleted package version ${version.id} with SHA tag ${version.metadata.container.tags[0]}`); + } \ No newline at end of file diff --git a/api/Common.go b/api/Common.go index 078ebac..a40f57d 100644 --- a/api/Common.go +++ b/api/Common.go @@ -1,6 +1,7 @@ package api import ( + "log" "net/http" "sync" "time" @@ -8,6 +9,7 @@ import ( "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "github.com/komari-monitor/komari/common" + "github.com/patrickmn/go-cache" "github.com/komari-monitor/komari/database/dbcore" "github.com/komari-monitor/komari/database/models" @@ -15,7 +17,7 @@ import ( ) var ( - Records = utils.NewSafeMap[string, []common.Report]() + Records = cache.New(1*time.Minute, 1*time.Minute) ) type TerminalSession struct { @@ -29,37 +31,49 @@ var TerminalSessionsMutex = &sync.Mutex{} var TerminalSessions = make(map[string]*TerminalSession) func SaveClientReportToDB() error { - lastMinute := time.Now().Add(-time.Minute * 1).Unix() - record := []models.Record{} - var err error + lastMinute := time.Now().Add(-time.Minute).Unix() + var records []models.Record - // 遍历所有的客户端记录 - Records.Range(func(uuid string, reports []common.Report) bool { - // 删除一分钟前的记录 - filtered := reports[:0] + // 遍历所有客户端记录 + for uuid, x := range Records.Items() { + if uuid == "" { + continue + } + + reports, ok := x.Object.([]common.Report) + if !ok { + log.Printf("Invalid report type for UUID %s", uuid) + continue + } + + // 过滤一分钟前的记录 + var filtered []common.Report for _, r := range reports { if r.UpdatedAt.Unix() >= lastMinute { filtered = append(filtered, r) } } - Records.Store(uuid, filtered) - if uuid == "" { - return true + // 更新缓存 + Records.Set(uuid, filtered, cache.DefaultExpiration) + + // 计算平均报告并添加到记录列表 + if len(filtered) > 0 { + r := utils.AverageReport(uuid, time.Now(), filtered) + records = append(records, r) } + } - r := utils.AverageReport(uuid, time.Now(), filtered) - record = append(record, r) - + // 批量插入数据库 + if len(records) > 0 { db := dbcore.GetDBInstance() - err = db.Model(&models.Record{}).Create(record).Error - if err != nil { - return false + if err := db.Model(&models.Record{}).Create(&records).Error; err != nil { + log.Printf("Failed to save records to database: %v", err) + return err } - return true - }) + } - return err + return nil } type Response struct { diff --git a/api/client/report.go b/api/client/report.go index 0dad635..e6b0a04 100644 --- a/api/client/report.go +++ b/api/client/report.go @@ -19,6 +19,7 @@ import ( "github.com/komari-monitor/komari/database/tasks" "github.com/komari-monitor/komari/utils/notification" "github.com/komari-monitor/komari/ws" + "github.com/patrickmn/go-cache" ) func UploadReport(c *gin.Context) { @@ -185,8 +186,8 @@ func SaveClientReport(uuid string, report common.Report) error { if report.CPU.Usage < 0.01 { report.CPU.Usage = 0.01 } - reports = append(reports, report) - api.Records.Set(uuid, reports) + reports = append(reports.([]common.Report), report) + api.Records.Set(uuid, reports, cache.DefaultExpiration) return nil } diff --git a/go.mod b/go.mod index 22d2d61..a8e5cec 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.3 github.com/oschwald/maxminddb-golang v1.13.1 + github.com/patrickmn/go-cache v2.1.0+incompatible github.com/pquerna/otp v1.5.0 github.com/spf13/cobra v1.9.1 github.com/stretchr/testify v1.10.0 diff --git a/go.sum b/go.sum index 518babf..0a4cb2c 100644 --- a/go.sum +++ b/go.sum @@ -74,6 +74,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5MbwsmL4MRQE= github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=