mirror of
https://github.com/MengMengCode/CLICD.git
synced 2026-08-05 05:36:07 +08:00
Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5207082cd1 | |||
| 608b50f18a | |||
| b58a6b1030 | |||
| 366f889a8c | |||
| 814441e9a0 | |||
| aed11af105 | |||
| 3d95bb33c1 | |||
| ade1c6c093 | |||
| 5c4cc1cab3 | |||
| 109e47170f | |||
| 34637cc79d | |||
| 7d48889eea | |||
| 2bcdb9e095 | |||
| 2ab42e7f57 | |||
| 3257cbb2a3 | |||
| 1ff5d7a85e | |||
| a99781d418 | |||
| b993e57d05 | |||
| 7ae0c91813 | |||
| aab58aca6e | |||
| 0b27604f95 | |||
| 460614e274 | |||
| 007811ab41 | |||
| 95af3e44f2 | |||
| 2ad17fa520 | |||
| 08a1a057e7 |
@@ -58,6 +58,7 @@ backend/tmp/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
*.claude/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
@@ -65,3 +66,4 @@ Thumbs.db
|
||||
linux.txt
|
||||
push-release.ps1
|
||||
deploy.ps1
|
||||
backend/clicd
|
||||
|
||||
@@ -53,6 +53,28 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh
|
||||

|
||||

|
||||
|
||||
|
||||
## Disclaimer/免责声明
|
||||
|
||||
This open-source software does not distribute Windows system images, nor does it provide any means to bypass or circumvent Windows activation mechanisms.
|
||||
|
||||
All download links provided within the software point to resources officially supplied by Microsoft. Users of this software are responsible for obtaining the appropriate licenses from Microsoft before using any Windows operating system downloaded through these links. This project does not bypass activation requirements for installed systems, nor does it assume any responsibility for the consequences of users' actions when using this software.
|
||||
|
||||
This open-source software is intended solely for educational purposes, specifically for learning the principles of LXC and KVM. The copyright for the Windows logo and related icons belongs to Microsoft/Windows.
|
||||
|
||||
本开源软件不提供任何 Windows 操作系统镜像的分发服务,也不包含任何绕过、破解或免除 Windows 激活机制的功能。
|
||||
|
||||
软件内涉及的 Windows 系统下载链接均由微软官方提供。使用者在下载、安装和使用相关 Windows 系统时,应自行向微软或其授权渠道购买并获得相应的软件许可。本项目不会对安装后的 Windows 系统进行任何形式的激活绕过、破解或免激活处理。
|
||||
|
||||
对于使用者因使用本软件而产生的任何行为及其后果,包括但不限于软件许可、系统使用、数据丢失、法律责任或其他相关问题,本项目及其开发者不承担任何责任。
|
||||
|
||||
本开源软件仅供学习和研究 LXC、KVM 等虚拟化技术原理之目的使用,不得用于任何违反适用法律法规、软件许可协议或第三方权益的行为。
|
||||
|
||||
本软件中涉及的 Windows 名称、标识、图标及相关知识产权均归 Microsoft Corporation 及其权利人所有。本项目与微软公司不存在任何关联、授权或合作关系。
|
||||
## Thanks/鸣谢
|
||||
|
||||
- [Linux.do](https://linux.do) — 一个充满灵感的科技社区
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/?repos=MengMengCode%2FCLICD&type=date&legend=top-left">
|
||||
@@ -61,8 +83,4 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=MengMengCode/CLICD&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=MengMengCode/CLICD&type=date&legend=top-left" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- [Linux.do](https://linux.do) — 一个充满灵感的科技社区
|
||||
</a>
|
||||
+26
-5
@@ -1,12 +1,33 @@
|
||||
module clicd
|
||||
|
||||
go 1.22.0
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.5
|
||||
|
||||
require (
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
golang.org/x/crypto v0.28.0
|
||||
golang.org/x/term v0.28.0
|
||||
golang.org/x/crypto v0.45.0
|
||||
golang.org/x/term v0.37.0
|
||||
)
|
||||
|
||||
require golang.org/x/sys v0.29.0 // indirect
|
||||
require (
|
||||
golang.org/x/sys v0.38.0
|
||||
modernc.org/sqlite v1.29.10
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 // indirect
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
||||
modernc.org/libc v1.61.13 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.8.2 // indirect
|
||||
modernc.org/strutil v1.2.1 // indirect
|
||||
modernc.org/token v1.1.0 // indirect
|
||||
)
|
||||
|
||||
+59
-8
@@ -1,10 +1,61 @@
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
|
||||
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678 h1:mchzmB1XO2pMaKFRqk/+MV3mgGG96aqaPXaMifQU47w=
|
||||
golang.org/x/exp v0.0.0-20231108232855-2478ac86f678/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE=
|
||||
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
|
||||
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
|
||||
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
|
||||
modernc.org/cc/v4 v4.24.4 h1:TFkx1s6dCkQpd6dKurBNmpo+G8Zl4Sq/ztJ+2+DEsh0=
|
||||
modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo=
|
||||
modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo=
|
||||
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
||||
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
||||
modernc.org/gc/v2 v2.6.3 h1:aJVhcqAte49LF+mGveZ5KPlsp4tdGdAOT4sipJXADjw=
|
||||
modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
|
||||
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
|
||||
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.8.2 h1:cL9L4bcoAObu4NkxOlKWBWtNHIsnnACGF/TbqQ6sbcI=
|
||||
modernc.org/memory v1.8.2/go.mod h1:ZbjSvMO5NQ1A2i3bWeDiVMxIorXwdClKE/0SZ+BMotU=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.29.10 h1:3u93dz83myFnMilBGCOLbr+HjklS6+5rJLx4q86RDAg=
|
||||
modernc.org/sqlite v1.29.10/go.mod h1:ItX2a1OVGgNsFh6Dv60JQvGfJfTPHPVpV6DF59akYOA=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
|
||||
+100
-27
@@ -2,10 +2,10 @@ package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"time"
|
||||
|
||||
"clicd/internal/config"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
type ApiKey struct {
|
||||
@@ -79,14 +81,23 @@ func createApiKey(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// Generate key: clicd_sk_ + 32 hex chars
|
||||
rawBytes := make([]byte, 16)
|
||||
rand.Read(rawBytes)
|
||||
if _, err := rand.Read(rawBytes); err != nil {
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to generate API key"})
|
||||
return
|
||||
}
|
||||
rawKey := "clicd_sk_" + hex.EncodeToString(rawBytes)
|
||||
|
||||
keyHash, err := hashAPIKey(rawKey)
|
||||
if err != nil {
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to store API key"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().Format("2006-01-02 15:04:05")
|
||||
key := config.ApiKeyConfig{
|
||||
ID: generateShortID(),
|
||||
Name: req.Name,
|
||||
KeyHash: hashKey(rawKey),
|
||||
KeyHash: keyHash,
|
||||
Prefix: rawKey[:13] + "...",
|
||||
IPWhitelist: strings.TrimSpace(req.IPWhitelist),
|
||||
CreatedAt: now,
|
||||
@@ -114,10 +125,59 @@ func generateShortID() string {
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// hashKey creates a simple hash for storage (not reversible)
|
||||
func hashKey(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return hex.EncodeToString(sum[:])
|
||||
const (
|
||||
apiKeyHashPrefix = "argon2id"
|
||||
apiKeyHashTime = uint32(3)
|
||||
apiKeyHashMemory = uint32(64 * 1024)
|
||||
apiKeyHashThreads = uint8(1)
|
||||
apiKeyHashSaltLength = 16
|
||||
apiKeyHashKeyLength = uint32(32)
|
||||
)
|
||||
|
||||
// hashAPIKey stores API keys using a salted slow password-hash style function.
|
||||
func hashAPIKey(key string) (string, error) {
|
||||
salt := make([]byte, apiKeyHashSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hashAPIKeyWithSalt(key, salt), nil
|
||||
}
|
||||
|
||||
func hashAPIKeyWithSalt(key string, salt []byte) string {
|
||||
digest := argon2.IDKey([]byte(key), salt, apiKeyHashTime, apiKeyHashMemory, apiKeyHashThreads, apiKeyHashKeyLength)
|
||||
return fmt.Sprintf("%s$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||
apiKeyHashPrefix,
|
||||
apiKeyHashMemory,
|
||||
apiKeyHashTime,
|
||||
apiKeyHashThreads,
|
||||
hex.EncodeToString(salt),
|
||||
hex.EncodeToString(digest),
|
||||
)
|
||||
}
|
||||
|
||||
func verifyAPIKeyHash(rawKey, storedHash string) bool {
|
||||
parts := strings.Split(storedHash, "$")
|
||||
if len(parts) != 5 || parts[0] != apiKeyHashPrefix || parts[1] != "v=19" {
|
||||
return false
|
||||
}
|
||||
var memory, iterations uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[2], "m=%d,t=%d,p=%d", &memory, &iterations, &threads); err != nil {
|
||||
return false
|
||||
}
|
||||
if memory != apiKeyHashMemory || iterations != apiKeyHashTime || threads != apiKeyHashThreads {
|
||||
return false
|
||||
}
|
||||
salt, err := hex.DecodeString(parts[3])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return false
|
||||
}
|
||||
expected, err := hex.DecodeString(parts[4])
|
||||
if err != nil || len(expected) == 0 {
|
||||
return false
|
||||
}
|
||||
digest := argon2.IDKey([]byte(rawKey), salt, iterations, memory, threads, uint32(len(expected)))
|
||||
return subtle.ConstantTimeCompare(digest, expected) == 1
|
||||
}
|
||||
|
||||
func legacyHashKey(key string) string {
|
||||
@@ -128,20 +188,36 @@ func legacyHashKey(key string) string {
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// validateApiKey checks if the given key is valid and IP is allowed
|
||||
func validateApiKey(rawKey, clientIP string) bool {
|
||||
hashed := hashKey(rawKey)
|
||||
func matchApiKey(rawKey string) (idx int, needsRehash bool) {
|
||||
legacyHashed := legacyHashKey(rawKey)
|
||||
for _, k := range config.AppConfig.ApiKeys {
|
||||
if subtle.ConstantTimeCompare([]byte(k.KeyHash), []byte(hashed)) == 1 ||
|
||||
subtle.ConstantTimeCompare([]byte(k.KeyHash), []byte(legacyHashed)) == 1 {
|
||||
if k.IPWhitelist == "" {
|
||||
return true
|
||||
}
|
||||
return isIPAllowed(clientIP, k.IPWhitelist)
|
||||
for i, k := range config.AppConfig.ApiKeys {
|
||||
if verifyAPIKeyHash(rawKey, k.KeyHash) {
|
||||
return i, false
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(k.KeyHash), []byte(legacyHashed)) == 1 {
|
||||
return i, true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return -1, false
|
||||
}
|
||||
|
||||
// validateApiKey checks if the given key is valid and IP is allowed.
|
||||
func validateApiKey(rawKey, clientIP string) bool {
|
||||
idx, needsRehash := matchApiKey(rawKey)
|
||||
if idx < 0 {
|
||||
return false
|
||||
}
|
||||
k := config.AppConfig.ApiKeys[idx]
|
||||
if k.IPWhitelist != "" && !isIPAllowed(clientIP, k.IPWhitelist) {
|
||||
return false
|
||||
}
|
||||
if needsRehash {
|
||||
if newHash, err := hashAPIKey(rawKey); err == nil {
|
||||
config.AppConfig.ApiKeys[idx].KeyHash = newHash
|
||||
config.SaveConfig()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func apiKeyFromRequest(r *http.Request) string {
|
||||
@@ -228,17 +304,14 @@ func ip4ToUint32(ip net.IP) uint32 {
|
||||
return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
|
||||
}
|
||||
|
||||
// updateApiKeyLastUsed marks the key as recently used
|
||||
// updateApiKeyLastUsed marks the key as recently used.
|
||||
func updateApiKeyLastUsed(rawKey string) {
|
||||
hashed := hashKey(rawKey)
|
||||
now := time.Now().Format("2006-01-02 15:04:05")
|
||||
for i := range config.AppConfig.ApiKeys {
|
||||
if config.AppConfig.ApiKeys[i].KeyHash == hashed {
|
||||
config.AppConfig.ApiKeys[i].LastUsed = now
|
||||
config.SaveConfig()
|
||||
return
|
||||
}
|
||||
idx, _ := matchApiKey(rawKey)
|
||||
if idx < 0 {
|
||||
return
|
||||
}
|
||||
config.AppConfig.ApiKeys[idx].LastUsed = time.Now().Format("2006-01-02 15:04:05")
|
||||
config.SaveConfig()
|
||||
}
|
||||
|
||||
// ApiKeyMiddleware authenticates requests via X-API-Key header or Authorization bearer.
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"clicd/internal/config"
|
||||
)
|
||||
|
||||
func TestHashAPIKeyUsesSaltedArgon2idHash(t *testing.T) {
|
||||
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
|
||||
|
||||
h1, err := hashAPIKey(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h2, err := hashAPIKey(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if h1 == h2 {
|
||||
t.Fatal("expected salted hashes to differ")
|
||||
}
|
||||
if !strings.HasPrefix(h1, apiKeyHashPrefix+"$") || !strings.HasPrefix(h2, apiKeyHashPrefix+"$") {
|
||||
t.Fatalf("expected argon2id hashes, got %q and %q", h1, h2)
|
||||
}
|
||||
if !verifyAPIKeyHash(raw, h1) || !verifyAPIKeyHash(raw, h2) {
|
||||
t.Fatal("argon2id hashes did not verify")
|
||||
}
|
||||
if verifyAPIKeyHash(raw+"x", h1) {
|
||||
t.Fatal("argon2id hash verified wrong key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateApiKeyAllowsArgon2idAndUpdatesLastUsed(t *testing.T) {
|
||||
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
|
||||
hash, err := hashAPIKey(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.AppConfig = &config.ClicdConfig{
|
||||
ApiKeys: []config.ApiKeyConfig{{
|
||||
ID: "key1",
|
||||
Name: "test",
|
||||
KeyHash: hash,
|
||||
}},
|
||||
}
|
||||
|
||||
if !validateApiKey(raw, "127.0.0.1") {
|
||||
t.Fatal("validateApiKey rejected valid argon2id key")
|
||||
}
|
||||
updateApiKeyLastUsed(raw)
|
||||
if config.AppConfig.ApiKeys[0].LastUsed == "" {
|
||||
t.Fatal("LastUsed was not updated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateApiKeyMigratesLegacyHash(t *testing.T) {
|
||||
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
|
||||
config.AppConfig = &config.ClicdConfig{
|
||||
ApiKeys: []config.ApiKeyConfig{{
|
||||
ID: "legacy",
|
||||
Name: "legacy",
|
||||
KeyHash: legacyHashKey(raw),
|
||||
}},
|
||||
}
|
||||
|
||||
if !validateApiKey(raw, "127.0.0.1") {
|
||||
t.Fatal("validateApiKey rejected valid legacy key")
|
||||
}
|
||||
migrated := config.AppConfig.ApiKeys[0].KeyHash
|
||||
if migrated == legacyHashKey(raw) {
|
||||
t.Fatal("legacy key hash was not migrated")
|
||||
}
|
||||
if !verifyAPIKeyHash(raw, migrated) {
|
||||
t.Fatal("migrated key hash does not verify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateApiKeyAppliesIPWhitelist(t *testing.T) {
|
||||
raw := "clicd_sk_0123456789abcdef0123456789abcdef"
|
||||
hash, err := hashAPIKey(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.AppConfig = &config.ClicdConfig{
|
||||
ApiKeys: []config.ApiKeyConfig{{
|
||||
ID: "key1",
|
||||
Name: "test",
|
||||
KeyHash: hash,
|
||||
IPWhitelist: "192.0.2.10",
|
||||
}},
|
||||
}
|
||||
|
||||
if validateApiKey(raw, "198.51.100.10") {
|
||||
t.Fatal("validateApiKey allowed disallowed IP")
|
||||
}
|
||||
if !validateApiKey(raw, "192.0.2.10") {
|
||||
t.Fatal("validateApiKey rejected allowed IP")
|
||||
}
|
||||
}
|
||||
@@ -75,8 +75,10 @@ func claimsFromToken(tokenString string) (jwt.MapClaims, bool) {
|
||||
if subUser, _ := claims["sub_user"].(string); subUser != "" {
|
||||
tokenVersionFloat, hasVersion := claims["token_version"].(float64)
|
||||
tokenVersion := int(tokenVersionFloat)
|
||||
foundSubUser := false
|
||||
for i := range config.AppConfig.SubUsers {
|
||||
if config.AppConfig.SubUsers[i].Username == subUser {
|
||||
foundSubUser = true
|
||||
stored := config.AppConfig.SubUsers[i].TokenVersion
|
||||
// If stored version > 0, require token_version to match exactly.
|
||||
// This also rejects legacy tokens that lack token_version entirely.
|
||||
@@ -86,6 +88,9 @@ func claimsFromToken(tokenString string) (jwt.MapClaims, bool) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !foundSubUser {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
return claims, ok
|
||||
|
||||
@@ -2,10 +2,12 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"clicd/internal/config"
|
||||
"clicd/internal/lxc"
|
||||
@@ -394,7 +396,24 @@ func resetSSHPassword(w http.ResponseWriter, r *http.Request, id int) {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "容器已到期,不允许此操作"})
|
||||
return
|
||||
}
|
||||
newPassword, err := resetPasswordByRuntime(id)
|
||||
var req struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if r.Body != nil {
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err := decoder.Decode(&req); err != nil && err.Error() != "EOF" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
|
||||
return
|
||||
}
|
||||
}
|
||||
password := strings.TrimSpace(req.Password)
|
||||
if password != "" {
|
||||
if err := validateSSHPassword(password); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
newPassword, err := resetPasswordByRuntime(id, password)
|
||||
if err != nil {
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
@@ -406,6 +425,29 @@ func resetSSHPassword(w http.ResponseWriter, r *http.Request, id int) {
|
||||
})
|
||||
}
|
||||
|
||||
func validateSSHPassword(password string) error {
|
||||
if len(password) < 8 || len(password) > 64 {
|
||||
return fmt.Errorf("密码长度必须为 8-64 位")
|
||||
}
|
||||
hasLetter := false
|
||||
hasDigit := false
|
||||
for _, r := range password {
|
||||
if unicode.IsSpace(r) {
|
||||
return fmt.Errorf("密码不能包含空白字符")
|
||||
}
|
||||
if unicode.IsLetter(r) {
|
||||
hasLetter = true
|
||||
}
|
||||
if unicode.IsDigit(r) {
|
||||
hasDigit = true
|
||||
}
|
||||
}
|
||||
if !hasLetter || !hasDigit {
|
||||
return fmt.Errorf("密码至少需要包含字母和数字")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func addPortMapping(w http.ResponseWriter, r *http.Request, id int) {
|
||||
var pm config.PortMapping
|
||||
if err := json.NewDecoder(r.Body).Decode(&pm); err != nil {
|
||||
|
||||
@@ -8,10 +8,11 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"clicd/internal/lxc"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
type HostInfo struct {
|
||||
@@ -135,8 +136,8 @@ func getMemoryInfo() MemoryInfo {
|
||||
}
|
||||
|
||||
func getDiskInfo() DiskInfo {
|
||||
var stat syscall.Statfs_t
|
||||
if err := syscall.Statfs("/", &stat); err != nil {
|
||||
var stat unix.Statfs_t
|
||||
if err := unix.Statfs("/", &stat); err != nil {
|
||||
// Try command-based fallback
|
||||
cmd := exec.Command("df", "-BG", "/")
|
||||
output, err := cmd.Output()
|
||||
|
||||
+276
-92
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -8,6 +9,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"clicd/internal/config"
|
||||
"clicd/internal/kvm"
|
||||
@@ -16,22 +18,143 @@ import (
|
||||
|
||||
// ImageInfo represents a template image with its download/enable status.
|
||||
type ImageInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Distro string `json:"distro"`
|
||||
Release string `json:"release"`
|
||||
Arch string `json:"arch"`
|
||||
Description string `json:"description"`
|
||||
Downloaded bool `json:"downloaded"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Downloading bool `json:"downloading"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
ManualPath string `json:"manual_path,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Distro string `json:"distro"`
|
||||
Release string `json:"release"`
|
||||
Arch string `json:"arch"`
|
||||
Description string `json:"description"`
|
||||
Downloaded bool `json:"downloaded"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Downloading bool `json:"downloading"`
|
||||
Progress int `json:"progress"`
|
||||
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
ManualPath string `json:"manual_path,omitempty"`
|
||||
Desktop string `json:"desktop,omitempty"`
|
||||
}
|
||||
|
||||
var imageDownloadsMu sync.Mutex
|
||||
var imageDownloads = map[string]bool{}
|
||||
var imageDownloads = map[string]*imageDownloadStatus{}
|
||||
|
||||
type imageDownloadStatus struct {
|
||||
Downloading bool
|
||||
Progress int
|
||||
DownloadedBytes int64
|
||||
TotalBytes int64
|
||||
Stage string
|
||||
Error string
|
||||
Cancel context.CancelFunc
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type imageDownloadSnapshot struct {
|
||||
Downloading bool
|
||||
Progress int
|
||||
DownloadedBytes int64
|
||||
TotalBytes int64
|
||||
Stage string
|
||||
Error string
|
||||
}
|
||||
|
||||
func imageDownloadInfo(id string) imageDownloadSnapshot {
|
||||
imageDownloadsMu.Lock()
|
||||
defer imageDownloadsMu.Unlock()
|
||||
st := imageDownloads[id]
|
||||
if st == nil {
|
||||
return imageDownloadSnapshot{}
|
||||
}
|
||||
return imageDownloadSnapshot{
|
||||
Downloading: st.Downloading,
|
||||
Progress: st.Progress,
|
||||
DownloadedBytes: st.DownloadedBytes,
|
||||
TotalBytes: st.TotalBytes,
|
||||
Stage: st.Stage,
|
||||
Error: st.Error,
|
||||
}
|
||||
}
|
||||
|
||||
func startImageDownload(id, stage string) (context.Context, bool) {
|
||||
imageDownloadsMu.Lock()
|
||||
defer imageDownloadsMu.Unlock()
|
||||
if st := imageDownloads[id]; st != nil && st.Downloading {
|
||||
return nil, false
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
imageDownloads[id] = &imageDownloadStatus{
|
||||
Downloading: true,
|
||||
Stage: stage,
|
||||
Cancel: cancel,
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
return ctx, true
|
||||
}
|
||||
|
||||
func updateImageDownload(id string, update func(*imageDownloadStatus)) {
|
||||
imageDownloadsMu.Lock()
|
||||
defer imageDownloadsMu.Unlock()
|
||||
st := imageDownloads[id]
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
update(st)
|
||||
st.UpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
func finishImageDownload(id string, err error) {
|
||||
imageDownloadsMu.Lock()
|
||||
defer imageDownloadsMu.Unlock()
|
||||
st := imageDownloads[id]
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
st.Downloading = false
|
||||
st.Cancel = nil
|
||||
st.UpdatedAt = time.Now()
|
||||
if err != nil {
|
||||
st.Error = err.Error()
|
||||
return
|
||||
}
|
||||
delete(imageDownloads, id)
|
||||
}
|
||||
|
||||
func clearImageDownload(id string) {
|
||||
imageDownloadsMu.Lock()
|
||||
delete(imageDownloads, id)
|
||||
imageDownloadsMu.Unlock()
|
||||
}
|
||||
|
||||
func isImageDownloadActive(id string) bool {
|
||||
imageDownloadsMu.Lock()
|
||||
defer imageDownloadsMu.Unlock()
|
||||
st := imageDownloads[id]
|
||||
return st != nil && st.Downloading
|
||||
}
|
||||
|
||||
func lxcImageDownloadTempName(id string) string {
|
||||
return fmt.Sprintf("clicd-img-dl-%s", id)
|
||||
}
|
||||
|
||||
func cleanupLXCImageDownloadTemp(id string) {
|
||||
tmpName := lxcImageDownloadTempName(id)
|
||||
exec.Command("lxc-destroy", "-n", tmpName, "-f").Run()
|
||||
os.RemoveAll(filepath.Join("/var/lib/lxc", tmpName))
|
||||
}
|
||||
|
||||
func cleanupOldImageDownloadErrors() {
|
||||
imageDownloadsMu.Lock()
|
||||
defer imageDownloadsMu.Unlock()
|
||||
cutoff := time.Now().Add(-10 * time.Minute)
|
||||
for id, st := range imageDownloads {
|
||||
if !st.Downloading && st.UpdatedAt.Before(cutoff) {
|
||||
delete(imageDownloads, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isImageDownloaded checks if the LXC download cache exists for a template.
|
||||
func isImageDownloaded(distro, release, arch string) bool {
|
||||
@@ -100,53 +223,65 @@ func HandleImages(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
enabledSet := getEnabledImageSet()
|
||||
cleanupOldImageDownloadErrors()
|
||||
|
||||
templates := lxc.GetTemplates()
|
||||
images := make([]ImageInfo, 0, len(templates)+len(kvm.GetImages()))
|
||||
for _, t := range templates {
|
||||
_, downloading := imageDownloads[t.ID]
|
||||
dl := imageDownloadInfo(t.ID)
|
||||
downloaded, size := imageDownloadedInfo(t.Distro, t.Release, t.Arch)
|
||||
images = append(images, ImageInfo{
|
||||
ID: t.ID,
|
||||
Name: t.Name,
|
||||
Type: config.VirtualizationLXC,
|
||||
Distro: t.Distro,
|
||||
Release: t.Release,
|
||||
Arch: t.Arch,
|
||||
Description: t.Description,
|
||||
Downloaded: downloaded,
|
||||
Enabled: enabledSet[t.ID],
|
||||
Downloading: downloading,
|
||||
SizeBytes: size,
|
||||
ID: t.ID,
|
||||
Name: t.Name,
|
||||
Type: config.VirtualizationLXC,
|
||||
Distro: t.Distro,
|
||||
Release: t.Release,
|
||||
Arch: t.Arch,
|
||||
Description: t.Description,
|
||||
Downloaded: downloaded,
|
||||
Enabled: enabledSet[t.ID],
|
||||
Downloading: dl.Downloading,
|
||||
Progress: dl.Progress,
|
||||
DownloadedBytes: dl.DownloadedBytes,
|
||||
TotalBytes: dl.TotalBytes,
|
||||
Stage: dl.Stage,
|
||||
Error: dl.Error,
|
||||
SizeBytes: size,
|
||||
})
|
||||
}
|
||||
for _, t := range kvm.GetImages() {
|
||||
_, downloading := imageDownloads[t.ID]
|
||||
dl := imageDownloadInfo(t.ID)
|
||||
downloaded, size := kvm.ImageDownloadedInfo(t.ID)
|
||||
manualPath := ""
|
||||
if t.Distro == "windows" {
|
||||
manualPath = kvm.ImagePath(t.ID)
|
||||
}
|
||||
images = append(images, ImageInfo{
|
||||
ID: t.ID,
|
||||
Name: t.Name,
|
||||
Type: config.VirtualizationKVM,
|
||||
Distro: t.Distro,
|
||||
Release: t.Release,
|
||||
Arch: t.Arch,
|
||||
Description: t.Description,
|
||||
Downloaded: downloaded,
|
||||
Enabled: enabledSet[t.ID],
|
||||
Downloading: downloading,
|
||||
SizeBytes: size,
|
||||
ManualPath: manualPath,
|
||||
ID: t.ID,
|
||||
Name: t.Name,
|
||||
Type: config.VirtualizationKVM,
|
||||
Distro: t.Distro,
|
||||
Release: t.Release,
|
||||
Arch: t.Arch,
|
||||
Description: t.Description,
|
||||
Downloaded: downloaded,
|
||||
Enabled: enabledSet[t.ID],
|
||||
Downloading: dl.Downloading,
|
||||
Progress: dl.Progress,
|
||||
DownloadedBytes: dl.DownloadedBytes,
|
||||
TotalBytes: dl.TotalBytes,
|
||||
Stage: dl.Stage,
|
||||
Error: dl.Error,
|
||||
SizeBytes: size,
|
||||
ManualPath: manualPath,
|
||||
Desktop: t.Desktop,
|
||||
})
|
||||
}
|
||||
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: images})
|
||||
}
|
||||
|
||||
// HandleImageDownload downloads a template image from the LXC image server.
|
||||
// HandleImageDownload starts a template image download in the background.
|
||||
func HandleImageDownload(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
|
||||
@@ -170,82 +305,127 @@ func HandleImageDownload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if ok, _ := kvm.ImageDownloadedInfo(image.ID); ok {
|
||||
ensureImageEnabled(image.ID)
|
||||
clearImageDownload(image.ID)
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Already downloaded"})
|
||||
return
|
||||
}
|
||||
imageDownloadsMu.Lock()
|
||||
if imageDownloads[req.TemplateID] {
|
||||
imageDownloadsMu.Unlock()
|
||||
ctx, ok := startImageDownload(image.ID, "downloading")
|
||||
if !ok {
|
||||
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Already downloading"})
|
||||
return
|
||||
}
|
||||
imageDownloads[req.TemplateID] = true
|
||||
imageDownloadsMu.Unlock()
|
||||
defer func() {
|
||||
imageDownloadsMu.Lock()
|
||||
delete(imageDownloads, req.TemplateID)
|
||||
imageDownloadsMu.Unlock()
|
||||
}()
|
||||
ensureImageEnabled(image.ID)
|
||||
if err := kvm.DownloadImage(*image); err != nil {
|
||||
message := "Download failed: " + err.Error()
|
||||
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: message})
|
||||
return
|
||||
}
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Downloaded successfully"})
|
||||
go func(image kvm.Image) {
|
||||
err := kvm.DownloadImageWithProgress(ctx, image, func(p kvm.DownloadProgress) {
|
||||
updateImageDownload(image.ID, func(st *imageDownloadStatus) {
|
||||
if p.Stage != "" {
|
||||
st.Stage = p.Stage
|
||||
}
|
||||
if p.DownloadedBytes > 0 || p.TotalBytes > 0 {
|
||||
st.DownloadedBytes = p.DownloadedBytes
|
||||
st.TotalBytes = p.TotalBytes
|
||||
}
|
||||
st.Progress = p.Percent
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
os.Remove(kvm.ImagePath(image.ID) + ".tmp")
|
||||
os.Remove(kvm.ImagePath(image.ID))
|
||||
finishImageDownload(image.ID, nil)
|
||||
return
|
||||
}
|
||||
finishImageDownload(image.ID, err)
|
||||
return
|
||||
}
|
||||
ensureImageEnabled(image.ID)
|
||||
finishImageDownload(image.ID, nil)
|
||||
}(*image)
|
||||
jsonResponse(w, http.StatusAccepted, APIResponse{Success: true, Message: "Download started"})
|
||||
return
|
||||
}
|
||||
|
||||
// Already downloaded? Just enable if needed.
|
||||
if isImageDownloaded(tmpl.Distro, tmpl.Release, tmpl.Arch) {
|
||||
ensureImageEnabled(tmpl.ID)
|
||||
clearImageDownload(tmpl.ID)
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Already downloaded"})
|
||||
return
|
||||
}
|
||||
|
||||
// Already downloading?
|
||||
imageDownloadsMu.Lock()
|
||||
if imageDownloads[req.TemplateID] {
|
||||
imageDownloadsMu.Unlock()
|
||||
ctx, ok := startImageDownload(tmpl.ID, "lxc-create")
|
||||
if !ok {
|
||||
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Already downloading"})
|
||||
return
|
||||
}
|
||||
imageDownloads[req.TemplateID] = true
|
||||
imageDownloadsMu.Unlock()
|
||||
|
||||
defer func() {
|
||||
imageDownloadsMu.Lock()
|
||||
delete(imageDownloads, req.TemplateID)
|
||||
imageDownloadsMu.Unlock()
|
||||
}()
|
||||
|
||||
// Auto-enable on download
|
||||
ensureImageEnabled(tmpl.ID)
|
||||
|
||||
// Download via lxc-create with a temp container, then destroy it.
|
||||
tmpName := fmt.Sprintf("clicd-img-dl-%s", tmpl.ID)
|
||||
args := []string{"-n", tmpName, "-t", "download", "--",
|
||||
"-d", tmpl.Distro, "-r", tmpl.Release, "-a", tmpl.Arch}
|
||||
if tmpl.Variant != "" {
|
||||
args = append(args, "--variant", tmpl.Variant)
|
||||
}
|
||||
cmd := exec.Command("lxc-create", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
// Clean up the temp container unconditionally.
|
||||
exec.Command("lxc-destroy", "-n", tmpName, "-f").Run()
|
||||
os.RemoveAll(filepath.Join("/var/lib/lxc", tmpName))
|
||||
|
||||
if err != nil {
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{
|
||||
Success: false,
|
||||
Message: fmt.Sprintf("Download failed: %v, output: %s", err, string(output)),
|
||||
go func(tmpl lxc.Template) {
|
||||
// Download via lxc-create with a temp container, then destroy it.
|
||||
tmpName := lxcImageDownloadTempName(tmpl.ID)
|
||||
args := []string{"-n", tmpName, "-t", "download", "--",
|
||||
"-d", tmpl.Distro, "-r", tmpl.Release, "-a", tmpl.Arch}
|
||||
if tmpl.Variant != "" {
|
||||
args = append(args, "--variant", tmpl.Variant)
|
||||
}
|
||||
updateImageDownload(tmpl.ID, func(st *imageDownloadStatus) {
|
||||
st.Stage = "lxc-create"
|
||||
})
|
||||
cmd := exec.CommandContext(ctx, "lxc-create", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
// Clean up the temp container unconditionally.
|
||||
cleanupLXCImageDownloadTemp(tmpl.ID)
|
||||
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
finishImageDownload(tmpl.ID, nil)
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("Download failed: %v, output: %s", err, string(output))
|
||||
finishImageDownload(tmpl.ID, err)
|
||||
return
|
||||
}
|
||||
ensureImageEnabled(tmpl.ID)
|
||||
finishImageDownload(tmpl.ID, nil)
|
||||
}(*tmpl)
|
||||
|
||||
jsonResponse(w, http.StatusAccepted, APIResponse{Success: true, Message: "Download started"})
|
||||
}
|
||||
|
||||
// HandleImageCancel cancels an in-progress image download.
|
||||
func HandleImageCancel(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
TemplateID string `json:"template_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.TemplateID == "" {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "template_id required"})
|
||||
return
|
||||
}
|
||||
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Downloaded successfully"})
|
||||
imageDownloadsMu.Lock()
|
||||
st := imageDownloads[req.TemplateID]
|
||||
if st == nil || !st.Downloading || st.Cancel == nil {
|
||||
imageDownloadsMu.Unlock()
|
||||
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "No active download"})
|
||||
return
|
||||
}
|
||||
cancel := st.Cancel
|
||||
st.Stage = "canceling"
|
||||
st.UpdatedAt = time.Now()
|
||||
imageDownloadsMu.Unlock()
|
||||
|
||||
cancel()
|
||||
if image := kvm.FindImage(req.TemplateID); image != nil {
|
||||
os.Remove(kvm.ImagePath(image.ID) + ".tmp")
|
||||
os.Remove(kvm.ImagePath(image.ID))
|
||||
}
|
||||
if tmpl := lxc.FindTemplate(req.TemplateID); tmpl != nil {
|
||||
go cleanupLXCImageDownloadTemp(tmpl.ID)
|
||||
}
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: "Cancel requested"})
|
||||
}
|
||||
|
||||
// HandleImageDelete deletes a cached template image from disk.
|
||||
@@ -262,6 +442,10 @@ func HandleImageDelete(w http.ResponseWriter, r *http.Request) {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "template_id required"})
|
||||
return
|
||||
}
|
||||
if isImageDownloadActive(req.TemplateID) {
|
||||
jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Image is downloading; cancel it before deleting"})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl := lxc.FindTemplate(req.TemplateID)
|
||||
if tmpl == nil {
|
||||
@@ -336,7 +520,7 @@ func HandleEnabledImages(w http.ResponseWriter, r *http.Request) {
|
||||
if downloaded, _ := kvm.ImageDownloadedInfo(t.ID); enabledSet[t.ID] && downloaded {
|
||||
result = append(result, map[string]string{
|
||||
"id": t.ID, "name": t.Name, "distro": t.Distro, "release": t.Release, "arch": t.Arch,
|
||||
"description": t.Description, "type": config.VirtualizationKVM,
|
||||
"description": t.Description, "type": config.VirtualizationKVM, "desktop": t.Desktop,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,12 +72,12 @@ func reinstallByRuntime(id int, templateID string) error {
|
||||
return lxcManager.ReinstallContainer(id, templateID)
|
||||
}
|
||||
|
||||
func resetPasswordByRuntime(id int) (string, error) {
|
||||
func resetPasswordByRuntime(id int, password string) (string, error) {
|
||||
c := config.FindContainer(id)
|
||||
if c != nil && c.IsKVM() {
|
||||
return kvmManager.ResetSSHPassword(id)
|
||||
return kvmManager.ResetSSHPassword(id, password)
|
||||
}
|
||||
return lxcManager.ResetSSHPassword(id)
|
||||
return lxcManager.ResetSSHPassword(id, password)
|
||||
}
|
||||
|
||||
func assignIPv6ByRuntime(id int) (*config.Container, error) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -557,10 +558,10 @@ func countPorts(totalCounts map[int]int, destCounts map[int]map[string]int, port
|
||||
|
||||
func (ss *SecurityScanner) addAlert(name, alertType, severity, srcIP, dstIP string, port int, detail, logLine string) {
|
||||
ss.mu.Lock()
|
||||
defer ss.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-5 * time.Minute)
|
||||
shouldShutdown := false
|
||||
|
||||
for i := range ss.alerts {
|
||||
a := &ss.alerts[i]
|
||||
@@ -579,6 +580,11 @@ func (ss *SecurityScanner) addAlert(name, alertType, severity, srcIP, dstIP stri
|
||||
if severityRank(severity) > severityRank(a.Severity) {
|
||||
a.Severity = severity
|
||||
}
|
||||
shouldShutdown = config.AppConfig.SecurityAutoShutdown
|
||||
ss.mu.Unlock()
|
||||
if shouldShutdown {
|
||||
autoShutdownAlertContainer(name, alertType, severity)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -599,10 +605,16 @@ func (ss *SecurityScanner) addAlert(name, alertType, severity, srcIP, dstIP stri
|
||||
|
||||
ss.alerts = append(ss.alerts, alert)
|
||||
config.AddAuditLog("security_"+alertType, name, fmt.Sprintf("[%s] %s", severity, detail), "system")
|
||||
shouldShutdown = config.AppConfig.SecurityAutoShutdown
|
||||
|
||||
if len(ss.alerts) > 200 {
|
||||
ss.alerts = ss.alerts[len(ss.alerts)-200:]
|
||||
}
|
||||
ss.mu.Unlock()
|
||||
|
||||
if shouldShutdown {
|
||||
autoShutdownAlertContainer(name, alertType, severity)
|
||||
}
|
||||
}
|
||||
|
||||
func severityRank(severity string) int {
|
||||
@@ -620,6 +632,22 @@ func severityRank(severity string) int {
|
||||
}
|
||||
}
|
||||
|
||||
func autoShutdownAlertContainer(containerName, alertType, severity string) {
|
||||
c := config.FindContainerByName(containerName)
|
||||
if c == nil || c.Status != "running" {
|
||||
return
|
||||
}
|
||||
reason := fmt.Sprintf("%s 告警触发策略临时封禁", alertType)
|
||||
if severity != "" {
|
||||
reason = fmt.Sprintf("[%s] %s", severity, reason)
|
||||
}
|
||||
config.SetContainerPolicyBlock(c.ID, true, reason)
|
||||
taskID, queued := globalQueue.EnqueueSecurityStop(c.ID, c.Name)
|
||||
if queued {
|
||||
config.AddAuditLog("security_auto_shutdown", c.Name, fmt.Sprintf("[%s] %s 告警触发自动关机任务 %s", severity, alertType, taskID), "system")
|
||||
}
|
||||
}
|
||||
|
||||
// HandleSecurityAlerts returns all security alerts.
|
||||
func HandleSecurityAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
@@ -627,19 +655,35 @@ func HandleSecurityAlerts(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ss := ensureScanner()
|
||||
ss.mu.Lock()
|
||||
reversed := make([]SecurityAlert, len(ss.alerts))
|
||||
for i, a := range ss.alerts {
|
||||
reversed[len(ss.alerts)-1-i] = a
|
||||
}
|
||||
ss.mu.Unlock()
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: mergedSecurityAlerts()})
|
||||
}
|
||||
|
||||
if reversed == nil {
|
||||
reversed = []SecurityAlert{}
|
||||
// HandleSecuritySettings returns or updates security automation settings.
|
||||
func HandleSecuritySettings(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]bool{
|
||||
"auto_shutdown": config.AppConfig.SecurityAutoShutdown,
|
||||
}})
|
||||
case http.MethodPut:
|
||||
var req struct {
|
||||
AutoShutdown bool `json:"auto_shutdown"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
|
||||
return
|
||||
}
|
||||
config.AppConfig.SecurityAutoShutdown = req.AutoShutdown
|
||||
if err := config.SaveConfig(); err != nil {
|
||||
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]bool{
|
||||
"auto_shutdown": config.AppConfig.SecurityAutoShutdown,
|
||||
}})
|
||||
default:
|
||||
jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"})
|
||||
}
|
||||
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: reversed})
|
||||
}
|
||||
|
||||
// HandleSecurityCheck triggers immediate security check for a container.
|
||||
@@ -738,13 +782,12 @@ func HandleContainerSecuritySummary(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ss := ensureScanner()
|
||||
ss.mu.Lock()
|
||||
critical := 0
|
||||
high := 0
|
||||
medium := 0
|
||||
low := 0
|
||||
for _, a := range ss.alerts {
|
||||
alerts := mergedSecurityAlerts()
|
||||
for _, a := range alerts {
|
||||
switch a.Severity {
|
||||
case "critical":
|
||||
critical++
|
||||
@@ -756,8 +799,7 @@ func HandleContainerSecuritySummary(w http.ResponseWriter, r *http.Request) {
|
||||
low++
|
||||
}
|
||||
}
|
||||
total := len(ss.alerts)
|
||||
ss.mu.Unlock()
|
||||
total := len(alerts)
|
||||
|
||||
summary := map[string]interface{}{
|
||||
"total_alerts": total,
|
||||
@@ -769,3 +811,117 @@ func HandleContainerSecuritySummary(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: summary})
|
||||
}
|
||||
|
||||
func mergedSecurityAlerts() []SecurityAlert {
|
||||
ss := ensureScanner()
|
||||
ss.mu.Lock()
|
||||
alerts := make([]SecurityAlert, len(ss.alerts))
|
||||
copy(alerts, ss.alerts)
|
||||
ss.mu.Unlock()
|
||||
|
||||
seen := make(map[string]bool)
|
||||
for _, alert := range alerts {
|
||||
seen[securityAlertKey(alert)] = true
|
||||
}
|
||||
|
||||
for i, log := range config.AppConfig.AuditLogs {
|
||||
alert, ok := alertFromSecurityAuditLog(log, i)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key := securityAlertKey(alert)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
alerts = append(alerts, alert)
|
||||
}
|
||||
|
||||
sort.SliceStable(alerts, func(i, j int) bool {
|
||||
ti, errI := time.Parse("2006-01-02 15:04:05", alerts[i].Timestamp)
|
||||
tj, errJ := time.Parse("2006-01-02 15:04:05", alerts[j].Timestamp)
|
||||
if errI == nil && errJ == nil && !ti.Equal(tj) {
|
||||
return ti.After(tj)
|
||||
}
|
||||
return alerts[i].Timestamp > alerts[j].Timestamp
|
||||
})
|
||||
|
||||
if len(alerts) > 200 {
|
||||
alerts = alerts[:200]
|
||||
}
|
||||
if alerts == nil {
|
||||
return []SecurityAlert{}
|
||||
}
|
||||
return alerts
|
||||
}
|
||||
|
||||
func securityAlertKey(alert SecurityAlert) string {
|
||||
return strings.Join([]string{
|
||||
alert.Timestamp,
|
||||
alert.ContainerName,
|
||||
alert.Type,
|
||||
alert.Detail,
|
||||
strconv.Itoa(alert.TargetPort),
|
||||
}, "\x1f")
|
||||
}
|
||||
|
||||
func alertFromSecurityAuditLog(log config.AuditLog, index int) (SecurityAlert, bool) {
|
||||
if !strings.HasPrefix(log.Action, "security_") || log.Action == "security_auto_shutdown" || log.Action == "security_policy_unblock" {
|
||||
return SecurityAlert{}, false
|
||||
}
|
||||
alertType := strings.TrimPrefix(log.Action, "security_")
|
||||
severity, detail := parseSecurityAuditDetail(log.Detail)
|
||||
targetPort := parseDetailPort(detail)
|
||||
|
||||
targetIP := ""
|
||||
if targetPort > 0 || alertType == "horizontal_scan" || alertType == "brute_force" {
|
||||
targetIP = "*"
|
||||
}
|
||||
|
||||
return SecurityAlert{
|
||||
ID: fmt.Sprintf("audit-security-%d", index),
|
||||
ContainerName: log.Target,
|
||||
Type: alertType,
|
||||
Severity: severity,
|
||||
SourceIP: "",
|
||||
TargetIP: targetIP,
|
||||
TargetPort: targetPort,
|
||||
Detail: detail,
|
||||
LogLine: "",
|
||||
Timestamp: log.Time,
|
||||
Count: 1,
|
||||
}, true
|
||||
}
|
||||
|
||||
func parseSecurityAuditDetail(detail string) (string, string) {
|
||||
severity := "medium"
|
||||
if strings.HasPrefix(detail, "[") {
|
||||
if end := strings.Index(detail, "]"); end > 1 {
|
||||
severity = detail[1:end]
|
||||
detail = strings.TrimSpace(detail[end+1:])
|
||||
}
|
||||
}
|
||||
return severity, detail
|
||||
}
|
||||
|
||||
func parseDetailPort(detail string) int {
|
||||
for _, marker := range []string{"端口 ", "端口"} {
|
||||
idx := strings.Index(detail, marker)
|
||||
if idx == -1 {
|
||||
continue
|
||||
}
|
||||
start := idx + len(marker)
|
||||
for start < len(detail) && (detail[start] == ' ' || detail[start] == ':' || detail[start] == '(') {
|
||||
start++
|
||||
}
|
||||
end := start
|
||||
for end < len(detail) && detail[end] >= '0' && detail[end] <= '9' {
|
||||
end++
|
||||
}
|
||||
if end > start {
|
||||
port, _ := strconv.Atoi(detail[start:end])
|
||||
return port
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ type terminalResizeMessage struct {
|
||||
|
||||
type webSSHTicket struct {
|
||||
ContainerName string
|
||||
SubUser bool
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
@@ -52,16 +53,22 @@ func HandleWebSSHTicket(w http.ResponseWriter, r *http.Request) {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this container"})
|
||||
return
|
||||
}
|
||||
if config.FindContainerByName(req.ContainerName) == nil {
|
||||
c := config.FindContainerByName(req.ContainerName)
|
||||
if c == nil {
|
||||
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
|
||||
return
|
||||
}
|
||||
if isSubUserRequest(r) && c.PolicyBlocked {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: policyBlockedMessage(c)})
|
||||
return
|
||||
}
|
||||
|
||||
ticket := randomHex(32)
|
||||
webSSHTickets.Lock()
|
||||
cleanupExpiredWebSSHTicketsLocked(time.Now())
|
||||
webSSHTickets.items[ticket] = webSSHTicket{
|
||||
ContainerName: req.ContainerName,
|
||||
SubUser: isSubUserRequest(r),
|
||||
ExpiresAt: time.Now().Add(60 * time.Second),
|
||||
}
|
||||
webSSHTickets.Unlock()
|
||||
@@ -86,7 +93,8 @@ func HandleWebSSH(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if !consumeWebSSHTicket(ticket, containerName) {
|
||||
item, ok := consumeWebSSHTicket(ticket, containerName)
|
||||
if !ok {
|
||||
http.Error(w, "invalid or expired ticket", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
@@ -96,6 +104,10 @@ func HandleWebSSH(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "container not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if item.SubUser && c.PolicyBlocked {
|
||||
http.Error(w, "虚拟机被策略临时封禁", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if c.Status != "running" {
|
||||
http.Error(w, "container is not running", http.StatusBadRequest)
|
||||
return
|
||||
@@ -359,17 +371,17 @@ func writeWebSocketText(ws *websocket.Conn, writeMu *sync.Mutex, msg string) {
|
||||
_ = ws.WriteMessage(websocket.TextMessage, []byte(msg))
|
||||
}
|
||||
|
||||
func consumeWebSSHTicket(ticket, containerName string) bool {
|
||||
func consumeWebSSHTicket(ticket, containerName string) (webSSHTicket, bool) {
|
||||
now := time.Now()
|
||||
webSSHTickets.Lock()
|
||||
defer webSSHTickets.Unlock()
|
||||
cleanupExpiredWebSSHTicketsLocked(now)
|
||||
item, ok := webSSHTickets.items[ticket]
|
||||
if !ok {
|
||||
return false
|
||||
return webSSHTicket{}, false
|
||||
}
|
||||
delete(webSSHTickets.items, ticket)
|
||||
return item.ContainerName == containerName && now.Before(item.ExpiresAt)
|
||||
return item, item.ContainerName == containerName && now.Before(item.ExpiresAt)
|
||||
}
|
||||
|
||||
func cleanupExpiredWebSSHTicketsLocked(now time.Time) {
|
||||
|
||||
@@ -352,7 +352,11 @@ func SubUserMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
||||
}
|
||||
action := ""
|
||||
if len(parts) > 1 {
|
||||
action = parts[1]
|
||||
action = strings.Join(parts[1:], "/")
|
||||
}
|
||||
if c.PolicyBlocked && isSubUserBlockedAction(action, r.Method) {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: policyBlockedMessage(c)})
|
||||
return
|
||||
}
|
||||
if !isSubUserContainerActionAllowed(action, r.Method) {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Action is not allowed for this link"})
|
||||
@@ -412,6 +416,25 @@ func isContainerAllowed(allowed subUserAccess, c *config.Container) bool {
|
||||
return c != nil && c.UUID != "" && allowed.uuids[c.UUID]
|
||||
}
|
||||
|
||||
func isSubUserBlockedAction(action string, method string) bool {
|
||||
if action == "" {
|
||||
return method != http.MethodGet
|
||||
}
|
||||
switch action {
|
||||
case "usage", "traffic":
|
||||
return method != http.MethodGet
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func policyBlockedMessage(c *config.Container) string {
|
||||
if c != nil && c.PolicyBlockedReason != "" {
|
||||
return "虚拟机被策略临时封禁:" + c.PolicyBlockedReason
|
||||
}
|
||||
return "虚拟机被策略临时封禁"
|
||||
}
|
||||
|
||||
func isSubUserContainerActionAllowed(action string, method string) bool {
|
||||
if action == "" {
|
||||
return method == http.MethodGet
|
||||
|
||||
@@ -196,6 +196,24 @@ func (q *TaskQueue) enqueueSingleWithAudit(containerID int, containerName string
|
||||
return task.ID
|
||||
}
|
||||
|
||||
func (q *TaskQueue) EnqueueSecurityStop(containerID int, containerName string) (string, bool) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
|
||||
for _, task := range q.tasks {
|
||||
if task.Type != TaskStop || task.ContainerID != containerID {
|
||||
continue
|
||||
}
|
||||
if task.Status == "pending" || task.Status == "running" {
|
||||
return task.ID, false
|
||||
}
|
||||
}
|
||||
|
||||
taskID := q.enqueueSingleWithAudit(containerID, containerName, TaskStop, "", "system:security", "", "")
|
||||
q.persistTasks()
|
||||
return taskID, true
|
||||
}
|
||||
|
||||
// createWorker handles TaskCreate: lxc-create, resource setup, start, and SSH init.
|
||||
// If a restored task already has a same-name container in config, it resumes
|
||||
// initialization instead of creating another ct-{id}.
|
||||
@@ -337,10 +355,14 @@ func (q *TaskQueue) opWorker() {
|
||||
switch task.Type {
|
||||
case TaskStart:
|
||||
config.UpdateContainerStatus(task.ContainerID, "running")
|
||||
clearPolicyBlockAfterAdminRecovery(task)
|
||||
case TaskStop:
|
||||
config.UpdateContainerStatus(task.ContainerID, "stopped")
|
||||
case TaskRestart:
|
||||
config.UpdateContainerStatus(task.ContainerID, "running")
|
||||
clearPolicyBlockAfterAdminRecovery(task)
|
||||
case TaskReinstall:
|
||||
clearPolicyBlockAfterAdminRecovery(task)
|
||||
}
|
||||
}
|
||||
q.persistTasks()
|
||||
@@ -348,6 +370,17 @@ func (q *TaskQueue) opWorker() {
|
||||
}
|
||||
}
|
||||
|
||||
func clearPolicyBlockAfterAdminRecovery(task *Task) {
|
||||
if task == nil || strings.HasPrefix(task.User, "user:") || task.User == "system:security" {
|
||||
return
|
||||
}
|
||||
c := config.FindContainer(task.ContainerID)
|
||||
if c != nil && c.PolicyBlocked {
|
||||
config.SetContainerPolicyBlock(c.ID, false, "")
|
||||
config.AddAuditLog("security_policy_unblock", c.Name, "管理员操作后解除策略临时封禁", task.User)
|
||||
}
|
||||
}
|
||||
|
||||
func resolveTaskContainer(task *Task) error {
|
||||
if task.Type == TaskCreate {
|
||||
return nil
|
||||
|
||||
@@ -18,6 +18,10 @@ import (
|
||||
type webVNCTicket struct {
|
||||
ContainerName string
|
||||
ContainerUUID string
|
||||
Username string
|
||||
SubUser bool
|
||||
ClientIP string
|
||||
UserAgent string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
@@ -48,17 +52,26 @@ func HandleVNCTicket(w http.ResponseWriter, r *http.Request) {
|
||||
jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"})
|
||||
return
|
||||
}
|
||||
if isSubUserRequest(r) && c.PolicyBlocked {
|
||||
jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: policyBlockedMessage(c)})
|
||||
return
|
||||
}
|
||||
if !c.IsKVM() {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "VNC console is only available for KVM VMs"})
|
||||
return
|
||||
}
|
||||
|
||||
username, isSubUser := vncRequesterIdentity(r)
|
||||
ticket := randomHex(32)
|
||||
webVNCTickets.Lock()
|
||||
cleanupExpiredWebVNCTicketsLocked(time.Now())
|
||||
webVNCTickets.items[ticket] = webVNCTicket{
|
||||
ContainerName: c.Name,
|
||||
ContainerUUID: c.UUID,
|
||||
Username: username,
|
||||
SubUser: isSubUser,
|
||||
ClientIP: clientIP(r),
|
||||
UserAgent: r.UserAgent(),
|
||||
ExpiresAt: time.Now().Add(60 * time.Second),
|
||||
}
|
||||
webVNCTickets.Unlock()
|
||||
@@ -83,7 +96,7 @@ func HandleVNCProxy(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
item, ok := consumeWebVNCTicket(ticket, containerName)
|
||||
item, ok := consumeWebVNCTicket(ticket, containerName, r)
|
||||
if !ok {
|
||||
http.Error(w, "invalid or expired ticket", http.StatusUnauthorized)
|
||||
return
|
||||
@@ -94,6 +107,10 @@ func HandleVNCProxy(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "container not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if item.SubUser && c.PolicyBlocked {
|
||||
http.Error(w, "虚拟机被策略临时封禁", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if !c.IsKVM() {
|
||||
http.Error(w, "VNC console is only available for KVM VMs", http.StatusBadRequest)
|
||||
return
|
||||
@@ -127,7 +144,7 @@ func HandleVNCProxy(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer ws.Close()
|
||||
|
||||
log.Printf("WebVNC connected for container %s -> 127.0.0.1:%d", containerName, vncPort)
|
||||
log.Printf("WebVNC connected for container %s as %s (sub_user=%t) -> 127.0.0.1:%d", containerName, item.Username, item.SubUser, vncPort)
|
||||
|
||||
done := make(chan string, 2)
|
||||
var writeMu sync.Mutex
|
||||
@@ -137,7 +154,21 @@ func HandleVNCProxy(w http.ResponseWriter, r *http.Request) {
|
||||
reason := <-done
|
||||
_ = vncConn.Close()
|
||||
_ = ws.Close()
|
||||
log.Printf("WebVNC disconnected for container %s: %s", containerName, reason)
|
||||
log.Printf("WebVNC disconnected for container %s as %s: %s", containerName, item.Username, reason)
|
||||
}
|
||||
|
||||
func vncRequesterIdentity(r *http.Request) (string, bool) {
|
||||
claims, ok := claimsFromRequest(r)
|
||||
if !ok {
|
||||
return "api-key", false
|
||||
}
|
||||
if subUser, ok := claims["sub_user"].(string); ok && subUser != "" {
|
||||
return subUser, true
|
||||
}
|
||||
if username, ok := claims["username"].(string); ok && username != "" {
|
||||
return username, false
|
||||
}
|
||||
return "unknown", false
|
||||
}
|
||||
|
||||
func webVNCTicketFromRequest(r *http.Request) string {
|
||||
@@ -165,7 +196,7 @@ func webVNCResponseProtocol(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func consumeWebVNCTicket(ticket, containerName string) (webVNCTicket, bool) {
|
||||
func consumeWebVNCTicket(ticket, containerName string, r *http.Request) (webVNCTicket, bool) {
|
||||
now := time.Now()
|
||||
webVNCTickets.Lock()
|
||||
defer webVNCTickets.Unlock()
|
||||
@@ -175,7 +206,10 @@ func consumeWebVNCTicket(ticket, containerName string) (webVNCTicket, bool) {
|
||||
return webVNCTicket{}, false
|
||||
}
|
||||
delete(webVNCTickets.items, ticket)
|
||||
return item, item.ContainerName == containerName && now.Before(item.ExpiresAt)
|
||||
return item, item.ContainerName == containerName &&
|
||||
item.ClientIP == clientIP(r) &&
|
||||
item.UserAgent == r.UserAgent() &&
|
||||
now.Before(item.ExpiresAt)
|
||||
}
|
||||
|
||||
func cleanupExpiredWebVNCTicketsLocked(now time.Time) {
|
||||
|
||||
+242
-13
@@ -20,6 +20,11 @@ import (
|
||||
|
||||
var manager = lxc.NewManager()
|
||||
|
||||
const (
|
||||
clicdBackupDir = "/root/clicd-backups"
|
||||
clicdNewBinaryPath = "/usr/local/bin/clicd.new"
|
||||
)
|
||||
|
||||
// Run starts the CLI interface.
|
||||
func Run() {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
@@ -198,11 +203,18 @@ func cliCreateContainer(reader *bufio.Reader) {
|
||||
container := config.FindContainerByName(name)
|
||||
fmt.Printf("容器 %s 创建成功\n", name)
|
||||
if container != nil {
|
||||
fmt.Printf("SSH: root / %s, port %d -> 22\n", container.SSHPassword, container.SSHPort)
|
||||
fmt.Print(formatSSHAccess(container.SSHPort))
|
||||
}
|
||||
restartWebPanelForConfigChange()
|
||||
}
|
||||
|
||||
func formatSSHAccess(sshPort int) string {
|
||||
if sshPort <= 0 {
|
||||
return "SSH: root, 端口未分配。密码已保存,请在 Web 面板中查看或重置。\n"
|
||||
}
|
||||
return fmt.Sprintf("SSH: root, port %d -> 22。密码已保存,请在 Web 面板中查看或重置。\n", sshPort)
|
||||
}
|
||||
|
||||
func cliStartContainer(reader *bufio.Reader) {
|
||||
id, name := selectContainer(reader, "开机")
|
||||
if id == 0 {
|
||||
@@ -532,13 +544,14 @@ func upgradeFromReleaseAsset(assetURL, latest string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
backupDir := "/root/clicd-backups"
|
||||
backupDir := clicdBackupDir
|
||||
if err := os.MkdirAll(backupDir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
backupPath := filepath.Join(backupDir, fmt.Sprintf("clicd.%s.%s", strings.TrimPrefix(latest, "v"), time.Now().Format("20060102-150405")))
|
||||
backupName := fmt.Sprintf("clicd.%s.%s", safeReleaseBackupComponent(latest), time.Now().Format("20060102-150405"))
|
||||
if _, err := os.Stat("/usr/local/bin/clicd"); err == nil {
|
||||
if err := copyFile("/usr/local/bin/clicd", backupPath, 0755); err != nil {
|
||||
backupPath, err := copyFileToBackup("/usr/local/bin/clicd", backupName, 0755)
|
||||
if err != nil {
|
||||
return fmt.Errorf("备份旧二进制失败: %w", err)
|
||||
}
|
||||
fmt.Printf("旧版本已备份: %s\n", backupPath)
|
||||
@@ -548,8 +561,8 @@ func upgradeFromReleaseAsset(assetURL, latest string) error {
|
||||
if err := stopService("clicd"); err != nil {
|
||||
fmt.Printf("停止 Web 服务失败,继续尝试替换: %v\n", err)
|
||||
}
|
||||
tmpBin := "/usr/local/bin/clicd.new"
|
||||
if err := copyFile(newBinary, tmpBin, 0755); err != nil {
|
||||
tmpBin := clicdNewBinaryPath
|
||||
if err := copyFileToUpgradeTemp(newBinary, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmpBin, "/usr/local/bin/clicd"); err != nil {
|
||||
@@ -614,25 +627,69 @@ func findFile(root, name string) (string, error) {
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func copyFile(src, dst string, mode os.FileMode) error {
|
||||
func copyFileToBackup(src, fileName string, mode os.FileMode) (string, error) {
|
||||
if fileName == "" || strings.Contains(fileName, "/") || strings.Contains(fileName, "\\") || strings.Contains(fileName, "..") {
|
||||
return "", fmt.Errorf("unsafe backup file name: %s", fileName)
|
||||
}
|
||||
dst := filepath.Join(clicdBackupDir, fileName)
|
||||
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := copyIntoOpenFile(src, out, mode); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
func copyFileToUpgradeTemp(src string, mode os.FileMode) error {
|
||||
out, err := os.OpenFile(clicdNewBinaryPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return copyIntoOpenFile(src, out, mode)
|
||||
}
|
||||
|
||||
func copyIntoOpenFile(src string, out *os.File, mode os.FileMode) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
|
||||
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
if _, err := io.Copy(out, in); err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(out, in); err != nil {
|
||||
if err := out.Chmod(mode); err != nil {
|
||||
out.Close()
|
||||
return err
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(dst, mode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeReleaseBackupComponent(tag string) string {
|
||||
tag = strings.TrimPrefix(strings.TrimSpace(tag), "v")
|
||||
var b strings.Builder
|
||||
for _, r := range tag {
|
||||
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '.' || r == '_' || r == '-' {
|
||||
b.WriteRune(r)
|
||||
continue
|
||||
}
|
||||
b.WriteByte('_')
|
||||
}
|
||||
component := strings.Trim(b.String(), "._-")
|
||||
if component == "" {
|
||||
return "unknown"
|
||||
}
|
||||
if len(component) > 64 {
|
||||
return component[:64]
|
||||
}
|
||||
return component
|
||||
}
|
||||
|
||||
func sameVersion(current, latest string) bool {
|
||||
@@ -681,7 +738,7 @@ func cliImportExistingContainers() {
|
||||
func cliUninstall(reader *bufio.Reader) {
|
||||
fmt.Println("\n--- 卸载 CLICD ---")
|
||||
fmt.Println("将删除 CLICD 服务和 /usr/local/bin/clicd。")
|
||||
fmt.Println("同时会删除 /root/.clicd、/var/lib/lxc 下全部 LXC 容器,以及 /var/cache/lxc 镜像缓存。")
|
||||
fmt.Println("同时会删除 /root/.clicd、/var/lib/lxc、/var/lib/clicd、镜像缓存、备份、临时文件、/swapfile 和 CLICD 网络规则。")
|
||||
|
||||
if os.Geteuid() != 0 {
|
||||
fmt.Println("卸载需要 root 权限。")
|
||||
@@ -696,6 +753,10 @@ func cliUninstall(reader *bufio.Reader) {
|
||||
}
|
||||
|
||||
destroyAllLXCContainers()
|
||||
destroyAllKVMDomains()
|
||||
cleanupCLICDNetworking()
|
||||
removeCLICDHostHooks()
|
||||
removeCLICDQuotaRecords()
|
||||
stopAndRemoveService()
|
||||
removePath("/usr/local/bin/clicd")
|
||||
removePath("/etc/sysctl.d/99-clicd.conf")
|
||||
@@ -703,13 +764,18 @@ func cliUninstall(reader *bufio.Reader) {
|
||||
removePath("/var/log/clicd.err")
|
||||
removePath("/root/.clicd")
|
||||
removePath("/var/lib/lxc")
|
||||
removePath("/var/lib/clicd")
|
||||
removePath("/var/cache/lxc")
|
||||
removePath("/var/cache/clicd")
|
||||
removePath("/root/clicd-backups")
|
||||
removeCLICDTmpFiles()
|
||||
removeCLICDSwapfile()
|
||||
|
||||
reloadSysctl()
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("CLICD 已卸载。")
|
||||
fmt.Println("服务、二进制、配置、容器和 LXC 镜像缓存均已删除。")
|
||||
fmt.Println("服务、二进制、配置、容器/虚拟机、本地镜像、缓存、备份、临时文件和 CLICD 网络规则均已删除。")
|
||||
}
|
||||
|
||||
func destroyAllLXCContainers() {
|
||||
@@ -730,6 +796,151 @@ func destroyAllLXCContainers() {
|
||||
}
|
||||
}
|
||||
|
||||
func destroyAllKVMDomains() {
|
||||
if !commandExists("virsh") {
|
||||
return
|
||||
}
|
||||
out, err := exec.Command("virsh", "list", "--all", "--name").Output()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
name := strings.TrimSpace(line)
|
||||
if isCLICDKVMDomain(name) {
|
||||
removeKVMDomain(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isCLICDKVMDomain(name string) bool {
|
||||
if !strings.HasPrefix(name, "vm-") || len(name) <= len("vm-") {
|
||||
return false
|
||||
}
|
||||
for _, r := range strings.TrimPrefix(name, "vm-") {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if dirExists("/var/lib/clicd/kvm/instances/" + name) {
|
||||
return true
|
||||
}
|
||||
out, err := exec.Command("virsh", "dumpxml", name).Output()
|
||||
return err == nil && strings.Contains(string(out), "/var/lib/clicd/kvm/")
|
||||
}
|
||||
|
||||
func removeKVMDomain(name string) {
|
||||
fmt.Printf("Removing KVM domain %s...\n", name)
|
||||
runQuiet("virsh", "destroy", name)
|
||||
if runCommandOK("virsh", "undefine", name, "--remove-all-storage", "--nvram") {
|
||||
return
|
||||
}
|
||||
if runCommandOK("virsh", "undefine", name, "--nvram") {
|
||||
return
|
||||
}
|
||||
runQuiet("virsh", "undefine", name)
|
||||
}
|
||||
|
||||
func cleanupCLICDNetworking() {
|
||||
removeCLICDNATRules()
|
||||
for _, bridge := range []string{"lxcbr0", "virbr0"} {
|
||||
deleteFilterRule("FORWARD", "-i", bridge, "-j", "ACCEPT")
|
||||
deleteFilterRule("FORWARD", "-o", bridge, "-j", "ACCEPT")
|
||||
deleteFilterRule("FORWARD", "-i", bridge, "-o", bridge, "-j", "ACCEPT")
|
||||
deleteIP6TablesBridgeRules(bridge)
|
||||
}
|
||||
}
|
||||
|
||||
func removeCLICDNATRules() {
|
||||
if commandExists("iptables") {
|
||||
for {
|
||||
out, err := exec.Command("sh", "-c", "iptables -t nat -L PREROUTING -n --line-numbers 2>/dev/null | grep 'clicd-' | awk '{print $1}' | head -n 1").Output()
|
||||
line := strings.TrimSpace(string(out))
|
||||
if err != nil || line == "" {
|
||||
break
|
||||
}
|
||||
if !runCommandOK("iptables", "-t", "nat", "-D", "PREROUTING", line) {
|
||||
break
|
||||
}
|
||||
}
|
||||
deleteNATRule("POSTROUTING", "-s", "10.0.3.0/24", "-o", "eth+", "-j", "MASQUERADE")
|
||||
deleteNATRule("POSTROUTING", "-s", "192.168.122.0/24", "-o", "eth+", "-j", "MASQUERADE")
|
||||
}
|
||||
}
|
||||
|
||||
func deleteNATRule(args ...string) {
|
||||
fullArgs := append([]string{"-t", "nat", "-D"}, args...)
|
||||
for runCommandOK("iptables", fullArgs...) {
|
||||
}
|
||||
}
|
||||
|
||||
func deleteFilterRule(args ...string) {
|
||||
fullArgs := append([]string{"-D"}, args...)
|
||||
for runCommandOK("iptables", fullArgs...) {
|
||||
}
|
||||
}
|
||||
|
||||
func deleteIP6TablesBridgeRules(bridge string) {
|
||||
if !commandExists("ip6tables") {
|
||||
return
|
||||
}
|
||||
for {
|
||||
cmd := fmt.Sprintf("ip6tables -S FORWARD 2>/dev/null | grep -- %s | sed 's/^-A /-D /' | head -n 1", shellQuote(bridge))
|
||||
out, err := exec.Command("sh", "-c", cmd).Output()
|
||||
rule := strings.TrimSpace(string(out))
|
||||
if err != nil || rule == "" {
|
||||
return
|
||||
}
|
||||
if !runCommandOK("sh", "-c", "ip6tables "+rule) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeCLICDHostHooks() {
|
||||
runQuiet("systemctl", "stop", "clicd-kvm-ipv6.service")
|
||||
runQuiet("systemctl", "disable", "clicd-kvm-ipv6.service")
|
||||
runQuiet("rc-service", "clicd-kvm-ipv6", "stop")
|
||||
runQuiet("rc-update", "del", "clicd-kvm-ipv6", "default")
|
||||
removePath("/usr/local/sbin/clicd-kvm-ipv6-init")
|
||||
removePath("/etc/systemd/system/clicd-kvm-ipv6.service")
|
||||
removePath("/etc/local.d/clicd-kvm-ipv6.start")
|
||||
removePath("/etc/network/if-up.d/clicd-kvm-ipv6")
|
||||
}
|
||||
|
||||
func removeCLICDQuotaRecords() {
|
||||
for _, path := range []string{"/etc/projects", "/etc/projid"} {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var kept []string
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
if strings.TrimSpace(line) == "" || strings.Contains(line, "clicd-") {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, line)
|
||||
}
|
||||
_ = os.WriteFile(path, []byte(strings.Join(kept, "\n")+"\n"), 0644)
|
||||
}
|
||||
}
|
||||
|
||||
func removeCLICDTmpFiles() {
|
||||
for _, pattern := range []string{"/tmp/clicd-*", "/tmp/clicd.*"} {
|
||||
matches, _ := filepath.Glob(pattern)
|
||||
for _, path := range matches {
|
||||
removePath(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeCLICDSwapfile() {
|
||||
if !fileExists("/swapfile") {
|
||||
return
|
||||
}
|
||||
runQuiet("swapoff", "/swapfile")
|
||||
removePath("/swapfile")
|
||||
}
|
||||
|
||||
func removeLXCContainerPath(path string) {
|
||||
unmountPathTree(path)
|
||||
detachLoopDevices(path)
|
||||
@@ -819,6 +1030,16 @@ func removePath(path string) {
|
||||
fmt.Printf("Removed %s\n", path)
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
func dirExists(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && info.IsDir()
|
||||
}
|
||||
|
||||
func reloadSysctl() {
|
||||
if commandExists("sysctl") {
|
||||
runQuiet("sysctl", "--system")
|
||||
@@ -830,10 +1051,18 @@ func commandExists(name string) bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func runCommandOK(name string, args ...string) bool {
|
||||
return exec.Command(name, args...).Run() == nil
|
||||
}
|
||||
|
||||
func runQuiet(name string, args ...string) {
|
||||
_ = exec.Command(name, args...).Run()
|
||||
}
|
||||
|
||||
func shellQuote(value string) string {
|
||||
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
|
||||
}
|
||||
|
||||
func restartWebPanelForConfigChange() {
|
||||
if err := restartService("clicd"); err != nil {
|
||||
fmt.Printf("Web 面板重载跳过: %v\n", err)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSafeReleaseBackupComponent(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"v1.2.3": "1.2.3",
|
||||
" release/candidate ": "release_candidate",
|
||||
"../../etc/passwd": "etc_passwd",
|
||||
"": "unknown",
|
||||
}
|
||||
for input, want := range tests {
|
||||
if got := safeReleaseBackupComponent(input); got != want {
|
||||
t.Fatalf("safeReleaseBackupComponent(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyFileToBackupRejectsUnsafeFileName(t *testing.T) {
|
||||
unsafeNames := []string{
|
||||
"../clicd",
|
||||
"..\\clicd",
|
||||
"subdir/clicd",
|
||||
"",
|
||||
}
|
||||
for _, name := range unsafeNames {
|
||||
if _, err := copyFileToBackup("missing-source", name, 0755); err == nil || !strings.Contains(err.Error(), "unsafe backup file name") {
|
||||
t.Fatalf("copyFileToBackup(%q) error = %v, want unsafe backup file name", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSSHAccessDoesNotExposePassword(t *testing.T) {
|
||||
out := formatSSHAccess(2222)
|
||||
if strings.Contains(out, "/") {
|
||||
t.Fatalf("formatSSHAccess output contains credential separator: %q", out)
|
||||
}
|
||||
if strings.Contains(strings.ToLower(out), "password123") {
|
||||
t.Fatalf("formatSSHAccess output exposed password: %q", out)
|
||||
}
|
||||
if !strings.Contains(out, "2222 -> 22") {
|
||||
t.Fatalf("formatSSHAccess output = %q, want SSH port mapping", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSSHAccessHandlesMissingPort(t *testing.T) {
|
||||
out := formatSSHAccess(0)
|
||||
if !strings.Contains(out, "端口未分配") {
|
||||
t.Fatalf("formatSSHAccess output = %q, want missing port message", out)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package config
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -108,6 +107,9 @@ type Container struct {
|
||||
SnapshotScheduleLastRun string `json:"snapshot_schedule_last_run"`
|
||||
SnapshotScheduleNextRun string `json:"snapshot_schedule_next_run"`
|
||||
SnapshotScheduleCreatedBy string `json:"snapshot_schedule_created_by"`
|
||||
PolicyBlocked bool `json:"policy_blocked"`
|
||||
PolicyBlockedReason string `json:"policy_blocked_reason,omitempty"`
|
||||
PolicyBlockedAt string `json:"policy_blocked_at,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -198,23 +200,24 @@ type Snapshot struct {
|
||||
|
||||
// ClicdConfig is the main configuration structure
|
||||
type ClicdConfig struct {
|
||||
AdminUser string `json:"admin_user"`
|
||||
AdminPassHash string `json:"admin_pass_hash"`
|
||||
JWTSecret string `json:"jwt_secret"`
|
||||
Port int `json:"port"`
|
||||
DataDir string `json:"data_dir"`
|
||||
Containers []Container `json:"containers"`
|
||||
NextContainerID int `json:"next_container_id"`
|
||||
NextVNCPort int `json:"next_vnc_port"`
|
||||
NextSSHPort int `json:"next_ssh_port"`
|
||||
SetupComplete bool `json:"setup_complete"`
|
||||
SubUsers []SubUser `json:"sub_users"`
|
||||
ApiKeys []ApiKeyConfig `json:"api_keys"`
|
||||
AuditLogs []AuditLog `json:"audit_logs"`
|
||||
Tasks []SavedTask `json:"tasks"`
|
||||
LoginLogs []SavedLoginLog `json:"login_logs"`
|
||||
EnabledImages []string `json:"enabled_images"`
|
||||
Snapshots []Snapshot `json:"snapshots"`
|
||||
AdminUser string `json:"admin_user"`
|
||||
AdminPassHash string `json:"admin_pass_hash"`
|
||||
JWTSecret string `json:"jwt_secret"`
|
||||
Port int `json:"port"`
|
||||
DataDir string `json:"data_dir"`
|
||||
Containers []Container `json:"containers"`
|
||||
NextContainerID int `json:"next_container_id"`
|
||||
NextVNCPort int `json:"next_vnc_port"`
|
||||
NextSSHPort int `json:"next_ssh_port"`
|
||||
SetupComplete bool `json:"setup_complete"`
|
||||
SubUsers []SubUser `json:"sub_users"`
|
||||
ApiKeys []ApiKeyConfig `json:"api_keys"`
|
||||
AuditLogs []AuditLog `json:"audit_logs"`
|
||||
Tasks []SavedTask `json:"tasks"`
|
||||
LoginLogs []SavedLoginLog `json:"login_logs"`
|
||||
EnabledImages []string `json:"enabled_images"`
|
||||
Snapshots []Snapshot `json:"snapshots"`
|
||||
SecurityAutoShutdown bool `json:"security_auto_shutdown"`
|
||||
}
|
||||
|
||||
var configPath string
|
||||
@@ -277,69 +280,91 @@ func InitConfig() (*ClicdConfig, error) {
|
||||
dataDir := getDataDir()
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(cfgPath), 0700); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %v", err)
|
||||
return nil, fmt.Errorf("failed to create data directory: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(dataDir, 0700); err != nil {
|
||||
return nil, fmt.Errorf("failed to create data directory: %v", err)
|
||||
}
|
||||
if err := openConfigDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
|
||||
// First run: generate new config
|
||||
adminUser := "admin"
|
||||
adminPass := generateRandomString(16)
|
||||
jwtSecret := generateRandomString(32)
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(adminPass), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to hash password: %v", err)
|
||||
cfg, ok, err := loadConfigFromDB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
AppConfig = cfg
|
||||
normalizeConfigDefaults(dataDir)
|
||||
if migrateLoadedConfig() {
|
||||
if err := SaveConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
AppConfig = &ClicdConfig{
|
||||
AdminUser: adminUser,
|
||||
AdminPassHash: string(hash),
|
||||
JWTSecret: jwtSecret,
|
||||
Port: 8999,
|
||||
DataDir: dataDir,
|
||||
Containers: []Container{},
|
||||
NextContainerID: 1,
|
||||
NextVNCPort: 5900,
|
||||
NextSSHPort: 22000,
|
||||
SetupComplete: false,
|
||||
SubUsers: []SubUser{},
|
||||
AuditLogs: []AuditLog{},
|
||||
Tasks: []SavedTask{},
|
||||
LoginLogs: []SavedLoginLog{},
|
||||
Snapshots: []Snapshot{},
|
||||
}
|
||||
|
||||
if err := SaveConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fmt.Println("\n========================================")
|
||||
fmt.Println(" CLICD - LXC Container Manager")
|
||||
fmt.Println("========================================")
|
||||
fmt.Printf(" Username: %s\n", adminUser)
|
||||
fmt.Printf(" Password: %s\n", adminPass)
|
||||
fmt.Println("========================================")
|
||||
fmt.Println(" Please save these credentials!")
|
||||
fmt.Println(" Web Interface: http://0.0.0.0:8999")
|
||||
fmt.Println("========================================")
|
||||
fmt.Println()
|
||||
|
||||
return AppConfig, nil
|
||||
}
|
||||
|
||||
// Load existing config
|
||||
data, err := os.ReadFile(cfgPath)
|
||||
legacy, ok, err := loadLegacyJSONConfig(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read config: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
AppConfig = legacy
|
||||
normalizeConfigDefaults(dataDir)
|
||||
if migrateLoadedConfig() {
|
||||
// Save below persists normalized legacy data into SQLite.
|
||||
}
|
||||
if err := SaveConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return AppConfig, nil
|
||||
}
|
||||
|
||||
AppConfig = &ClicdConfig{}
|
||||
if err := json.Unmarshal(data, AppConfig); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse config: %v", err)
|
||||
adminUser := "admin"
|
||||
adminPass := generateRandomString(16)
|
||||
jwtSecret := generateRandomString(32)
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(adminPass), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to hash password: %v", err)
|
||||
}
|
||||
|
||||
AppConfig = &ClicdConfig{
|
||||
AdminUser: adminUser,
|
||||
AdminPassHash: string(hash),
|
||||
JWTSecret: jwtSecret,
|
||||
Port: 8999,
|
||||
DataDir: dataDir,
|
||||
Containers: []Container{},
|
||||
NextContainerID: 1,
|
||||
NextVNCPort: 5900,
|
||||
NextSSHPort: 22000,
|
||||
SetupComplete: false,
|
||||
SubUsers: []SubUser{},
|
||||
AuditLogs: []AuditLog{},
|
||||
Tasks: []SavedTask{},
|
||||
LoginLogs: []SavedLoginLog{},
|
||||
Snapshots: []Snapshot{},
|
||||
}
|
||||
|
||||
if err := SaveConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fmt.Println("\n========================================")
|
||||
fmt.Println(" CLICD - LXC Container Manager")
|
||||
fmt.Println("========================================")
|
||||
fmt.Printf(" Username: %s\n", adminUser)
|
||||
fmt.Printf(" Password: %s\n", adminPass)
|
||||
fmt.Println("========================================")
|
||||
fmt.Println(" Please save these credentials!")
|
||||
fmt.Println(" Web Interface: http://0.0.0.0:8999")
|
||||
fmt.Println("========================================")
|
||||
fmt.Println()
|
||||
|
||||
return AppConfig, nil
|
||||
}
|
||||
|
||||
func normalizeConfigDefaults(dataDir string) {
|
||||
if AppConfig.Port == 0 {
|
||||
AppConfig.Port = 8999
|
||||
}
|
||||
@@ -361,6 +386,27 @@ func InitConfig() (*ClicdConfig, error) {
|
||||
if AppConfig.Snapshots == nil {
|
||||
AppConfig.Snapshots = make([]Snapshot, 0)
|
||||
}
|
||||
if AppConfig.SubUsers == nil {
|
||||
AppConfig.SubUsers = make([]SubUser, 0)
|
||||
}
|
||||
if AppConfig.ApiKeys == nil {
|
||||
AppConfig.ApiKeys = make([]ApiKeyConfig, 0)
|
||||
}
|
||||
if AppConfig.AuditLogs == nil {
|
||||
AppConfig.AuditLogs = make([]AuditLog, 0)
|
||||
}
|
||||
if AppConfig.Tasks == nil {
|
||||
AppConfig.Tasks = make([]SavedTask, 0)
|
||||
}
|
||||
if AppConfig.LoginLogs == nil {
|
||||
AppConfig.LoginLogs = make([]SavedLoginLog, 0)
|
||||
}
|
||||
if AppConfig.EnabledImages == nil {
|
||||
AppConfig.EnabledImages = make([]string, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func migrateLoadedConfig() bool {
|
||||
changed := ensureContainerUUIDs()
|
||||
if ensureContainerVirtualization() {
|
||||
changed = true
|
||||
@@ -380,13 +426,7 @@ func InitConfig() (*ClicdConfig, error) {
|
||||
if removeLegacyVNCMappings() {
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
if err := SaveConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return AppConfig, nil
|
||||
return changed
|
||||
}
|
||||
|
||||
func ensureContainerVirtualization() bool {
|
||||
@@ -537,11 +577,7 @@ func removeLegacyVNCMappings() bool {
|
||||
|
||||
// SaveConfig saves configuration to disk
|
||||
func SaveConfig() error {
|
||||
data, err := json.MarshalIndent(AppConfig, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal config: %v", err)
|
||||
}
|
||||
return os.WriteFile(getConfigPath(), data, 0600)
|
||||
return saveConfigToDB()
|
||||
}
|
||||
|
||||
// AddContainer adds a container to the config
|
||||
@@ -717,6 +753,22 @@ func UpdateContainerStatus(id int, status string) {
|
||||
}
|
||||
}
|
||||
|
||||
func SetContainerPolicyBlock(id int, blocked bool, reason string) {
|
||||
c := FindContainer(id)
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.PolicyBlocked = blocked
|
||||
if blocked {
|
||||
c.PolicyBlockedReason = reason
|
||||
c.PolicyBlockedAt = time.Now().Format("2006-01-02 15:04:05")
|
||||
} else {
|
||||
c.PolicyBlockedReason = ""
|
||||
c.PolicyBlockedAt = ""
|
||||
}
|
||||
SaveConfig()
|
||||
}
|
||||
|
||||
// UpdateVNC refreshes all container statuses
|
||||
func UpdateVNC(containers []Container) {
|
||||
AppConfig.Containers = containers
|
||||
|
||||
@@ -0,0 +1,865 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
var (
|
||||
dbMu sync.Mutex
|
||||
db *sql.DB
|
||||
)
|
||||
|
||||
type savedTaskConfig struct {
|
||||
Name string `json:"name"`
|
||||
Virtualization string `json:"virtualization,omitempty"`
|
||||
TemplateID string `json:"template_id"`
|
||||
VCPU float64 `json:"vcpu"`
|
||||
CPUPercent int `json:"cpu_percent"`
|
||||
RAMMB int `json:"ram_mb"`
|
||||
DiskGB int `json:"disk_gb"`
|
||||
NetworkBWMbps int `json:"network_bw_mbps"`
|
||||
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
|
||||
TrafficMode string `json:"traffic_mode"`
|
||||
TrafficInGB int `json:"traffic_in_gb"`
|
||||
TrafficOutGB int `json:"traffic_out_gb"`
|
||||
IOSpeedMBps int `json:"io_speed_mbps"`
|
||||
ExtraPorts []int `json:"extra_ports"`
|
||||
PortMappingCount int `json:"port_mapping_count"`
|
||||
SnapshotLimit int `json:"snapshot_limit"`
|
||||
AssignIPv6 bool `json:"assign_ipv6"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
|
||||
func parseSavedTaskConfig(raw string) savedTaskConfig {
|
||||
if raw == "" {
|
||||
return savedTaskConfig{}
|
||||
}
|
||||
var cfg savedTaskConfig
|
||||
_ = json.Unmarshal([]byte(raw), &cfg)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func encodeSavedTaskConfig(cfg savedTaskConfig) string {
|
||||
data, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func getDBPath() string {
|
||||
cfgPath := getConfigPath()
|
||||
ext := filepath.Ext(cfgPath)
|
||||
if ext == "" {
|
||||
return cfgPath + ".db"
|
||||
}
|
||||
return strings.TrimSuffix(cfgPath, ext) + ".db"
|
||||
}
|
||||
|
||||
func openConfigDB() error {
|
||||
if db != nil {
|
||||
return nil
|
||||
}
|
||||
dbPath := getDBPath()
|
||||
if err := os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil {
|
||||
return fmt.Errorf("failed to create database directory: %v", err)
|
||||
}
|
||||
next, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open sqlite database: %v", err)
|
||||
}
|
||||
next.SetMaxOpenConns(1)
|
||||
next.SetMaxIdleConns(1)
|
||||
|
||||
for _, stmt := range []string{
|
||||
"PRAGMA journal_mode=WAL",
|
||||
"PRAGMA synchronous=NORMAL",
|
||||
"PRAGMA busy_timeout=5000",
|
||||
"PRAGMA foreign_keys=ON",
|
||||
} {
|
||||
if _, err := next.Exec(stmt); err != nil {
|
||||
_ = next.Close()
|
||||
return fmt.Errorf("failed to initialize sqlite pragma: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
db = next
|
||||
return ensureSchema()
|
||||
}
|
||||
|
||||
func ensureSchema() error {
|
||||
stmts := []string{
|
||||
`CREATE TABLE IF NOT EXISTS app_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS containers (
|
||||
id INTEGER PRIMARY KEY,
|
||||
uuid TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
virtualization TEXT,
|
||||
lxc_name TEXT,
|
||||
kvm_name TEXT,
|
||||
disk_image TEXT,
|
||||
mac_address TEXT,
|
||||
template TEXT,
|
||||
vcpu REAL,
|
||||
ram_mb INTEGER,
|
||||
disk_gb INTEGER,
|
||||
network_bw_mbps INTEGER,
|
||||
monthly_traffic_gb INTEGER,
|
||||
traffic_mode TEXT,
|
||||
traffic_in_gb INTEGER,
|
||||
traffic_out_gb INTEGER,
|
||||
traffic_used_rx INTEGER,
|
||||
traffic_used_tx INTEGER,
|
||||
traffic_reset_date TEXT,
|
||||
io_speed_mbps INTEGER,
|
||||
status TEXT,
|
||||
ip TEXT,
|
||||
ipv6 TEXT,
|
||||
ipv6_prefix_len INTEGER,
|
||||
ipv6_interface TEXT,
|
||||
vnc_port INTEGER,
|
||||
ssh_port INTEGER,
|
||||
ssh_password TEXT,
|
||||
ssh_host_key TEXT,
|
||||
port_mapping_limit INTEGER,
|
||||
snapshot_limit INTEGER,
|
||||
created_at TEXT,
|
||||
expires_at TEXT,
|
||||
snapshot_schedule_enabled INTEGER,
|
||||
snapshot_schedule_interval_hours INTEGER,
|
||||
snapshot_schedule_time TEXT,
|
||||
snapshot_schedule_last_run TEXT,
|
||||
snapshot_schedule_next_run TEXT,
|
||||
snapshot_schedule_created_by TEXT,
|
||||
policy_blocked INTEGER,
|
||||
policy_blocked_reason TEXT,
|
||||
policy_blocked_at TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS port_mappings (
|
||||
container_id INTEGER NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
container_port INTEGER NOT NULL,
|
||||
host_port INTEGER NOT NULL,
|
||||
protocol TEXT,
|
||||
description TEXT,
|
||||
PRIMARY KEY (container_id, position)
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS sub_users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password TEXT,
|
||||
pass_hash TEXT,
|
||||
access_code TEXT,
|
||||
created_at TEXT,
|
||||
token_version INTEGER
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS sub_user_container_names (
|
||||
sub_user_id TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
container_name TEXT NOT NULL,
|
||||
PRIMARY KEY (sub_user_id, position)
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS sub_user_container_uuids (
|
||||
sub_user_id TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
container_uuid TEXT NOT NULL,
|
||||
PRIMARY KEY (sub_user_id, position)
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
key_hash TEXT,
|
||||
prefix TEXT,
|
||||
ip_whitelist TEXT,
|
||||
created_at TEXT,
|
||||
last_used TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
time TEXT,
|
||||
action TEXT,
|
||||
target TEXT,
|
||||
detail TEXT,
|
||||
user TEXT,
|
||||
ip TEXT,
|
||||
user_agent TEXT,
|
||||
success_set INTEGER,
|
||||
success INTEGER,
|
||||
error TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS tasks (
|
||||
id TEXT PRIMARY KEY,
|
||||
type TEXT,
|
||||
container_id INTEGER,
|
||||
container_name TEXT,
|
||||
status TEXT,
|
||||
error TEXT,
|
||||
created_at TEXT,
|
||||
template_id TEXT,
|
||||
user TEXT,
|
||||
cfg_name TEXT,
|
||||
cfg_virtualization TEXT,
|
||||
cfg_template_id TEXT,
|
||||
cfg_vcpu REAL,
|
||||
cfg_cpu_percent INTEGER,
|
||||
cfg_ram_mb INTEGER,
|
||||
cfg_disk_gb INTEGER,
|
||||
cfg_network_bw_mbps INTEGER,
|
||||
cfg_monthly_traffic_gb INTEGER,
|
||||
cfg_traffic_mode TEXT,
|
||||
cfg_traffic_in_gb INTEGER,
|
||||
cfg_traffic_out_gb INTEGER,
|
||||
cfg_io_speed_mbps INTEGER,
|
||||
cfg_port_mapping_count INTEGER,
|
||||
cfg_snapshot_limit INTEGER,
|
||||
cfg_assign_ipv6 INTEGER,
|
||||
cfg_expires_at TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS task_extra_ports (
|
||||
task_id TEXT NOT NULL,
|
||||
position INTEGER NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
PRIMARY KEY (task_id, position)
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS login_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
time TEXT,
|
||||
username TEXT,
|
||||
ip TEXT,
|
||||
user_agent TEXT,
|
||||
success INTEGER
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS enabled_images (
|
||||
position INTEGER PRIMARY KEY,
|
||||
image_id TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS snapshots (
|
||||
id TEXT PRIMARY KEY,
|
||||
container_id INTEGER,
|
||||
container_name TEXT,
|
||||
lxc_name TEXT,
|
||||
created_at TEXT,
|
||||
created_by TEXT,
|
||||
scheduled INTEGER,
|
||||
path TEXT,
|
||||
size_bytes INTEGER
|
||||
)`,
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
return fmt.Errorf("failed to create sqlite schema: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadConfigFromDB() (*ClicdConfig, bool, error) {
|
||||
meta := map[string]string{}
|
||||
rows, err := db.Query("SELECT key, value FROM app_meta")
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
meta[k] = v
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if meta["admin_user"] == "" {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
cfg := &ClicdConfig{
|
||||
AdminUser: meta["admin_user"],
|
||||
AdminPassHash: meta["admin_pass_hash"],
|
||||
JWTSecret: meta["jwt_secret"],
|
||||
Port: atoi(meta["port"]),
|
||||
DataDir: meta["data_dir"],
|
||||
NextContainerID: atoi(meta["next_container_id"]),
|
||||
NextVNCPort: atoi(meta["next_vnc_port"]),
|
||||
NextSSHPort: atoi(meta["next_ssh_port"]),
|
||||
SetupComplete: atob(meta["setup_complete"]),
|
||||
SecurityAutoShutdown: atob(meta["security_auto_shutdown"]),
|
||||
}
|
||||
|
||||
if cfg.Containers, err = loadContainers(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.SubUsers, err = loadSubUsers(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.ApiKeys, err = loadAPIKeys(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.AuditLogs, err = loadAuditLogs(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.Tasks, err = loadTasks(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.LoginLogs, err = loadLoginLogs(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.EnabledImages, err = loadEnabledImages(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if cfg.Snapshots, err = loadSnapshots(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return cfg, true, nil
|
||||
}
|
||||
|
||||
func saveConfigToDB() error {
|
||||
if db == nil {
|
||||
return fmt.Errorf("sqlite database is not initialized")
|
||||
}
|
||||
dbMu.Lock()
|
||||
defer dbMu.Unlock()
|
||||
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
for _, table := range []string{
|
||||
"port_mappings",
|
||||
"sub_user_container_names",
|
||||
"sub_user_container_uuids",
|
||||
"containers",
|
||||
"sub_users",
|
||||
"api_keys",
|
||||
"audit_logs",
|
||||
"task_extra_ports",
|
||||
"tasks",
|
||||
"login_logs",
|
||||
"enabled_images",
|
||||
"snapshots",
|
||||
"app_meta",
|
||||
} {
|
||||
if _, err := tx.Exec("DELETE FROM " + table); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := saveMeta(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveContainers(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveSubUsers(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveAPIKeys(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveAuditLogs(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveTasksDB(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveLoginLogs(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveEnabledImages(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := saveSnapshots(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func saveMeta(tx *sql.Tx) error {
|
||||
values := map[string]string{
|
||||
"admin_user": AppConfig.AdminUser,
|
||||
"admin_pass_hash": AppConfig.AdminPassHash,
|
||||
"jwt_secret": AppConfig.JWTSecret,
|
||||
"port": strconv.Itoa(AppConfig.Port),
|
||||
"data_dir": AppConfig.DataDir,
|
||||
"next_container_id": strconv.Itoa(AppConfig.NextContainerID),
|
||||
"next_vnc_port": strconv.Itoa(AppConfig.NextVNCPort),
|
||||
"next_ssh_port": strconv.Itoa(AppConfig.NextSSHPort),
|
||||
"setup_complete": btoa(AppConfig.SetupComplete),
|
||||
"security_auto_shutdown": btoa(AppConfig.SecurityAutoShutdown),
|
||||
"schema_version": "1",
|
||||
"updated_at": time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
for k, v := range values {
|
||||
if _, err := tx.Exec("INSERT INTO app_meta(key, value) VALUES (?, ?)", k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveContainers(tx *sql.Tx) error {
|
||||
for _, c := range AppConfig.Containers {
|
||||
if _, err := tx.Exec(`INSERT INTO containers (
|
||||
id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, mac_address, template,
|
||||
vcpu, ram_mb, disk_gb, network_bw_mbps, monthly_traffic_gb, traffic_mode, traffic_in_gb,
|
||||
traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date, io_speed_mbps,
|
||||
status, ip, ipv6, ipv6_prefix_len, ipv6_interface, vnc_port, ssh_port, ssh_password,
|
||||
ssh_host_key, port_mapping_limit, snapshot_limit, created_at, expires_at,
|
||||
snapshot_schedule_enabled, snapshot_schedule_interval_hours, snapshot_schedule_time,
|
||||
snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by,
|
||||
policy_blocked, policy_blocked_reason, policy_blocked_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
c.ID, c.UUID, c.Name, c.Virtualization, c.LXCName, c.KVMName, c.DiskImage, c.MACAddress, c.Template,
|
||||
c.VCPU, c.RAMMB, c.DiskGB, c.NetworkBWMbps, c.MonthlyTrafficGB, c.TrafficMode, c.TrafficInGB,
|
||||
c.TrafficOutGB, c.TrafficUsedRX, c.TrafficUsedTX, c.TrafficResetDate, c.IOSpeedMBps,
|
||||
c.Status, c.IP, c.IPv6, c.IPv6PrefixLen, c.IPv6Interface, c.VNCPort, c.SSHPort, c.SSHPassword,
|
||||
c.SSHHostKey, c.PortMappingLimit, c.SnapshotLimit, c.CreatedAt, c.ExpiresAt,
|
||||
boolInt(c.SnapshotScheduleEnabled), c.SnapshotScheduleIntervalHours, c.SnapshotScheduleTime,
|
||||
c.SnapshotScheduleLastRun, c.SnapshotScheduleNextRun, c.SnapshotScheduleCreatedBy,
|
||||
boolInt(c.PolicyBlocked), c.PolicyBlockedReason, c.PolicyBlockedAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, pm := range c.PortMappings {
|
||||
if _, err := tx.Exec(`INSERT INTO port_mappings(container_id, position, container_port, host_port, protocol, description)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, c.ID, i, pm.ContainerPort, pm.HostPort, pm.Protocol, pm.Description); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveSubUsers(tx *sql.Tx) error {
|
||||
for _, su := range AppConfig.SubUsers {
|
||||
if _, err := tx.Exec(`INSERT INTO sub_users(id, username, password, pass_hash, access_code, created_at, token_version)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`, su.ID, su.Username, su.Password, su.PassHash, su.AccessCode, su.CreatedAt, su.TokenVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, name := range su.ContainerNames {
|
||||
if _, err := tx.Exec(`INSERT INTO sub_user_container_names(sub_user_id, position, container_name) VALUES (?, ?, ?)`, su.ID, i, name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i, uuid := range su.ContainerUUIDs {
|
||||
if _, err := tx.Exec(`INSERT INTO sub_user_container_uuids(sub_user_id, position, container_uuid) VALUES (?, ?, ?)`, su.ID, i, uuid); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveAPIKeys(tx *sql.Tx) error {
|
||||
for _, k := range AppConfig.ApiKeys {
|
||||
if _, err := tx.Exec(`INSERT INTO api_keys(id, name, key_hash, prefix, ip_whitelist, created_at, last_used)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`, k.ID, k.Name, k.KeyHash, k.Prefix, k.IPWhitelist, k.CreatedAt, k.LastUsed); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveAuditLogs(tx *sql.Tx) error {
|
||||
for _, log := range AppConfig.AuditLogs {
|
||||
successSet := 0
|
||||
success := 0
|
||||
if log.Success != nil {
|
||||
successSet = 1
|
||||
if *log.Success {
|
||||
success = 1
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(`INSERT INTO audit_logs(time, action, target, detail, user, ip, user_agent, success_set, success, error)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, log.Time, log.Action, log.Target, log.Detail, log.User, log.IP, log.UserAgent, successSet, success, log.Error); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveTasksDB(tx *sql.Tx) error {
|
||||
for _, task := range AppConfig.Tasks {
|
||||
cfg := parseSavedTaskConfig(task.Config)
|
||||
if _, err := tx.Exec(`INSERT INTO tasks(
|
||||
id, type, container_id, container_name, status, error, created_at, template_id, user,
|
||||
cfg_name, cfg_virtualization, cfg_template_id, cfg_vcpu, cfg_cpu_percent, cfg_ram_mb, cfg_disk_gb,
|
||||
cfg_network_bw_mbps, cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
|
||||
cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_port_mapping_count, cfg_snapshot_limit,
|
||||
cfg_assign_ipv6, cfg_expires_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
task.ID, task.Type, task.ContainerID, task.ContainerName, task.Status, task.Error, task.CreatedAt, task.TemplateID, task.User,
|
||||
cfg.Name, cfg.Virtualization, cfg.TemplateID, cfg.VCPU, cfg.CPUPercent, cfg.RAMMB, cfg.DiskGB,
|
||||
cfg.NetworkBWMbps, cfg.MonthlyTrafficGB, cfg.TrafficMode, cfg.TrafficInGB,
|
||||
cfg.TrafficOutGB, cfg.IOSpeedMBps, cfg.PortMappingCount, cfg.SnapshotLimit,
|
||||
boolInt(cfg.AssignIPv6), cfg.ExpiresAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, port := range cfg.ExtraPorts {
|
||||
if _, err := tx.Exec(`INSERT INTO task_extra_ports(task_id, position, port) VALUES (?, ?, ?)`, task.ID, i, port); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveLoginLogs(tx *sql.Tx) error {
|
||||
for _, log := range AppConfig.LoginLogs {
|
||||
if _, err := tx.Exec(`INSERT INTO login_logs(time, username, ip, user_agent, success) VALUES (?, ?, ?, ?, ?)`,
|
||||
log.Time, log.Username, log.IP, log.UserAgent, boolInt(log.Success)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveEnabledImages(tx *sql.Tx) error {
|
||||
for i, id := range AppConfig.EnabledImages {
|
||||
if _, err := tx.Exec(`INSERT INTO enabled_images(position, image_id) VALUES (?, ?)`, i, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveSnapshots(tx *sql.Tx) error {
|
||||
for _, snapshot := range AppConfig.Snapshots {
|
||||
if _, err := tx.Exec(`INSERT INTO snapshots(id, container_id, container_name, lxc_name, created_at, created_by, scheduled, path, size_bytes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, snapshot.ID, snapshot.ContainerID, snapshot.ContainerName, snapshot.LXCName, snapshot.CreatedAt, snapshot.CreatedBy, boolInt(snapshot.Scheduled), snapshot.Path, snapshot.SizeBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadContainers() ([]Container, error) {
|
||||
rows, err := db.Query(`SELECT
|
||||
id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, mac_address, template,
|
||||
vcpu, ram_mb, disk_gb, network_bw_mbps, monthly_traffic_gb, traffic_mode, traffic_in_gb,
|
||||
traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date, io_speed_mbps,
|
||||
status, ip, ipv6, ipv6_prefix_len, ipv6_interface, vnc_port, ssh_port, ssh_password,
|
||||
ssh_host_key, port_mapping_limit, snapshot_limit, created_at, expires_at,
|
||||
snapshot_schedule_enabled, snapshot_schedule_interval_hours, snapshot_schedule_time,
|
||||
snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by,
|
||||
policy_blocked, policy_blocked_reason, policy_blocked_at
|
||||
FROM containers ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := []Container{}
|
||||
for rows.Next() {
|
||||
var c Container
|
||||
var scheduleEnabled, policyBlocked int
|
||||
if err := rows.Scan(
|
||||
&c.ID, &c.UUID, &c.Name, &c.Virtualization, &c.LXCName, &c.KVMName, &c.DiskImage, &c.MACAddress, &c.Template,
|
||||
&c.VCPU, &c.RAMMB, &c.DiskGB, &c.NetworkBWMbps, &c.MonthlyTrafficGB, &c.TrafficMode, &c.TrafficInGB,
|
||||
&c.TrafficOutGB, &c.TrafficUsedRX, &c.TrafficUsedTX, &c.TrafficResetDate, &c.IOSpeedMBps,
|
||||
&c.Status, &c.IP, &c.IPv6, &c.IPv6PrefixLen, &c.IPv6Interface, &c.VNCPort, &c.SSHPort, &c.SSHPassword,
|
||||
&c.SSHHostKey, &c.PortMappingLimit, &c.SnapshotLimit, &c.CreatedAt, &c.ExpiresAt,
|
||||
&scheduleEnabled, &c.SnapshotScheduleIntervalHours, &c.SnapshotScheduleTime,
|
||||
&c.SnapshotScheduleLastRun, &c.SnapshotScheduleNextRun, &c.SnapshotScheduleCreatedBy,
|
||||
&policyBlocked, &c.PolicyBlockedReason, &c.PolicyBlockedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.SnapshotScheduleEnabled = scheduleEnabled != 0
|
||||
c.PolicyBlocked = policyBlocked != 0
|
||||
result = append(result, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range result {
|
||||
result[i].PortMappings, err = loadPortMappings(result[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadPortMappings(containerID int) ([]PortMapping, error) {
|
||||
rows, err := db.Query(`SELECT container_port, host_port, protocol, description FROM port_mappings WHERE container_id = ? ORDER BY position`, containerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []PortMapping{}
|
||||
for rows.Next() {
|
||||
var pm PortMapping
|
||||
if err := rows.Scan(&pm.ContainerPort, &pm.HostPort, &pm.Protocol, &pm.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, pm)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadSubUsers() ([]SubUser, error) {
|
||||
rows, err := db.Query(`SELECT id, username, password, pass_hash, access_code, created_at, token_version FROM sub_users ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []SubUser{}
|
||||
for rows.Next() {
|
||||
var su SubUser
|
||||
if err := rows.Scan(&su.ID, &su.Username, &su.Password, &su.PassHash, &su.AccessCode, &su.CreatedAt, &su.TokenVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, su)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range result {
|
||||
result[i].ContainerNames, err = loadStringList("sub_user_container_names", "container_name", "sub_user_id", result[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[i].ContainerUUIDs, err = loadStringList("sub_user_container_uuids", "container_uuid", "sub_user_id", result[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadStringList(table, valueColumn, keyColumn, key string) ([]string, error) {
|
||||
rows, err := db.Query(fmt.Sprintf(`SELECT %s FROM %s WHERE %s = ? ORDER BY position`, valueColumn, table, keyColumn), key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
values := []string{}
|
||||
for rows.Next() {
|
||||
var value string
|
||||
if err := rows.Scan(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func loadAPIKeys() ([]ApiKeyConfig, error) {
|
||||
rows, err := db.Query(`SELECT id, name, key_hash, prefix, ip_whitelist, created_at, last_used FROM api_keys ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []ApiKeyConfig{}
|
||||
for rows.Next() {
|
||||
var k ApiKeyConfig
|
||||
if err := rows.Scan(&k.ID, &k.Name, &k.KeyHash, &k.Prefix, &k.IPWhitelist, &k.CreatedAt, &k.LastUsed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, k)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadAuditLogs() ([]AuditLog, error) {
|
||||
rows, err := db.Query(`SELECT time, action, target, detail, user, ip, user_agent, success_set, success, error FROM audit_logs ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []AuditLog{}
|
||||
for rows.Next() {
|
||||
var log AuditLog
|
||||
var successSet, success int
|
||||
if err := rows.Scan(&log.Time, &log.Action, &log.Target, &log.Detail, &log.User, &log.IP, &log.UserAgent, &successSet, &success, &log.Error); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if successSet != 0 {
|
||||
value := success != 0
|
||||
log.Success = &value
|
||||
}
|
||||
result = append(result, log)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadTasks() ([]SavedTask, error) {
|
||||
rows, err := db.Query(`SELECT
|
||||
id, type, container_id, container_name, status, error, created_at, template_id, user,
|
||||
cfg_name, cfg_virtualization, cfg_template_id, cfg_vcpu, cfg_cpu_percent, cfg_ram_mb, cfg_disk_gb,
|
||||
cfg_network_bw_mbps, cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
|
||||
cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_port_mapping_count, cfg_snapshot_limit,
|
||||
cfg_assign_ipv6, cfg_expires_at
|
||||
FROM tasks ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []SavedTask{}
|
||||
configs := []savedTaskConfig{}
|
||||
for rows.Next() {
|
||||
var t SavedTask
|
||||
var cfg savedTaskConfig
|
||||
var assignIPv6 int
|
||||
if err := rows.Scan(
|
||||
&t.ID, &t.Type, &t.ContainerID, &t.ContainerName, &t.Status, &t.Error, &t.CreatedAt, &t.TemplateID, &t.User,
|
||||
&cfg.Name, &cfg.Virtualization, &cfg.TemplateID, &cfg.VCPU, &cfg.CPUPercent, &cfg.RAMMB, &cfg.DiskGB,
|
||||
&cfg.NetworkBWMbps, &cfg.MonthlyTrafficGB, &cfg.TrafficMode, &cfg.TrafficInGB,
|
||||
&cfg.TrafficOutGB, &cfg.IOSpeedMBps, &cfg.PortMappingCount, &cfg.SnapshotLimit,
|
||||
&assignIPv6, &cfg.ExpiresAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.AssignIPv6 = assignIPv6 != 0
|
||||
result = append(result, t)
|
||||
configs = append(configs, cfg)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range result {
|
||||
configs[i].ExtraPorts, err = loadTaskExtraPorts(result[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[i].Config = encodeSavedTaskConfig(configs[i])
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadTaskExtraPorts(taskID string) ([]int, error) {
|
||||
rows, err := db.Query(`SELECT port FROM task_extra_ports WHERE task_id = ? ORDER BY position`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []int{}
|
||||
for rows.Next() {
|
||||
var port int
|
||||
if err := rows.Scan(&port); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, port)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadLoginLogs() ([]SavedLoginLog, error) {
|
||||
rows, err := db.Query(`SELECT time, username, ip, user_agent, success FROM login_logs ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []SavedLoginLog{}
|
||||
for rows.Next() {
|
||||
var log SavedLoginLog
|
||||
var success int
|
||||
if err := rows.Scan(&log.Time, &log.Username, &log.IP, &log.UserAgent, &success); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Success = success != 0
|
||||
result = append(result, log)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadEnabledImages() ([]string, error) {
|
||||
rows, err := db.Query(`SELECT image_id FROM enabled_images ORDER BY position`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, id)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadSnapshots() ([]Snapshot, error) {
|
||||
rows, err := db.Query(`SELECT id, container_id, container_name, lxc_name, created_at, created_by, scheduled, path, size_bytes FROM snapshots ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []Snapshot{}
|
||||
for rows.Next() {
|
||||
var snapshot Snapshot
|
||||
var scheduled int
|
||||
if err := rows.Scan(&snapshot.ID, &snapshot.ContainerID, &snapshot.ContainerName, &snapshot.LXCName, &snapshot.CreatedAt, &snapshot.CreatedBy, &scheduled, &snapshot.Path, &snapshot.SizeBytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
snapshot.Scheduled = scheduled != 0
|
||||
result = append(result, snapshot)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func loadLegacyJSONConfig(path string) (*ClicdConfig, bool, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if os.IsNotExist(err) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("failed to read legacy config: %v", err)
|
||||
}
|
||||
cfg := &ClicdConfig{}
|
||||
if err := json.Unmarshal(data, cfg); err != nil {
|
||||
return nil, false, fmt.Errorf("failed to parse legacy config: %v", err)
|
||||
}
|
||||
return cfg, true, nil
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func btoa(value bool) string {
|
||||
if value {
|
||||
return "1"
|
||||
}
|
||||
return "0"
|
||||
}
|
||||
|
||||
func atob(value string) bool {
|
||||
return value == "1" || strings.EqualFold(value, "true")
|
||||
}
|
||||
|
||||
func atoi(value string) int {
|
||||
n, _ := strconv.Atoi(value)
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSQLiteConfigMigratesLegacyJSONAndPersists(t *testing.T) {
|
||||
resetConfigStoreForTest(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
t.Cleanup(func() {
|
||||
resetConfigStoreForTest(t)
|
||||
})
|
||||
legacyPath := filepath.Join(dir, "config.json")
|
||||
SetConfigPath(legacyPath)
|
||||
|
||||
legacy := ClicdConfig{
|
||||
AdminUser: "admin",
|
||||
AdminPassHash: "hash",
|
||||
JWTSecret: "secret",
|
||||
Port: 8999,
|
||||
DataDir: dir,
|
||||
NextContainerID: 2,
|
||||
NextVNCPort: 5900,
|
||||
NextSSHPort: 22000,
|
||||
Containers: []Container{{
|
||||
ID: 1,
|
||||
UUID: "uuid-1",
|
||||
Name: "ct1",
|
||||
Virtualization: "lxc",
|
||||
Template: "debian-12",
|
||||
Status: "running",
|
||||
PortMappingLimit: 2,
|
||||
SnapshotLimit: 3,
|
||||
PortMappings: []PortMapping{{
|
||||
ContainerPort: 22,
|
||||
HostPort: 22001,
|
||||
Protocol: "tcp",
|
||||
Description: "SSH",
|
||||
}},
|
||||
}},
|
||||
AuditLogs: []AuditLog{{
|
||||
Time: "2026-06-07 17:29:00",
|
||||
Action: "security_horizontal_scan",
|
||||
Target: "ct1",
|
||||
Detail: "[medium] 可疑横向探测",
|
||||
User: "system",
|
||||
}},
|
||||
LoginLogs: []SavedLoginLog{{
|
||||
Time: "2026-06-07 17:29:01 CST",
|
||||
Username: "admin",
|
||||
IP: "127.0.0.1",
|
||||
UserAgent: "test",
|
||||
Success: true,
|
||||
}},
|
||||
Tasks: []SavedTask{{
|
||||
ID: "task-1",
|
||||
Type: "create",
|
||||
ContainerName: "ct2",
|
||||
Status: "pending",
|
||||
CreatedAt: "2026-06-07 17:29:02",
|
||||
Config: `{"name":"ct2","template_id":"debian-12","vcpu":1,"ram_mb":512,"disk_gb":5,"extra_ports":[80,443],"assign_ipv6":true}`,
|
||||
}},
|
||||
EnabledImages: []string{"debian-12"},
|
||||
Snapshots: []Snapshot{{
|
||||
ID: "snap-1",
|
||||
ContainerID: 1,
|
||||
ContainerName: "ct1",
|
||||
LXCName: "ct-1",
|
||||
CreatedAt: "2026-06-07 17:30:00",
|
||||
Path: filepath.Join(dir, "snap-1"),
|
||||
}},
|
||||
}
|
||||
data, err := json.Marshal(legacy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(legacyPath, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := InitConfig()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Containers) != 1 || len(cfg.Containers[0].PortMappings) != 1 {
|
||||
t.Fatalf("legacy config was not migrated: %+v", cfg.Containers)
|
||||
}
|
||||
if len(cfg.Tasks) != 1 || !strings.Contains(cfg.Tasks[0].Config, `"extra_ports":[80,443]`) {
|
||||
t.Fatalf("task config was not restored from sqlite columns: %+v", cfg.Tasks)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "config.db")); err != nil {
|
||||
t.Fatalf("sqlite database was not created: %v", err)
|
||||
}
|
||||
|
||||
cfg.Containers[0].Status = "stopped"
|
||||
if err := SaveConfig(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resetConfigStoreForTest(t)
|
||||
SetConfigPath(legacyPath)
|
||||
cfg, err = InitConfig()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cfg.Containers[0].Status; got != "stopped" {
|
||||
t.Fatalf("expected sqlite value to win after migration, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func resetConfigStoreForTest(t *testing.T) {
|
||||
t.Helper()
|
||||
if db != nil {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db = nil
|
||||
}
|
||||
AppConfig = nil
|
||||
configPath = ""
|
||||
}
|
||||
+233
-28
@@ -2,7 +2,9 @@ package kvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
@@ -114,7 +116,22 @@ func ImageDownloadedInfo(id string) (bool, int64) {
|
||||
return true, info.Size()
|
||||
}
|
||||
|
||||
// DownloadProgress reports KVM image download/conversion progress.
|
||||
type DownloadProgress struct {
|
||||
Stage string
|
||||
DownloadedBytes int64
|
||||
TotalBytes int64
|
||||
Percent int
|
||||
}
|
||||
|
||||
// DownloadProgressFunc receives download progress updates.
|
||||
type DownloadProgressFunc func(DownloadProgress)
|
||||
|
||||
func DownloadImage(image Image) error {
|
||||
return DownloadImageWithProgress(context.Background(), image, nil)
|
||||
}
|
||||
|
||||
func DownloadImageWithProgress(ctx context.Context, image Image, progress DownloadProgressFunc) error {
|
||||
if err := os.MkdirAll(CacheDir(), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -134,11 +151,15 @@ func DownloadImage(image Image) error {
|
||||
tmp := target + ".tmp"
|
||||
_ = os.Remove(tmp)
|
||||
if image.Distro == "windows" {
|
||||
if err := downloadFileWithValidator(image.URL, tmp, validateWindowsISOResponse(target)); err != nil {
|
||||
if err := downloadFileWithValidator(ctx, image.URL, tmp, validateWindowsISOResponse(target), progress); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
} else if err := downloadFile(image.URL, tmp); err != nil {
|
||||
} else if err := downloadFile(ctx, image.URL, tmp, progress); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
@@ -153,8 +174,12 @@ func DownloadImage(image Image) error {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := normalizeQCOW2(tmp, target); err != nil {
|
||||
if progress != nil {
|
||||
progress(DownloadProgress{Stage: "converting", Percent: 100})
|
||||
}
|
||||
if err := normalizeQCOW2(ctx, tmp, target); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
_ = os.Remove(target)
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -168,11 +193,11 @@ func DeleteImage(id string) error {
|
||||
|
||||
type downloadResponseValidator func(*http.Response) error
|
||||
|
||||
func downloadFile(url, target string) error {
|
||||
return downloadFileWithValidator(url, target, nil)
|
||||
func downloadFile(ctx context.Context, url, target string, progress DownloadProgressFunc) error {
|
||||
return downloadFileWithValidator(ctx, url, target, nil, progress)
|
||||
}
|
||||
|
||||
func downloadFileWithValidator(url, target string, validate downloadResponseValidator) error {
|
||||
func downloadFileWithValidator(ctx context.Context, url, target string, validate downloadResponseValidator, progress DownloadProgressFunc) error {
|
||||
client := http.Client{
|
||||
Timeout: 30 * time.Minute,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
@@ -186,7 +211,7 @@ func downloadFileWithValidator(url, target string, validate downloadResponseVali
|
||||
return nil
|
||||
},
|
||||
}
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -210,7 +235,48 @@ func downloadFileWithValidator(url, target string, validate downloadResponseVali
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
if _, err := io.Copy(out, resp.Body); err != nil {
|
||||
total := resp.ContentLength
|
||||
if total < 0 {
|
||||
total = 0
|
||||
}
|
||||
if progress != nil {
|
||||
progress(DownloadProgress{Stage: "downloading", TotalBytes: total})
|
||||
}
|
||||
buf := make([]byte, 256*1024)
|
||||
var downloaded int64
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
n, readErr := resp.Body.Read(buf)
|
||||
if n > 0 {
|
||||
written, writeErr := out.Write(buf[:n])
|
||||
downloaded += int64(written)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
if written != n {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
if progress != nil {
|
||||
percent := 0
|
||||
if total > 0 {
|
||||
percent = int(downloaded * 100 / total)
|
||||
if percent > 99 {
|
||||
percent = 99
|
||||
}
|
||||
}
|
||||
progress(DownloadProgress{Stage: "downloading", DownloadedBytes: downloaded, TotalBytes: total, Percent: percent})
|
||||
}
|
||||
}
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return out.Sync()
|
||||
@@ -266,11 +332,11 @@ func validateWindowsISO(path, target string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeQCOW2(src, target string) error {
|
||||
func normalizeQCOW2(ctx context.Context, src, target string) error {
|
||||
if err := requireCommand("qemu-img"); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.Command("qemu-img", "convert", "-O", "qcow2", src, target)
|
||||
cmd := exec.CommandContext(ctx, "qemu-img", "convert", "-O", "qcow2", src, target)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
return fmt.Errorf("qemu-img convert failed: %v, output: %s", err, string(output))
|
||||
}
|
||||
@@ -371,13 +437,21 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
}
|
||||
xml = windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, ImagePath(image.ID), unattendPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps)
|
||||
} else {
|
||||
if image.Desktop != "" {
|
||||
if cfg.RAMMB < 2048 {
|
||||
cfg.RAMMB = 2048
|
||||
}
|
||||
if cfg.DiskGB < 20 {
|
||||
cfg.DiskGB = 20
|
||||
}
|
||||
}
|
||||
if err := createOverlayDisk(ImagePath(image.ID), diskPath, cfg.DiskGB); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := createSeedISO(seedPath, vmName, cfg.Name, sshPassword, mac, ipv6); err != nil {
|
||||
if err := createSeedISO(seedPath, vmName, cfg.Name, sshPassword, mac, ipv6, *image); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
xml = domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, seedPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps)
|
||||
xml = domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, seedPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps, image.Desktop != "")
|
||||
}
|
||||
xmlPath := filepath.Join(m.instanceDir(vmName), "domain.xml")
|
||||
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
|
||||
@@ -639,7 +713,7 @@ func (m *Manager) ReinstallContainer(id int, templateID string) error {
|
||||
return m.StartContainer(id)
|
||||
}
|
||||
|
||||
func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
func (m *Manager) ResetSSHPassword(id int, password string) (string, error) {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
return "", fmt.Errorf("container not found: %d", id)
|
||||
@@ -650,7 +724,9 @@ func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
if c.Status != "running" {
|
||||
return "", fmt.Errorf("KVM VM must be running before password reset")
|
||||
}
|
||||
password := generateRandomString(16)
|
||||
if strings.TrimSpace(password) == "" {
|
||||
password = generateRandomString(16)
|
||||
}
|
||||
if err := runKVMGuestAgentSSHSetup(c.VirshName(), password); err == nil {
|
||||
c.SSHPassword = password
|
||||
c.SSHHostKey = ""
|
||||
@@ -663,10 +739,14 @@ func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
if err := m.EnsureSSH(id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
chpasswdInput, err := chpasswdStdin("root", password)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
client, err := ssh.Dial("tcp", net.JoinHostPort(c.IP, "22"), &ssh.ClientConfig{
|
||||
User: "root",
|
||||
Auth: []ssh.AuthMethod{ssh.Password(c.SSHPassword)},
|
||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||
HostKeyCallback: kvmHostKeyCallback(c),
|
||||
Timeout: 8 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -678,8 +758,8 @@ func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
defer session.Close()
|
||||
cmd := fmt.Sprintf("printf 'root:%s\\n' | chpasswd", shellQuote(password))
|
||||
if output, err := session.CombinedOutput(cmd); err != nil {
|
||||
session.Stdin = bytes.NewReader(chpasswdInput)
|
||||
if output, err := session.CombinedOutput("chpasswd"); err != nil {
|
||||
return "", fmt.Errorf("failed to reset password: %v, output: %s", err, string(output))
|
||||
}
|
||||
c.SSHPassword = password
|
||||
@@ -706,7 +786,7 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
|
||||
xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
|
||||
} else {
|
||||
seedPath := filepath.Join(m.instanceDir(c.VirshName()), "seed.iso")
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps, isKVMDesktopTemplate(c.Template))
|
||||
}
|
||||
xmlPath := filepath.Join(m.instanceDir(c.VirshName()), "domain.xml")
|
||||
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
|
||||
@@ -731,7 +811,7 @@ func (m *Manager) ensureDomainDefinition(c *config.Container) error {
|
||||
xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
|
||||
} else {
|
||||
seedPath := filepath.Join(m.instanceDir(c.VirshName()), "seed.iso")
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
|
||||
xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps, isKVMDesktopTemplate(c.Template))
|
||||
}
|
||||
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
|
||||
return err
|
||||
@@ -1399,7 +1479,7 @@ func ensureDefaultNetwork() error {
|
||||
}
|
||||
// Start and autostart the default network
|
||||
if out, err := exec.Command("virsh", "net-info", "default").Output(); err == nil {
|
||||
if !strings.Contains(strings.ToLower(string(out)), "active:") || !strings.Contains(strings.ToLower(string(out)), "yes") {
|
||||
if !libvirtNetworkActive(string(out)) {
|
||||
if startOut, startErr := exec.Command("virsh", "net-start", "default").CombinedOutput(); startErr != nil {
|
||||
return fmt.Errorf("failed to start libvirt default network: %v, output: %s", startErr, string(startOut))
|
||||
}
|
||||
@@ -1411,6 +1491,19 @@ func ensureDefaultNetwork() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func libvirtNetworkActive(info string) bool {
|
||||
for _, line := range strings.Split(info, "\n") {
|
||||
key, value, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(key), "Active") {
|
||||
return strings.EqualFold(strings.TrimSpace(value), "yes")
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func createOverlayDisk(base, target string, diskGB int) error {
|
||||
if diskGB < 1 {
|
||||
diskGB = 5
|
||||
@@ -1438,7 +1531,7 @@ func ensureVirtioWinISO() error {
|
||||
virtioURL := "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso"
|
||||
tmp := virtioPath + ".tmp"
|
||||
_ = os.Remove(tmp)
|
||||
if err := downloadFile(virtioURL, tmp); err != nil {
|
||||
if err := downloadFile(context.Background(), virtioURL, tmp, nil); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return fmt.Errorf("failed to download virtio-win.iso: %v", err)
|
||||
}
|
||||
@@ -1668,8 +1761,11 @@ func shellQuoteWindows(value string) string {
|
||||
return `"` + strings.ReplaceAll(value, `"`, `\"`) + `"`
|
||||
}
|
||||
|
||||
func createSeedISO(seedPath, instanceID, hostname, password, mac, ipv6 string) error {
|
||||
func createSeedISO(seedPath, instanceID, hostname, password, mac, ipv6 string, image Image) error {
|
||||
guestSetup := kvmSSHSetupScript(password)
|
||||
if desktopSetup := kvmDesktopSetupScript(image); desktopSetup != "" {
|
||||
guestSetup += "\n" + desktopSetup
|
||||
}
|
||||
if strings.TrimSpace(ipv6) != "" {
|
||||
guestSetup += "\n" + kvmIPv6SetupScript(ipv6)
|
||||
}
|
||||
@@ -1743,7 +1839,12 @@ func indentScript(script string, spaces int) string {
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string, ioSpeedMBps int, networkBWMbps int) string {
|
||||
func isKVMDesktopTemplate(templateID string) bool {
|
||||
image := FindImage(templateID)
|
||||
return image != nil && image.Desktop != ""
|
||||
}
|
||||
|
||||
func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string, ioSpeedMBps int, networkBWMbps int, desktop bool) string {
|
||||
if vcpu < 1 {
|
||||
vcpu = 1
|
||||
}
|
||||
@@ -1767,6 +1868,12 @@ func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string,
|
||||
<outbound average='%d'/>
|
||||
</bandwidth>`, averageKiB, averageKiB)
|
||||
}
|
||||
video := "<video><model type='virtio'/></video>"
|
||||
input := ""
|
||||
if desktop {
|
||||
video = "<video><model type='qxl' ram='65536' vram='65536' heads='1' primary='yes'/></video>"
|
||||
input = "\n\t <input type='tablet' bus='usb'/>"
|
||||
}
|
||||
return fmt.Sprintf(`<domain type='kvm'>
|
||||
<name>%s</name>
|
||||
%s
|
||||
@@ -1810,10 +1917,10 @@ func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string,
|
||||
<memballoon model='virtio'>
|
||||
<stats period='10'/>
|
||||
</memballoon>
|
||||
<graphics type='vnc' port='-1' autoport='yes' listen='127.0.0.1'/>
|
||||
<video><model type='virtio'/></video>
|
||||
<graphics type='vnc' port='-1' autoport='yes' listen='127.0.0.1'/>%s
|
||||
%s
|
||||
</devices>
|
||||
</domain>`, xmlEscape(name), domainUUIDXML(name), ramMB, ramMB, vcpu, vcpu, xmlEscape(diskPath), iotune, xmlEscape(seedPath), xmlEscape(mac), bandwidth)
|
||||
</domain>`, xmlEscape(name), domainUUIDXML(name), ramMB, ramMB, vcpu, vcpu, xmlEscape(diskPath), iotune, xmlEscape(seedPath), xmlEscape(mac), bandwidth, input, video)
|
||||
}
|
||||
|
||||
func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, unattendISOPath, mac string, ioSpeedMBps int, networkBWMbps int) string {
|
||||
@@ -2122,7 +2229,7 @@ func (m *Manager) EnsureSSH(id int) error {
|
||||
client, err := ssh.Dial("tcp", net.JoinHostPort(c.IP, "22"), &ssh.ClientConfig{
|
||||
User: "root",
|
||||
Auth: []ssh.AuthMethod{ssh.Password(c.SSHPassword)},
|
||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||
HostKeyCallback: kvmHostKeyCallback(c),
|
||||
Timeout: 8 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -2263,6 +2370,64 @@ fi
|
||||
`
|
||||
}
|
||||
|
||||
func kvmDesktopSetupScript(image Image) string {
|
||||
if strings.ToLower(strings.TrimSpace(image.Desktop)) != "xfce" {
|
||||
return ""
|
||||
}
|
||||
packages := ""
|
||||
switch image.Distro {
|
||||
case "ubuntu":
|
||||
packages = "xubuntu-desktop"
|
||||
case "debian":
|
||||
packages = "task-xfce-desktop"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
return `if command -v apt-get >/dev/null 2>&1; then
|
||||
{
|
||||
exec >>/var/log/clicd-desktop-setup.log 2>&1
|
||||
echo "CLICD XFCE setup started at $(date -Is)"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
export APT_LISTCHANGES_FRONTEND=none
|
||||
apt-get update || true
|
||||
apt-get install -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold ` + packages + ` || apt-get install -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold xfce4 lightdm lightdm-gtk-greeter dbus-x11 xorg || true
|
||||
if command -v useradd >/dev/null 2>&1 && ! id clicd >/dev/null 2>&1; then
|
||||
useradd -m -s /bin/bash clicd || true
|
||||
fi
|
||||
if command -v chpasswd >/dev/null 2>&1 && id clicd >/dev/null 2>&1; then
|
||||
printf 'clicd:%s\n' "$ROOT_PASSWORD" | chpasswd || true
|
||||
fi
|
||||
usermod -aG sudo clicd >/dev/null 2>&1 || true
|
||||
usermod -aG autologin clicd >/dev/null 2>&1 || true
|
||||
if id clicd >/dev/null 2>&1; then
|
||||
printf 'startxfce4\n' >/home/clicd/.xsession || true
|
||||
chown clicd:clicd /home/clicd/.xsession >/dev/null 2>&1 || true
|
||||
fi
|
||||
mkdir -p /etc/lightdm/lightdm.conf.d
|
||||
cat >/etc/lightdm/lightdm.conf.d/50-clicd-autologin.conf <<'EOF'
|
||||
[Seat:*]
|
||||
autologin-user=clicd
|
||||
autologin-user-timeout=0
|
||||
user-session=xfce
|
||||
greeter-session=lightdm-gtk-greeter
|
||||
EOF
|
||||
if [ -x /usr/sbin/lightdm ]; then
|
||||
printf '/usr/sbin/lightdm\n' >/etc/X11/default-display-manager || true
|
||||
fi
|
||||
if command -v systemctl >/dev/null 2>&1; then
|
||||
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||
systemctl set-default graphical.target >/dev/null 2>&1 || true
|
||||
systemctl enable display-manager.service >/dev/null 2>&1 || true
|
||||
systemctl enable lightdm.service >/dev/null 2>&1 || true
|
||||
systemctl restart lightdm.service >/dev/null 2>&1 || systemctl start lightdm.service >/dev/null 2>&1 || true
|
||||
fi
|
||||
apt-get clean || true
|
||||
echo "CLICD XFCE setup finished at $(date -Is)"
|
||||
} || true
|
||||
fi
|
||||
`
|
||||
}
|
||||
|
||||
func qemuGuestPing(name string) error {
|
||||
out, err := exec.Command("virsh", "qemu-agent-command", name, `{"execute":"guest-ping"}`).CombinedOutput()
|
||||
if err != nil {
|
||||
@@ -3030,7 +3195,7 @@ func (m *Manager) applyGuestIPv6OverSSH(c *config.Container) error {
|
||||
client, err := ssh.Dial("tcp", net.JoinHostPort(c.IP, "22"), &ssh.ClientConfig{
|
||||
User: "root",
|
||||
Auth: []ssh.AuthMethod{ssh.Password(c.SSHPassword)},
|
||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||
HostKeyCallback: kvmHostKeyCallback(c),
|
||||
Timeout: 8 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -3217,6 +3382,46 @@ func shellQuote(value string) string {
|
||||
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
|
||||
}
|
||||
|
||||
func chpasswdStdin(username, password string) ([]byte, error) {
|
||||
if username == "" || strings.ContainsAny(username, ":\n\r") {
|
||||
return nil, fmt.Errorf("invalid chpasswd username")
|
||||
}
|
||||
if strings.ContainsAny(password, "\n\r") {
|
||||
return nil, fmt.Errorf("password cannot contain newlines")
|
||||
}
|
||||
return []byte(username + ":" + password + "\n"), nil
|
||||
}
|
||||
|
||||
func kvmHostKeyCallback(c *config.Container) ssh.HostKeyCallback {
|
||||
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
return verifyKVMHostKey(c, key, config.SaveConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func verifyKVMHostKey(c *config.Container, key ssh.PublicKey, save func() error) error {
|
||||
if c == nil {
|
||||
return fmt.Errorf("KVM container is nil")
|
||||
}
|
||||
fingerprint := sshHostKeyFingerprint(key)
|
||||
if c.SSHHostKey != "" && c.SSHHostKey != fingerprint {
|
||||
return fmt.Errorf("KVM SSH host key mismatch")
|
||||
}
|
||||
if c.SSHHostKey == "" {
|
||||
c.SSHHostKey = fingerprint
|
||||
if save != nil {
|
||||
if err := save(); err != nil {
|
||||
return fmt.Errorf("failed to save KVM SSH host key: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sshHostKeyFingerprint(key ssh.PublicKey) string {
|
||||
sum := sha256.Sum256(key.Marshal())
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func allocateDefaultEqualPorts(c *config.Container, count int) []int {
|
||||
if count <= 0 {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package kvm
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"clicd/internal/config"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
func TestChpasswdStdinPreservesShellMetacharacters(t *testing.T) {
|
||||
password := `pa'";$(touch /tmp/pwned); echo #\\word`
|
||||
got, err := chpasswdStdin("root", password)
|
||||
if err != nil {
|
||||
t.Fatalf("chpasswdStdin returned error: %v", err)
|
||||
}
|
||||
|
||||
want := []byte("root:" + password + "\n")
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("chpasswdStdin = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChpasswdStdinRejectsNewlines(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
username string
|
||||
password string
|
||||
}{
|
||||
{name: "username newline", username: "root\nadmin", password: "safe"},
|
||||
{name: "username colon", username: "root:admin", password: "safe"},
|
||||
{name: "password newline", username: "root", password: "safe\nroot:evil"},
|
||||
{name: "password carriage return", username: "root", password: "safe\rroot:evil"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := chpasswdStdin(tc.username, tc.password); err == nil {
|
||||
t.Fatal("chpasswdStdin returned nil error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyKVMHostKeyCapturesAndRejectsMismatch(t *testing.T) {
|
||||
key1 := testSSHPublicKey(t)
|
||||
key2 := testSSHPublicKey(t)
|
||||
|
||||
saves := 0
|
||||
c := &config.Container{}
|
||||
save := func() error {
|
||||
saves++
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := verifyKVMHostKey(c, key1, save); err != nil {
|
||||
t.Fatalf("first host key verification returned error: %v", err)
|
||||
}
|
||||
if c.SSHHostKey == "" {
|
||||
t.Fatal("first host key verification did not capture fingerprint")
|
||||
}
|
||||
if c.SSHHostKey != sshHostKeyFingerprint(key1) {
|
||||
t.Fatalf("captured fingerprint = %q, want %q", c.SSHHostKey, sshHostKeyFingerprint(key1))
|
||||
}
|
||||
if saves != 1 {
|
||||
t.Fatalf("save count = %d, want 1", saves)
|
||||
}
|
||||
|
||||
if err := verifyKVMHostKey(c, key1, save); err != nil {
|
||||
t.Fatalf("same host key verification returned error: %v", err)
|
||||
}
|
||||
if saves != 1 {
|
||||
t.Fatalf("save count after same key = %d, want 1", saves)
|
||||
}
|
||||
|
||||
if err := verifyKVMHostKey(c, key2, save); err == nil {
|
||||
t.Fatal("mismatched host key verification returned nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func testSSHPublicKey(t *testing.T) ssh.PublicKey {
|
||||
t.Helper()
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromKey(privateKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signer.PublicKey()
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type Image struct {
|
||||
Arch string `json:"arch"`
|
||||
Description string `json:"description"`
|
||||
URL string `json:"url"`
|
||||
Desktop string `json:"desktop,omitempty"`
|
||||
}
|
||||
|
||||
func GetImages() []Image {
|
||||
@@ -22,6 +23,13 @@ func GetImages() []Image {
|
||||
Description: "Ubuntu 24.04 LTS cloud image for KVM",
|
||||
URL: "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img",
|
||||
},
|
||||
{
|
||||
ID: "kvm-ubuntu-noble-xfce", Name: "Ubuntu 24.04 XFCE KVM",
|
||||
Distro: "ubuntu", Release: "noble", Arch: "amd64",
|
||||
Description: "Ubuntu 24.04 LTS cloud image with XFCE desktop provisioned via cloud-init",
|
||||
URL: "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img",
|
||||
Desktop: "xfce",
|
||||
},
|
||||
{
|
||||
ID: "kvm-ubuntu-jammy", Name: "Ubuntu 22.04 KVM",
|
||||
Distro: "ubuntu", Release: "jammy", Arch: "amd64",
|
||||
@@ -34,6 +42,13 @@ func GetImages() []Image {
|
||||
Description: "Debian 12 generic cloud image for KVM",
|
||||
URL: "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
|
||||
},
|
||||
{
|
||||
ID: "kvm-debian-bookworm-xfce", Name: "Debian 12 XFCE KVM",
|
||||
Distro: "debian", Release: "bookworm", Arch: "amd64",
|
||||
Description: "Debian 12 generic cloud image with XFCE desktop provisioned via cloud-init",
|
||||
URL: "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
|
||||
Desktop: "xfce",
|
||||
},
|
||||
{
|
||||
ID: "kvm-debian-bullseye", Name: "Debian 11 KVM",
|
||||
Distro: "debian", Release: "bullseye", Arch: "amd64",
|
||||
@@ -73,7 +88,7 @@ func GetImages() []Image {
|
||||
{
|
||||
ID: "kvm-windows-10", Name: "Windows 10 KVM",
|
||||
Distro: "windows", Release: "10", Arch: "amd64",
|
||||
Description: "Windows ISO for KVM (automatic unattended install from image index 1, network, Administrator password, RDP, firewall, and QEMU Guest Agent initialization)",
|
||||
Description: "Windows 10 Enterprise LTSC Evaluation",
|
||||
URL: "https://go.microsoft.com/fwlink/?LinkID=2195404",
|
||||
},
|
||||
}
|
||||
|
||||
+150
-28
@@ -11,11 +11,11 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"clicd/internal/config"
|
||||
@@ -402,9 +402,10 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
|
||||
// Set root password AFTER shiftRootfsForUnprivileged,
|
||||
// otherwise /etc/shadow ownership breaks and SSHD cannot authenticate.
|
||||
setCmd := m.rootfsCommand(rootfsPath,
|
||||
"sh", "-c", fmt.Sprintf("printf '%%s:%%s\\n' root %s | chpasswd", shellQuote(sshPassword)))
|
||||
setCmd.Run()
|
||||
if err := m.runRootfsCommand(rootfsPath,
|
||||
"sh", "-c", fmt.Sprintf("printf '%%s:%%s\\n' root %s | chpasswd", shellQuote(sshPassword))); err != nil {
|
||||
fmt.Printf("Warning: failed to set root password in %s: %v\n", lxcName, err)
|
||||
}
|
||||
|
||||
fmt.Printf("Container %d (%s) created successfully\n", id, cfg.Name)
|
||||
return nil
|
||||
@@ -429,7 +430,7 @@ func (m *Manager) preconfigureNetwork(rootfsPath, templateID string) {
|
||||
content := "auto lo\niface lo inet loopback\n\nauto eth0\niface eth0 inet dhcp\n"
|
||||
_ = os.MkdirAll(filepath.Dir(interfaces), 0755)
|
||||
_ = os.WriteFile(interfaces, []byte(content), 0644)
|
||||
_ = exec.Command("chroot", rootfsPath, "rc-update", "add", "networking", "boot").Run()
|
||||
_ = m.runRootfsCommand(rootfsPath, "rc-update", "add", "networking", "boot")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -451,7 +452,7 @@ method=ignore
|
||||
path := filepath.Join(nmDir, "eth0.nmconnection")
|
||||
_ = os.WriteFile(path, []byte(keyfile), 0600)
|
||||
}
|
||||
_ = exec.Command("chroot", rootfsPath, "systemctl", "enable", "NetworkManager").Run()
|
||||
_ = m.runRootfsCommand(rootfsPath, "systemctl", "enable", "NetworkManager")
|
||||
}
|
||||
|
||||
networkdDir := filepath.Join(rootfsPath, "etc", "systemd", "network")
|
||||
@@ -466,7 +467,7 @@ IPv6AcceptRA=no
|
||||
_ = os.WriteFile(filepath.Join(networkdDir, "10-eth0.network"), []byte(network), 0644)
|
||||
}
|
||||
if !isRHELFamily {
|
||||
_ = exec.Command("chroot", rootfsPath, "systemctl", "enable", "systemd-networkd").Run()
|
||||
_ = m.runRootfsCommand(rootfsPath, "systemctl", "enable", "systemd-networkd")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,7 +476,10 @@ func (m *Manager) preconfigureSSH(rootfsPath, password, templateID string) error
|
||||
_ = templateID
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
cmd := m.rootfsCommand(rootfsPath, "sh", "-c", sshSetupScript(password, false))
|
||||
cmd, err := m.rootfsCommand(rootfsPath, "sh", "-c", sshSetupScript(password, false))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd = exec.CommandContext(ctx, cmd.Path, cmd.Args[1:]...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
@@ -989,6 +993,27 @@ func parseSubIDRange(path, user string) (int, error) {
|
||||
return 0, fmt.Errorf("%s must contain a %s subordinate id range with at least 65536 ids", path, user)
|
||||
}
|
||||
|
||||
func (m *Manager) ensureUnprivilegedLXCPathAccess(lxcName string) error {
|
||||
// Unprivileged container root maps to a subordinate host UID, so it needs
|
||||
// execute permission on the LXC parent and container directories to reach
|
||||
// rootfs. Some distributions create /var/lib/lxc as 750/700, which causes
|
||||
// lxc-start to abort with "Could not access /var/lib/lxc".
|
||||
for _, path := range []string{m.LxcPath, filepath.Join(m.LxcPath, lxcName)} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := info.Mode().Perm()
|
||||
if mode&0001 != 0 {
|
||||
continue
|
||||
}
|
||||
if err := os.Chmod(path, mode|0001); err != nil {
|
||||
return fmt.Errorf("failed to fix LXC path permissions for %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
uidBase, gidBase, err := unprivilegedIDMap()
|
||||
if err != nil {
|
||||
@@ -996,6 +1021,9 @@ func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
}
|
||||
rootfsPath := filepath.Join(m.LxcPath, lxcName, "rootfs")
|
||||
marker := filepath.Join(rootfsPath, ".clicd-unprivileged-shifted")
|
||||
if err := m.ensureUnprivilegedLXCPathAccess(lxcName); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Stat(marker); err == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -1004,11 +1032,10 @@ func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rootStat, ok := rootInfo.Sys().(*syscall.Stat_t)
|
||||
rootDev, _, _, ok := fileStatFields(rootInfo)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to read rootfs device for %s", rootfsPath)
|
||||
}
|
||||
rootDev := rootStat.Dev
|
||||
|
||||
if err := filepath.WalkDir(rootfsPath, func(path string, _ os.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
@@ -1018,18 +1045,16 @@ func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
dev, uid, gid, ok := fileStatFields(info)
|
||||
if !ok {
|
||||
return fmt.Errorf("failed to read uid/gid for %s", path)
|
||||
}
|
||||
if path != rootfsPath && stat.Dev != rootDev {
|
||||
if path != rootfsPath && dev != rootDev {
|
||||
if info.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
uid := int(stat.Uid)
|
||||
gid := int(stat.Gid)
|
||||
if uid >= uidBase && uid < uidBase+65536 && gid >= gidBase && gid < gidBase+65536 {
|
||||
return nil
|
||||
}
|
||||
@@ -1039,7 +1064,7 @@ func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
if gid >= 0 && gid < 65536 {
|
||||
gid += gidBase
|
||||
}
|
||||
return syscall.Lchown(path, uid, gid)
|
||||
return os.Lchown(path, uid, gid)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("failed to shift rootfs ownership for unprivileged LXC: %v", err)
|
||||
}
|
||||
@@ -1047,7 +1072,7 @@ func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
if err := os.WriteFile(marker, []byte("1\n"), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := syscall.Lchown(marker, uidBase, gidBase); err != nil {
|
||||
if err := os.Lchown(marker, uidBase, gidBase); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1062,6 +1087,48 @@ func (m *Manager) shiftRootfsForUnprivileged(lxcName string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileStatFields(info os.FileInfo) (dev uint64, uid int, gid int, ok bool) {
|
||||
if info == nil || info.Sys() == nil {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
stat := reflect.ValueOf(info.Sys())
|
||||
if stat.Kind() == reflect.Pointer {
|
||||
if stat.IsNil() {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
stat = stat.Elem()
|
||||
}
|
||||
if stat.Kind() != reflect.Struct {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
devValue, devOK := numericField(stat, "Dev")
|
||||
uidValue, uidOK := numericField(stat, "Uid")
|
||||
gidValue, gidOK := numericField(stat, "Gid")
|
||||
if !devOK || !uidOK || !gidOK {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
return devValue, int(uidValue), int(gidValue), true
|
||||
}
|
||||
|
||||
func numericField(v reflect.Value, name string) (uint64, bool) {
|
||||
field := v.FieldByName(name)
|
||||
if !field.IsValid() {
|
||||
return 0, false
|
||||
}
|
||||
switch field.Kind() {
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
return field.Uint(), true
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
value := field.Int()
|
||||
if value < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return uint64(value), true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) unmountRootfsChildMounts(rootfsPath string) {
|
||||
rootAbs, err := filepath.Abs(rootfsPath)
|
||||
if err != nil {
|
||||
@@ -1822,14 +1889,17 @@ pgrep -x sshd >/dev/null 2>&1 || exit 33
|
||||
}
|
||||
|
||||
// ResetSSHPassword resets the root password of a container
|
||||
func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
func (m *Manager) ResetSSHPassword(id int, password string) (string, error) {
|
||||
c := config.FindContainer(id)
|
||||
if c == nil {
|
||||
return "", fmt.Errorf("container not found: %d", id)
|
||||
}
|
||||
lxcName := c.LxcName()
|
||||
|
||||
newPassword := generateRandomString(16)
|
||||
newPassword := strings.TrimSpace(password)
|
||||
if newPassword == "" {
|
||||
newPassword = generateRandomString(16)
|
||||
}
|
||||
|
||||
if c.Status == "running" {
|
||||
c.SSHPassword = newPassword
|
||||
@@ -1845,7 +1915,10 @@ func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
if err := m.preconfigureSSH(rootfsPath, newPassword, c.Template); err != nil {
|
||||
return "", fmt.Errorf("failed to configure SSH: %v", err)
|
||||
}
|
||||
cmd := m.rootfsCommand(rootfsPath, "sh", "-c", fmt.Sprintf("printf '%%s:%%s\\n' root %s | chpasswd", shellQuote(newPassword)))
|
||||
cmd, err := m.rootfsCommand(rootfsPath, "sh", "-c", fmt.Sprintf("printf '%%s:%%s\\n' root %s | chpasswd", shellQuote(newPassword)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to set password: %v, output: %s", err, string(output))
|
||||
@@ -1857,22 +1930,70 @@ func (m *Manager) ResetSSHPassword(id int) (string, error) {
|
||||
return newPassword, nil
|
||||
}
|
||||
|
||||
func (m *Manager) rootfsCommand(rootfsPath string, args ...string) *exec.Cmd {
|
||||
marker := filepath.Join(rootfsPath, ".clicd-unprivileged-shifted")
|
||||
func (m *Manager) rootfsCommand(rootfsPath string, args ...string) (*exec.Cmd, error) {
|
||||
cleanRootfsPath, err := m.safeRootfsPath(rootfsPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
marker := filepath.Join(cleanRootfsPath, ".clicd-unprivileged-shifted")
|
||||
if _, err := os.Stat(marker); err == nil {
|
||||
uidBase, gidBase, mapErr := unprivilegedIDMap()
|
||||
if mapErr == nil {
|
||||
cmdArgs := []string{
|
||||
"-m", fmt.Sprintf("u:0:%d:65536", uidBase),
|
||||
"-m", fmt.Sprintf("g:0:%d:65536", gidBase),
|
||||
"--", "chroot", rootfsPath,
|
||||
"--", "chroot", "--", cleanRootfsPath,
|
||||
}
|
||||
cmdArgs = append(cmdArgs, args...)
|
||||
return exec.Command("lxc-usernsexec", cmdArgs...)
|
||||
return exec.Command("lxc-usernsexec", cmdArgs...), nil
|
||||
}
|
||||
}
|
||||
cmdArgs := append([]string{rootfsPath}, args...)
|
||||
return exec.Command("chroot", cmdArgs...)
|
||||
cmdArgs := append([]string{"--", cleanRootfsPath}, args...)
|
||||
return exec.Command("chroot", cmdArgs...), nil
|
||||
}
|
||||
|
||||
func (m *Manager) runRootfsCommand(rootfsPath string, args ...string) error {
|
||||
cmd, err := m.rootfsCommand(rootfsPath, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func (m *Manager) safeRootfsPath(rootfsPath string) (string, error) {
|
||||
if rootfsPath == "" {
|
||||
return "", fmt.Errorf("empty rootfs path")
|
||||
}
|
||||
if !filepath.IsAbs(rootfsPath) {
|
||||
return "", fmt.Errorf("rootfs path must be absolute: %s", rootfsPath)
|
||||
}
|
||||
|
||||
cleanRootfsPath := filepath.Clean(rootfsPath)
|
||||
cleanLxcPath, err := filepath.Abs(m.LxcPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve LXC path: %v", err)
|
||||
}
|
||||
cleanLxcPath = filepath.Clean(cleanLxcPath)
|
||||
|
||||
if cleanRootfsPath == cleanLxcPath {
|
||||
return "", fmt.Errorf("refusing LXC base path as rootfs: %s", cleanRootfsPath)
|
||||
}
|
||||
if filepath.Base(cleanRootfsPath) != "rootfs" {
|
||||
return "", fmt.Errorf("refusing non-rootfs path: %s", cleanRootfsPath)
|
||||
}
|
||||
if filepath.Dir(cleanRootfsPath) == cleanLxcPath {
|
||||
return "", fmt.Errorf("refusing rootfs directly under LXC path: %s", cleanRootfsPath)
|
||||
}
|
||||
|
||||
rel, err := filepath.Rel(cleanLxcPath, cleanRootfsPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to validate rootfs path: %v", err)
|
||||
}
|
||||
if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || filepath.IsAbs(rel) {
|
||||
return "", fmt.Errorf("refusing unsafe rootfs path: %s", cleanRootfsPath)
|
||||
}
|
||||
return cleanRootfsPath, nil
|
||||
}
|
||||
|
||||
func (m *Manager) cleanupContainerStorage(lxcName string) error {
|
||||
@@ -2202,9 +2323,10 @@ func (m *Manager) ReinstallContainer(id int, templateID string) error {
|
||||
if err := m.shiftRootfsForUnprivileged(lxcName); err != nil {
|
||||
return err
|
||||
}
|
||||
setCmd := m.rootfsCommand(rootfsPath,
|
||||
"sh", "-c", fmt.Sprintf("printf '%%s:%%s\\n' root %s | chpasswd", shellQuote(c.SSHPassword)))
|
||||
setCmd.Run()
|
||||
if err := m.runRootfsCommand(rootfsPath,
|
||||
"sh", "-c", fmt.Sprintf("printf '%%s:%%s\\n' root %s | chpasswd", shellQuote(c.SSHPassword))); err != nil {
|
||||
fmt.Printf("Warning: failed to set root password in %s after reinstall: %v\n", lxcName, err)
|
||||
}
|
||||
|
||||
// Update template and keep everything else the same
|
||||
c.Template = templateID
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package lxc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRootfsCommandAddsSeparatorAndPreservesArgs(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
rootfs := filepath.Join(base, "ct-1", "rootfs")
|
||||
if err := os.MkdirAll(rootfs, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
m := &Manager{LxcPath: base}
|
||||
cmd, err := m.rootfsCommand(rootfs, "sh", "-c", "true", "--flag")
|
||||
if err != nil {
|
||||
t.Fatalf("rootfsCommand returned error: %v", err)
|
||||
}
|
||||
|
||||
want := []string{"chroot", "--", rootfs, "sh", "-c", "true", "--flag"}
|
||||
if !reflect.DeepEqual(cmd.Args, want) {
|
||||
t.Fatalf("cmd.Args = %#v, want %#v", cmd.Args, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootfsCommandAllowsLeadingDashContainerName(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
rootfs := filepath.Join(base, "-ct", "rootfs")
|
||||
if err := os.MkdirAll(rootfs, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
m := &Manager{LxcPath: base}
|
||||
cmd, err := m.rootfsCommand(rootfs, "true")
|
||||
if err != nil {
|
||||
t.Fatalf("rootfsCommand returned error: %v", err)
|
||||
}
|
||||
|
||||
want := []string{"chroot", "--", rootfs, "true"}
|
||||
if !reflect.DeepEqual(cmd.Args, want) {
|
||||
t.Fatalf("cmd.Args = %#v, want %#v", cmd.Args, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootfsCommandRejectsUnsafeRootfsPaths(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
m := &Manager{LxcPath: base}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
}{
|
||||
{name: "outside base", path: filepath.Join(outside, "ct-1", "rootfs")},
|
||||
{name: "base path", path: base},
|
||||
{name: "not rootfs", path: filepath.Join(base, "ct-1", "not-rootfs")},
|
||||
{name: "rootfs directly under base", path: filepath.Join(base, "rootfs")},
|
||||
{name: "relative rootfs", path: filepath.Join("ct-1", "rootfs")},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := m.rootfsCommand(tc.path, "true"); err == nil {
|
||||
t.Fatalf("rootfsCommand(%q) returned nil error", tc.path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeRootfsPathRejectsSiblingPrefix(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
base := filepath.Join(parent, "lxc")
|
||||
siblingRootfs := filepath.Join(parent, "lxc-evil", "ct-1", "rootfs")
|
||||
m := &Manager{LxcPath: base}
|
||||
|
||||
if _, err := m.safeRootfsPath(siblingRootfs); err == nil || !strings.Contains(err.Error(), "unsafe rootfs path") {
|
||||
t.Fatalf("safeRootfsPath returned %v, want unsafe rootfs path error", err)
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@ func setupRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/templates", corsMiddleware(api.AuthMiddleware(api.HandleTemplates)))
|
||||
mux.HandleFunc("/api/images", corsMiddleware(api.AdminMiddleware(api.HandleImages)))
|
||||
mux.HandleFunc("/api/images/download", corsMiddleware(api.AdminMiddleware(api.HandleImageDownload)))
|
||||
mux.HandleFunc("/api/images/cancel", corsMiddleware(api.AdminMiddleware(api.HandleImageCancel)))
|
||||
mux.HandleFunc("/api/images/delete", corsMiddleware(api.AdminMiddleware(api.HandleImageDelete)))
|
||||
mux.HandleFunc("/api/images/toggle", corsMiddleware(api.AdminMiddleware(api.HandleImageToggle)))
|
||||
mux.HandleFunc("/api/images/enabled", corsMiddleware(api.AuthMiddleware(api.SubUserMiddleware(api.HandleEnabledImages))))
|
||||
@@ -102,6 +103,7 @@ func setupRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/security/check", corsMiddleware(api.AdminMiddleware(api.HandleSecurityCheck)))
|
||||
mux.HandleFunc("/api/security/logs", corsMiddleware(api.AdminMiddleware(api.HandleSecurityLogs)))
|
||||
mux.HandleFunc("/api/security/summary", corsMiddleware(api.AdminMiddleware(api.HandleContainerSecuritySummary)))
|
||||
mux.HandleFunc("/api/security/settings", corsMiddleware(api.AdminMiddleware(api.HandleSecuritySettings)))
|
||||
mux.HandleFunc("/api/ssh-ticket", corsMiddleware(api.AuthMiddleware(api.HandleWebSSHTicket)))
|
||||
mux.HandleFunc("/api/ssh", api.HandleWebSSH) // WebSocket
|
||||
mux.HandleFunc("/api/vnc-ticket", corsMiddleware(api.AuthMiddleware(api.HandleVNCTicket)))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package version
|
||||
|
||||
var (
|
||||
Version = "1.0.13"
|
||||
Version = "1.1.4"
|
||||
Repo = "MengMengCode/CLICD"
|
||||
)
|
||||
|
||||
@@ -11,11 +11,3 @@ func Current() string {
|
||||
}
|
||||
return Version
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Generated
+563
-713
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "clicd-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,7 +9,7 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@novnc/novnc": "1.6.0",
|
||||
"@novnc/novnc": "1.5.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"axios": "^1.7.7",
|
||||
@@ -21,11 +21,11 @@
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.49",
|
||||
"tailwindcss": "^3.4.15",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.11"
|
||||
"vite": "^8.0.16"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ export default function ContainerCard({ container, onRefresh }: ContainerCardPro
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
|
||||
<div className="w-10 h-10 flex items-center justify-center">
|
||||
<Server className="w-5 h-5 text-gray-700" />
|
||||
</div>
|
||||
<div>
|
||||
|
||||
@@ -27,6 +27,23 @@ interface SidebarProps {
|
||||
onToggle: () => void
|
||||
}
|
||||
|
||||
function GitHubIcon({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
className={className}
|
||||
viewBox="0 0 1024 1024"
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M512 42.666667A464.64 464.64 0 0 0 42.666667 502.186667 460.373333 460.373333 0 0 0 363.52 938.666667c23.466667 4.266667 32-9.813333 32-22.186667v-78.08c-130.56 27.733333-158.293333-61.44-158.293333-61.44a122.026667 122.026667 0 0 0-52.053334-67.413333c-42.666667-28.16 3.413333-27.733333 3.413334-27.733334a98.56 98.56 0 0 1 71.68 47.36 101.12 101.12 0 0 0 136.533333 37.973334 99.413333 99.413333 0 0 1 29.866667-61.44c-104.106667-11.52-213.333333-50.773333-213.333334-226.986667a177.066667 177.066667 0 0 1 47.36-124.16 161.28 161.28 0 0 1 4.693334-121.173333s39.68-12.373333 128 46.933333a455.68 455.68 0 0 1 234.666666 0c89.6-59.306667 128-46.933333 128-46.933333a161.28 161.28 0 0 1 4.693334 121.173333A177.066667 177.066667 0 0 1 810.666667 477.866667c0 176.64-110.08 215.466667-213.333334 226.986666a106.666667 106.666667 0 0 1 32 85.333334v125.866666c0 14.933333 8.533333 26.88 32 22.186667A460.8 460.8 0 0 0 981.333333 502.186667 464.64 464.64 0 0 0 512 42.666667"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
@@ -66,14 +83,14 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
|
||||
<div className="flex items-center justify-between h-14 px-4 border-b border-gray-200 dark:border-gray-700">
|
||||
{!collapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-7 h-7 bg-gray-100 rounded flex items-center justify-center dark:bg-gray-800">
|
||||
<div className="w-7 h-7 flex items-center justify-center">
|
||||
<AppIcon className="w-5 h-5" />
|
||||
</div>
|
||||
<span className="font-bold text-black text-sm dark:text-white">CLICD</span>
|
||||
</div>
|
||||
)}
|
||||
{collapsed && (
|
||||
<div className="w-7 h-7 bg-gray-100 rounded flex items-center justify-center mx-auto dark:bg-gray-800">
|
||||
<div className="w-7 h-7 flex items-center justify-center mx-auto">
|
||||
<AppIcon className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
@@ -239,9 +256,29 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
|
||||
{version && (
|
||||
<div className={`px-3 py-2 text-xs text-gray-400 dark:text-gray-500 ${collapsed ? 'text-center' : ''}`}>
|
||||
{collapsed ? (
|
||||
<span title={`v${version}`}>v{version.split('.').slice(0, 2).join('.')}</span>
|
||||
<a
|
||||
href="https://github.com/MengMengCode/CLICD"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title={`CLICD v${version}`}
|
||||
className="inline-flex items-center justify-center rounded text-gray-400 transition-colors hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
|
||||
>
|
||||
<GitHubIcon className="h-4 w-4" />
|
||||
</a>
|
||||
) : (
|
||||
<span>v{version}</span>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<a
|
||||
href="https://github.com/MengMengCode/CLICD"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title="CLICD"
|
||||
className="inline-flex min-w-0 items-center gap-1 rounded text-gray-500 transition-colors hover:text-gray-950 dark:text-gray-400 dark:hover:text-white"
|
||||
>
|
||||
<GitHubIcon className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="truncate">CLICD</span>
|
||||
</a>
|
||||
<span className="shrink-0">v{version}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -21,6 +21,46 @@ export default function WebVNCViewer({ containerName, onClose }: WebVNCViewerPro
|
||||
}
|
||||
}
|
||||
|
||||
const ensureResizeObserver = () => {
|
||||
if ('ResizeObserver' in window) return
|
||||
|
||||
class FallbackResizeObserver {
|
||||
private target: Element | null = null
|
||||
private timer = 0
|
||||
private lastWidth = -1
|
||||
private lastHeight = -1
|
||||
|
||||
constructor(private callback: ResizeObserverCallback) {}
|
||||
|
||||
observe = (target: Element) => {
|
||||
this.target = target
|
||||
this.check()
|
||||
this.timer = window.setInterval(this.check, 250)
|
||||
window.addEventListener('resize', this.check)
|
||||
}
|
||||
|
||||
unobserve = () => this.disconnect()
|
||||
|
||||
disconnect = () => {
|
||||
if (this.timer) window.clearInterval(this.timer)
|
||||
this.timer = 0
|
||||
window.removeEventListener('resize', this.check)
|
||||
this.target = null
|
||||
}
|
||||
|
||||
private check = () => {
|
||||
if (!this.target) return
|
||||
const contentRect = this.target.getBoundingClientRect()
|
||||
if (contentRect.width === this.lastWidth && contentRect.height === this.lastHeight) return
|
||||
this.lastWidth = contentRect.width
|
||||
this.lastHeight = contentRect.height
|
||||
this.callback([{ target: this.target, contentRect } as ResizeObserverEntry], this as unknown as ResizeObserver)
|
||||
}
|
||||
}
|
||||
|
||||
;(window as unknown as { ResizeObserver: typeof ResizeObserver }).ResizeObserver = FallbackResizeObserver as unknown as typeof ResizeObserver
|
||||
}
|
||||
|
||||
const connect = async () => {
|
||||
const target = screenRef.current
|
||||
if (!target) return
|
||||
@@ -47,7 +87,10 @@ export default function WebVNCViewer({ containerName, onClose }: WebVNCViewerPro
|
||||
}
|
||||
|
||||
try {
|
||||
const rfb = new RFB(target, getWebVNCUrl(containerName, ticket))
|
||||
ensureResizeObserver()
|
||||
const rfb = new RFB(target, getWebVNCUrl(containerName), {
|
||||
wsProtocols: ['binary', `clicd-vnc-ticket.${ticket}`],
|
||||
})
|
||||
rfb.scaleViewport = true
|
||||
rfb.resizeSession = false
|
||||
rfb.focusOnClick = true
|
||||
@@ -76,7 +119,8 @@ export default function WebVNCViewer({ containerName, onClose }: WebVNCViewerPro
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
setStatus('error')
|
||||
setErrorMsg('WebVNC 初始化失败')
|
||||
const message = err instanceof Error && err.message ? `:${err.message}` : ''
|
||||
setErrorMsg(`WebVNC 初始化失败${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef, type ReactNode } from 'react'
|
||||
import { useParams, useNavigate } from 'react-router-dom'
|
||||
import {
|
||||
ArrowLeft,
|
||||
AlertTriangle,
|
||||
Camera,
|
||||
Clock,
|
||||
Copy,
|
||||
@@ -143,6 +144,10 @@ export default function ContainerDetail() {
|
||||
const [resourceEdit, setResourceEdit] = useState({ vcpu: 1, ramMb: 512, ioMbps: 500, bwMbps: 100 })
|
||||
const [savingResource, setSavingResource] = useState(false)
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [showResetPassword, setShowResetPassword] = useState(false)
|
||||
const [resetPasswordDraft, setResetPasswordDraft] = useState('')
|
||||
const [resetPasswordResult, setResetPasswordResult] = useState('')
|
||||
const [resetPasswordSaving, setResetPasswordSaving] = useState(false)
|
||||
const [showSnapshots, setShowSnapshots] = useState(false)
|
||||
const [snapshots, setSnapshots] = useState<Snapshot[]>([])
|
||||
const [snapshotQuota, setSnapshotQuota] = useState(3)
|
||||
@@ -299,8 +304,17 @@ export default function ContainerDetail() {
|
||||
start: '开机中...', stop: '关机中...', restart: '重启中...', delete: '删除中...', reinstall: '重装中...',
|
||||
}
|
||||
|
||||
const ensureSubUserCanOperate = async () => {
|
||||
if (isSubUser && container?.policy_blocked) {
|
||||
await dialog.alert('策略临时封禁', container.policy_blocked_reason || '虚拟机被策略临时封禁,暂不能执行操作。')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const handleAction = async (action: string) => {
|
||||
if (!containerIdentifier) return
|
||||
if (!(await ensureSubUserCanOperate())) return
|
||||
setActionLoading(action)
|
||||
try {
|
||||
switch (action) {
|
||||
@@ -433,20 +447,58 @@ export default function ContainerDetail() {
|
||||
}
|
||||
}
|
||||
|
||||
const generateResetPassword = () => {
|
||||
const letters = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
||||
const digits = '23456789'
|
||||
const symbols = '!@#$%*-_+='
|
||||
const all = letters + digits + symbols
|
||||
const pick = (chars: string) => chars[Math.floor(Math.random() * chars.length)]
|
||||
let password = pick(letters) + pick(digits)
|
||||
while (password.length < 16) password += pick(all)
|
||||
setResetPasswordDraft(password.split('').sort(() => Math.random() - 0.5).join(''))
|
||||
setResetPasswordResult('')
|
||||
}
|
||||
|
||||
const resetPasswordError = (password: string) => {
|
||||
if (password.length < 8 || password.length > 64) return '密码长度必须为 8-64 位'
|
||||
if (/\s/.test(password)) return '密码不能包含空白字符'
|
||||
if (!/[A-Za-z]/.test(password)) return '密码至少需要包含字母'
|
||||
if (!/\d/.test(password)) return '密码至少需要包含数字'
|
||||
return ''
|
||||
}
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
if (!containerIdentifier || !(await dialog.confirm('重置密码', `确定要重置容器 ${container?.name} 的 SSH 密码吗?`))) return
|
||||
if (!containerIdentifier) return
|
||||
const password = resetPasswordDraft.trim()
|
||||
const validationError = resetPasswordError(password)
|
||||
if (validationError) {
|
||||
await dialog.alert('密码格式不正确', validationError)
|
||||
return
|
||||
}
|
||||
setResetPasswordSaving(true)
|
||||
try {
|
||||
const res = await resetSSHPassword(containerIdentifier)
|
||||
const res = await resetSSHPassword(containerIdentifier, password)
|
||||
if (res.data.success) {
|
||||
await dialog.alert('密码已重置', `新密码: ${(res.data.data as { password: string })?.password}`)
|
||||
const nextPassword = (res.data.data as { password: string })?.password || password
|
||||
setResetPasswordResult(nextPassword)
|
||||
setResetPasswordDraft(nextPassword)
|
||||
await fetchContainer()
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (err: unknown) {
|
||||
console.error(err)
|
||||
dialog.alert('密码重置失败', '请稍后重试')
|
||||
const error = err as { response?: { data?: { message?: string } } }
|
||||
dialog.alert('密码重置失败', error.response?.data?.message || '请稍后重试')
|
||||
} finally {
|
||||
setResetPasswordSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openResetPassword = () => {
|
||||
setResetPasswordDraft('')
|
||||
setResetPasswordResult('')
|
||||
setShowResetPassword(true)
|
||||
}
|
||||
|
||||
const handleAssignIPv6 = async () => {
|
||||
if (!containerIdentifier) return
|
||||
setActionLoading('ipv6')
|
||||
@@ -462,11 +514,13 @@ export default function ContainerDetail() {
|
||||
}
|
||||
|
||||
const openAddMapping = () => {
|
||||
if (isSubUser && container?.policy_blocked) return
|
||||
setDraft(emptyDraft)
|
||||
setShowNat(true)
|
||||
}
|
||||
|
||||
const openEditMapping = (pm: PortMapping, index: number) => {
|
||||
if (isSubUser && container?.policy_blocked) return
|
||||
if (isSubUser) {
|
||||
// Sub-user: only edit container_port in a simple modal
|
||||
setDraft({
|
||||
@@ -489,6 +543,7 @@ export default function ContainerDetail() {
|
||||
|
||||
const submitMapping = async (): Promise<boolean> => {
|
||||
if (!containerIdentifier) return false
|
||||
if (!(await ensureSubUserCanOperate())) return false
|
||||
if (draft.index === null && container) {
|
||||
const currentCount = container.port_mappings?.length || 0
|
||||
const limit = container.port_mapping_limit || Math.max(currentCount, 2)
|
||||
@@ -541,6 +596,7 @@ export default function ContainerDetail() {
|
||||
|
||||
const removeMapping = async (index: number) => {
|
||||
if (!containerIdentifier || !(await dialog.confirm('删除映射', '确定要删除这条映射规则吗?'))) return
|
||||
if (!(await ensureSubUserCanOperate())) return
|
||||
try {
|
||||
await deletePortMapping(containerIdentifier, index)
|
||||
await fetchContainer()
|
||||
@@ -553,6 +609,7 @@ export default function ContainerDetail() {
|
||||
|
||||
const handleCreateSnapshot = async () => {
|
||||
if (!containerIdentifier) return
|
||||
if (!(await ensureSubUserCanOperate())) return
|
||||
if (isSubUser && snapshots.length >= snapshotQuota) {
|
||||
await dialog.alert('快照配额已满', '已达到管理员设置的快照配额,请先删除旧快照。')
|
||||
return
|
||||
@@ -577,6 +634,7 @@ export default function ContainerDetail() {
|
||||
}
|
||||
|
||||
const openSnapshotSchedule = () => {
|
||||
if (isSubUser && container?.policy_blocked) return
|
||||
setSnapshotScheduleDraft({
|
||||
intervalHours: Math.max(snapshotSchedule?.interval_hours || 24, 24),
|
||||
time: snapshotSchedule?.time || '03:00',
|
||||
@@ -586,6 +644,7 @@ export default function ContainerDetail() {
|
||||
|
||||
const saveSnapshotSchedule = async (enabled: boolean) => {
|
||||
if (!containerIdentifier) return
|
||||
if (!(await ensureSubUserCanOperate())) return
|
||||
const intervalHours = snapshotScheduleDraft.intervalHours
|
||||
const scheduleTime = snapshotScheduleDraft.time || '03:00'
|
||||
if (enabled && intervalHours < 24) {
|
||||
@@ -625,6 +684,7 @@ export default function ContainerDetail() {
|
||||
|
||||
const handleDeleteSnapshot = async (snapshot: Snapshot) => {
|
||||
if (!containerIdentifier) return
|
||||
if (!(await ensureSubUserCanOperate())) return
|
||||
if (!(await dialog.confirm('删除快照', `确定删除 ${snapshot.created_at} 的快照吗?`))) return
|
||||
setSnapshotBusy(snapshot.id)
|
||||
try {
|
||||
@@ -640,6 +700,7 @@ export default function ContainerDetail() {
|
||||
|
||||
const handleRestoreSnapshot = async (snapshot: Snapshot) => {
|
||||
if (!containerIdentifier) return
|
||||
if (!(await ensureSubUserCanOperate())) return
|
||||
if (!(await dialog.confirm('恢复快照', `确定恢复到 ${snapshot.created_at} 的快照吗?当前容器数据会被覆盖。`))) return
|
||||
setSnapshotBusy(snapshot.id)
|
||||
try {
|
||||
@@ -681,6 +742,9 @@ export default function ContainerDetail() {
|
||||
const isWindows = container.template?.includes('windows')
|
||||
const canOpenVNC = isKVM && isRunning
|
||||
const isExpired = container.expires_at ? new Date(container.expires_at) < new Date() : false
|
||||
const isPolicyBlocked = !!container.policy_blocked
|
||||
const isSubUserPolicyBlocked = isSubUser && isPolicyBlocked
|
||||
const policyBlockedText = container.policy_blocked_reason || '虚拟机被策略临时封禁'
|
||||
const publicHost = hostInfo?.network.public_ipv4 || PUBLIC_HOST
|
||||
const maxVCPU = hostInfo?.cpu.cores || 64
|
||||
const maxRAMMB = hostInfo?.ram.total_mb ? Number(hostInfo.ram.total_mb) : undefined
|
||||
@@ -703,7 +767,7 @@ export default function ContainerDetail() {
|
||||
const diskIOBps = (usage?.disk_read_bps || 0) + (usage?.disk_write_bps || 0)
|
||||
const mappingCount = container.port_mappings?.length || 0
|
||||
const mappingLimit = container.port_mapping_limit || Math.max(mappingCount, 2)
|
||||
const canAddMapping = isSubUser ? mappingCount < mappingLimit : true
|
||||
const canAddMapping = isSubUser ? mappingCount < mappingLimit && !isSubUserPolicyBlocked : true
|
||||
const managementUrl = subUser?.access_code
|
||||
? `${window.location.origin}/login?code=${encodeURIComponent(subUser.access_code)}`
|
||||
: ''
|
||||
@@ -760,7 +824,7 @@ export default function ContainerDetail() {
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-5">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-14 h-14 bg-slate-100 rounded-lg flex items-center justify-center">
|
||||
<div className="w-14 h-14 flex items-center justify-center">
|
||||
{getTemplateIcon(container.template || '') || <Cpu className="w-7 h-7 text-slate-700" />}
|
||||
</div>
|
||||
<div>
|
||||
@@ -774,34 +838,35 @@ export default function ContainerDetail() {
|
||||
<InfoTag color="emerald">内网 {container.ip || '-'}</InfoTag>
|
||||
<InfoTag color="amber">NAT {mappingCount} 条</InfoTag>
|
||||
<InfoTag color="violet">{isWindows ? 'RDP' : 'SSH'} {publicHost}:{container.ssh_port}</InfoTag>
|
||||
{isPolicyBlocked && <InfoTag color="red">策略封禁</InfoTag>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 flex-wrap justify-end">
|
||||
{!isRunning ? (
|
||||
<ActionButton dark disabled={!!taskStatus || isExpired} onClick={() => handleAction('start')}>
|
||||
<ActionButton dark disabled={!!taskStatus || isExpired || isSubUserPolicyBlocked} onClick={() => handleAction('start')}>
|
||||
<Play className="w-3.5 h-3.5" />
|
||||
{isExpired ? '已到期' : taskStatus === 'start' ? taskActionLabels['start'] : '开机'}
|
||||
{isSubUserPolicyBlocked ? '已封禁' : isExpired ? '已到期' : taskStatus === 'start' ? taskActionLabels['start'] : '开机'}
|
||||
</ActionButton>
|
||||
) : (
|
||||
<>
|
||||
<ActionButton disabled={!!taskStatus || isExpired} onClick={() => handleAction('stop')}>
|
||||
<ActionButton disabled={!!taskStatus || isExpired || isSubUserPolicyBlocked} onClick={() => handleAction('stop')}>
|
||||
<Square className="w-3.5 h-3.5" />
|
||||
{isExpired ? '已到期' : taskStatus === 'stop' ? taskActionLabels['stop'] : '关机'}
|
||||
{isSubUserPolicyBlocked ? '已封禁' : isExpired ? '已到期' : taskStatus === 'stop' ? taskActionLabels['stop'] : '关机'}
|
||||
</ActionButton>
|
||||
<ActionButton disabled={!!taskStatus || isExpired} onClick={() => handleAction('restart')}>
|
||||
<ActionButton disabled={!!taskStatus || isExpired || isSubUserPolicyBlocked} onClick={() => handleAction('restart')}>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
{isExpired ? '已到期' : taskStatus === 'restart' ? taskActionLabels['restart'] : '重启'}
|
||||
{isSubUserPolicyBlocked ? '已封禁' : isExpired ? '已到期' : taskStatus === 'restart' ? taskActionLabels['restart'] : '重启'}
|
||||
</ActionButton>
|
||||
{!isWindows && (
|
||||
<ActionButton dark onClick={() => setShowSSH(true)}>
|
||||
<ActionButton dark disabled={isSubUserPolicyBlocked} onClick={() => setShowSSH(true)}>
|
||||
<TerminalSquare className="w-3.5 h-3.5" />
|
||||
WebSSH
|
||||
</ActionButton>
|
||||
)}
|
||||
{isKVM && (
|
||||
<ActionButton dark disabled={!canOpenVNC} onClick={() => setShowVNC(true)}>
|
||||
<ActionButton dark disabled={!canOpenVNC || isSubUserPolicyBlocked} onClick={() => setShowVNC(true)}>
|
||||
<Monitor className="w-3.5 h-3.5" />
|
||||
WebVNC
|
||||
</ActionButton>
|
||||
@@ -815,12 +880,12 @@ export default function ContainerDetail() {
|
||||
</ActionButton>
|
||||
)}
|
||||
<>
|
||||
<ActionButton onClick={() => setShowNat(true)}>
|
||||
<ActionButton disabled={isSubUserPolicyBlocked} onClick={() => setShowNat(true)}>
|
||||
<Settings className="w-3.5 h-3.5" />
|
||||
NAT 管理
|
||||
</ActionButton>
|
||||
</>
|
||||
<ActionButton onClick={() => setShowSnapshots(true)} disabled={!!taskStatus || !!snapshotBusy}>
|
||||
<ActionButton onClick={() => setShowSnapshots(true)} disabled={!!taskStatus || !!snapshotBusy || isSubUserPolicyBlocked}>
|
||||
<Camera className="w-3.5 h-3.5" />
|
||||
快照
|
||||
</ActionButton>
|
||||
@@ -840,9 +905,34 @@ export default function ContainerDetail() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isSubUserPolicyBlocked && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div>
|
||||
<div className="font-medium">虚拟机被策略临时封禁</div>
|
||||
<div className="mt-1 text-xs text-red-600">{policyBlockedText}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
|
||||
<Panel title="连接信息">
|
||||
{isWindows ? (
|
||||
<Panel
|
||||
title="连接信息"
|
||||
extra={!isSubUser && !isWindows && !isSubUserPolicyBlocked ? (
|
||||
<button
|
||||
onClick={openResetPassword}
|
||||
className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs text-gray-600 hover:bg-gray-100 hover:text-black"
|
||||
>
|
||||
<Key className="w-3.5 h-3.5" />
|
||||
重置 SSH 密码
|
||||
</button>
|
||||
) : undefined}
|
||||
>
|
||||
{isSubUserPolicyBlocked ? (
|
||||
<div className="rounded-md border border-red-100 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||
虚拟机被策略临时封禁,连接信息暂不可用。
|
||||
</div>
|
||||
) : isWindows ? (
|
||||
<>
|
||||
<PlainRow label="RDP 地址" value={`${publicHost}:${container.ssh_port}`} mono />
|
||||
<PlainRow label="用户名" value="Administrator" mono />
|
||||
@@ -888,12 +978,6 @@ export default function ContainerDetail() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!isSubUser && (
|
||||
<button onClick={handleResetPassword} className="inline-flex items-center gap-1.5 text-xs text-gray-600 hover:text-black">
|
||||
<Key className="w-3 h-3" />
|
||||
重置 SSH 密码
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
@@ -1046,6 +1130,60 @@ export default function ContainerDetail() {
|
||||
|
||||
<ResourceStatsPanel range={range} onRangeChange={setRange} onRefresh={() => { fetchContainer(); fetchUsage() }} charts={charts} />
|
||||
|
||||
{showResetPassword && (
|
||||
<Modal title="重置 SSH 密码" onClose={() => setShowResetPassword(false)}>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs text-gray-500 mb-1">新 SSH 密码</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={resetPasswordDraft}
|
||||
onChange={(e) => { setResetPasswordDraft(e.target.value); setResetPasswordResult('') }}
|
||||
placeholder="请输入 8-64 位,至少包含字母和数字"
|
||||
className={inputClass}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={generateResetPassword}
|
||||
className="px-3 py-2 border border-gray-300 rounded-md text-gray-600 hover:bg-gray-50 hover:text-black"
|
||||
title="生成随机密码"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
{resetPasswordDraft && resetPasswordError(resetPasswordDraft) && (
|
||||
<p className="mt-1 text-xs text-red-600">{resetPasswordError(resetPasswordDraft)}</p>
|
||||
)}
|
||||
</div>
|
||||
{resetPasswordResult && (
|
||||
<div className="p-3 bg-green-50 border border-green-200 rounded-md">
|
||||
<div className="text-xs text-green-700 mb-1">密码已修改成功</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-mono text-sm text-green-900 break-all">{resetPasswordResult}</span>
|
||||
<button onClick={() => copyText(resetPasswordResult)} className="p-1 text-green-700 hover:text-green-900 rounded" title="复制">
|
||||
<Copy className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-gray-500 leading-relaxed">
|
||||
Linux LXC/KVM 修改 root SSH 密码通常无需重启;KVM 需要虚拟机运行且 guest agent 或 SSH 可用。
|
||||
</p>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button onClick={() => setShowResetPassword(false)} className="px-4 py-2 text-sm text-gray-600 border border-gray-200 rounded-md hover:bg-gray-50">取消</button>
|
||||
<button
|
||||
onClick={handleResetPassword}
|
||||
disabled={resetPasswordSaving || !resetPasswordDraft || !!resetPasswordError(resetPasswordDraft)}
|
||||
className="px-4 py-2 text-sm bg-black text-white rounded-md hover:bg-gray-800 disabled:opacity-50"
|
||||
>
|
||||
{resetPasswordSaving ? '修改中...' : '确认修改'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{showSSH && (
|
||||
<Modal title={`WebSSH - ${container.name}`} onClose={() => setShowSSH(false)} wide>
|
||||
<div className="h-[70vh] min-h-[520px]">
|
||||
@@ -1507,13 +1645,14 @@ function StatusBadge({ running }: { running: boolean }) {
|
||||
)
|
||||
}
|
||||
|
||||
function InfoTag({ color, children }: { color: 'blue' | 'emerald' | 'amber' | 'violet' | 'slate'; children: ReactNode }) {
|
||||
function InfoTag({ color, children }: { color: 'blue' | 'emerald' | 'amber' | 'violet' | 'slate' | 'red'; children: ReactNode }) {
|
||||
const classes = {
|
||||
blue: 'bg-blue-50 text-blue-700 border-blue-100',
|
||||
emerald: 'bg-emerald-50 text-emerald-700 border-emerald-100',
|
||||
amber: 'bg-amber-50 text-amber-700 border-amber-100',
|
||||
violet: 'bg-violet-50 text-violet-700 border-violet-100',
|
||||
slate: 'bg-slate-50 text-slate-700 border-slate-100',
|
||||
red: 'bg-red-50 text-red-700 border-red-100',
|
||||
}
|
||||
return <span className={`px-1.5 py-0.5 border rounded text-[11px] whitespace-nowrap ${classes[color]}`}>{children}</span>
|
||||
}
|
||||
|
||||
@@ -392,6 +392,7 @@ export default function Containers() {
|
||||
const isRunning = container.status === 'running'
|
||||
const task = (container.id > 0 ? taskStatusMap[container.id] : taskNameMap[container.name]) || container.createTask
|
||||
const isPlaceholder = !!container.isPlaceholder
|
||||
const isPolicyBlocked = !!container.policy_blocked
|
||||
const usage = usageByName[container.name]
|
||||
const isKVM = (container.virtualization || 'lxc') === 'kvm'
|
||||
|
||||
@@ -436,7 +437,7 @@ export default function Containers() {
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-2.5 py-2 align-top">
|
||||
<StatusBadge running={isRunning} task={task} placeholder={isPlaceholder} />
|
||||
<StatusBadge running={isRunning} task={task} placeholder={isPlaceholder} policyBlocked={isPolicyBlocked} />
|
||||
</td>
|
||||
<td className="px-2.5 py-2 align-top text-xs text-gray-600 whitespace-nowrap">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
@@ -580,8 +581,17 @@ type DisplayContainer = Container & {
|
||||
createTask?: Task
|
||||
}
|
||||
|
||||
function StatusBadge({ running, task, placeholder }: { running: boolean; task?: Task; placeholder?: boolean }) {
|
||||
function StatusBadge({ running, task, placeholder, policyBlocked }: { running: boolean; task?: Task; placeholder?: boolean; policyBlocked?: boolean }) {
|
||||
const baseClass = "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium whitespace-nowrap"
|
||||
if (policyBlocked) {
|
||||
return (
|
||||
<span className={`${baseClass} bg-red-50 text-red-700`}>
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-red-500"></span>
|
||||
策略封禁
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (task?.status === 'failed') {
|
||||
return (
|
||||
<span className={`${baseClass} bg-red-50 text-red-700`}>
|
||||
|
||||
@@ -9,8 +9,9 @@ import {
|
||||
ToggleRight,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import { getImages, downloadImage, deleteImage, toggleImage, ImageInfo } from '../services/api'
|
||||
import { getImages, downloadImage, cancelImageDownload, deleteImage, toggleImage, ImageInfo } from '../services/api'
|
||||
import { useDialog } from '../components/Dialog'
|
||||
|
||||
export default function ImageManagement() {
|
||||
@@ -34,10 +35,14 @@ export default function ImageManagement() {
|
||||
|
||||
useEffect(() => {
|
||||
fetchImages()
|
||||
const interval = setInterval(fetchImages, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchImages])
|
||||
|
||||
useEffect(() => {
|
||||
const hasDownloads = images.some((img) => img.downloading)
|
||||
const interval = setInterval(fetchImages, hasDownloads ? 1500 : 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchImages, images])
|
||||
|
||||
const handleDownload = async (templateId: string) => {
|
||||
setActionLoading(templateId)
|
||||
setError('')
|
||||
@@ -51,6 +56,19 @@ export default function ImageManagement() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancelDownload = async (templateId: string) => {
|
||||
setActionLoading(templateId)
|
||||
setError('')
|
||||
try {
|
||||
await cancelImageDownload(templateId)
|
||||
await fetchImages()
|
||||
} catch (err: unknown) {
|
||||
setError(apiErrorMessage(err, '取消失败'))
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (templateId: string) => {
|
||||
if (!(await dialog.confirm('删除镜像', '确定要删除该镜像缓存吗?删除后需要重新下载才能使用。'))) return
|
||||
setActionLoading(templateId)
|
||||
@@ -125,6 +143,7 @@ export default function ImageManagement() {
|
||||
downloadedCount={lxcImages.filter((img) => img.downloaded).length}
|
||||
totalCount={lxcImages.length}
|
||||
onDownload={handleDownload}
|
||||
onCancelDownload={handleCancelDownload}
|
||||
onDelete={handleDelete}
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
@@ -136,6 +155,7 @@ export default function ImageManagement() {
|
||||
downloadedCount={kvmImages.filter((img) => img.downloaded).length}
|
||||
totalCount={kvmImages.length}
|
||||
onDownload={handleDownload}
|
||||
onCancelDownload={handleCancelDownload}
|
||||
onDelete={handleDelete}
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
@@ -150,6 +170,7 @@ function ImageTable({
|
||||
downloadedCount,
|
||||
totalCount,
|
||||
onDownload,
|
||||
onCancelDownload,
|
||||
onDelete,
|
||||
onToggle,
|
||||
}: {
|
||||
@@ -159,6 +180,7 @@ function ImageTable({
|
||||
downloadedCount: number
|
||||
totalCount: number
|
||||
onDownload: (id: string) => void
|
||||
onCancelDownload: (id: string) => void
|
||||
onDelete: (id: string) => void
|
||||
onToggle: (id: string, enabled: boolean) => void
|
||||
}) {
|
||||
@@ -202,7 +224,7 @@ function ImageTable({
|
||||
<tr key={img.id} className="hover:bg-gray-50 transition-colors">
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0">
|
||||
<span className="w-8 h-8 flex items-center justify-center flex-shrink-0">
|
||||
{getTemplateIcon(img.id)}
|
||||
</span>
|
||||
<div>
|
||||
@@ -242,13 +264,18 @@ function ImageTable({
|
||||
)}
|
||||
|
||||
{img.downloading && (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-amber-50 border border-amber-200 rounded-md text-amber-700 text-xs font-medium">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
下载中...
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onCancelDownload(img.id)}
|
||||
disabled={isBusy}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border border-red-200 text-red-600 hover:bg-red-50 transition-colors text-xs font-medium disabled:opacity-50"
|
||||
title="取消下载并清理临时文件"
|
||||
>
|
||||
{isBusy ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <X className="w-3.5 h-3.5" />}
|
||||
{isBusy ? '取消中...' : '取消'}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{img.downloaded && (
|
||||
{img.downloaded && !img.downloading && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => onToggle(img.id, img.enabled)}
|
||||
@@ -287,10 +314,33 @@ function ImageTable({
|
||||
|
||||
function StatusBadge({ img }: { img: ImageInfo }) {
|
||||
if (img.downloading) {
|
||||
const progress = Math.max(0, Math.min(100, img.progress || 0))
|
||||
const showProgress = img.stage === 'downloading' && progress > 0
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium bg-amber-50 text-amber-700">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />
|
||||
下载中
|
||||
<div className="inline-flex flex-col gap-1">
|
||||
<span
|
||||
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium bg-amber-50 text-amber-700"
|
||||
title={downloadStatusTitle(img)}
|
||||
>
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse" />
|
||||
{downloadStatusLabel(img)}
|
||||
</span>
|
||||
{showProgress && (
|
||||
<span className="block h-1 w-24 overflow-hidden rounded-full bg-amber-100">
|
||||
<span className="block h-full rounded-full bg-amber-500 transition-all" style={{ width: `${progress}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (img.error) {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium bg-red-50 text-red-600"
|
||||
title={img.error}
|
||||
>
|
||||
<AlertCircle className="w-3 h-3" />
|
||||
下载失败
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -318,6 +368,23 @@ function StatusBadge({ img }: { img: ImageInfo }) {
|
||||
)
|
||||
}
|
||||
|
||||
function downloadStatusLabel(img: ImageInfo) {
|
||||
if (img.stage === 'canceling') return '取消中'
|
||||
if (img.stage === 'converting') return '转换中'
|
||||
if (img.stage === 'lxc-create') return '下载中'
|
||||
if (img.progress > 0) return `下载中 ${Math.min(100, img.progress)}%`
|
||||
return '下载中'
|
||||
}
|
||||
|
||||
function downloadStatusTitle(img: ImageInfo) {
|
||||
const parts = [downloadStatusLabel(img)]
|
||||
if (img.stage) parts.push(`阶段:${img.stage}`)
|
||||
if (img.downloaded_bytes > 0 || img.total_bytes > 0) {
|
||||
parts.push(`${formatSize(img.downloaded_bytes)} / ${formatSize(img.total_bytes)}`)
|
||||
}
|
||||
return parts.join(',')
|
||||
}
|
||||
|
||||
function isWindowsImage(img: ImageInfo) {
|
||||
return img.distro === 'windows' || img.id.toLowerCase().includes('windows')
|
||||
}
|
||||
|
||||
@@ -3,13 +3,6 @@ import { Lock, User } from 'lucide-react'
|
||||
import AppIcon from '../components/AppIcon'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
|
||||
async function sha256Hash(input: string): Promise<string> {
|
||||
const msgBuffer = new TextEncoder().encode(input)
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
const { login, accessCodeLogin } = useAuth()
|
||||
const [username, setUsername] = useState('')
|
||||
@@ -47,7 +40,7 @@ export default function Login() {
|
||||
<div className="w-full max-w-md">
|
||||
<div className="bg-white rounded-lg border border-gray-200 shadow-sm p-8">
|
||||
<div className="flex flex-col items-center mb-8">
|
||||
<div className="w-16 h-16 rounded-lg border border-gray-200 bg-gray-50 flex items-center justify-center mb-4">
|
||||
<div className="w-16 h-16 flex items-center justify-center mb-4">
|
||||
<AppIcon className="w-10 h-10" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-gray-950">CLICD</h1>
|
||||
@@ -113,7 +106,7 @@ export default function Login() {
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-xs text-gray-400 mt-6">CLICD v1.0.0</p>
|
||||
<p className="text-center text-xs text-gray-400 mt-6">CLICD v1.1.4</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
+156
-13
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { RefreshCw } from 'lucide-react'
|
||||
import { getSecurityAlerts, SecurityAlert } from '../services/api'
|
||||
import { FileText, Power, RefreshCw, X } from 'lucide-react'
|
||||
import { getSecurityAlerts, getSecurityLogs, getSecuritySettings, SecurityAlert, SecurityLog, updateSecuritySettings } from '../services/api'
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
port_scan: '端口扫描',
|
||||
@@ -23,12 +23,18 @@ const severityLabels: Record<string, string> = {
|
||||
|
||||
export default function Security() {
|
||||
const [alerts, setAlerts] = useState<SecurityAlert[]>([])
|
||||
const [autoShutdown, setAutoShutdown] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [savingSettings, setSavingSettings] = useState(false)
|
||||
const [logAlert, setLogAlert] = useState<SecurityAlert | null>(null)
|
||||
const [logs, setLogs] = useState<SecurityLog[]>([])
|
||||
const [logsLoading, setLogsLoading] = useState(false)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const alertRes = await getSecurityAlerts()
|
||||
const [alertRes, settingsRes] = await Promise.all([getSecurityAlerts(), getSecuritySettings()])
|
||||
if (alertRes.data.data) setAlerts(alertRes.data.data)
|
||||
if (settingsRes.data.data) setAutoShutdown(settingsRes.data.data.auto_shutdown)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
} finally {
|
||||
@@ -42,6 +48,36 @@ export default function Security() {
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchData])
|
||||
|
||||
const handleAutoShutdownChange = async () => {
|
||||
const next = !autoShutdown
|
||||
setAutoShutdown(next)
|
||||
setSavingSettings(true)
|
||||
try {
|
||||
const res = await updateSecuritySettings({ auto_shutdown: next })
|
||||
if (res.data.data) setAutoShutdown(res.data.data.auto_shutdown)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
setAutoShutdown(!next)
|
||||
} finally {
|
||||
setSavingSettings(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openLogs = async (alert: SecurityAlert) => {
|
||||
setLogAlert(alert)
|
||||
setLogs([])
|
||||
setLogsLoading(true)
|
||||
try {
|
||||
const res = await getSecurityLogs(alert.container_name)
|
||||
setLogs(filterRelatedLogs(res.data.data || [], alert))
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
setLogs([])
|
||||
} finally {
|
||||
setLogsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
@@ -52,15 +88,33 @@ export default function Security() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h1 className="text-xl font-semibold text-black">安全告警</h1>
|
||||
<button
|
||||
onClick={fetchData}
|
||||
className="inline-flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 text-sm"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
刷新
|
||||
</button>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={autoShutdown}
|
||||
onClick={handleAutoShutdownChange}
|
||||
disabled={savingSettings}
|
||||
title="告警自动关机"
|
||||
className={`inline-flex h-9 items-center gap-2 rounded-md border px-3 text-sm transition-colors disabled:opacity-60 ${
|
||||
autoShutdown
|
||||
? 'border-red-200 bg-red-50 text-red-700 hover:bg-red-100'
|
||||
: 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<Power className="w-4 h-4" />
|
||||
<span>{autoShutdown ? '自动关机已开' : '自动关机已关'}</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={fetchData}
|
||||
className="inline-flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 text-sm"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
@@ -93,12 +147,24 @@ export default function Security() {
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-gray-800 whitespace-nowrap">{typeLabels[alert.type] || alert.type}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-700 whitespace-nowrap">{alert.container_name}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-600 whitespace-nowrap">{alert.source_ip}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-600 whitespace-nowrap">{alert.source_ip || '-'}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-600 whitespace-nowrap">
|
||||
{formatTarget(alert)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-gray-600 whitespace-nowrap">{alert.count}</td>
|
||||
<td className="px-4 py-2.5 text-gray-600 min-w-[260px]">{alert.detail}</td>
|
||||
<td className="px-4 py-2.5 text-gray-600 min-w-[300px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1">{alert.detail}</span>
|
||||
<button
|
||||
onClick={() => openLogs(alert)}
|
||||
className="inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-300 px-2 py-1 text-xs text-gray-700 hover:bg-gray-50"
|
||||
title="查看相关记录"
|
||||
>
|
||||
<FileText className="h-3.5 w-3.5" />
|
||||
查看
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -106,6 +172,69 @@ export default function Security() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{logAlert && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
|
||||
<div className="w-full max-w-4xl overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl">
|
||||
<div className="flex items-start justify-between gap-3 border-b border-gray-200 px-4 py-3">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-black">相关连接记录</h3>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
{logAlert.container_name} · {typeLabels[logAlert.type] || logAlert.type} · {formatTarget(logAlert)}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setLogAlert(null)}
|
||||
className="rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-black"
|
||||
title="关闭"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="max-h-[70vh] overflow-auto">
|
||||
{logAlert.log_line && (
|
||||
<div className="border-b border-gray-100 bg-gray-50 px-4 py-3">
|
||||
<div className="mb-1 text-xs font-medium text-gray-600">告警原始记录</div>
|
||||
<pre className="whitespace-pre-wrap break-all rounded border border-gray-200 bg-white p-3 text-xs text-gray-700">{logAlert.log_line}</pre>
|
||||
</div>
|
||||
)}
|
||||
{logsLoading ? (
|
||||
<div className="p-8 text-center text-sm text-gray-500">正在加载连接记录...</div>
|
||||
) : logs.length === 0 ? (
|
||||
<div className="p-8 text-center text-sm text-gray-500">
|
||||
暂无可用连接记录。历史告警对应的 conntrack 记录可能已经过期。
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-gray-100 bg-gray-50 text-left text-xs font-medium text-gray-500">
|
||||
<th className="px-4 py-2.5">协议</th>
|
||||
<th className="px-4 py-2.5">状态</th>
|
||||
<th className="px-4 py-2.5">源地址</th>
|
||||
<th className="px-4 py-2.5">目标地址</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{logs.map((log, index) => (
|
||||
<tr key={`${log.src_ip}-${log.src_port}-${log.dst_ip}-${log.dst_port}-${index}`}>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-700">{log.protocol || '-'}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-700">{log.state || '-'}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-600">
|
||||
{formatEndpoint(log.src_ip, log.src_port)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 font-mono text-xs text-gray-600">
|
||||
{formatEndpoint(log.dst_ip, log.dst_port)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -129,3 +258,17 @@ function formatTarget(alert: SecurityAlert): string {
|
||||
if (!alert.target_ip) return '-'
|
||||
return alert.target_port > 0 ? `${alert.target_ip}:${alert.target_port}` : alert.target_ip
|
||||
}
|
||||
|
||||
function filterRelatedLogs(logs: SecurityLog[], alert: SecurityAlert): SecurityLog[] {
|
||||
return logs.filter((log) => {
|
||||
if (alert.source_ip && log.src_ip !== alert.source_ip) return false
|
||||
if (alert.target_ip && alert.target_ip !== '*' && log.dst_ip !== alert.target_ip) return false
|
||||
if (alert.target_port > 0 && log.dst_port !== alert.target_port) return false
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
function formatEndpoint(ip: string, port: number): string {
|
||||
if (!ip) return '-'
|
||||
return port > 0 ? `${ip}:${port}` : ip
|
||||
}
|
||||
|
||||
@@ -81,6 +81,9 @@ export interface Container {
|
||||
snapshot_schedule_last_run: string
|
||||
snapshot_schedule_next_run: string
|
||||
snapshot_schedule_created_by: string
|
||||
policy_blocked?: boolean
|
||||
policy_blocked_reason?: string
|
||||
policy_blocked_at?: string
|
||||
}
|
||||
|
||||
export interface Template {
|
||||
@@ -91,6 +94,7 @@ export interface Template {
|
||||
release: string
|
||||
arch: string
|
||||
variant?: string
|
||||
desktop?: string
|
||||
description: string
|
||||
}
|
||||
|
||||
@@ -241,8 +245,8 @@ export const restartContainer = (id: ContainerIdentifier) =>
|
||||
export const reinstallContainer = (id: ContainerIdentifier, templateId: string) =>
|
||||
api.post<APIResponse>(`/containers/${id}/reinstall`, { template_id: templateId })
|
||||
|
||||
export const resetSSHPassword = (id: ContainerIdentifier) =>
|
||||
api.post<APIResponse<{ password: string }>>(`/containers/${id}/reset-password`)
|
||||
export const resetSSHPassword = (id: ContainerIdentifier, password?: string) =>
|
||||
api.post<APIResponse<{ password: string }>>(`/containers/${id}/reset-password`, password ? { password } : {})
|
||||
|
||||
export const getContainerUsage = (id: ContainerIdentifier) =>
|
||||
api.get<APIResponse<ContainerUsage>>(`/containers/${id}/usage`)
|
||||
@@ -354,15 +358,24 @@ export interface ImageInfo {
|
||||
downloaded: boolean
|
||||
enabled: boolean
|
||||
downloading: boolean
|
||||
progress: number
|
||||
downloaded_bytes: number
|
||||
total_bytes: number
|
||||
stage?: string
|
||||
error?: string
|
||||
size_bytes: number
|
||||
manual_path?: string
|
||||
desktop?: string
|
||||
}
|
||||
|
||||
export const getImages = () =>
|
||||
api.get<APIResponse<ImageInfo[]>>('/images')
|
||||
|
||||
export const downloadImage = (templateId: string) =>
|
||||
api.post<APIResponse>('/images/download', { template_id: templateId }, { timeout: 1800000 }) // 30min timeout
|
||||
api.post<APIResponse>('/images/download', { template_id: templateId })
|
||||
|
||||
export const cancelImageDownload = (templateId: string) =>
|
||||
api.post<APIResponse>('/images/cancel', { template_id: templateId })
|
||||
|
||||
export const deleteImage = (templateId: string) =>
|
||||
api.delete<APIResponse>('/images/delete', { data: { template_id: templateId } })
|
||||
@@ -443,10 +456,9 @@ export const getWebSSHUrl = (containerName: string) => {
|
||||
return `${protocol}//${window.location.host}/api/ssh?${params.toString()}`
|
||||
}
|
||||
|
||||
export const getWebVNCUrl = (containerName: string, ticket?: string) => {
|
||||
export const getWebVNCUrl = (containerName: string) => {
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const params = new URLSearchParams({ container: containerName })
|
||||
if (ticket) params.set('ticket', ticket)
|
||||
return `${protocol}//${window.location.host}/api/vnc?${params.toString()}`
|
||||
}
|
||||
|
||||
@@ -524,6 +536,19 @@ export interface SecuritySummary {
|
||||
low: number
|
||||
}
|
||||
|
||||
export interface SecuritySettings {
|
||||
auto_shutdown: boolean
|
||||
}
|
||||
|
||||
export interface SecurityLog {
|
||||
src_ip: string
|
||||
dst_ip: string
|
||||
src_port: number
|
||||
dst_port: number
|
||||
protocol: string
|
||||
state: string
|
||||
}
|
||||
|
||||
export const getSecurityAlerts = () =>
|
||||
api.get<APIResponse<SecurityAlert[]>>('/security/alerts')
|
||||
|
||||
@@ -531,11 +556,17 @@ export const checkContainerSecurity = (containerName: string) =>
|
||||
api.post<APIResponse>('/security/check', { container_name: containerName })
|
||||
|
||||
export const getSecurityLogs = (containerName: string) =>
|
||||
api.get<APIResponse>('/security/logs', { params: { container: containerName } })
|
||||
api.get<APIResponse<SecurityLog[]>>('/security/logs', { params: { container: containerName } })
|
||||
|
||||
export const getSecuritySummary = () =>
|
||||
api.get<APIResponse<SecuritySummary>>('/security/summary')
|
||||
|
||||
export const getSecuritySettings = () =>
|
||||
api.get<APIResponse<SecuritySettings>>('/security/settings')
|
||||
|
||||
export const updateSecuritySettings = (data: SecuritySettings) =>
|
||||
api.put<APIResponse<SecuritySettings>>('/security/settings', data)
|
||||
|
||||
export const createWebSSHTicket = (containerName: string) =>
|
||||
api.post<APIResponse<{ ticket: string }>>('/ssh-ticket', { container_name: containerName })
|
||||
|
||||
|
||||
+500
-86
@@ -5,17 +5,36 @@ REPO="${CLICD_REPO:-MengMengCode/CLICD}"
|
||||
CLICD_INSTALL_VERSION="${CLICD_VERSION:-latest}"
|
||||
ASSET="clicd-linux-amd64.tar.gz"
|
||||
ACTION="${1:-install}"
|
||||
ACTION_CONFIRM="${2:-}"
|
||||
ISSUE_URL="https://github.com/${REPO}/issues"
|
||||
LOG_FILE="${CLICD_LOG_FILE:-/var/log/clicd-install.log}"
|
||||
|
||||
echo "====================================="
|
||||
echo " CLICD Installer"
|
||||
echo " CLICD 中文安装/卸载脚本"
|
||||
echo "====================================="
|
||||
|
||||
write_log_file() {
|
||||
if [ "$(id -u 2>/dev/null || echo 1)" = "0" ]; then
|
||||
printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null || true)" "$*" >> "$LOG_FILE" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
log() {
|
||||
echo "[clicd] $*"
|
||||
write_log_file "[clicd] $*"
|
||||
}
|
||||
|
||||
warn() {
|
||||
echo "[clicd][警告] $*" >&2
|
||||
write_log_file "[警告] $*"
|
||||
}
|
||||
|
||||
die() {
|
||||
echo "ERROR: $*" >&2
|
||||
echo "[clicd][错误] $*" >&2
|
||||
write_log_file "[错误] $*"
|
||||
echo "" >&2
|
||||
echo "安装/卸载未完成。请查看日志:$LOG_FILE" >&2
|
||||
echo "如果你确认这是程序问题,请提交 issue:$ISSUE_URL" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -31,13 +50,70 @@ is_openrc() {
|
||||
has_cmd rc-service && has_cmd rc-update
|
||||
}
|
||||
|
||||
run_step() {
|
||||
step_name="$1"
|
||||
shift
|
||||
log "开始:$step_name"
|
||||
if "$@" >> "$LOG_FILE" 2>&1; then
|
||||
log "完成:$step_name"
|
||||
return 0
|
||||
fi
|
||||
rc="$?"
|
||||
echo "" >&2
|
||||
echo "[clicd][错误] 步骤失败:$step_name,退出码:$rc" >&2
|
||||
echo "[clicd][错误] 最近 80 行日志:$LOG_FILE" >&2
|
||||
tail -n 80 "$LOG_FILE" >&2 2>/dev/null || true
|
||||
echo "" >&2
|
||||
echo "请将上述日志和系统信息提交到:$ISSUE_URL" >&2
|
||||
exit "$rc"
|
||||
}
|
||||
|
||||
check_os_compatibility() {
|
||||
log "系统检测:ID=${OS_ID} ID_LIKE=${OS_LIKE} ARCH=$(uname -m 2>/dev/null || echo unknown)"
|
||||
case "$(uname -m 2>/dev/null || echo unknown)" in
|
||||
x86_64|amd64)
|
||||
;;
|
||||
*)
|
||||
die "当前安装包仅支持 x86_64/amd64,当前架构:$(uname -m 2>/dev/null || echo unknown)。"
|
||||
;;
|
||||
esac
|
||||
if ! is_systemd && ! is_openrc; then
|
||||
die "未检测到 systemd 或 OpenRC,无法安装服务。"
|
||||
fi
|
||||
case "$OS_ID" in
|
||||
ubuntu|debian|alpine|centos|rhel|rocky|almalinux|fedora)
|
||||
;;
|
||||
*)
|
||||
if ! has_cmd apt-get && ! has_cmd apk && ! has_cmd dnf && ! has_cmd yum; then
|
||||
die "暂不支持当前 Linux 发行版:${OS_ID} ${OS_LIKE}。请提交 issue 并附上 /etc/os-release。"
|
||||
fi
|
||||
warn "发行版 ${OS_ID} 不在主要支持列表,将按检测到的软件包管理器尝试安装。"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
check_storage_compatibility() {
|
||||
root_fs="$(findmnt -no FSTYPE / 2>/dev/null || echo unknown)"
|
||||
avail_kb="$(df -Pk / 2>/dev/null | awk 'NR==2 {print $4}' || echo 0)"
|
||||
log "存储检测:根文件系统=${root_fs} 可用空间=${avail_kb}KB"
|
||||
if [ "${avail_kb:-0}" -lt 5242880 ]; then
|
||||
warn "根分区可用空间低于 5GB,下载镜像或创建 KVM/LXC 时可能失败。"
|
||||
fi
|
||||
}
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "Please run as root: sudo ./install.sh"
|
||||
echo "Or: curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | sudo sh"
|
||||
echo "Uninstall: curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | sudo sh -s -- uninstall"
|
||||
echo "请使用 root 权限运行:sudo ./install.sh"
|
||||
echo "或执行:curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | sudo sh"
|
||||
echo "卸载:curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | sudo sh -s -- uninstall"
|
||||
echo "问题反馈:$ISSUE_URL"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
: > "$LOG_FILE" 2>/dev/null || true
|
||||
log "日志文件:$LOG_FILE"
|
||||
log "仓库地址:https://github.com/${REPO}"
|
||||
log "问题反馈:$ISSUE_URL"
|
||||
|
||||
OS_ID="unknown"
|
||||
OS_LIKE=""
|
||||
if [ -r /etc/os-release ]; then
|
||||
@@ -48,17 +124,21 @@ fi
|
||||
|
||||
usage() {
|
||||
cat << EOF
|
||||
Usage:
|
||||
./install.sh
|
||||
./install.sh uninstall
|
||||
用法:
|
||||
./install.sh 安装或升级 CLICD
|
||||
./install.sh uninstall 卸载 CLICD(会删除容器、虚拟机、镜像缓存和配置数据)
|
||||
|
||||
Environment:
|
||||
CLICD_REPO=owner/repo
|
||||
CLICD_VERSION=latest|v1.0.0
|
||||
环境变量:
|
||||
CLICD_REPO=owner/repo 默认:${REPO}
|
||||
CLICD_VERSION=latest|v1.0.0 默认:latest
|
||||
CLICD_LOG_FILE=/path/file.log 默认:${LOG_FILE}
|
||||
|
||||
Examples:
|
||||
示例:
|
||||
curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | sudo sh
|
||||
curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | sudo sh -s -- uninstall
|
||||
|
||||
日志:${LOG_FILE}
|
||||
问题反馈:${ISSUE_URL}
|
||||
EOF
|
||||
}
|
||||
|
||||
@@ -68,7 +148,7 @@ remove_path() {
|
||||
return
|
||||
fi
|
||||
rm -rf "$path"
|
||||
log "Removed $path"
|
||||
log "已删除 $path"
|
||||
}
|
||||
|
||||
unmount_path_tree() {
|
||||
@@ -125,21 +205,198 @@ remove_lxc_container_dir() {
|
||||
detach_container_loop_devices "$container_dir"
|
||||
|
||||
if rm -rf "$container_dir" >/dev/null 2>&1; then
|
||||
log "Removed $container_dir"
|
||||
log "已删除 $container_dir"
|
||||
return
|
||||
fi
|
||||
|
||||
log "Retrying removal after terminating processes using $container_dir..."
|
||||
log "检测到 $container_dir 被占用,终止占用进程后重试删除..."
|
||||
kill_path_users "$container_dir/rootfs"
|
||||
kill_path_users "$container_dir"
|
||||
unmount_path_tree "$container_dir"
|
||||
detach_container_loop_devices "$container_dir"
|
||||
rm -rf "$container_dir"
|
||||
log "Removed $container_dir"
|
||||
log "已删除 $container_dir"
|
||||
}
|
||||
|
||||
remove_kvm_domain() {
|
||||
domain="$1"
|
||||
case "$domain" in
|
||||
vm-[0-9]*)
|
||||
;;
|
||||
*)
|
||||
return
|
||||
;;
|
||||
esac
|
||||
suffix="${domain#vm-}"
|
||||
case "$suffix" in
|
||||
""|*[!0-9]*)
|
||||
return
|
||||
;;
|
||||
esac
|
||||
if [ ! -d "/var/lib/clicd/kvm/instances/$domain" ] &&
|
||||
! virsh dumpxml "$domain" 2>/dev/null | grep -q '/var/lib/clicd/kvm/'; then
|
||||
return
|
||||
fi
|
||||
|
||||
log "正在删除 KVM 虚拟机域 $domain..."
|
||||
virsh destroy "$domain" >/dev/null 2>&1 || true
|
||||
virsh undefine "$domain" --remove-all-storage --nvram >/dev/null 2>&1 ||
|
||||
virsh undefine "$domain" --nvram >/dev/null 2>&1 ||
|
||||
virsh undefine "$domain" >/dev/null 2>&1 ||
|
||||
true
|
||||
}
|
||||
|
||||
destroy_clicd_kvm_domains() {
|
||||
if ! has_cmd virsh; then
|
||||
return
|
||||
fi
|
||||
|
||||
log "正在销毁 CLICD 创建的 KVM 虚拟机..."
|
||||
virsh list --all --name 2>/dev/null | while IFS= read -r domain; do
|
||||
[ -n "$domain" ] || continue
|
||||
remove_kvm_domain "$domain"
|
||||
done
|
||||
}
|
||||
|
||||
delete_iptables_lines() {
|
||||
table="$1"
|
||||
chain="$2"
|
||||
pattern="$3"
|
||||
if ! has_cmd iptables; then
|
||||
return
|
||||
fi
|
||||
|
||||
while :; do
|
||||
line="$(iptables -t "$table" -L "$chain" -n --line-numbers 2>/dev/null | awk -v pat="$pattern" '$0 ~ pat {print $1; exit}')"
|
||||
[ -n "$line" ] || break
|
||||
iptables -t "$table" -D "$chain" "$line" >/dev/null 2>&1 || break
|
||||
done
|
||||
}
|
||||
|
||||
delete_iptables_rule() {
|
||||
table="$1"
|
||||
shift
|
||||
if ! has_cmd iptables; then
|
||||
return
|
||||
fi
|
||||
|
||||
while iptables -t "$table" -D "$@" >/dev/null 2>&1; do
|
||||
:
|
||||
done
|
||||
}
|
||||
|
||||
delete_filter_rule() {
|
||||
if ! has_cmd iptables; then
|
||||
return
|
||||
fi
|
||||
|
||||
while iptables -D "$@" >/dev/null 2>&1; do
|
||||
:
|
||||
done
|
||||
}
|
||||
|
||||
delete_ip6tables_bridge_rules() {
|
||||
if ! has_cmd ip6tables; then
|
||||
return
|
||||
fi
|
||||
|
||||
for bridge in lxcbr0 virbr0; do
|
||||
while :; do
|
||||
rule="$(ip6tables -S FORWARD 2>/dev/null | grep -- "$bridge" | sed 's/^-A /-D /' | head -n 1)"
|
||||
[ -n "$rule" ] || break
|
||||
# shellcheck disable=SC2086
|
||||
ip6tables $rule >/dev/null 2>&1 || break
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
cleanup_clicd_networking() {
|
||||
log "正在清理 CLICD 防火墙和网桥规则..."
|
||||
delete_iptables_lines nat PREROUTING 'clicd-'
|
||||
delete_iptables_rule nat POSTROUTING -s 10.0.3.0/24 -o eth+ -j MASQUERADE
|
||||
delete_iptables_rule nat POSTROUTING -s 192.168.122.0/24 -o eth+ -j MASQUERADE
|
||||
|
||||
for bridge in lxcbr0 virbr0; do
|
||||
delete_filter_rule FORWARD -i "$bridge" -j ACCEPT
|
||||
delete_filter_rule FORWARD -o "$bridge" -j ACCEPT
|
||||
delete_filter_rule FORWARD -i "$bridge" -o "$bridge" -j ACCEPT
|
||||
done
|
||||
delete_ip6tables_bridge_rules
|
||||
}
|
||||
|
||||
remove_clicd_host_hooks() {
|
||||
if has_cmd systemctl; then
|
||||
systemctl stop clicd-kvm-ipv6.service >/dev/null 2>&1 || true
|
||||
systemctl disable clicd-kvm-ipv6.service >/dev/null 2>&1 || true
|
||||
fi
|
||||
if has_cmd rc-service; then
|
||||
rc-service clicd-kvm-ipv6 stop >/dev/null 2>&1 || true
|
||||
fi
|
||||
if has_cmd rc-update; then
|
||||
rc-update del clicd-kvm-ipv6 default >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
remove_path /usr/local/sbin/clicd-kvm-ipv6-init
|
||||
remove_path /etc/systemd/system/clicd-kvm-ipv6.service
|
||||
remove_path /etc/local.d/clicd-kvm-ipv6.start
|
||||
remove_path /etc/network/if-up.d/clicd-kvm-ipv6
|
||||
}
|
||||
|
||||
remove_clicd_quota_records() {
|
||||
for file in /etc/projects /etc/projid; do
|
||||
[ -f "$file" ] || continue
|
||||
tmp="${file}.clicd-clean.$$"
|
||||
grep -v 'clicd-' "$file" > "$tmp" || true
|
||||
cat "$tmp" > "$file"
|
||||
rm -f "$tmp"
|
||||
log "已清理 $file 中的 CLICD 配额记录"
|
||||
done
|
||||
}
|
||||
|
||||
remove_clicd_tmp_files() {
|
||||
current_dir="$(pwd -P 2>/dev/null || pwd)"
|
||||
for path in /tmp/clicd-* /tmp/clicd.*; do
|
||||
[ -e "$path" ] || [ -L "$path" ] || continue
|
||||
abs_path="$(cd "$(dirname "$path")" 2>/dev/null && pwd -P)/$(basename "$path")"
|
||||
if [ "$abs_path" = "$current_dir" ]; then
|
||||
log "跳过当前安装目录 $path,避免中断后续安装步骤。"
|
||||
continue
|
||||
fi
|
||||
rm -rf "$path"
|
||||
log "已删除 $path"
|
||||
done
|
||||
}
|
||||
|
||||
remove_clicd_swapfile() {
|
||||
if [ ! -e /swapfile ]; then
|
||||
return
|
||||
fi
|
||||
swapoff /swapfile >/dev/null 2>&1 || true
|
||||
remove_path /swapfile
|
||||
}
|
||||
|
||||
|
||||
confirm_uninstall() {
|
||||
if [ "${CLICD_UNINSTALL_CONFIRM:-}" = "1" ] || [ "${CLICD_UNINSTALL_CONFIRM:-}" = "yes" ] || [ "$ACTION_CONFIRM" = "--yes" ] || [ "$ACTION_CONFIRM" = "-y" ]; then
|
||||
return
|
||||
fi
|
||||
echo ""
|
||||
echo "[clicd][警告] 卸载会停止并删除 CLICD 服务、配置数据库、CLICD 创建的 LXC/KVM 实例和缓存数据。" >&2
|
||||
echo "[clicd][警告] 为避免误删生产数据,脚本只会删除名称形如 ct-数字 的 LXC 容器和 vm-数字 的 KVM 域。" >&2
|
||||
echo "如需确认卸载,请输入:YES" >&2
|
||||
if [ -t 0 ]; then
|
||||
read answer
|
||||
else
|
||||
answer=""
|
||||
fi
|
||||
if [ "$answer" != "YES" ]; then
|
||||
die "已取消卸载。如需非交互卸载,请设置 CLICD_UNINSTALL_CONFIRM=1。"
|
||||
fi
|
||||
}
|
||||
|
||||
uninstall_clicd() {
|
||||
log "Uninstalling CLICD..."
|
||||
confirm_uninstall
|
||||
log "正在卸载 CLICD..."
|
||||
|
||||
if has_cmd systemctl; then
|
||||
systemctl stop clicd >/dev/null 2>&1 || true
|
||||
@@ -153,11 +410,15 @@ uninstall_clicd() {
|
||||
rc-update del clicd default >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
log "Destroying LXC containers under /var/lib/lxc..."
|
||||
for container_dir in /var/lib/lxc/*; do
|
||||
log "正在删除 CLICD 创建的 LXC 容器(/var/lib/lxc/ct-数字)..."
|
||||
for container_dir in /var/lib/lxc/ct-[0-9]*; do
|
||||
[ -d "$container_dir" ] || continue
|
||||
remove_lxc_container_dir "$container_dir"
|
||||
done
|
||||
destroy_clicd_kvm_domains
|
||||
cleanup_clicd_networking
|
||||
remove_clicd_host_hooks
|
||||
remove_clicd_quota_records
|
||||
|
||||
remove_path /etc/systemd/system/clicd.service
|
||||
remove_path /etc/init.d/clicd
|
||||
@@ -166,9 +427,14 @@ uninstall_clicd() {
|
||||
remove_path /var/log/clicd.log
|
||||
remove_path /var/log/clicd.err
|
||||
remove_path /root/.clicd
|
||||
unmount_path_tree /var/lib/lxc
|
||||
remove_path /var/lib/lxc
|
||||
remove_path /var/cache/lxc
|
||||
# /var/lib/lxc 可能包含非 CLICD 容器,生产环境不整体删除。
|
||||
unmount_path_tree /var/lib/clicd
|
||||
remove_path /var/lib/clicd
|
||||
# /var/cache/lxc 是 LXC 全局镜像缓存,可能被其他工具复用,生产环境不整体删除。
|
||||
remove_path /var/cache/clicd
|
||||
warn "保留 /root/clicd-backups,避免误删部署/回滚备份。确认不需要后可手动删除。"
|
||||
remove_clicd_tmp_files
|
||||
remove_clicd_swapfile
|
||||
|
||||
if has_cmd systemctl; then
|
||||
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||
@@ -180,9 +446,13 @@ uninstall_clicd() {
|
||||
|
||||
echo ""
|
||||
echo "====================================="
|
||||
echo " CLICD Uninstalled"
|
||||
echo " CLICD 卸载完成"
|
||||
echo "====================================="
|
||||
echo " Removed service, binary, config, containers, and LXC image cache."
|
||||
echo " 已删除服务、二进制、SQLite/配置数据、CLICD LXC/KVM 实例、"
|
||||
echo " CLICD 镜像缓存、防火墙规则、主机钩子、配额记录和临时文件。"
|
||||
echo " 已保留 /root/clicd-backups 和 LXC 全局缓存,避免误删生产备份/共享镜像。"
|
||||
echo " 日志:$LOG_FILE"
|
||||
echo " 问题反馈:$ISSUE_URL"
|
||||
echo "====================================="
|
||||
}
|
||||
|
||||
@@ -198,12 +468,12 @@ case "$ACTION" in
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
die "Unknown action: $ACTION"
|
||||
die "未知操作:$ACTION"
|
||||
;;
|
||||
esac
|
||||
|
||||
install_apk() {
|
||||
log "Installing dependencies with apk..."
|
||||
log "正在使用 apk 安装依赖..."
|
||||
apk update
|
||||
apk add --no-cache \
|
||||
ca-certificates \
|
||||
@@ -220,15 +490,22 @@ install_apk() {
|
||||
bridge-utils \
|
||||
iproute2 \
|
||||
iptables \
|
||||
dnsmasq
|
||||
dnsmasq \
|
||||
dbus \
|
||||
qemu-system-x86_64 \
|
||||
qemu-img \
|
||||
libvirt \
|
||||
libvirt-daemon \
|
||||
libvirt-client \
|
||||
libvirt-qemu
|
||||
|
||||
for pkg in lxcfs shadow conntrack-tools quota-tools e2fsprogs xfsprogs; do
|
||||
apk add --no-cache "$pkg" >/dev/null 2>&1 || log "Optional package not installed: $pkg"
|
||||
for pkg in lxcfs shadow conntrack-tools quota-tools e2fsprogs xfsprogs cloud-utils genisoimage xorriso; do
|
||||
apk add --no-cache "$pkg" >/dev/null 2>&1 || warn "可选依赖未安装:$pkg"
|
||||
done
|
||||
}
|
||||
|
||||
install_apt() {
|
||||
log "Installing dependencies with apt..."
|
||||
log "正在使用 apt 安装依赖..."
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y \
|
||||
@@ -251,10 +528,14 @@ install_apt() {
|
||||
xfsprogs \
|
||||
dnsmasq-base \
|
||||
qemu-kvm \
|
||||
qemu-utils \
|
||||
libvirt-daemon-system \
|
||||
libvirt-clients \
|
||||
cloud-image-utils \
|
||||
genisoimage \
|
||||
xorriso \
|
||||
virtinst \
|
||||
virt-manager
|
||||
ovmf
|
||||
}
|
||||
|
||||
enable_el_repos() {
|
||||
@@ -271,7 +552,7 @@ enable_el_repos() {
|
||||
}
|
||||
|
||||
install_dnf() {
|
||||
log "Installing dependencies with dnf..."
|
||||
log "正在使用 dnf 安装依赖..."
|
||||
enable_el_repos
|
||||
dnf install -y \
|
||||
ca-certificates \
|
||||
@@ -290,13 +571,23 @@ install_dnf() {
|
||||
quota \
|
||||
e2fsprogs \
|
||||
xfsprogs \
|
||||
dnsmasq
|
||||
dnsmasq \
|
||||
qemu-kvm \
|
||||
qemu-img \
|
||||
libvirt \
|
||||
libvirt-daemon-kvm \
|
||||
libvirt-client \
|
||||
virt-install \
|
||||
cloud-utils \
|
||||
genisoimage
|
||||
|
||||
dnf install -y lxcfs >/dev/null 2>&1 || log "Optional package not installed: lxcfs"
|
||||
for pkg in lxcfs xorriso edk2-ovmf; do
|
||||
dnf install -y "$pkg" >/dev/null 2>&1 || warn "可选依赖未安装:$pkg"
|
||||
done
|
||||
}
|
||||
|
||||
install_yum() {
|
||||
log "Installing dependencies with yum..."
|
||||
log "正在使用 yum 安装依赖..."
|
||||
enable_el_repos
|
||||
yum install -y \
|
||||
ca-certificates \
|
||||
@@ -315,9 +606,19 @@ install_yum() {
|
||||
quota \
|
||||
e2fsprogs \
|
||||
xfsprogs \
|
||||
dnsmasq
|
||||
dnsmasq \
|
||||
qemu-kvm \
|
||||
qemu-img \
|
||||
libvirt \
|
||||
libvirt-daemon-kvm \
|
||||
libvirt-client \
|
||||
virt-install \
|
||||
cloud-utils \
|
||||
genisoimage
|
||||
|
||||
yum install -y lxcfs >/dev/null 2>&1 || log "Optional package not installed: lxcfs"
|
||||
for pkg in lxcfs xorriso edk2-ovmf; do
|
||||
yum install -y "$pkg" >/dev/null 2>&1 || warn "可选依赖未安装:$pkg"
|
||||
done
|
||||
}
|
||||
|
||||
install_dependencies() {
|
||||
@@ -334,7 +635,7 @@ install_dependencies() {
|
||||
elif has_cmd yum; then
|
||||
install_yum
|
||||
else
|
||||
die "dnf/yum not found on $OS_ID"
|
||||
die "当前系统 $OS_ID 未找到 dnf/yum,无法安装依赖。"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
@@ -347,18 +648,27 @@ install_dependencies() {
|
||||
elif has_cmd yum; then
|
||||
install_yum
|
||||
else
|
||||
die "Unsupported Linux distribution: ${OS_ID} ${OS_LIKE}"
|
||||
die "暂不支持当前 Linux 发行版:${OS_ID} ${OS_LIKE}。请提交 issue 并附上 /etc/os-release。"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
has_cmd lxc-create || die "lxc-create is still missing after dependency installation."
|
||||
has_cmd iptables || die "iptables is still missing after dependency installation."
|
||||
has_cmd ip || die "iproute2/ip command is still missing after dependency installation."
|
||||
has_cmd lxc-create || die "依赖安装后仍未找到 lxc-create,请检查 LXC 软件源/安装日志。"
|
||||
has_cmd iptables || die "依赖安装后仍未找到 iptables,请检查系统网络工具包。"
|
||||
has_cmd ip || die "依赖安装后仍未找到 ip 命令,请检查 iproute2 安装。"
|
||||
has_cmd virsh || die "依赖安装后仍未找到 virsh,请检查 libvirt-client/libvirt-clients 安装。"
|
||||
has_cmd qemu-img || die "依赖安装后仍未找到 qemu-img,请检查 qemu-utils/qemu-img 安装。"
|
||||
has_cmd cloud-localds || die "依赖安装后仍未找到 cloud-localds,请检查 cloud-image-utils/cloud-utils 安装。"
|
||||
if ! has_cmd genisoimage && ! has_cmd mkisofs && ! has_cmd xorriso; then
|
||||
die "Windows KVM 初始化需要 genisoimage、mkisofs 或 xorriso 中任意一个。"
|
||||
fi
|
||||
if [ ! -e /dev/kvm ]; then
|
||||
warn "未检测到 /dev/kvm。LXC 可用,但 KVM 虚拟机需要硬件虚拟化或嵌套虚拟化。"
|
||||
fi
|
||||
}
|
||||
|
||||
configure_kernel_networking() {
|
||||
log "Enabling kernel forwarding settings..."
|
||||
log "正在启用内核转发配置..."
|
||||
cat > /etc/sysctl.d/99-clicd.conf << 'EOF'
|
||||
net.ipv4.ip_forward = 1
|
||||
net.ipv6.conf.all.forwarding = 1
|
||||
@@ -370,14 +680,43 @@ EOF
|
||||
sysctl --system >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
setup_lxc_services() {
|
||||
log "Configuring LXC services..."
|
||||
systemd_unit_exists() {
|
||||
unit="$1"
|
||||
systemctl list-unit-files "$unit" >/dev/null 2>&1 || [ -e "/etc/systemd/system/$unit" ] || [ -e "/usr/lib/systemd/system/$unit" ] || [ -e "/lib/systemd/system/$unit" ]
|
||||
}
|
||||
|
||||
systemd_enable_now_if_exists() {
|
||||
unit="$1"
|
||||
if systemd_unit_exists "$unit"; then
|
||||
systemctl enable --now "$unit" >/dev/null 2>&1 || warn "服务 $unit 启动失败,将继续安装并在运行时降级处理。"
|
||||
return
|
||||
fi
|
||||
log "未检测到 systemd 单元 $unit,跳过。"
|
||||
}
|
||||
|
||||
systemd_existing_units() {
|
||||
for unit in "$@"; do
|
||||
if systemd_unit_exists "$unit"; then
|
||||
printf ' %s' "$unit"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
setup_runtime_services() {
|
||||
log "正在配置 LXC 和 KVM 服务..."
|
||||
|
||||
if is_systemd; then
|
||||
systemctl enable --now lxcfs >/dev/null 2>&1 || true
|
||||
systemctl enable --now lxc-net >/dev/null 2>&1 || true
|
||||
systemctl enable --now lxc >/dev/null 2>&1 || true
|
||||
systemctl enable --now libvirtd >/dev/null 2>&1 || true
|
||||
systemd_enable_now_if_exists lxcfs.service
|
||||
systemd_enable_now_if_exists lxc-net.service
|
||||
systemd_enable_now_if_exists lxc.service
|
||||
if systemd_unit_exists libvirtd.service; then
|
||||
systemd_enable_now_if_exists libvirtd.service
|
||||
log "检测到 libvirt 传统 libvirtd 服务,已使用 libvirtd 模式。"
|
||||
else
|
||||
systemd_enable_now_if_exists virtqemud.service
|
||||
systemd_enable_now_if_exists virtqemud.socket
|
||||
fi
|
||||
systemd_enable_now_if_exists virtlogd.socket
|
||||
return
|
||||
fi
|
||||
|
||||
@@ -388,41 +727,102 @@ setup_lxc_services() {
|
||||
rc-service lxc start >/dev/null 2>&1 || true
|
||||
rc-update add lxcfs default >/dev/null 2>&1 || true
|
||||
rc-service lxcfs start >/dev/null 2>&1 || true
|
||||
rc-update add dbus default >/dev/null 2>&1 || true
|
||||
rc-service dbus start >/dev/null 2>&1 || true
|
||||
rc-update add libvirtd default >/dev/null 2>&1 || true
|
||||
rc-service libvirtd start >/dev/null 2>&1 || true
|
||||
rc-update add virtlogd default >/dev/null 2>&1 || true
|
||||
rc-service virtlogd start >/dev/null 2>&1 || true
|
||||
return
|
||||
fi
|
||||
|
||||
die "No supported service manager found. CLICD supports systemd or OpenRC."
|
||||
die "未检测到支持的服务管理器。CLICD 当前支持 systemd 或 OpenRC。"
|
||||
}
|
||||
|
||||
|
||||
libvirt_network_active() {
|
||||
virsh net-info default 2>/dev/null | awk -F: 'tolower($1) ~ /^[[:space:]]*active[[:space:]]*$/ {gsub(/^[ \t]+|[ \t]+$/, "", $2); print tolower($2)}' | grep -qx yes
|
||||
}
|
||||
|
||||
setup_default_libvirt_network() {
|
||||
if ! has_cmd virsh; then
|
||||
warn "未找到 virsh,跳过 libvirt default NAT 网络检查。"
|
||||
return
|
||||
fi
|
||||
log "正在检查 libvirt default NAT 网络..."
|
||||
if ! virsh net-info default >/dev/null 2>&1; then
|
||||
net_xml="$(mktemp /tmp/clicd-default-net.XXXXXX.xml)"
|
||||
cat > "$net_xml" << 'EOF'
|
||||
<network>
|
||||
<name>default</name>
|
||||
<bridge name='virbr0'/>
|
||||
<forward mode='nat'/>
|
||||
<ip address='192.168.122.1' netmask='255.255.255.0'>
|
||||
<dhcp>
|
||||
<range start='192.168.122.2' end='192.168.122.254'/>
|
||||
</dhcp>
|
||||
</ip>
|
||||
</network>
|
||||
EOF
|
||||
virsh net-define "$net_xml"
|
||||
rm -f "$net_xml"
|
||||
fi
|
||||
if ! libvirt_network_active; then
|
||||
virsh net-start default
|
||||
fi
|
||||
virsh net-autostart default >/dev/null
|
||||
if ! libvirt_network_active; then
|
||||
die "libvirt default 网络仍未启动。请执行 virsh net-info default 查看详情。"
|
||||
fi
|
||||
log "libvirt default NAT 网络已启用。"
|
||||
}
|
||||
|
||||
setup_subids() {
|
||||
log "Setting up subordinate UID/GID ranges..."
|
||||
log "正在配置 subordinate UID/GID 范围..."
|
||||
touch /etc/subuid /etc/subgid
|
||||
grep -q '^root:' /etc/subuid 2>/dev/null || echo 'root:100000:65536' >> /etc/subuid
|
||||
grep -q '^root:' /etc/subgid 2>/dev/null || echo 'root:100000:65536' >> /etc/subgid
|
||||
}
|
||||
|
||||
configure_lxc_storage_access() {
|
||||
log "Configuring LXC storage directory permissions..."
|
||||
mkdir -p /var/lib/lxc
|
||||
chmod 755 /var/lib/lxc
|
||||
}
|
||||
|
||||
try_enable_project_quota() {
|
||||
root_src="$(findmnt -no SOURCE / 2>/dev/null || true)"
|
||||
root_fs="$(findmnt -no FSTYPE / 2>/dev/null || true)"
|
||||
|
||||
if [ "$root_fs" != "ext4" ] || [ -z "$root_src" ] || [ ! -b "$root_src" ]; then
|
||||
log "Project quota auto-enable skipped for root filesystem: ${root_fs:-unknown}"
|
||||
case "$root_fs" in
|
||||
ext4)
|
||||
;;
|
||||
xfs|btrfs|zfs|overlay|unknown|"")
|
||||
log "根文件系统 ${root_fs:-unknown} 不需要/不适合自动启用 ext4 project quota,CLICD 将使用兼容磁盘限制模式。"
|
||||
return
|
||||
;;
|
||||
*)
|
||||
log "根文件系统 ${root_fs:-unknown} 不在自动 project quota 支持范围,CLICD 将使用兼容磁盘限制模式。"
|
||||
return
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$root_src" ] || [ ! -b "$root_src" ]; then
|
||||
log "根分区来源 ${root_src:-unknown} 不是块设备,跳过 project quota 自动检查,CLICD 将使用兼容磁盘限制模式。"
|
||||
return
|
||||
fi
|
||||
|
||||
if ! has_cmd tune2fs; then
|
||||
log "Project quota auto-enable skipped because tune2fs is unavailable."
|
||||
log "未找到 tune2fs,跳过 project quota 检查,CLICD 将使用兼容磁盘限制模式。"
|
||||
return
|
||||
fi
|
||||
|
||||
if tune2fs -l "$root_src" 2>/dev/null | grep -q 'project'; then
|
||||
log "Ext4 project quota support already appears to be enabled."
|
||||
log "检测到 ext4 project quota 已可用。"
|
||||
return
|
||||
fi
|
||||
|
||||
log "Ext4 project quota is not enabled. Disk limits will fall back to loopback images."
|
||||
log "ext4 project quota 未启用,CLICD 将自动回退到 loopback 镜像磁盘限制模式。"
|
||||
}
|
||||
|
||||
download_release_if_needed() {
|
||||
@@ -436,8 +836,8 @@ download_release_if_needed() {
|
||||
download_url="https://github.com/${REPO}/releases/download/${CLICD_INSTALL_VERSION}/${ASSET}"
|
||||
fi
|
||||
|
||||
log "clicd binary not found in current directory."
|
||||
log "Downloading release package: ${download_url}"
|
||||
log "当前目录未找到 clicd 二进制,将下载发行版包。"
|
||||
log "正在下载发行版包:${download_url}"
|
||||
|
||||
tmp_dir="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp_dir"' 0
|
||||
@@ -447,12 +847,12 @@ download_release_if_needed() {
|
||||
elif has_cmd wget; then
|
||||
wget -O "$tmp_dir/$ASSET" "$download_url"
|
||||
else
|
||||
die "curl or wget is required to download the release package."
|
||||
die "下载发行版包需要 curl 或 wget。"
|
||||
fi
|
||||
|
||||
tar -xzf "$tmp_dir/$ASSET" -C "$tmp_dir"
|
||||
cd "$tmp_dir/clicd-linux-amd64"
|
||||
[ -f "./clicd" ] || die "Downloaded release package did not contain clicd."
|
||||
[ -f "./clicd" ] || die "下载的发行版包中未找到 clicd 二进制。"
|
||||
}
|
||||
|
||||
install_binary() {
|
||||
@@ -468,20 +868,28 @@ install_binary() {
|
||||
chmod +x "$tmp_bin"
|
||||
mv -f "$tmp_bin" /usr/local/bin/clicd
|
||||
chmod +x /usr/local/bin/clicd
|
||||
log "Installed binary: /usr/local/bin/clicd"
|
||||
log "已安装二进制:/usr/local/bin/clicd"
|
||||
}
|
||||
|
||||
install_systemd_service() {
|
||||
cat > /etc/systemd/system/clicd.service << 'EOF'
|
||||
libvirt_after="$(systemd_existing_units libvirtd.service virtqemud.service virtqemud.socket virtlogd.socket)"
|
||||
libvirt_wants="$(systemd_existing_units libvirtd.service virtqemud.socket virtlogd.socket)"
|
||||
lxc_after="$(systemd_existing_units lxc.service lxcfs.service lxc-net.service)"
|
||||
|
||||
cat > /etc/systemd/system/clicd.service << EOF
|
||||
[Unit]
|
||||
Description=CLICD - LXC Container Manager
|
||||
After=network.target lxc.service
|
||||
Description=CLICD - LXC/KVM Container Manager
|
||||
After=network-online.target${lxc_after}${libvirt_after}
|
||||
Wants=network-online.target${libvirt_wants}
|
||||
StartLimitIntervalSec=60
|
||||
StartLimitBurst=10
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/clicd server
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
LimitNOFILE=1048576
|
||||
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
|
||||
[Install]
|
||||
@@ -498,7 +906,7 @@ install_openrc_service() {
|
||||
#!/sbin/openrc-run
|
||||
|
||||
name="CLICD"
|
||||
description="CLICD - LXC Container Manager"
|
||||
description="CLICD - LXC/KVM Container Manager"
|
||||
command="/usr/local/bin/clicd"
|
||||
command_args="server"
|
||||
command_background=true
|
||||
@@ -508,7 +916,7 @@ error_log="/var/log/clicd.err"
|
||||
|
||||
depend() {
|
||||
need net
|
||||
after lxc
|
||||
after lxc libvirtd
|
||||
}
|
||||
EOF
|
||||
|
||||
@@ -518,51 +926,57 @@ EOF
|
||||
}
|
||||
|
||||
install_service() {
|
||||
log "Installing CLICD service..."
|
||||
log "正在安装 CLICD 服务..."
|
||||
|
||||
if is_systemd; then
|
||||
install_systemd_service
|
||||
elif is_openrc; then
|
||||
install_openrc_service
|
||||
else
|
||||
die "No supported service manager found. CLICD supports systemd or OpenRC."
|
||||
die "未检测到支持的服务管理器。CLICD 当前支持 systemd 或 OpenRC。"
|
||||
fi
|
||||
}
|
||||
|
||||
print_summary() {
|
||||
echo ""
|
||||
echo "====================================="
|
||||
echo " Installation Complete"
|
||||
echo " 安装完成"
|
||||
echo "====================================="
|
||||
echo " Web: http://YOUR_SERVER_IP:8999"
|
||||
echo " Binary: /usr/local/bin/clicd"
|
||||
echo " Web 面板:http://YOUR_SERVER_IP:8999"
|
||||
echo " 二进制:/usr/local/bin/clicd"
|
||||
echo " 安装日志:$LOG_FILE"
|
||||
echo " 问题反馈:$ISSUE_URL"
|
||||
if is_systemd; then
|
||||
echo " Service: systemctl {start|stop|restart|status} clicd"
|
||||
echo " Logs: journalctl -u clicd -f"
|
||||
echo " 服务:systemctl {start|stop|restart|status} clicd"
|
||||
echo " 运行日志:journalctl -u clicd -f"
|
||||
elif is_openrc; then
|
||||
echo " Service: rc-service clicd {start|stop|restart|status}"
|
||||
echo " Logs: tail -f /var/log/clicd.log /var/log/clicd.err"
|
||||
echo " 服务:rc-service clicd {start|stop|restart|status}"
|
||||
echo " 运行日志:tail -f /var/log/clicd.log /var/log/clicd.err"
|
||||
fi
|
||||
echo "====================================="
|
||||
echo ""
|
||||
echo "Initial credentials, if this was the first run:"
|
||||
echo "首次安装时的初始账号信息:"
|
||||
if is_systemd; then
|
||||
journalctl -u clicd --no-pager -n 80 | grep -E "Username:|Password:" || true
|
||||
else
|
||||
grep -E "Username:|Password:" /var/log/clicd.log /var/log/clicd.err 2>/dev/null || true
|
||||
fi
|
||||
echo ""
|
||||
echo "If no password is shown, this server already had /root/.clicd/config.json."
|
||||
echo "The existing admin password cannot be recovered from the bcrypt hash."
|
||||
echo "如果没有显示密码,说明服务器已有 /root/.clicd/config.db。"
|
||||
echo "已有管理员密码使用 bcrypt 存储,无法反查;请使用面板内修改密码或重置配置。"
|
||||
}
|
||||
|
||||
install_dependencies
|
||||
configure_kernel_networking
|
||||
setup_lxc_services
|
||||
setup_subids
|
||||
try_enable_project_quota
|
||||
download_release_if_needed
|
||||
install_binary
|
||||
install_service
|
||||
run_step "兼容性检查" check_os_compatibility
|
||||
run_step "存储环境检查" check_storage_compatibility
|
||||
run_step "安装系统依赖" install_dependencies
|
||||
run_step "配置内核网络参数" configure_kernel_networking
|
||||
run_step "配置运行时服务" setup_runtime_services
|
||||
run_step "配置 libvirt default NAT 网络" setup_default_libvirt_network
|
||||
run_step "配置 UID/GID 映射" setup_subids
|
||||
run_step "Configure LXC storage permissions" configure_lxc_storage_access
|
||||
run_step "检查 project quota" try_enable_project_quota
|
||||
run_step "下载发行版包" download_release_if_needed
|
||||
run_step "安装 CLICD 二进制" install_binary
|
||||
run_step "安装并启动 CLICD 服务" install_service
|
||||
sleep 2
|
||||
print_summary
|
||||
|
||||
Reference in New Issue
Block a user