diff --git a/README.md b/README.md
index 9a87f91..893cf98 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
-CLICD
+CLICD
@@ -73,7 +73,7 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh
| 虚拟化管理 | 在同一个面板里管理 LXC 容器和 KVM 虚拟机,支持创建、重装、开机、关机、重启、删除、重置密码、到期时间和批量操作。 |
| 镜像与模板 | 内置模板和镜像管理,支持 Ubuntu、Debian、Alpine、CentOS、Arch Linux、Fedora、Rocky Linux 等常见发行版,镜像可按需下载、取消、启用、禁用和清理缓存。 |
| 网络能力 | 支持 NAT4 端口配额、随机可用端口、TCP/UDP 端口映射、公网 IPv4 池管理、IPv6 前缀检测、IPv6 状态检查和容器级 IPv6 分配。 |
-| 资源限制 | 支持 CPU、内存、磁盘、Swap、带宽用量、流量重置、流量限制和资源限制管理;容器到期或超额后可自动关机,避免资源和流量失控。 |
+| 资源限制 | 支持 CPU、内存、磁盘、Swap、独立上行/下行带宽、读/写 I/O 限速、流量重置、流量限制和资源限制管理;容器到期或超额后可自动关机,避免资源和流量失控。 |
| 远程控制 | 内置 WebSSH 和 WebVNC 票据访问,用户可以直接在浏览器打开终端或控制台,不需要手动复制连接信息。 |
| 快照能力 | 支持快照总览、容器快照、创建快照、删除快照、恢复快照、计划快照和快照配额。 |
| 安全告警 | 基于 conntrack 做轻量安全检测,可识别端口扫描、横向扫描、爆破倾向、SMTP 滥用、UDP 反射、挖矿端口、代理/VPN/Tor 等风险,并提供安全日志、汇总和设置项。 |
diff --git a/backend/internal/api/firewall.go b/backend/internal/api/firewall.go
index 35af498..a3b27b0 100644
--- a/backend/internal/api/firewall.go
+++ b/backend/internal/api/firewall.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"math/rand"
"net/http"
+ "net/netip"
"strconv"
"strings"
@@ -29,8 +30,9 @@ func getFirewall(w http.ResponseWriter, r *http.Request, id int) {
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
Data: map[string]interface{}{
- "enabled": c.FirewallEnabled,
- "rules": c.FirewallRules,
+ "enabled": c.FirewallEnabled,
+ "default_action": normalizeFirewallDefaultAction(c.FirewallDefaultAction),
+ "rules": c.FirewallRules,
},
})
}
@@ -43,17 +45,32 @@ func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
}
var req struct {
- Enabled *bool `json:"enabled"`
- Rules *[]config.FirewallRule `json:"rules"`
+ Enabled *bool `json:"enabled"`
+ DefaultAction *string `json:"default_action"`
+ Rules *[]config.FirewallRule `json:"rules"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
+ oldEnabled := c.FirewallEnabled
+ oldDefaultAction := c.FirewallDefaultAction
+ oldRules := append([]config.FirewallRule(nil), c.FirewallRules...)
+
if req.Enabled != nil {
c.FirewallEnabled = *req.Enabled
}
+ if req.DefaultAction != nil {
+ action := normalizeFirewallDefaultAction(*req.DefaultAction)
+ if action == "" {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid default action"})
+ return
+ }
+ c.FirewallDefaultAction = action
+ } else if strings.TrimSpace(c.FirewallDefaultAction) == "" {
+ c.FirewallDefaultAction = "DROP"
+ }
if req.Rules != nil {
// Validate and assign IDs to new rules
rules := *req.Rules
@@ -61,9 +78,14 @@ func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
rules[i].Direction = strings.ToLower(strings.TrimSpace(rules[i].Direction))
rules[i].Protocol = strings.ToLower(strings.TrimSpace(rules[i].Protocol))
rules[i].Action = strings.ToUpper(strings.TrimSpace(rules[i].Action))
+ rules[i].Network = normalizeFirewallNetwork(rules[i].Network)
rules[i].SourceIP = strings.TrimSpace(rules[i].SourceIP)
rules[i].Port = strings.TrimSpace(rules[i].Port)
+ if rules[i].Network == "" {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid network"})
+ return
+ }
if rules[i].Direction != "in" && rules[i].Direction != "out" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid direction: " + rules[i].Direction})
return
@@ -76,11 +98,21 @@ func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid action: " + rules[i].Action})
return
}
- if rules[i].ID == "" {
+ if rules[i].SourceIP != "" {
+ if err := validateFirewallIPSpec(rules[i].SourceIP, rules[i].Network); err != nil {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid IP: " + err.Error()})
+ return
+ }
+ }
+ if rules[i].ID == "" || strings.HasPrefix(rules[i].ID, "tmp-") {
rules[i].ID = generateFirewallRuleID()
}
// Validate port spec
if rules[i].Port != "" {
+ if rules[i].Protocol != "tcp" && rules[i].Protocol != "udp" {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Ports are only supported for TCP and UDP rules"})
+ return
+ }
if err := validatePortSpec(rules[i].Port); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid port: " + err.Error()})
return
@@ -90,11 +122,14 @@ func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
c.FirewallRules = rules
}
- config.SaveConfig()
-
// Apply firewall rules to iptables if container is running
if c.Status == "running" {
if err := lxc.ApplyFirewallRules(id); err != nil {
+ c.FirewallEnabled = oldEnabled
+ c.FirewallDefaultAction = oldDefaultAction
+ c.FirewallRules = oldRules
+ _ = lxc.ApplyFirewallRules(id)
+ config.SaveConfig()
jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to apply firewall rules: " + err.Error()})
return
}
@@ -102,28 +137,54 @@ func updateFirewall(w http.ResponseWriter, r *http.Request, id int) {
// If disabled and not running, clean any lingering rules
lxc.CleanFirewallRules(id)
}
+ config.SaveConfig()
jsonResponse(w, http.StatusOK, APIResponse{
Success: true,
Message: "Firewall updated",
Data: map[string]interface{}{
- "enabled": c.FirewallEnabled,
- "rules": c.FirewallRules,
+ "enabled": c.FirewallEnabled,
+ "default_action": normalizeFirewallDefaultAction(c.FirewallDefaultAction),
+ "rules": c.FirewallRules,
},
})
}
+func normalizeFirewallDefaultAction(action string) string {
+ action = strings.ToUpper(strings.TrimSpace(action))
+ if action == "ACCEPT" || action == "DROP" {
+ return action
+ }
+ return ""
+}
+
+func normalizeFirewallNetwork(network string) string {
+ network = strings.ToLower(strings.TrimSpace(network))
+ switch network {
+ case "", "ipv4", "nat4":
+ return "ipv4"
+ case "ipv6":
+ return "ipv6"
+ case "all", "both":
+ return "all"
+ default:
+ return ""
+ }
+}
+
func validatePortSpec(port string) error {
port = strings.TrimSpace(port)
if port == "" {
return nil
}
// Support: "22", "80,443", "8000-9000", "80,443,8000-9000"
+ partCount := 0
for _, part := range strings.Split(port, ",") {
part = strings.TrimSpace(part)
if part == "" {
- continue
+ return &portValidationError{port}
}
+ partCount++
if strings.Contains(part, "-") {
// Range
bounds := strings.SplitN(part, "-", 2)
@@ -135,6 +196,9 @@ func validatePortSpec(port string) error {
if err != nil || hi < 1 || hi > 65535 {
return &portValidationError{part}
}
+ if hi < lo {
+ return &portValidationError{part}
+ }
} else {
p, err := strconv.Atoi(part)
if err != nil || p < 1 || p > 65535 {
@@ -142,9 +206,48 @@ func validatePortSpec(port string) error {
}
}
}
+ if partCount > 15 {
+ return &portValidationError{"too many ports; maximum 15 items per rule"}
+ }
return nil
}
+func validateFirewallIPSpec(value string, network string) error {
+ var addr netip.Addr
+ if strings.Contains(value, "/") {
+ prefix, err := netip.ParsePrefix(value)
+ if err != nil {
+ return err
+ }
+ addr = prefix.Addr()
+ } else {
+ parsed, err := netip.ParseAddr(value)
+ if err != nil {
+ return err
+ }
+ addr = parsed
+ }
+ switch network {
+ case "ipv4":
+ if !addr.Is4() {
+ return &ipValidationError{"IPv4 rule requires an IPv4 address or CIDR: " + value}
+ }
+ case "ipv6":
+ if !addr.Is6() || addr.Is4In6() {
+ return &ipValidationError{"IPv6 rule requires an IPv6 address or CIDR: " + value}
+ }
+ }
+ return nil
+}
+
+type ipValidationError struct {
+ value string
+}
+
+func (e *ipValidationError) Error() string {
+ return e.value
+}
+
type portValidationError struct {
port string
}
diff --git a/backend/internal/api/handlers.go b/backend/internal/api/handlers.go
index c64808a..8ff60e7 100644
--- a/backend/internal/api/handlers.go
+++ b/backend/internal/api/handlers.go
@@ -2,6 +2,8 @@ package api
import (
"encoding/json"
+ "fmt"
+ "io"
"net/http"
"strconv"
"strings"
@@ -210,10 +212,21 @@ func listContainers(w http.ResponseWriter, r *http.Request) {
func createContainer(w http.ResponseWriter, r *http.Request) {
var cfg lxc.ContainerConfig
- if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
return
}
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(body, &cfg); err != nil {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request body"})
+ return
+ }
+ _ = json.Unmarshal(body, &fields)
+ if err := normalizeCreateResourceLimits(&cfg, fields); err != nil {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
+ return
+ }
if cfg.Name == "" {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Container name is required"})
return
@@ -386,10 +399,14 @@ func updateTrafficLimit(w http.ResponseWriter, r *http.Request, id int) {
func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
var req struct {
- VCPU float64 `json:"vcpu"`
- RAMMB int `json:"ram_mb"`
- IOMBps int `json:"io_speed_mbps"`
- BWMbps int `json:"network_bw_mbps"`
+ VCPU *float64 `json:"vcpu"`
+ RAMMB *int `json:"ram_mb"`
+ IOMBps *int `json:"io_speed_mbps"`
+ IOReadMBps *int `json:"io_read_mbps"`
+ IOWriteMBps *int `json:"io_write_mbps"`
+ BWMbps *int `json:"network_bw_mbps"`
+ NetworkDownMbps *int `json:"network_down_mbps"`
+ NetworkUpMbps *int `json:"network_up_mbps"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "Invalid request"})
@@ -404,21 +421,35 @@ func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
// Update config
nextVCPU := c.VCPU
nextRAMMB := c.RAMMB
- if req.VCPU > 0 {
- nextVCPU = req.VCPU
+ if req.VCPU != nil {
+ nextVCPU = *req.VCPU
}
- if req.RAMMB > 0 {
- nextRAMMB = req.RAMMB
+ if req.RAMMB != nil {
+ nextRAMMB = *req.RAMMB
}
if err := validateRuntimeResourceRequest(c.Runtime(), nextVCPU, nextRAMMB, c.DiskGB); err != nil {
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
return
}
+ for name, value := range map[string]*int{
+ "network_bw_mbps": req.BWMbps,
+ "network_down_mbps": req.NetworkDownMbps,
+ "network_up_mbps": req.NetworkUpMbps,
+ "io_speed_mbps": req.IOMBps,
+ "io_read_mbps": req.IOReadMBps,
+ "io_write_mbps": req.IOWriteMBps,
+ } {
+ if err := rejectNegativeLimit(name, value); err != nil {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
+ return
+ }
+ }
c.VCPU = nextVCPU
c.RAMMB = nextRAMMB
- c.IOSpeedMBps = req.IOMBps
- c.NetworkBWMbps = req.BWMbps
+ applyNetworkLimitPatch(c, req.BWMbps, req.NetworkDownMbps, req.NetworkUpMbps)
+ applyIOLimitPatch(c, req.IOMBps, req.IOReadMBps, req.IOWriteMBps)
+ config.NormalizeContainerResourceAliases(c)
config.SaveConfig()
// Re-apply resource limits to running container
@@ -436,6 +467,114 @@ func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) {
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Message: msg})
}
+func normalizeCreateResourceLimits(cfg *lxc.ContainerConfig, fields map[string]json.RawMessage) error {
+ if cfg == nil {
+ return nil
+ }
+ if err := rejectNegativeCreateLimits(*cfg); err != nil {
+ return err
+ }
+ bwSet := hasJSONField(fields, "network_bw_mbps")
+ downSet := hasJSONField(fields, "network_down_mbps")
+ upSet := hasJSONField(fields, "network_up_mbps")
+ if bwSet {
+ if !downSet {
+ cfg.NetworkDownMbps = cfg.NetworkBWMbps
+ }
+ if !upSet {
+ cfg.NetworkUpMbps = cfg.NetworkBWMbps
+ }
+ }
+ ioSet := hasJSONField(fields, "io_speed_mbps")
+ readSet := hasJSONField(fields, "io_read_mbps")
+ writeSet := hasJSONField(fields, "io_write_mbps")
+ if ioSet {
+ if !readSet {
+ cfg.IOReadMBps = cfg.IOSpeedMBps
+ }
+ if !writeSet {
+ cfg.IOWriteMBps = cfg.IOSpeedMBps
+ }
+ }
+ cfg.NormalizeResourceAliases()
+ return nil
+}
+
+func rejectNegativeCreateLimits(cfg lxc.ContainerConfig) error {
+ for name, value := range map[string]int{
+ "network_bw_mbps": cfg.NetworkBWMbps,
+ "network_down_mbps": cfg.NetworkDownMbps,
+ "network_up_mbps": cfg.NetworkUpMbps,
+ "io_speed_mbps": cfg.IOSpeedMBps,
+ "io_read_mbps": cfg.IOReadMBps,
+ "io_write_mbps": cfg.IOWriteMBps,
+ } {
+ if value < 0 {
+ return fmt.Errorf("%s cannot be negative", name)
+ }
+ }
+ return nil
+}
+
+func hasJSONField(fields map[string]json.RawMessage, name string) bool {
+ if fields == nil {
+ return false
+ }
+ _, ok := fields[name]
+ return ok
+}
+
+func rejectNegativeLimit(name string, value *int) error {
+ if value != nil && *value < 0 {
+ return fmt.Errorf("%s cannot be negative", name)
+ }
+ return nil
+}
+
+func applyNetworkLimitPatch(c *config.Container, legacy *int, down *int, up *int) {
+ if c == nil {
+ return
+ }
+ config.NormalizeContainerResourceAliases(c)
+ nextDown := c.NetworkDownMbps
+ nextUp := c.NetworkUpMbps
+ if legacy != nil {
+ nextDown = *legacy
+ nextUp = *legacy
+ }
+ if down != nil {
+ nextDown = *down
+ }
+ if up != nil {
+ nextUp = *up
+ }
+ c.NetworkDownMbps = nextDown
+ c.NetworkUpMbps = nextUp
+ c.NetworkBWMbps = config.LegacySymmetricLimit(nextDown, nextUp)
+}
+
+func applyIOLimitPatch(c *config.Container, legacy *int, read *int, write *int) {
+ if c == nil {
+ return
+ }
+ config.NormalizeContainerResourceAliases(c)
+ nextRead := c.IOReadMBps
+ nextWrite := c.IOWriteMBps
+ if legacy != nil {
+ nextRead = *legacy
+ nextWrite = *legacy
+ }
+ if read != nil {
+ nextRead = *read
+ }
+ if write != nil {
+ nextWrite = *write
+ }
+ c.IOReadMBps = nextRead
+ c.IOWriteMBps = nextWrite
+ c.IOSpeedMBps = config.LegacySymmetricLimit(nextRead, nextWrite)
+}
+
func getRandomPort(w http.ResponseWriter, r *http.Request, id int) {
c := config.FindContainer(id)
if c == nil {
diff --git a/backend/internal/api/runtime.go b/backend/internal/api/runtime.go
index 55c186c..289967b 100644
--- a/backend/internal/api/runtime.go
+++ b/backend/internal/api/runtime.go
@@ -32,6 +32,7 @@ func runtimeFromTemplateID(templateID string) string {
func createByRuntime(cfg lxc.ContainerConfig) error {
cfg.Virtualization = runtimeFromRequest(cfg.Virtualization)
+ cfg.NormalizeResourceAliases()
if cfg.Virtualization == config.VirtualizationKVM {
return kvmManager.CreateContainer(cfg)
}
diff --git a/backend/internal/api/taskqueue.go b/backend/internal/api/taskqueue.go
index 512f6f3..52dfdba 100644
--- a/backend/internal/api/taskqueue.go
+++ b/backend/internal/api/taskqueue.go
@@ -98,6 +98,7 @@ func (q *TaskQueue) EnqueueWithAudit(containerID int, containerName string, task
}
if cfg != nil {
task.Config = *cfg
+ task.Config.NormalizeResourceAliases()
}
q.enqueueTask(task)
q.persistTasks()
@@ -162,6 +163,7 @@ func (q *TaskQueue) enqueueBatchCreateList(configs []lxc.ContainerConfig, user s
var result []string
for _, cfg := range configs {
cfgCopy := cfg
+ cfgCopy.NormalizeResourceAliases()
id := q.nextID
q.nextID++
task := &Task{
@@ -246,6 +248,7 @@ func (q *TaskQueue) createWorker() {
if task.Config.Name == "" {
task.Config.Name = task.ContainerName
}
+ task.Config.NormalizeResourceAliases()
if task.Config.Name == "" {
task.Status = "failed"
task.Error = "container name is required"
@@ -592,6 +595,11 @@ func HandleBatchCreate(w http.ResponseWriter, r *http.Request) {
if req.Containers[i].VCPU <= 0 {
req.Containers[i].VCPU = 1
}
+ if err := rejectNegativeCreateLimits(req.Containers[i]); err != nil {
+ jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: name + ": " + err.Error()})
+ return
+ }
+ req.Containers[i].NormalizeResourceAliases()
req.Containers[i].Virtualization = runtimeFromRequest(req.Containers[i].Virtualization)
if req.Containers[i].RAMMB < 128 {
req.Containers[i].RAMMB = 512
@@ -820,6 +828,7 @@ func RestoreTasks() {
if cfg.Name == "" {
cfg.Name = containerName
}
+ cfg.NormalizeResourceAliases()
containerID := st.ContainerID
if containerID <= 0 && containerName != "" {
if c := config.FindContainerByName(containerName); c != nil {
diff --git a/backend/internal/cli/cli.go b/backend/internal/cli/cli.go
index 3d26060..5bead1e 100644
--- a/backend/internal/cli/cli.go
+++ b/backend/internal/cli/cli.go
@@ -388,6 +388,7 @@ func cliCreateContainer(reader *bufio.Reader) {
IOSpeedMBps: promptInt(reader, "IO 速度 (MB/s)", 500),
ExtraPorts: promptPortList(reader, "额外 NAT 端口,多个用逗号分隔"),
}
+ cfg.NormalizeResourceAliases()
cliPrintf("\n正在创建容器 %s ...\n", name)
if err := manager.CreateContainer(cfg); err != nil {
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 3f46883..3e3d9ce 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -24,11 +24,12 @@ type PortMapping struct {
type FirewallRule struct {
ID string `json:"id"`
- Direction string `json:"direction"` // "in" or "out"
- Protocol string `json:"protocol"` // "tcp", "udp", "icmp", "all"
- Port string `json:"port"` // "" = all, "22", "80,443", "8000-9000"
- SourceIP string `json:"source_ip"` // "" = any
- Action string `json:"action"` // "ACCEPT" or "DROP"
+ Network string `json:"network,omitempty"` // "ipv4", "ipv6", or "all"; empty defaults to "ipv4"
+ Direction string `json:"direction"` // "in" or "out"
+ Protocol string `json:"protocol"` // "tcp", "udp", "icmp", "all"
+ Port string `json:"port"` // "" = all, "22", "80,443", "8000-9000"
+ SourceIP string `json:"source_ip"` // "" = any
+ Action string `json:"action"` // "ACCEPT" or "DROP"
Description string `json:"description"`
Enabled bool `json:"enabled"`
}
@@ -114,6 +115,8 @@ type Container struct {
RAMMB int `json:"ram_mb"`
DiskGB int `json:"disk_gb"`
NetworkBWMbps int `json:"network_bw_mbps"`
+ NetworkDownMbps int `json:"network_down_mbps"`
+ NetworkUpMbps int `json:"network_up_mbps"`
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
TrafficMode string `json:"traffic_mode"` // "total" or "in_out"
TrafficInGB int `json:"traffic_in_gb"` // 0 = unlimited
@@ -122,6 +125,8 @@ type Container struct {
TrafficUsedTX int64 `json:"traffic_used_tx"`
TrafficResetDate string `json:"traffic_reset_date"`
IOSpeedMBps int `json:"io_speed_mbps"`
+ IOReadMBps int `json:"io_read_mbps"`
+ IOWriteMBps int `json:"io_write_mbps"`
Status string `json:"status"`
IP string `json:"ip"`
PublicIPv4s []PublicIPv4Assignment `json:"public_ipv4s,omitempty"`
@@ -136,7 +141,8 @@ type Container struct {
PortMappings []PortMapping `json:"port_mappings"`
PortMappingLimit int `json:"port_mapping_limit"`
FirewallEnabled bool `json:"firewall_enabled"`
- FirewallRules []FirewallRule `json:"firewall_rules"`
+ FirewallDefaultAction string `json:"firewall_default_action"`
+ FirewallRules []FirewallRule `json:"firewall_rules"`
SnapshotLimit int `json:"snapshot_limit"`
CreatedAt string `json:"created_at"`
ExpiresAt string `json:"expires_at"`
@@ -702,6 +708,9 @@ func migrateLoadedConfig() bool {
if ensureContainerNetworkAssignments() {
changed = true
}
+ if ensureContainerResourceAliases() {
+ changed = true
+ }
if ensureContainerSnapshotScheduleDefaults() {
changed = true
}
@@ -800,6 +809,91 @@ func ensureContainerNetworkAssignments() bool {
return changed
}
+func ensureContainerResourceAliases() bool {
+ changed := false
+ for i := range AppConfig.Containers {
+ if NormalizeContainerResourceAliases(&AppConfig.Containers[i]) {
+ changed = true
+ }
+ }
+ return changed
+}
+
+func NormalizeContainerResourceAliases(c *Container) bool {
+ if c == nil {
+ return false
+ }
+ changed := false
+ if c.NetworkBWMbps < 0 {
+ c.NetworkBWMbps = 0
+ changed = true
+ }
+ if c.NetworkDownMbps < 0 {
+ c.NetworkDownMbps = 0
+ changed = true
+ }
+ if c.NetworkUpMbps < 0 {
+ c.NetworkUpMbps = 0
+ changed = true
+ }
+ if c.NetworkDownMbps == 0 && c.NetworkUpMbps == 0 && c.NetworkBWMbps > 0 {
+ c.NetworkDownMbps = c.NetworkBWMbps
+ c.NetworkUpMbps = c.NetworkBWMbps
+ changed = true
+ }
+ nextNetworkBW := LegacySymmetricLimit(c.NetworkDownMbps, c.NetworkUpMbps)
+ if c.NetworkBWMbps != nextNetworkBW {
+ c.NetworkBWMbps = nextNetworkBW
+ changed = true
+ }
+
+ if c.IOSpeedMBps < 0 {
+ c.IOSpeedMBps = 0
+ changed = true
+ }
+ if c.IOReadMBps < 0 {
+ c.IOReadMBps = 0
+ changed = true
+ }
+ if c.IOWriteMBps < 0 {
+ c.IOWriteMBps = 0
+ changed = true
+ }
+ if c.IOReadMBps == 0 && c.IOWriteMBps == 0 && c.IOSpeedMBps > 0 {
+ c.IOReadMBps = c.IOSpeedMBps
+ c.IOWriteMBps = c.IOSpeedMBps
+ changed = true
+ }
+ nextIO := LegacySymmetricLimit(c.IOReadMBps, c.IOWriteMBps)
+ if c.IOSpeedMBps != nextIO {
+ c.IOSpeedMBps = nextIO
+ changed = true
+ }
+ return changed
+}
+
+func LegacySymmetricLimit(a, b int) int {
+ if a < 0 {
+ a = 0
+ }
+ if b < 0 {
+ b = 0
+ }
+ if a == b {
+ return a
+ }
+ if a == 0 {
+ return b
+ }
+ if b == 0 {
+ return a
+ }
+ if a < b {
+ return a
+ }
+ return b
+}
+
func migrateSubUsers() bool {
changed := false
for i := range AppConfig.SubUsers {
@@ -884,6 +978,7 @@ func AddContainer(c Container) {
c.UUID = NewContainerUUID()
}
c.Virtualization = NormalizeVirtualization(c.Virtualization)
+ NormalizeContainerResourceAliases(&c)
AppConfig.Containers = append(AppConfig.Containers, c)
SaveConfig()
}
diff --git a/backend/internal/config/store_sqlite.go b/backend/internal/config/store_sqlite.go
index 8231817..658d5a7 100644
--- a/backend/internal/config/store_sqlite.go
+++ b/backend/internal/config/store_sqlite.go
@@ -28,11 +28,15 @@ type savedTaskConfig struct {
RAMMB int `json:"ram_mb"`
DiskGB int `json:"disk_gb"`
NetworkBWMbps int `json:"network_bw_mbps"`
+ NetworkDownMbps int `json:"network_down_mbps"`
+ NetworkUpMbps int `json:"network_up_mbps"`
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
TrafficMode string `json:"traffic_mode"`
TrafficInGB int `json:"traffic_in_gb"`
TrafficOutGB int `json:"traffic_out_gb"`
IOSpeedMBps int `json:"io_speed_mbps"`
+ IOReadMBps int `json:"io_read_mbps"`
+ IOWriteMBps int `json:"io_write_mbps"`
ExtraPorts []int `json:"extra_ports"`
PortMappingCount int `json:"port_mapping_count"`
AssignNAT *bool `json:"assign_nat,omitempty"`
@@ -55,10 +59,12 @@ func parseSavedTaskConfig(raw string) savedTaskConfig {
}
var cfg savedTaskConfig
_ = json.Unmarshal([]byte(raw), &cfg)
+ normalizeSavedTaskConfigLimits(&cfg)
return cfg
}
func encodeSavedTaskConfig(cfg savedTaskConfig) string {
+ normalizeSavedTaskConfigLimits(&cfg)
data, err := json.Marshal(cfg)
if err != nil {
return ""
@@ -66,6 +72,41 @@ func encodeSavedTaskConfig(cfg savedTaskConfig) string {
return string(data)
}
+func normalizeSavedTaskConfigLimits(cfg *savedTaskConfig) {
+ if cfg == nil {
+ return
+ }
+ if cfg.NetworkBWMbps < 0 {
+ cfg.NetworkBWMbps = 0
+ }
+ if cfg.NetworkDownMbps < 0 {
+ cfg.NetworkDownMbps = 0
+ }
+ if cfg.NetworkUpMbps < 0 {
+ cfg.NetworkUpMbps = 0
+ }
+ if cfg.NetworkDownMbps == 0 && cfg.NetworkUpMbps == 0 && cfg.NetworkBWMbps > 0 {
+ cfg.NetworkDownMbps = cfg.NetworkBWMbps
+ cfg.NetworkUpMbps = cfg.NetworkBWMbps
+ }
+ cfg.NetworkBWMbps = LegacySymmetricLimit(cfg.NetworkDownMbps, cfg.NetworkUpMbps)
+
+ if cfg.IOSpeedMBps < 0 {
+ cfg.IOSpeedMBps = 0
+ }
+ if cfg.IOReadMBps < 0 {
+ cfg.IOReadMBps = 0
+ }
+ if cfg.IOWriteMBps < 0 {
+ cfg.IOWriteMBps = 0
+ }
+ if cfg.IOReadMBps == 0 && cfg.IOWriteMBps == 0 && cfg.IOSpeedMBps > 0 {
+ cfg.IOReadMBps = cfg.IOSpeedMBps
+ cfg.IOWriteMBps = cfg.IOSpeedMBps
+ }
+ cfg.IOSpeedMBps = LegacySymmetricLimit(cfg.IOReadMBps, cfg.IOWriteMBps)
+}
+
func encodeStringSlice(values []string) string {
if len(values) == 0 {
return ""
@@ -148,6 +189,8 @@ func ensureSchema() error {
ram_mb INTEGER,
disk_gb INTEGER,
network_bw_mbps INTEGER,
+ network_down_mbps INTEGER NOT NULL DEFAULT 0,
+ network_up_mbps INTEGER NOT NULL DEFAULT 0,
monthly_traffic_gb INTEGER,
traffic_mode TEXT,
traffic_in_gb INTEGER,
@@ -156,6 +199,8 @@ func ensureSchema() error {
traffic_used_tx INTEGER,
traffic_reset_date TEXT,
io_speed_mbps INTEGER,
+ io_read_mbps INTEGER NOT NULL DEFAULT 0,
+ io_write_mbps INTEGER NOT NULL DEFAULT 0,
status TEXT,
ip TEXT,
ipv6 TEXT,
@@ -282,11 +327,15 @@ func ensureSchema() error {
cfg_ram_mb INTEGER,
cfg_disk_gb INTEGER,
cfg_network_bw_mbps INTEGER,
+ cfg_network_down_mbps INTEGER NOT NULL DEFAULT 0,
+ cfg_network_up_mbps INTEGER NOT NULL DEFAULT 0,
cfg_monthly_traffic_gb INTEGER,
cfg_traffic_mode TEXT,
cfg_traffic_in_gb INTEGER,
cfg_traffic_out_gb INTEGER,
cfg_io_speed_mbps INTEGER,
+ cfg_io_read_mbps INTEGER NOT NULL DEFAULT 0,
+ cfg_io_write_mbps INTEGER NOT NULL DEFAULT 0,
cfg_port_mapping_count INTEGER,
cfg_assign_nat INTEGER,
cfg_snapshot_limit INTEGER,
@@ -340,6 +389,7 @@ func ensureSchema() error {
}
func ensureSchemaMigrations() error {
+ added := map[string]bool{}
for _, column := range []struct {
table string
name string
@@ -352,6 +402,10 @@ func ensureSchemaMigrations() error {
{"api_keys", "last_used_ip", "TEXT"},
{"tasks", "ip", "TEXT"},
{"tasks", "user_agent", "TEXT"},
+ {"tasks", "cfg_network_down_mbps", "INTEGER NOT NULL DEFAULT 0"},
+ {"tasks", "cfg_network_up_mbps", "INTEGER NOT NULL DEFAULT 0"},
+ {"tasks", "cfg_io_read_mbps", "INTEGER NOT NULL DEFAULT 0"},
+ {"tasks", "cfg_io_write_mbps", "INTEGER NOT NULL DEFAULT 0"},
{"tasks", "cfg_assign_ipv4", "INTEGER"},
{"tasks", "cfg_ipv4_count", "INTEGER"},
{"tasks", "cfg_public_ipv4s", "TEXT"},
@@ -364,20 +418,61 @@ func ensureSchemaMigrations() error {
{"port_mappings", "host_ip", "TEXT"},
{"container_public_ipv4s", "prefix_len", "INTEGER"},
{"container_public_ipv4s", "gateway", "TEXT"},
+ {"containers", "network_down_mbps", "INTEGER NOT NULL DEFAULT 0"},
+ {"containers", "network_up_mbps", "INTEGER NOT NULL DEFAULT 0"},
+ {"containers", "io_read_mbps", "INTEGER NOT NULL DEFAULT 0"},
+ {"containers", "io_write_mbps", "INTEGER NOT NULL DEFAULT 0"},
{"containers", "firewall_enabled", "INTEGER NOT NULL DEFAULT 0"},
+ {"containers", "firewall_default_action", "TEXT NOT NULL DEFAULT 'DROP'"},
{"containers", "firewall_rules", "TEXT"},
} {
- if err := ensureColumn(column.table, column.name, column.def); err != nil {
+ wasAdded, err := ensureColumn(column.table, column.name, column.def)
+ if err != nil {
+ return err
+ }
+ if wasAdded {
+ added[column.table+"."+column.name] = true
+ }
+ }
+ if added["containers.network_down_mbps"] || added["containers.network_up_mbps"] {
+ if _, err := db.Exec(`UPDATE containers
+ SET network_down_mbps = COALESCE(NULLIF(network_down_mbps, 0), COALESCE(network_bw_mbps, 0)),
+ network_up_mbps = COALESCE(NULLIF(network_up_mbps, 0), COALESCE(network_bw_mbps, 0))
+ WHERE COALESCE(network_bw_mbps, 0) > 0`); err != nil {
+ return err
+ }
+ }
+ if added["containers.io_read_mbps"] || added["containers.io_write_mbps"] {
+ if _, err := db.Exec(`UPDATE containers
+ SET io_read_mbps = COALESCE(NULLIF(io_read_mbps, 0), COALESCE(io_speed_mbps, 0)),
+ io_write_mbps = COALESCE(NULLIF(io_write_mbps, 0), COALESCE(io_speed_mbps, 0))
+ WHERE COALESCE(io_speed_mbps, 0) > 0`); err != nil {
+ return err
+ }
+ }
+ if added["tasks.cfg_network_down_mbps"] || added["tasks.cfg_network_up_mbps"] {
+ if _, err := db.Exec(`UPDATE tasks
+ SET cfg_network_down_mbps = COALESCE(NULLIF(cfg_network_down_mbps, 0), COALESCE(cfg_network_bw_mbps, 0)),
+ cfg_network_up_mbps = COALESCE(NULLIF(cfg_network_up_mbps, 0), COALESCE(cfg_network_bw_mbps, 0))
+ WHERE COALESCE(cfg_network_bw_mbps, 0) > 0`); err != nil {
+ return err
+ }
+ }
+ if added["tasks.cfg_io_read_mbps"] || added["tasks.cfg_io_write_mbps"] {
+ if _, err := db.Exec(`UPDATE tasks
+ SET cfg_io_read_mbps = COALESCE(NULLIF(cfg_io_read_mbps, 0), COALESCE(cfg_io_speed_mbps, 0)),
+ cfg_io_write_mbps = COALESCE(NULLIF(cfg_io_write_mbps, 0), COALESCE(cfg_io_speed_mbps, 0))
+ WHERE COALESCE(cfg_io_speed_mbps, 0) > 0`); err != nil {
return err
}
}
return nil
}
-func ensureColumn(table, name, def string) error {
+func ensureColumn(table, name, def string) (bool, error) {
rows, err := db.Query("PRAGMA table_info(" + table + ")")
if err != nil {
- return err
+ return false, err
}
defer rows.Close()
for rows.Next() {
@@ -386,17 +481,17 @@ func ensureColumn(table, name, def string) error {
var notNull, pk int
var defaultValue interface{}
if err := rows.Scan(&cid, &columnName, &columnType, ¬Null, &defaultValue, &pk); err != nil {
- return err
+ return false, err
}
if columnName == name {
- return nil
+ return false, nil
}
}
if err := rows.Err(); err != nil {
- return err
+ return false, err
}
_, err = db.Exec("ALTER TABLE " + table + " ADD COLUMN " + name + " " + def)
- return err
+ return err == nil, err
}
func loadConfigFromDB() (*ClicdConfig, bool, error) {
@@ -577,26 +672,31 @@ func saveMeta(tx *sql.Tx) error {
func saveContainers(tx *sql.Tx) error {
for _, c := range AppConfig.Containers {
+ NormalizeContainerResourceAliases(&c)
if _, err := tx.Exec(`INSERT INTO containers (
id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, mac_address, template,
- vcpu, ram_mb, disk_gb, network_bw_mbps, monthly_traffic_gb, traffic_mode, traffic_in_gb,
- traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date, io_speed_mbps,
+ vcpu, ram_mb, disk_gb, network_bw_mbps, network_down_mbps, network_up_mbps,
+ monthly_traffic_gb, traffic_mode, traffic_in_gb,
+ traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date,
+ io_speed_mbps, io_read_mbps, io_write_mbps,
status, ip, ipv6, ipv6_prefix_len, ipv6_interface, vnc_port, ssh_port, ssh_password,
ssh_host_key, port_mapping_limit, snapshot_limit, created_at, expires_at,
snapshot_schedule_enabled, snapshot_schedule_interval_hours, snapshot_schedule_time,
snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by,
policy_blocked, policy_blocked_reason, policy_blocked_at,
- firewall_enabled, firewall_rules
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ firewall_enabled, firewall_default_action, firewall_rules
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
c.ID, c.UUID, c.Name, c.Virtualization, c.LXCName, c.KVMName, c.DiskImage, c.MACAddress, c.Template,
- c.VCPU, c.RAMMB, c.DiskGB, c.NetworkBWMbps, c.MonthlyTrafficGB, c.TrafficMode, c.TrafficInGB,
- c.TrafficOutGB, c.TrafficUsedRX, c.TrafficUsedTX, c.TrafficResetDate, c.IOSpeedMBps,
+ c.VCPU, c.RAMMB, c.DiskGB, c.NetworkBWMbps, c.NetworkDownMbps, c.NetworkUpMbps,
+ c.MonthlyTrafficGB, c.TrafficMode, c.TrafficInGB,
+ c.TrafficOutGB, c.TrafficUsedRX, c.TrafficUsedTX, c.TrafficResetDate,
+ c.IOSpeedMBps, c.IOReadMBps, c.IOWriteMBps,
c.Status, c.IP, c.IPv6, c.IPv6PrefixLen, c.IPv6Interface, c.VNCPort, c.SSHPort, c.SSHPassword,
c.SSHHostKey, c.PortMappingLimit, c.SnapshotLimit, c.CreatedAt, c.ExpiresAt,
boolInt(c.SnapshotScheduleEnabled), c.SnapshotScheduleIntervalHours, c.SnapshotScheduleTime,
c.SnapshotScheduleLastRun, c.SnapshotScheduleNextRun, c.SnapshotScheduleCreatedBy,
boolInt(c.PolicyBlocked), c.PolicyBlockedReason, c.PolicyBlockedAt,
- boolInt(c.FirewallEnabled), marshalFirewallRules(c.FirewallRules),
+ boolInt(c.FirewallEnabled), normalizeFirewallDefaultAction(c.FirewallDefaultAction), marshalFirewallRules(c.FirewallRules),
); err != nil {
return err
}
@@ -731,15 +831,19 @@ func saveTasksDB(tx *sql.Tx) error {
if _, err := tx.Exec(`INSERT INTO tasks(
id, type, container_id, container_name, status, error, created_at, template_id, user, ip, user_agent,
cfg_name, cfg_virtualization, cfg_template_id, cfg_vcpu, cfg_cpu_percent, cfg_ram_mb, cfg_disk_gb,
- cfg_network_bw_mbps, cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
- cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
+ cfg_network_bw_mbps, cfg_network_down_mbps, cfg_network_up_mbps,
+ cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
+ cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_io_read_mbps, cfg_io_write_mbps,
+ cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
cfg_assign_ipv4, cfg_ipv4_count, cfg_public_ipv4s, cfg_assign_ipv6, cfg_ipv6_count, cfg_ipv6_addresses,
cfg_ssh_auth_mode, cfg_ssh_password, cfg_ssh_public_key, cfg_expires_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
task.ID, task.Type, task.ContainerID, task.ContainerName, task.Status, task.Error, task.CreatedAt, task.TemplateID, task.User, task.IP, task.UserAgent,
cfg.Name, cfg.Virtualization, cfg.TemplateID, cfg.VCPU, cfg.CPUPercent, cfg.RAMMB, cfg.DiskGB,
- cfg.NetworkBWMbps, cfg.MonthlyTrafficGB, cfg.TrafficMode, cfg.TrafficInGB,
- cfg.TrafficOutGB, cfg.IOSpeedMBps, cfg.PortMappingCount, boolPtrInt(cfg.AssignNAT), cfg.SnapshotLimit,
+ cfg.NetworkBWMbps, cfg.NetworkDownMbps, cfg.NetworkUpMbps,
+ cfg.MonthlyTrafficGB, cfg.TrafficMode, cfg.TrafficInGB,
+ cfg.TrafficOutGB, cfg.IOSpeedMBps, cfg.IOReadMBps, cfg.IOWriteMBps,
+ cfg.PortMappingCount, boolPtrInt(cfg.AssignNAT), cfg.SnapshotLimit,
boolInt(cfg.AssignIPv4), cfg.IPv4Count, encodeStringSlice(cfg.PublicIPv4s),
boolInt(cfg.AssignIPv6), cfg.IPv6Count, encodeStringSlice(cfg.IPv6Addresses),
cfg.SSHAuthMode, cfg.SSHPassword, cfg.SSHPublicKey, cfg.ExpiresAt,
@@ -787,14 +891,16 @@ func saveSnapshots(tx *sql.Tx) error {
func loadContainers() ([]Container, error) {
rows, err := db.Query(`SELECT
id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, mac_address, template,
- vcpu, ram_mb, disk_gb, network_bw_mbps, monthly_traffic_gb, traffic_mode, traffic_in_gb,
- traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date, io_speed_mbps,
+ vcpu, ram_mb, disk_gb, network_bw_mbps, network_down_mbps, network_up_mbps,
+ monthly_traffic_gb, traffic_mode, traffic_in_gb,
+ traffic_out_gb, traffic_used_rx, traffic_used_tx, traffic_reset_date,
+ io_speed_mbps, io_read_mbps, io_write_mbps,
status, ip, ipv6, ipv6_prefix_len, ipv6_interface, vnc_port, ssh_port, ssh_password,
ssh_host_key, port_mapping_limit, snapshot_limit, created_at, expires_at,
snapshot_schedule_enabled, snapshot_schedule_interval_hours, snapshot_schedule_time,
snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by,
policy_blocked, policy_blocked_reason, policy_blocked_at,
- firewall_enabled, firewall_rules
+ firewall_enabled, firewall_default_action, firewall_rules
FROM containers ORDER BY id`)
if err != nil {
return nil, err
@@ -805,26 +911,31 @@ func loadContainers() ([]Container, error) {
for rows.Next() {
var c Container
var scheduleEnabled, policyBlocked, firewallEnabled int
+ var firewallDefaultAction string
var firewallRulesJSON sql.NullString
if err := rows.Scan(
&c.ID, &c.UUID, &c.Name, &c.Virtualization, &c.LXCName, &c.KVMName, &c.DiskImage, &c.MACAddress, &c.Template,
- &c.VCPU, &c.RAMMB, &c.DiskGB, &c.NetworkBWMbps, &c.MonthlyTrafficGB, &c.TrafficMode, &c.TrafficInGB,
- &c.TrafficOutGB, &c.TrafficUsedRX, &c.TrafficUsedTX, &c.TrafficResetDate, &c.IOSpeedMBps,
+ &c.VCPU, &c.RAMMB, &c.DiskGB, &c.NetworkBWMbps, &c.NetworkDownMbps, &c.NetworkUpMbps,
+ &c.MonthlyTrafficGB, &c.TrafficMode, &c.TrafficInGB,
+ &c.TrafficOutGB, &c.TrafficUsedRX, &c.TrafficUsedTX, &c.TrafficResetDate,
+ &c.IOSpeedMBps, &c.IOReadMBps, &c.IOWriteMBps,
&c.Status, &c.IP, &c.IPv6, &c.IPv6PrefixLen, &c.IPv6Interface, &c.VNCPort, &c.SSHPort, &c.SSHPassword,
&c.SSHHostKey, &c.PortMappingLimit, &c.SnapshotLimit, &c.CreatedAt, &c.ExpiresAt,
&scheduleEnabled, &c.SnapshotScheduleIntervalHours, &c.SnapshotScheduleTime,
&c.SnapshotScheduleLastRun, &c.SnapshotScheduleNextRun, &c.SnapshotScheduleCreatedBy,
&policyBlocked, &c.PolicyBlockedReason, &c.PolicyBlockedAt,
- &firewallEnabled, &firewallRulesJSON,
+ &firewallEnabled, &firewallDefaultAction, &firewallRulesJSON,
); err != nil {
return nil, err
}
c.SnapshotScheduleEnabled = scheduleEnabled != 0
c.PolicyBlocked = policyBlocked != 0
c.FirewallEnabled = firewallEnabled != 0
+ c.FirewallDefaultAction = normalizeFirewallDefaultAction(firewallDefaultAction)
if firewallRulesJSON.Valid && strings.TrimSpace(firewallRulesJSON.String) != "" {
_ = json.Unmarshal([]byte(firewallRulesJSON.String), &c.FirewallRules)
}
+ NormalizeContainerResourceAliases(&c)
result = append(result, c)
}
if err := rows.Err(); err != nil {
@@ -1018,8 +1129,10 @@ func loadTasks() ([]SavedTask, error) {
rows, err := db.Query(`SELECT
id, type, container_id, container_name, status, error, created_at, template_id, user, ip, user_agent,
cfg_name, cfg_virtualization, cfg_template_id, cfg_vcpu, cfg_cpu_percent, cfg_ram_mb, cfg_disk_gb,
- cfg_network_bw_mbps, cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
- cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
+ cfg_network_bw_mbps, cfg_network_down_mbps, cfg_network_up_mbps,
+ cfg_monthly_traffic_gb, cfg_traffic_mode, cfg_traffic_in_gb,
+ cfg_traffic_out_gb, cfg_io_speed_mbps, cfg_io_read_mbps, cfg_io_write_mbps,
+ cfg_port_mapping_count, cfg_assign_nat, cfg_snapshot_limit,
cfg_assign_ipv4, cfg_ipv4_count, cfg_public_ipv4s, cfg_assign_ipv6, cfg_ipv6_count, cfg_ipv6_addresses,
cfg_ssh_auth_mode, cfg_ssh_password, cfg_ssh_public_key, cfg_expires_at
FROM tasks ORDER BY created_at, id`)
@@ -1039,8 +1152,10 @@ func loadTasks() ([]SavedTask, error) {
if err := rows.Scan(
&t.ID, &t.Type, &t.ContainerID, &t.ContainerName, &t.Status, &t.Error, &t.CreatedAt, &t.TemplateID, &t.User, &ip, &userAgent,
&cfg.Name, &cfg.Virtualization, &cfg.TemplateID, &cfg.VCPU, &cfg.CPUPercent, &cfg.RAMMB, &cfg.DiskGB,
- &cfg.NetworkBWMbps, &cfg.MonthlyTrafficGB, &cfg.TrafficMode, &cfg.TrafficInGB,
- &cfg.TrafficOutGB, &cfg.IOSpeedMBps, &cfg.PortMappingCount, &assignNAT, &cfg.SnapshotLimit,
+ &cfg.NetworkBWMbps, &cfg.NetworkDownMbps, &cfg.NetworkUpMbps,
+ &cfg.MonthlyTrafficGB, &cfg.TrafficMode, &cfg.TrafficInGB,
+ &cfg.TrafficOutGB, &cfg.IOSpeedMBps, &cfg.IOReadMBps, &cfg.IOWriteMBps,
+ &cfg.PortMappingCount, &assignNAT, &cfg.SnapshotLimit,
&assignIPv4, &ipv4Count, &publicIPv4s, &assignIPv6, &ipv6Count, &ipv6Addresses,
&sshAuthMode, &sshPassword, &sshPublicKey, &cfg.ExpiresAt,
); err != nil {
@@ -1065,6 +1180,7 @@ func loadTasks() ([]SavedTask, error) {
cfg.SSHAuthMode = sshAuthMode.String
cfg.SSHPassword = sshPassword.String
cfg.SSHPublicKey = sshPublicKey.String
+ normalizeSavedTaskConfigLimits(&cfg)
result = append(result, t)
configs = append(configs, cfg)
}
@@ -1189,6 +1305,14 @@ func marshalFirewallRules(rules []FirewallRule) interface{} {
return string(data)
}
+func normalizeFirewallDefaultAction(action string) string {
+ action = strings.ToUpper(strings.TrimSpace(action))
+ if action == "ACCEPT" {
+ return "ACCEPT"
+ }
+ return "DROP"
+}
+
func boolPtrInt(value *bool) interface{} {
if value == nil {
return nil
diff --git a/backend/internal/kvm/kvm.go b/backend/internal/kvm/kvm.go
index 2158c8d..9515089 100644
--- a/backend/internal/kvm/kvm.go
+++ b/backend/internal/kvm/kvm.go
@@ -346,6 +346,7 @@ func normalizeQCOW2(ctx context.Context, src, target string) error {
}
func (m *Manager) CreateContainer(cfg lxc.ContainerConfig) error {
+ cfg.NormalizeResourceAliases()
image := FindImage(cfg.TemplateID)
if image == nil {
return fmt.Errorf("KVM image not found: %s", cfg.TemplateID)
@@ -456,7 +457,7 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
if err := createWindowsUnattendISO(unattendPath, cfg.Name, winAdminPassword, ipv6List, ipv4List); err != nil {
return nil, err
}
- xml = windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, ImagePath(image.ID), unattendPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps)
+ xml = windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, ImagePath(image.ID), unattendPath, mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps)
} else {
if image.Desktop != "" {
if cfg.RAMMB < 2048 {
@@ -472,7 +473,7 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
if err := createSeedISO(seedPath, vmName, cfg.Name, sshPassword, sshPublicKey, mac, ipv6List, ipv4List, *image, sshAuthMode); err != nil {
return nil, err
}
- xml = domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, seedPath, mac, cfg.IOSpeedMBps, cfg.NetworkBWMbps, image.Desktop != "")
+ xml = domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, seedPath, mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps, image.Desktop != "")
}
xmlPath := filepath.Join(m.instanceDir(vmName), "domain.xml")
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
@@ -542,12 +543,16 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
RAMMB: cfg.RAMMB,
DiskGB: cfg.DiskGB,
NetworkBWMbps: cfg.NetworkBWMbps,
+ NetworkDownMbps: cfg.NetworkDownMbps,
+ NetworkUpMbps: cfg.NetworkUpMbps,
MonthlyTrafficGB: cfg.MonthlyTrafficGB,
TrafficMode: trafficMode,
TrafficInGB: cfg.TrafficInGB,
TrafficOutGB: cfg.TrafficOutGB,
TrafficResetDate: now[:7],
IOSpeedMBps: cfg.IOSpeedMBps,
+ IOReadMBps: cfg.IOReadMBps,
+ IOWriteMBps: cfg.IOWriteMBps,
PublicIPv4s: publicIPv4s,
IPv6Addresses: ipv6Assignments,
Status: "stopped",
@@ -781,11 +786,15 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...lx
RAMMB: c.RAMMB,
DiskGB: c.DiskGB,
NetworkBWMbps: c.NetworkBWMbps,
+ NetworkDownMbps: c.NetworkDownMbps,
+ NetworkUpMbps: c.NetworkUpMbps,
MonthlyTrafficGB: c.MonthlyTrafficGB,
TrafficMode: c.TrafficMode,
TrafficInGB: c.TrafficInGB,
TrafficOutGB: c.TrafficOutGB,
IOSpeedMBps: c.IOSpeedMBps,
+ IOReadMBps: c.IOReadMBps,
+ IOWriteMBps: c.IOWriteMBps,
PortMappingCount: c.PortMappingLimit,
SnapshotLimit: c.SnapshotLimit,
ExpiresAt: c.ExpiresAt,
@@ -882,6 +891,7 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
if c == nil || !c.IsKVM() {
return nil
}
+ config.NormalizeContainerResourceAliases(c)
if c.Status == "running" {
// Config already saved; domain definition will be refreshed on next start
return nil
@@ -893,10 +903,10 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
if IsWindowsImage(c.Template) {
winISO := ImagePath(c.Template)
unattendISO := existingWindowsUnattendISO(m.instanceDir(c.VirshName()))
- xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
+ xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps)
} else {
seedPath := filepath.Join(m.instanceDir(c.VirshName()), "seed.iso")
- xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps, isKVMDesktopTemplate(c.Template))
+ xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps, isKVMDesktopTemplate(c.Template))
}
xmlPath := filepath.Join(m.instanceDir(c.VirshName()), "domain.xml")
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
@@ -913,15 +923,16 @@ func (m *Manager) ensureDomainDefinition(c *config.Container) error {
if c == nil || !c.IsKVM() || c.DiskImage == "" || c.MACAddress == "" {
return nil
}
+ config.NormalizeContainerResourceAliases(c)
var xml string
xmlPath := filepath.Join(m.instanceDir(c.VirshName()), "domain.xml")
if IsWindowsImage(c.Template) {
winISO := ImagePath(c.Template)
unattendISO := existingWindowsUnattendISO(m.instanceDir(c.VirshName()))
- xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps)
+ xml = windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, winISO, unattendISO, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps)
} else {
seedPath := filepath.Join(m.instanceDir(c.VirshName()), "seed.iso")
- xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOSpeedMBps, c.NetworkBWMbps, isKVMDesktopTemplate(c.Template))
+ xml = domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, seedPath, c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps, isKVMDesktopTemplate(c.Template))
}
if err := os.WriteFile(xmlPath, []byte(xml), 0644); err != nil {
return err
@@ -2079,7 +2090,7 @@ func isKVMDesktopTemplate(templateID string) bool {
return image != nil && image.Desktop != ""
}
-func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string, ioSpeedMBps int, networkBWMbps int, desktop bool) string {
+func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string, ioReadMBps int, ioWriteMBps int, networkDownMbps int, networkUpMbps int, desktop bool) string {
if vcpu < 1 {
vcpu = 1
}
@@ -2087,21 +2098,32 @@ func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string,
ramMB = 512
}
iotune := ""
- if ioSpeedMBps > 0 {
- bytesPerSecond := int64(ioSpeedMBps) * 1024 * 1024
+ if ioReadMBps > 0 || ioWriteMBps > 0 {
+ var parts []string
+ if ioReadMBps > 0 {
+ parts = append(parts, fmt.Sprintf(" %d", int64(ioReadMBps)*1024*1024))
+ }
+ if ioWriteMBps > 0 {
+ parts = append(parts, fmt.Sprintf(" %d", int64(ioWriteMBps)*1024*1024))
+ }
iotune = fmt.Sprintf(`
- %d
- `, bytesPerSecond)
+%s
+ `, strings.Join(parts, "\n"))
}
bandwidth := ""
- if networkBWMbps > 0 {
- averageKiB := networkBWMbps * 128
+ if networkDownMbps > 0 || networkUpMbps > 0 {
+ var parts []string
+ if networkDownMbps > 0 {
+ parts = append(parts, fmt.Sprintf(" ", networkDownMbps*128))
+ }
+ if networkUpMbps > 0 {
+ parts = append(parts, fmt.Sprintf(" ", networkUpMbps*128))
+ }
bandwidth = fmt.Sprintf(`
-
-
- `, averageKiB, averageKiB)
+%s
+ `, strings.Join(parts, "\n"))
}
video := ""
input := ""
@@ -2158,7 +2180,7 @@ func domainXML(name string, vcpu int, ramMB int, diskPath, seedPath, mac string,
`, xmlEscape(name), domainUUIDXML(name), ramMB, ramMB, vcpu, vcpu, xmlEscape(diskPath), iotune, xmlEscape(seedPath), xmlEscape(mac), bandwidth, input, video)
}
-func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, unattendISOPath, mac string, ioSpeedMBps int, networkBWMbps int) string {
+func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, unattendISOPath, mac string, ioReadMBps int, ioWriteMBps int, networkDownMbps int, networkUpMbps int) string {
if vcpu < 1 {
vcpu = 1
}
@@ -2166,21 +2188,32 @@ func windowsDomainXML(name string, vcpu int, ramMB int, diskPath, winISOPath, un
ramMB = 2048
}
iotune := ""
- if ioSpeedMBps > 0 {
- bytesPerSecond := int64(ioSpeedMBps) * 1024 * 1024
+ if ioReadMBps > 0 || ioWriteMBps > 0 {
+ var parts []string
+ if ioReadMBps > 0 {
+ parts = append(parts, fmt.Sprintf(" %d", int64(ioReadMBps)*1024*1024))
+ }
+ if ioWriteMBps > 0 {
+ parts = append(parts, fmt.Sprintf(" %d", int64(ioWriteMBps)*1024*1024))
+ }
iotune = fmt.Sprintf(`
- %d
- `, bytesPerSecond)
+%s
+ `, strings.Join(parts, "\n"))
}
bandwidth := ""
- if networkBWMbps > 0 {
- averageKiB := networkBWMbps * 128
+ if networkDownMbps > 0 || networkUpMbps > 0 {
+ var parts []string
+ if networkDownMbps > 0 {
+ parts = append(parts, fmt.Sprintf(" ", networkDownMbps*128))
+ }
+ if networkUpMbps > 0 {
+ parts = append(parts, fmt.Sprintf(" ", networkUpMbps*128))
+ }
bandwidth = fmt.Sprintf(`
-
-
- `, averageKiB, averageKiB)
+%s
+ `, strings.Join(parts, "\n"))
}
virtioWinISO := virtioWinISOPath()
unattendDisk := ""
@@ -3231,6 +3264,11 @@ func (m *Manager) applyIPv6Runtime(c *config.Container) error {
}
ensureKVMIPv6NAT66(assignment.Address, uplink)
}
+ if c.Status == "running" {
+ if err := lxc.ApplyFirewallRules(c.ID); err != nil {
+ fmt.Printf("Warning: failed to re-apply firewall rules after KVM IPv6 setup for %s: %v\n", c.Name, err)
+ }
+ }
return nil
}
@@ -3307,7 +3345,7 @@ func ensureKVMIPv6ForwardRules(ipv6 string, bridge string) {
}
for _, rule := range rules {
check := append([]string{"-C"}, rule...)
- add := append([]string{"-I"}, append([]string{rule[0], "1"}, rule[1:]...)...)
+ add := append([]string{"-A"}, rule...)
if exec.Command("ip6tables", check...).Run() != nil {
exec.Command("ip6tables", add...).Run()
}
diff --git a/backend/internal/lxc/ipv6.go b/backend/internal/lxc/ipv6.go
index ec54547..b82226d 100644
--- a/backend/internal/lxc/ipv6.go
+++ b/backend/internal/lxc/ipv6.go
@@ -1610,6 +1610,9 @@ func (m *Manager) ApplyIPv6(id int) error {
ensureIPv6NAT66(assignment.Address, uplink)
}
}
+ if err := ApplyFirewallRules(c.ID); err != nil {
+ fmt.Printf("Warning: failed to re-apply firewall rules after IPv6 setup for %s: %v\n", c.Name, err)
+ }
return nil
}
diff --git a/backend/internal/lxc/lxc.go b/backend/internal/lxc/lxc.go
index fcfafaf..2b2d136 100644
--- a/backend/internal/lxc/lxc.go
+++ b/backend/internal/lxc/lxc.go
@@ -226,11 +226,15 @@ type ContainerConfig struct {
RAMMB int `json:"ram_mb"`
DiskGB int `json:"disk_gb"`
NetworkBWMbps int `json:"network_bw_mbps"`
+ NetworkDownMbps int `json:"network_down_mbps"`
+ NetworkUpMbps int `json:"network_up_mbps"`
MonthlyTrafficGB int `json:"monthly_traffic_gb"`
TrafficMode string `json:"traffic_mode"` // "total" or "in_out"
TrafficInGB int `json:"traffic_in_gb"` // 0=unlimited
TrafficOutGB int `json:"traffic_out_gb"` // 0=unlimited
IOSpeedMBps int `json:"io_speed_mbps"`
+ IOReadMBps int `json:"io_read_mbps"`
+ IOWriteMBps int `json:"io_write_mbps"`
ExtraPorts []int `json:"extra_ports"`
PortMappingCount int `json:"port_mapping_count"`
AssignNAT *bool `json:"assign_nat,omitempty"`
@@ -247,12 +251,48 @@ type ContainerConfig struct {
ExpiresAt string `json:"expires_at"`
}
+func (cfg *ContainerConfig) NormalizeResourceAliases() {
+ if cfg == nil {
+ return
+ }
+ if cfg.NetworkBWMbps < 0 {
+ cfg.NetworkBWMbps = 0
+ }
+ if cfg.NetworkDownMbps < 0 {
+ cfg.NetworkDownMbps = 0
+ }
+ if cfg.NetworkUpMbps < 0 {
+ cfg.NetworkUpMbps = 0
+ }
+ if cfg.NetworkDownMbps == 0 && cfg.NetworkUpMbps == 0 && cfg.NetworkBWMbps > 0 {
+ cfg.NetworkDownMbps = cfg.NetworkBWMbps
+ cfg.NetworkUpMbps = cfg.NetworkBWMbps
+ }
+ cfg.NetworkBWMbps = config.LegacySymmetricLimit(cfg.NetworkDownMbps, cfg.NetworkUpMbps)
+
+ if cfg.IOSpeedMBps < 0 {
+ cfg.IOSpeedMBps = 0
+ }
+ if cfg.IOReadMBps < 0 {
+ cfg.IOReadMBps = 0
+ }
+ if cfg.IOWriteMBps < 0 {
+ cfg.IOWriteMBps = 0
+ }
+ if cfg.IOReadMBps == 0 && cfg.IOWriteMBps == 0 && cfg.IOSpeedMBps > 0 {
+ cfg.IOReadMBps = cfg.IOSpeedMBps
+ cfg.IOWriteMBps = cfg.IOSpeedMBps
+ }
+ cfg.IOSpeedMBps = config.LegacySymmetricLimit(cfg.IOReadMBps, cfg.IOWriteMBps)
+}
+
func (cfg ContainerConfig) WantsNAT() bool {
return cfg.AssignNAT == nil || *cfg.AssignNAT
}
// CreateContainer creates a new LXC container. Uses ct-{id} as LXC name internally.
func (m *Manager) CreateContainer(cfg ContainerConfig) error {
+ cfg.NormalizeResourceAliases()
tmpl := FindTemplate(cfg.TemplateID)
if tmpl == nil {
return fmt.Errorf("template not found: %s", cfg.TemplateID)
@@ -389,12 +429,16 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
RAMMB: cfg.RAMMB,
DiskGB: cfg.DiskGB,
NetworkBWMbps: cfg.NetworkBWMbps,
+ NetworkDownMbps: cfg.NetworkDownMbps,
+ NetworkUpMbps: cfg.NetworkUpMbps,
MonthlyTrafficGB: cfg.MonthlyTrafficGB,
TrafficMode: trafficMode,
TrafficInGB: cfg.TrafficInGB,
TrafficOutGB: cfg.TrafficOutGB,
TrafficResetDate: trafficResetDate,
IOSpeedMBps: cfg.IOSpeedMBps,
+ IOReadMBps: cfg.IOReadMBps,
+ IOWriteMBps: cfg.IOWriteMBps,
Status: "stopped",
IP: "",
PublicIPv4s: publicIPv4s,
@@ -531,6 +575,7 @@ func (m *Manager) preconfigureSSH(rootfsPath, templateID string, sshAuthMode str
// applyResourceLimits applies cgroup v2 limits and mandatory security hardening to container config.
func (m *Manager) applyResourceLimits(lxcName string, cfg ContainerConfig) error {
+ cfg.NormalizeResourceAliases()
configFile := filepath.Join(m.LxcPath, lxcName, "config")
data, err := os.ReadFile(configFile)
@@ -599,12 +644,12 @@ func (m *Manager) applyResourceLimits(lxcName string, cfg ContainerConfig) error
ramBytes := int64(cfg.RAMMB) * 1024 * 1024
newLines = append(newLines, fmt.Sprintf("lxc.cgroup2.memory.max = %d", ramBytes))
}
- if cfg.IOSpeedMBps > 0 {
+ if cfg.IOReadMBps > 0 || cfg.IOWriteMBps > 0 {
// Note: lxc.cgroup2.io.max is skipped for unprivileged containers because
// LXC's cgfsng_setup_limits cannot resolve host device numbers (e.g. 8:1)
// in the unprivileged namespace context.
// IO limits are instead applied post-start via direct cgroup2 writes.
- fmt.Printf("Info: IO limit (%d MB/s) for %s will be applied post-start via cgroup2\n", cfg.IOSpeedMBps, lxcName)
+ fmt.Printf("Info: IO limit (read=%d MB/s write=%d MB/s) for %s will be applied post-start via cgroup2\n", cfg.IOReadMBps, cfg.IOWriteMBps, lxcName)
}
newContent := strings.Join(newLines, "\n")
@@ -614,18 +659,28 @@ func (m *Manager) applyResourceLimits(lxcName string, cfg ContainerConfig) error
return nil
}
-func (m *Manager) ioLimitLines(lxcName string, mbps int) ([]string, error) {
- if mbps <= 0 {
- return nil, nil
+func (m *Manager) ioLimitLines(lxcName string, readMBps int, writeMBps int) ([]string, error) {
+ if readMBps < 0 {
+ readMBps = 0
+ }
+ if writeMBps < 0 {
+ writeMBps = 0
}
devices, err := m.rootfsBlockDevices(lxcName)
if err != nil {
return nil, err
}
- ioBytes := mbps * 1024 * 1024
+ readValue := "max"
+ if readMBps > 0 {
+ readValue = strconv.Itoa(readMBps * 1024 * 1024)
+ }
+ writeValue := "max"
+ if writeMBps > 0 {
+ writeValue = strconv.Itoa(writeMBps * 1024 * 1024)
+ }
lines := make([]string, 0, len(devices))
for _, device := range devices {
- lines = append(lines, fmt.Sprintf("%s rbps=%d wbps=%d", device, ioBytes, ioBytes))
+ lines = append(lines, fmt.Sprintf("%s rbps=%s wbps=%s", device, readValue, writeValue))
}
return lines, nil
}
@@ -1253,8 +1308,12 @@ func (m *Manager) StartContainer(id int) error {
RAMMB: c.RAMMB,
DiskGB: c.DiskGB,
NetworkBWMbps: c.NetworkBWMbps,
+ NetworkDownMbps: c.NetworkDownMbps,
+ NetworkUpMbps: c.NetworkUpMbps,
MonthlyTrafficGB: c.MonthlyTrafficGB,
IOSpeedMBps: c.IOSpeedMBps,
+ IOReadMBps: c.IOReadMBps,
+ IOWriteMBps: c.IOWriteMBps,
AssignIPv6: c.IPv6 != "" || len(c.IPv6Addresses) > 0,
ExpiresAt: c.ExpiresAt,
}); err != nil {
@@ -1378,6 +1437,7 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
if c == nil || c.Status != "running" {
return nil
}
+ config.NormalizeContainerResourceAliases(c)
lxcName := c.LxcName()
// CPU: write cpu.max
@@ -1400,48 +1460,52 @@ func (m *Manager) ApplyContainerLimits(c *config.Container) error {
os.WriteFile(path, []byte(memLine), 0644)
}
- // IO speed: write io.max
- if c.IOSpeedMBps > 0 {
- ioLines, err := m.ioLimitLines(lxcName, c.IOSpeedMBps)
- if err != nil {
- return err
- }
- ioLine := strings.Join(ioLines, "\n")
- for _, path := range []string{
- fmt.Sprintf("/sys/fs/cgroup/lxc/%s/io.max", lxcName),
- fmt.Sprintf("/sys/fs/cgroup/lxc.payload.%s/io.max", lxcName),
- } {
- os.WriteFile(path, []byte(ioLine), 0644)
- }
+ // IO speed: write io.max, including max values to clear old per-direction limits.
+ ioLines, err := m.ioLimitLines(lxcName, c.IOReadMBps, c.IOWriteMBps)
+ if err != nil {
+ return err
+ }
+ ioLine := strings.Join(ioLines, "\n")
+ for _, path := range []string{
+ fmt.Sprintf("/sys/fs/cgroup/lxc/%s/io.max", lxcName),
+ fmt.Sprintf("/sys/fs/cgroup/lxc.payload.%s/io.max", lxcName),
+ } {
+ os.WriteFile(path, []byte(ioLine), 0644)
}
// Network bandwidth
- if c.NetworkBWMbps > 0 {
- m.applyBandwidthLimit(lxcName, c.NetworkBWMbps)
- } else {
- m.cleanupBandwidthLimit(lxcName)
- }
+ m.applyBandwidthLimit(lxcName, c.NetworkDownMbps, c.NetworkUpMbps)
return nil
}
-func (m *Manager) applyBandwidthLimit(lxcName string, mbps int) {
+func (m *Manager) applyBandwidthLimit(lxcName string, downMbps int, upMbps int) {
veth := m.getContainerVethByNS(lxcName)
if veth == "" {
fmt.Printf("Warning: could not find veth for %s\n", lxcName)
return
}
- rate := fmt.Sprintf("%dmbit", mbps)
- burst := fmt.Sprintf("%dkbit", mbps*100)
exec.Command("tc", "qdisc", "del", "dev", veth, "root").Run()
- exec.Command("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:", "htb", "default", "10").Run()
- exec.Command("tc", "class", "add", "dev", veth, "parent", "1:", "classid", "1:10", "htb", "rate", rate, "burst", burst).Run()
- fmt.Printf("Bandwidth limit: %s = %d Mbps on %s\n", lxcName, mbps, veth)
+ exec.Command("tc", "qdisc", "del", "dev", veth, "ingress").Run()
+ if downMbps > 0 {
+ rate := fmt.Sprintf("%dmbit", downMbps)
+ burst := fmt.Sprintf("%dkbit", downMbps*100)
+ exec.Command("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:", "htb", "default", "10").Run()
+ exec.Command("tc", "class", "add", "dev", veth, "parent", "1:", "classid", "1:10", "htb", "rate", rate, "burst", burst).Run()
+ }
+ if upMbps > 0 {
+ rate := fmt.Sprintf("%dmbit", upMbps)
+ burst := fmt.Sprintf("%dkbit", upMbps*100)
+ exec.Command("tc", "qdisc", "add", "dev", veth, "handle", "ffff:", "ingress").Run()
+ exec.Command("tc", "filter", "add", "dev", veth, "parent", "ffff:", "protocol", "all", "u32", "match", "u32", "0", "0", "police", "rate", rate, "burst", burst, "drop", "flowid", ":1").Run()
+ }
+ fmt.Printf("Bandwidth limit: %s down=%d Mbps up=%d Mbps on %s\n", lxcName, downMbps, upMbps, veth)
}
func (m *Manager) cleanupBandwidthLimit(lxcName string) {
veth := m.getContainerVethByNS(lxcName)
if veth != "" {
exec.Command("tc", "qdisc", "del", "dev", veth, "root").Run()
+ exec.Command("tc", "qdisc", "del", "dev", veth, "ingress").Run()
}
}
@@ -2447,6 +2511,8 @@ func (m *Manager) ImportExistingClicdContainers() ([]config.Container, error) {
RAMMB: 512,
DiskGB: 10,
NetworkBWMbps: 100,
+ NetworkDownMbps: 100,
+ NetworkUpMbps: 100,
MonthlyTrafficGB: 1000,
TrafficMode: "total",
Status: status,
@@ -2610,8 +2676,12 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co
RAMMB: c.RAMMB,
DiskGB: c.DiskGB,
NetworkBWMbps: c.NetworkBWMbps,
+ NetworkDownMbps: c.NetworkDownMbps,
+ NetworkUpMbps: c.NetworkUpMbps,
MonthlyTrafficGB: c.MonthlyTrafficGB,
IOSpeedMBps: c.IOSpeedMBps,
+ IOReadMBps: c.IOReadMBps,
+ IOWriteMBps: c.IOWriteMBps,
AssignIPv6: c.IPv6 != "" || len(c.IPv6Addresses) > 0,
ExpiresAt: c.ExpiresAt,
}
@@ -2694,9 +2764,8 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co
}
}
// Apply bandwidth limit after reinstall
- if c.NetworkBWMbps > 0 {
- m.applyBandwidthLimit(c.LxcName(), c.NetworkBWMbps)
- }
+ config.NormalizeContainerResourceAliases(c)
+ m.applyBandwidthLimit(c.LxcName(), c.NetworkDownMbps, c.NetworkUpMbps)
if c.IPv6 != "" || len(c.IPv6Addresses) > 0 {
if err := m.ApplyIPv6(id); err != nil {
fmt.Printf("Warning: failed to apply IPv6 after reinstall: %v\n", err)
diff --git a/backend/internal/lxc/portmap.go b/backend/internal/lxc/portmap.go
index d3fa0c0..39f68f3 100644
--- a/backend/internal/lxc/portmap.go
+++ b/backend/internal/lxc/portmap.go
@@ -67,6 +67,10 @@ func (m *Manager) ApplyPortMappings(id int) error {
applyIPv4EgressPolicy(c, bridge, subnet, tag)
+ if err := ApplyFirewallRules(id); err != nil {
+ return err
+ }
+
return nil
}
@@ -260,8 +264,8 @@ func EnsureForwardRules(bridge string) {
break
}
}
- insertArgs := append([]string{"-I", "FORWARD", "1"}, args...)
- exec.Command("iptables", insertArgs...).Run()
+ appendArgs := append([]string{"-A", "FORWARD"}, args...)
+ exec.Command("iptables", appendArgs...).Run()
}
}
@@ -576,6 +580,9 @@ func CleanFirewallRules(id int) {
cmd := exec.Command("bash", "-c",
fmt.Sprintf("iptables -S FORWARD 2>/dev/null | grep 'clicd-%s-fw-' | sed 's/^-A /-D /' | while read rule; do iptables $rule; done", tag))
cmd.CombinedOutput()
+ cmd = exec.Command("bash", "-c",
+ fmt.Sprintf("ip6tables -S FORWARD 2>/dev/null | grep 'clicd-%s-fw-' | sed 's/^-A /-D /' | while read rule; do ip6tables $rule; done", tag))
+ cmd.CombinedOutput()
// Also remove legacy default policy rules (without specific rule ID)
for _, suffix := range []string{"default-in", "default-out"} {
@@ -584,6 +591,9 @@ func CleanFirewallRules(id int) {
"-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-%s-%s", tag, suffix, proto),
).CombinedOutput()
}
+ exec.Command("ip6tables", "-D", "FORWARD",
+ "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-%s", tag, suffix),
+ ).CombinedOutput()
}
}
@@ -606,42 +616,140 @@ func ApplyFirewallRules(id int) error {
if c.IsKVM() {
bridge = "virbr0"
}
- containerIP := c.IP
- if containerIP == "" {
+ containerIP := strings.TrimSpace(c.IP)
+ containerIPv6s := firewallIPv6Addresses(c)
+ if containerIP == "" && len(containerIPv6s) == 0 {
return nil
}
tag := clicdTag(id)
- // Apply default DROP policy first (inserted at position 1).
- // Then insert ACCEPT rules (also at position 1), which pushes the DROPs down.
- // Final order: ACCEPT rules on top, DROP defaults below, bridge ACCEPT rules at the bottom.
- applyDefaultFirewallPolicy(tag, bridge, containerIP)
+ defaultAction := normalizeFirewallDefaultAction(c.FirewallDefaultAction)
+ if defaultAction == "DROP" {
+ if containerIP != "" {
+ if err := applyDefaultFirewallPolicy(tag, bridge, containerIP); err != nil {
+ return err
+ }
+ }
+ if err := applyDefaultFirewallIPv6Policy(tag, bridge, containerIPv6s); err != nil {
+ return err
+ }
+ }
- for _, rule := range c.FirewallRules {
+ for i := len(c.FirewallRules) - 1; i >= 0; i-- {
+ rule := c.FirewallRules[i]
if !rule.Enabled {
continue
}
- if err := applyOneFirewallRule(tag, bridge, containerIP, rule); err != nil {
- fmt.Printf("Warning: failed to apply firewall rule %s for container %d: %v\n", rule.ID, id, err)
+ if containerIP != "" && firewallRuleAppliesToFamily(rule, true) {
+ if err := applyOneFirewallRule(tag, bridge, containerIP, rule); err != nil {
+ return fmt.Errorf("failed to apply firewall rule %s for container %d: %w", rule.ID, id, err)
+ }
+ }
+ if len(containerIPv6s) > 0 && firewallRuleAppliesToFamily(rule, false) {
+ if err := applyOneFirewallIPv6Rule(tag, bridge, containerIPv6s, rule); err != nil {
+ return fmt.Errorf("failed to apply IPv6 firewall rule %s for container %d: %w", rule.ID, id, err)
+ }
}
}
return nil
}
+func normalizeFirewallDefaultAction(action string) string {
+ action = strings.ToUpper(strings.TrimSpace(action))
+ if action == "ACCEPT" {
+ return "ACCEPT"
+ }
+ return "DROP"
+}
+
+func normalizeFirewallNetwork(network string) string {
+ network = strings.ToLower(strings.TrimSpace(network))
+ switch network {
+ case "", "ipv4", "nat4":
+ return "ipv4"
+ case "ipv6":
+ return "ipv6"
+ case "all", "both":
+ return "all"
+ default:
+ return "ipv4"
+ }
+}
+
+func firewallRuleAppliesToFamily(rule config.FirewallRule, ipv4 bool) bool {
+ network := normalizeFirewallNetwork(rule.Network)
+ if network == "ipv4" {
+ return ipv4
+ }
+ if network == "ipv6" {
+ return !ipv4
+ }
+ if rule.SourceIP == "" {
+ return true
+ }
+ addr := firewallIPSpecAddr(rule.SourceIP)
+ if !addr.IsValid() {
+ return true
+ }
+ if ipv4 {
+ return addr.Is4()
+ }
+ return addr.Is6() && !addr.Is4In6()
+}
+
+func firewallIPSpecAddr(value string) netip.Addr {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return netip.Addr{}
+ }
+ if strings.Contains(value, "/") {
+ prefix, err := netip.ParsePrefix(value)
+ if err != nil {
+ return netip.Addr{}
+ }
+ return prefix.Addr()
+ }
+ addr, err := netip.ParseAddr(value)
+ if err != nil {
+ return netip.Addr{}
+ }
+ return addr
+}
+
+func firewallIPv6Addresses(c *config.Container) []string {
+ if c == nil {
+ return nil
+ }
+ c.NormalizeNetworkAssignments()
+ seen := map[string]bool{}
+ result := []string{}
+ for _, assignment := range c.IPv6Addresses {
+ ip := strings.TrimSpace(assignment.Address)
+ if ip == "" || seen[ip] {
+ continue
+ }
+ if addr, err := netip.ParseAddr(ip); err == nil && addr.Is6() && !addr.Is4In6() {
+ seen[ip] = true
+ result = append(result, ip)
+ }
+ }
+ return result
+}
+
func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallRule) error {
commentTag := fmt.Sprintf("clicd-%s-fw-%s", tag, rule.ID)
// Build base iptables args
args := []string{"-I", "FORWARD", "1"}
- // Direction: in = traffic arriving at container (-i bridge -d containerIP)
- // out = traffic leaving container (-o bridge -s containerIP)
+ // Direction: in = traffic arriving at container (-o bridge -d containerIP)
+ // out = traffic leaving container (-i bridge -s containerIP)
switch rule.Direction {
case "in":
- args = append(args, "-i", bridge, "-d", containerIP+"/32")
+ args = append(args, "-o", bridge, "-d", containerIP+"/32")
case "out":
- args = append(args, "-o", bridge, "-s", containerIP+"/32")
+ args = append(args, "-i", bridge, "-s", containerIP+"/32")
default:
return fmt.Errorf("invalid direction: %s", rule.Direction)
}
@@ -662,7 +770,7 @@ func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallR
if rule.Port != "" && (rule.Protocol == "tcp" || rule.Protocol == "udp") {
// For "in" direction, traffic going TO the container uses --dport
// For "out" direction, traffic going FROM the container uses --dport (destination port on remote)
- args = append(args, "--dport", normalizePortSpec(rule.Port))
+ args = append(args, firewallPortArgs(rule.Port)...)
}
// Source IP filter (for "out" direction, this matches the remote source; for "in", it matches the sender)
@@ -693,51 +801,145 @@ func applyOneFirewallRule(tag, bridge, containerIP string, rule config.FirewallR
return nil
}
+func applyOneFirewallIPv6Rule(tag, bridge string, containerIPs []string, rule config.FirewallRule) error {
+ for _, containerIP := range containerIPs {
+ commentTag := fmt.Sprintf("clicd-%s-fw-%s-v6-%s", tag, rule.ID, firewallCommentIPTag(containerIP))
+ args := []string{"-I", "FORWARD", "1"}
+
+ switch rule.Direction {
+ case "in":
+ args = append(args, "-o", bridge, "-d", containerIP+"/128")
+ case "out":
+ args = append(args, "-i", bridge, "-s", containerIP+"/128")
+ default:
+ return fmt.Errorf("invalid direction: %s", rule.Direction)
+ }
+
+ switch rule.Protocol {
+ case "tcp", "udp":
+ args = append(args, "-p", rule.Protocol)
+ case "icmp":
+ args = append(args, "-p", "ipv6-icmp")
+ case "all":
+ default:
+ return fmt.Errorf("invalid protocol: %s", rule.Protocol)
+ }
+
+ if rule.Port != "" && (rule.Protocol == "tcp" || rule.Protocol == "udp") {
+ args = append(args, firewallPortArgs(rule.Port)...)
+ }
+
+ if rule.SourceIP != "" {
+ switch rule.Direction {
+ case "in":
+ args = append(args, "-s", rule.SourceIP)
+ case "out":
+ args = append(args, "-d", rule.SourceIP)
+ }
+ }
+
+ action := "DROP"
+ if rule.Action == "ACCEPT" {
+ action = "ACCEPT"
+ }
+ args = append(args, "-j", action)
+ args = append(args, "-m", "comment", "--comment", commentTag)
+
+ cmd := exec.Command("ip6tables", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("ip6tables error: %s", string(output))
+ }
+ }
+ return nil
+}
+
+func firewallPortArgs(port string) []string {
+ spec := normalizePortSpec(port)
+ if strings.Contains(spec, ",") {
+ return []string{"-m", "multiport", "--dports", spec}
+ }
+ return []string{"--dport", spec}
+}
+
// normalizePortSpec converts user port input to iptables-compatible port spec.
-// "80,443" -> "80,443", "8000-9000" -> "8000:9000", "22" -> "22"
+// "80,443" -> "80,443", "8000-9000" -> "8000:9000", "80,443,8000-9000" -> "80,443,8000:9000"
func normalizePortSpec(port string) string {
port = strings.TrimSpace(port)
if port == "" {
return ""
}
- // Convert comma-separated to iptables format (already valid)
- // Convert dash range to colon range: "8000-9000" -> "8000:9000"
- if strings.Contains(port, "-") && !strings.Contains(port, ":") {
- parts := strings.SplitN(port, "-", 2)
- if len(parts) == 2 {
- return strings.TrimSpace(parts[0]) + ":" + strings.TrimSpace(parts[1])
+ parts := strings.Split(port, ",")
+ for i, part := range parts {
+ part = strings.TrimSpace(part)
+ if strings.Contains(part, "-") && !strings.Contains(part, ":") {
+ bounds := strings.SplitN(part, "-", 2)
+ if len(bounds) == 2 {
+ part = strings.TrimSpace(bounds[0]) + ":" + strings.TrimSpace(bounds[1])
+ }
}
+ parts[i] = part
}
- return port
+ return strings.Join(parts, ",")
}
-func applyDefaultFirewallPolicy(tag, bridge, containerIP string) {
- // Default DROP: inserted at position 1 so they sit above bridge ACCEPT rules.
- // The user-defined ACCEPT rules (also at position 1) were inserted first,
- // so they end up above these DROP defaults after the position-1 insertions.
- for _, proto := range []string{"tcp", "udp"} {
- args := []string{
- "-I", "FORWARD", "1",
- "-i", bridge,
- "-d", containerIP + "/32",
- "-p", proto,
- "-j", "DROP",
- "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-in-%s", tag, proto),
- }
- cmd := exec.Command("iptables", args...)
- cmd.CombinedOutput()
- }
-
- for _, proto := range []string{"tcp", "udp"} {
- args := []string{
+func applyDefaultFirewallPolicy(tag, bridge, containerIP string) error {
+ defaults := [][]string{
+ {
"-I", "FORWARD", "1",
"-o", bridge,
- "-s", containerIP + "/32",
- "-p", proto,
+ "-d", containerIP + "/32",
"-j", "DROP",
- "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-out-%s", tag, proto),
- }
- cmd := exec.Command("iptables", args...)
- cmd.CombinedOutput()
+ "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-in", tag),
+ },
+ {
+ "-I", "FORWARD", "1",
+ "-i", bridge,
+ "-s", containerIP + "/32",
+ "-j", "DROP",
+ "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-out", tag),
+ },
}
+ for _, args := range defaults {
+ cmd := exec.Command("iptables", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("iptables default firewall error: %s", string(output))
+ }
+ }
+ return nil
+}
+
+func applyDefaultFirewallIPv6Policy(tag, bridge string, containerIPs []string) error {
+ for _, containerIP := range containerIPs {
+ defaults := [][]string{
+ {
+ "-I", "FORWARD", "1",
+ "-o", bridge,
+ "-d", containerIP + "/128",
+ "-j", "DROP",
+ "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-in-v6-%s", tag, firewallCommentIPTag(containerIP)),
+ },
+ {
+ "-I", "FORWARD", "1",
+ "-i", bridge,
+ "-s", containerIP + "/128",
+ "-j", "DROP",
+ "-m", "comment", "--comment", fmt.Sprintf("clicd-%s-fw-default-out-v6-%s", tag, firewallCommentIPTag(containerIP)),
+ },
+ }
+ for _, args := range defaults {
+ cmd := exec.Command("ip6tables", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("ip6tables default firewall error: %s", string(output))
+ }
+ }
+ }
+ return nil
+}
+
+func firewallCommentIPTag(ip string) string {
+ replacer := strings.NewReplacer(":", "_", ".", "_", "/", "_")
+ return replacer.Replace(ip)
}
diff --git a/backend/internal/server/web/.gitkeep b/backend/internal/server/web/.gitkeep
index 8d1c8b6..30259b2 100644
--- a/backend/internal/server/web/.gitkeep
+++ b/backend/internal/server/web/.gitkeep
@@ -1 +1 @@
-
+
diff --git a/backend/internal/version/version.go b/backend/internal/version/version.go
index c993d5c..0eeb0f7 100644
--- a/backend/internal/version/version.go
+++ b/backend/internal/version/version.go
@@ -1,7 +1,7 @@
package version
var (
- Version = "1.1.17"
+ Version = "1.1.19"
Repo = "MengMengCode/CLICD"
)
diff --git a/docs/en/features/api.md b/docs/en/features/api.md
index 7d2512a..137f789 100644
--- a/docs/en/features/api.md
+++ b/docs/en/features/api.md
@@ -53,7 +53,11 @@ Create container example:
"ssh_auth_mode": "auto_password",
"ssh_password": "",
"ssh_public_key": "",
- "expires_at": ""
+ "expires_at": "",
+ "network_down_mbps": 100,
+ "network_up_mbps": 50,
+ "io_read_mbps": 120,
+ "io_write_mbps": 80
}
```
@@ -71,6 +75,12 @@ Field notes:
| `ssh_auth_mode` | Linux creation supports `auto_password`, `password`, and `key`; reinstall also supports `keep`. |
| `ssh_password` | Custom password for `password` mode. It must be 8-64 characters, include letters and digits, and contain no whitespace. |
| `ssh_public_key` | One-line SSH public key for `key` mode. |
+| `network_down_mbps` | Optional container download/downlink bandwidth limit in Mbps. `0` means unlimited. |
+| `network_up_mbps` | Optional container upload/uplink bandwidth limit in Mbps. `0` means unlimited. |
+| `io_read_mbps` | Optional disk read limit in MB/s. `0` means unlimited. |
+| `io_write_mbps` | Optional disk write limit in MB/s. `0` means unlimited. |
+| `network_bw_mbps` | Legacy-compatible field. Sets symmetric downlink/uplink bandwidth; new integrations should prefer the split fields. |
+| `io_speed_mbps` | Legacy-compatible field. Sets symmetric read/write I/O limits; new integrations should prefer the split fields. |
Reinstall example:
@@ -85,6 +95,102 @@ Reinstall example:
`keep` is only for reinstall and keeps the current SSH password. Windows KVM images ignore Linux SSH public key fields.
+## Resource and Traffic Limits
+
+`PUT /api/v1/containers/{id}/resource-limit` supports partial updates. Fields omitted from the request remain unchanged.
+
+```json
+{
+ "vcpu": 2,
+ "ram_mb": 1024,
+ "network_down_mbps": 100,
+ "network_up_mbps": 50,
+ "io_read_mbps": 120,
+ "io_write_mbps": 80
+}
+```
+
+Legacy `network_bw_mbps` and `io_speed_mbps` are still accepted. They mean symmetric downlink/uplink bandwidth and symmetric read/write I/O limits. New integrations should use the split fields to control download/upload and read/write independently.
+
+`PUT /api/v1/containers/{id}/traffic-limit` request body:
+
+```json
+{
+ "traffic_mode": "total",
+ "monthly_traffic_gb": 1024,
+ "traffic_in_gb": 0,
+ "traffic_out_gb": 0
+}
+```
+
+| Field | Description |
+| --- | --- |
+| `traffic_mode` | Traffic limit mode. Common values are `total` for a shared total limit and `split` for separate inbound/outbound limits. |
+| `monthly_traffic_gb` | Monthly total traffic quota for `total` mode, in GB. `0` means unlimited. |
+| `traffic_in_gb` | Monthly inbound quota for `split` mode, in GB. `0` means unlimited. |
+| `traffic_out_gb` | Monthly outbound quota for `split` mode, in GB. `0` means unlimited. |
+
+## Container Firewall
+
+Read container firewall settings with `GET /api/v1/containers/{id}/firewall` and update them with `PUT /api/v1/containers/{id}/firewall`. Updates are applied immediately when the container is running.
+
+Update example:
+
+```json
+{
+ "enabled": true,
+ "default_action": "DROP",
+ "rules": [
+ {
+ "direction": "in",
+ "protocol": "tcp",
+ "action": "ACCEPT",
+ "network": "ipv4",
+ "source_ip": "203.0.113.0/24",
+ "port": "22,80,443",
+ "description": "allow admin and web"
+ }
+ ]
+}
+```
+
+| Field | Description |
+| --- | --- |
+| `enabled` | Whether the container firewall is enabled. |
+| `default_action` | Default action: `ACCEPT` or `DROP`. |
+| `rules[].id` | Optional. Omit for new rules and the backend will generate one. |
+| `rules[].direction` | Direction: `in` or `out`. |
+| `rules[].protocol` | Protocol: `tcp`, `udp`, `icmp`, or `all`. |
+| `rules[].action` | Action: `ACCEPT` or `DROP`. |
+| `rules[].network` | Network type: `ipv4`, `ipv6`, or `all`. |
+| `rules[].source_ip` | Optional source IP, CIDR, or address range. |
+| `rules[].port` | Optional. Supported only for `tcp`/`udp`; examples: `22`, `80,443`, or `8000-9000`. |
+| `rules[].description` | Optional note. |
+
+## API Key Create and Update
+
+`POST /api/v1/api-keys` and `PATCH /api/v1/api-keys/{id}` use the same field shape. `name` is required when creating a key; updates overwrite the fields you send.
+
+```json
+{
+ "name": "Automation",
+ "ip_whitelist": "198.51.100.23,203.0.113.0/24",
+ "scopes": ["dashboard:read", "container:read", "container:power"],
+ "expires_at": "2026-12-31 23:59:59",
+ "disabled": false,
+ "container_uuids": ["00000000-0000-4000-8000-000000000005"]
+}
+```
+
+| Field | Description |
+| --- | --- |
+| `name` | API key name. Required when creating a key. |
+| `ip_whitelist` | Optional allowed source IPs/CIDRs, comma-separated. Empty means no IP restriction. |
+| `scopes` | Optional permission scopes. If omitted, the default read-only scopes are used. `*` grants all permissions. |
+| `expires_at` | Optional expiration time. Empty means no expiration. |
+| `disabled` | Whether this key is disabled. |
+| `container_uuids` | Optional container allowlist that limits the key to specific containers. |
+
## Python Example
Fetch containers:
@@ -140,6 +246,7 @@ print(resp.json())
| --- | --- | --- |
| GET | `/api/v1/dashboard` | Dashboard statistics |
| GET | `/api/v1/host-info` | Host resources |
+| GET | `/api/v1/host-report` | Host inspection report |
| GET | `/api/v1/routing` | NAT/IPv4/IPv6 routing |
| PUT | `/api/v1/routing` | Update public IPv4/IPv6 pools |
| POST | `/api/v1/routing/ipv4-scan` | Scan a public IPv4 segment |
@@ -151,10 +258,11 @@ print(resp.json())
| Method | Path | Description |
| --- | --- | --- |
-| GET | `/api/v1/containers` | Container list |
+| GET | `/api/v1/containers` | Container list (recommended) |
+| GET | `/api/v1/containers/list` | Compatible GET form for container list |
| POST | `/api/v1/containers/list` | Compatible POST form for container list |
| POST | `/api/v1/containers` | Create container |
-| GET | `/api/v1/containers/{id|uuid|name}` | Container details |
+| GET | `/api/v1/containers/{id\|uuid\|name}` | Container details |
| POST | `/api/v1/containers/{id}/start` | Start |
| POST | `/api/v1/containers/{id}/stop` | Stop |
| POST | `/api/v1/containers/{id}/restart` | Restart |
@@ -173,10 +281,12 @@ print(resp.json())
| Method | Path | Description |
| --- | --- | --- |
-| GET | `/api/v1/containers/{id}/random-port` | Random available port |
+| GET | `/api/v1/containers/{id}/random-port` | Random available port; accepts `host_ip` to check a specific host IP |
| POST | `/api/v1/containers/{id}/port-mappings` | Add port mapping |
| PUT | `/api/v1/containers/{id}/port-mappings/{index}` | Update port mapping |
| DELETE | `/api/v1/containers/{id}/port-mappings/{index}` | Delete port mapping |
+| GET | `/api/v1/containers/{id}/firewall` | Get container firewall settings |
+| PUT | `/api/v1/containers/{id}/firewall` | Update container firewall settings |
| GET | `/api/v1/snapshots` | Snapshot overview |
| GET | `/api/v1/containers/{id}/snapshots` | Container snapshots |
| POST | `/api/v1/containers/{id}/snapshots` | Create snapshot |
@@ -191,6 +301,7 @@ print(resp.json())
| --- | --- | --- |
| GET | `/api/v1/templates` | Template list |
| GET | `/api/v1/images` | Image management list |
+| GET | `/api/v1/images/enabled` | Enabled and downloaded images; supports `type=lxc\|kvm` |
| POST | `/api/v1/images/download` | Download image |
| POST | `/api/v1/images/cancel` | Cancel image download |
| DELETE | `/api/v1/images/delete` | Delete image cache |
@@ -203,6 +314,12 @@ print(resp.json())
| PUT | `/api/v1/security/settings` | Update security settings |
| GET | `/api/v1/swap` | Swap information |
| POST | `/api/v1/swap` | Adjust Swap |
+| GET | `/api/v1/language` | Current panel language |
+| POST/PUT | `/api/v1/language` | Update panel language |
+| GET | `/api/v1/ssl` | SSL settings (requires admin permission / `admin:access`) |
+| PUT | `/api/v1/ssl` | Update SSL settings (requires admin permission / `admin:access`) |
+| GET | `/api/v1/webssh-origins` | WebSSH Origin allowlist (requires admin permission / `admin:access`) |
+| PUT | `/api/v1/webssh-origins` | Update WebSSH Origin allowlist (requires admin permission / `admin:access`) |
| POST | `/api/v1/batch-create` | Batch create containers |
| POST | `/api/v1/batch-action` | Batch power action, delete, or reinstall |
| POST | `/api/v1/ssh-ticket` | Create WebSSH ticket |
@@ -255,6 +372,16 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
"load": { "load1": 0.01, "load5": 0.03, "load15": 0.01 }
}
},
+ "GET /api/v1/host-report": {
+ "success": true,
+ "data": {
+ "generated_at": "2026-06-12 10:00:00",
+ "summary": { "status": "ok", "warnings": 0 },
+ "host": { "hostname": "node-1", "kernel": "6.8.0" },
+ "resources": { "cpu_cores": 8, "ram_total_mb": 31825, "disk_total_gb": 1750.49 },
+ "network": { "public_ipv4": "203.0.113.10", "public_ipv6": "2001:db8:100::2" }
+ }
+ },
"GET /api/v1/routing": {
"success": true,
"data": {
@@ -331,6 +458,10 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
"vcpu": 1,
"ram_mb": 512,
"disk_gb": 10,
+ "network_down_mbps": 100,
+ "network_up_mbps": 50,
+ "io_read_mbps": 120,
+ "io_write_mbps": 80,
"status": "running",
"ip": "10.0.0.10",
"ipv6": "2001:db8:100::1005",
@@ -343,6 +474,12 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
}
]
},
+ "GET /api/v1/containers/list": {
+ "success": true,
+ "data": [
+ { "id": 5, "uuid": "00000000-0000-4000-8000-000000000005", "name": "example-vm", "status": "running", "ip": "10.0.0.10" }
+ ]
+ },
"POST /api/v1/containers/list": {
"success": true,
"data": [
@@ -410,7 +547,7 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
"success": true,
"data": {
"mode": "total",
- "limit_gb": 0,
+ "limit_gb": 1024,
"in_limit_gb": 0,
"out_limit_gb": 0,
"total_used_bytes": 142082,
@@ -453,7 +590,7 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
```json
{
- "GET /api/v1/containers/{id}/random-port": {
+ "GET /api/v1/containers/{id}/random-port?host_ip=203.0.113.10": {
"success": true,
"data": { "port": 61320 }
},
@@ -474,6 +611,21 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
"success": true,
"data": []
},
+ "GET /api/v1/containers/{id}/firewall": {
+ "success": true,
+ "data": {
+ "enabled": true,
+ "default_action": "DROP",
+ "rules": [
+ { "id": "a1b2c3d4", "direction": "in", "protocol": "tcp", "action": "ACCEPT", "network": "ipv4", "source_ip": "203.0.113.0/24", "port": "22,80,443", "description": "allow admin and web" }
+ ]
+ }
+ },
+ "PUT /api/v1/containers/{id}/firewall": {
+ "success": true,
+ "message": "Firewall updated",
+ "data": { "enabled": true, "default_action": "DROP", "rules": [] }
+ },
"GET /api/v1/snapshots": {
"success": true,
"data": null
@@ -539,6 +691,12 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "type": "lxc", "downloaded": true, "enabled": true, "downloading": false, "progress": 0, "size_bytes": 135005452 }
]
},
+ "GET /api/v1/images/enabled?type=lxc": {
+ "success": true,
+ "data": [
+ { "id": "ubuntu-noble", "name": "Ubuntu 24.04", "distro": "ubuntu", "release": "noble", "arch": "amd64", "variant": "default", "description": "Ubuntu 24.04 LTS", "type": "lxc" }
+ ]
+ },
"POST /api/v1/images/download": {
"success": true,
"message": "Already downloaded"
@@ -585,9 +743,35 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
},
"POST /api/v1/swap": {
"success": true,
- "message": "SWAP 已调整为 16384 MB",
+ "message": "SWAP adjusted to 16384 MB",
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
},
+ "GET /api/v1/language": {
+ "success": true,
+ "data": { "language": "zh" }
+ },
+ "PUT /api/v1/language": {
+ "success": true,
+ "data": { "language": "en" }
+ },
+ "GET /api/v1/ssl": {
+ "success": true,
+ "data": { "enabled": true, "mode": "self-signed", "target": "panel.example.com", "detected_host": "panel.example.com", "needs_restart": false }
+ },
+ "PUT /api/v1/ssl": {
+ "success": true,
+ "message": "SSL settings saved",
+ "data": { "enabled": true, "mode": "self-signed", "target": "panel.example.com", "needs_restart": true }
+ },
+ "GET /api/v1/webssh-origins": {
+ "success": true,
+ "data": { "origins": ["https://panel.example.com"], "current_origin": "https://panel.example.com" }
+ },
+ "PUT /api/v1/webssh-origins": {
+ "success": true,
+ "message": "Origin allowlist saved",
+ "data": { "origins": ["https://panel.example.com"], "current_origin": "https://panel.example.com" }
+ },
"POST /api/v1/batch-create": {
"success": true,
"data": ["task-12"]
@@ -654,17 +838,17 @@ The samples below are grouped by endpoint path. Resource numbers, task IDs, cont
"GET /api/v1/api-keys": {
"success": true,
"data": [
- { "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "last_used_ip": "198.51.100.23" }
+ { "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "expires_at": "", "disabled": false, "container_uuids": [], "last_used_ip": "198.51.100.23" }
]
},
"POST /api/v1/api-keys": {
"success": true,
"message": "API key created. Save this key now - it won't be shown again.",
- "data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"] }
+ "data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "ip_whitelist": "198.51.100.23", "scopes": ["dashboard:read", "container:read"], "expires_at": "2026-12-31 23:59:59", "disabled": false, "container_uuids": ["00000000-0000-4000-8000-000000000005"] }
},
"PATCH /api/v1/api-keys/{id}": {
"success": true,
- "data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "disabled": false }
+ "data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "expires_at": "2026-12-31 23:59:59", "disabled": false, "container_uuids": ["00000000-0000-4000-8000-000000000005"] }
},
"DELETE /api/v1/api-keys/{id}": {
"success": true,
diff --git a/docs/features/api.md b/docs/features/api.md
index b247a4b..86ef1cd 100644
--- a/docs/features/api.md
+++ b/docs/features/api.md
@@ -53,7 +53,11 @@ curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/da
"ssh_auth_mode": "auto_password",
"ssh_password": "",
"ssh_public_key": "",
- "expires_at": ""
+ "expires_at": "",
+ "network_down_mbps": 100,
+ "network_up_mbps": 50,
+ "io_read_mbps": 120,
+ "io_write_mbps": 80
}
```
@@ -71,6 +75,12 @@ curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/da
| `ssh_auth_mode` | Linux 创建支持 `auto_password`、`password`、`key`;重装额外支持 `keep`。 |
| `ssh_password` | `password` 模式下的自定义密码;8-64 位,至少包含字母和数字,不能包含空白字符。 |
| `ssh_public_key` | `key` 模式下的一行 SSH 公钥。 |
+| `network_down_mbps` | 可选;容器下行/下载带宽限制,单位 Mbps,`0` 表示不限制。 |
+| `network_up_mbps` | 可选;容器上行/上传带宽限制,单位 Mbps,`0` 表示不限制。 |
+| `io_read_mbps` | 可选;磁盘读取限速,单位 MB/s,`0` 表示不限制。 |
+| `io_write_mbps` | 可选;磁盘写入限速,单位 MB/s,`0` 表示不限制。 |
+| `network_bw_mbps` | 兼容旧字段;同时设置上下行对称带宽,新接入推荐使用拆分字段。 |
+| `io_speed_mbps` | 兼容旧字段;同时设置读写对称 IO 限速,新接入推荐使用拆分字段。 |
重装示例:
@@ -85,6 +95,102 @@ curl -H "Authorization: Bearer YOUR_API_KEY" https://panel.example.com/api/v1/da
`keep` 仅用于重装,表示沿用当前 SSH 密码。Windows KVM 镜像会忽略 Linux SSH 公钥相关字段。
+## 资源限制与流量限制
+
+`PUT /api/v1/containers/{id}/resource-limit` 支持按字段局部更新;未传的字段保持不变。
+
+```json
+{
+ "vcpu": 2,
+ "ram_mb": 1024,
+ "network_down_mbps": 100,
+ "network_up_mbps": 50,
+ "io_read_mbps": 120,
+ "io_write_mbps": 80
+}
+```
+
+旧版 `network_bw_mbps` 和 `io_speed_mbps` 仍可用,分别表示上下行对称带宽和读写对称 IO 限速。新接入建议使用拆分字段,以便分别控制下载/上传和读取/写入。
+
+`PUT /api/v1/containers/{id}/traffic-limit` 请求体:
+
+```json
+{
+ "traffic_mode": "total",
+ "monthly_traffic_gb": 1024,
+ "traffic_in_gb": 0,
+ "traffic_out_gb": 0
+}
+```
+
+| 字段 | 说明 |
+| --- | --- |
+| `traffic_mode` | 流量限制模式;常用 `total` 表示总量限制,`split` 表示入站/出站分别限制。 |
+| `monthly_traffic_gb` | `total` 模式下的月总流量额度,单位 GB;`0` 表示不限制。 |
+| `traffic_in_gb` | `split` 模式下的月入站额度,单位 GB;`0` 表示不限制。 |
+| `traffic_out_gb` | `split` 模式下的月出站额度,单位 GB;`0` 表示不限制。 |
+
+## 容器防火墙
+
+容器防火墙通过 `GET /api/v1/containers/{id}/firewall` 读取,通过 `PUT /api/v1/containers/{id}/firewall` 更新。容器运行中更新时会立即应用规则。
+
+更新示例:
+
+```json
+{
+ "enabled": true,
+ "default_action": "DROP",
+ "rules": [
+ {
+ "direction": "in",
+ "protocol": "tcp",
+ "action": "ACCEPT",
+ "network": "ipv4",
+ "source_ip": "203.0.113.0/24",
+ "port": "22,80,443",
+ "description": "allow admin and web"
+ }
+ ]
+}
+```
+
+| 字段 | 说明 |
+| --- | --- |
+| `enabled` | 是否启用容器防火墙。 |
+| `default_action` | 默认动作:`ACCEPT` 或 `DROP`。 |
+| `rules[].id` | 可选;新规则可省略,后端会自动生成。 |
+| `rules[].direction` | 方向:`in` 或 `out`。 |
+| `rules[].protocol` | 协议:`tcp`、`udp`、`icmp` 或 `all`。 |
+| `rules[].action` | 动作:`ACCEPT` 或 `DROP`。 |
+| `rules[].network` | 网络类型:`ipv4`、`ipv6` 或 `all`。 |
+| `rules[].source_ip` | 可选;源 IP、CIDR 或地址范围。 |
+| `rules[].port` | 可选;仅 `tcp`/`udp` 支持,可写 `22`、`80,443` 或 `8000-9000`。 |
+| `rules[].description` | 可选备注。 |
+
+## API Key 创建与更新
+
+`POST /api/v1/api-keys` 和 `PATCH /api/v1/api-keys/{id}` 使用相同的字段结构。创建时 `name` 必填;更新时根据需要覆盖字段。
+
+```json
+{
+ "name": "Automation",
+ "ip_whitelist": "198.51.100.23,203.0.113.0/24",
+ "scopes": ["dashboard:read", "container:read", "container:power"],
+ "expires_at": "2026-12-31 23:59:59",
+ "disabled": false,
+ "container_uuids": ["00000000-0000-4000-8000-000000000005"]
+}
+```
+
+| 字段 | 说明 |
+| --- | --- |
+| `name` | API Key 名称;创建时必填。 |
+| `ip_whitelist` | 可选;允许的来源 IP/CIDR,多个值用逗号分隔;空值表示不限制。 |
+| `scopes` | 可选;权限范围。省略时使用默认只读范围,传 `*` 表示全部权限。 |
+| `expires_at` | 可选;过期时间,空值表示不过期。 |
+| `disabled` | 是否禁用该 Key。 |
+| `container_uuids` | 可选;限制该 Key 只能访问指定容器。 |
+
## Python 示例
获取容器列表:
@@ -140,6 +246,7 @@ print(resp.json())
| --- | --- | --- |
| GET | `/api/v1/dashboard` | 控制面板统计 |
| GET | `/api/v1/host-info` | 主机资源 |
+| GET | `/api/v1/host-report` | 主机巡检报告 |
| GET | `/api/v1/routing` | NAT/IPv4/IPv6 路由 |
| PUT | `/api/v1/routing` | 更新公网 IPv4/IPv6 池 |
| POST | `/api/v1/routing/ipv4-scan` | 扫描公网 IPv4 段 |
@@ -151,10 +258,11 @@ print(resp.json())
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | `/api/v1/containers` | 容器列表 |
+| GET | `/api/v1/containers` | 容器列表(推荐) |
+| GET | `/api/v1/containers/list` | 容器列表兼容 GET 写法 |
| POST | `/api/v1/containers/list` | 容器列表兼容 POST 写法 |
| POST | `/api/v1/containers` | 创建容器 |
-| GET | `/api/v1/containers/{id|uuid|name}` | 容器详情 |
+| GET | `/api/v1/containers/{id\|uuid\|name}` | 容器详情 |
| POST | `/api/v1/containers/{id}/start` | 开机 |
| POST | `/api/v1/containers/{id}/stop` | 关机 |
| POST | `/api/v1/containers/{id}/restart` | 重启 |
@@ -173,10 +281,12 @@ print(resp.json())
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | `/api/v1/containers/{id}/random-port` | 随机可用端口 |
+| GET | `/api/v1/containers/{id}/random-port` | 随机可用端口;可传 `host_ip` 查询指定宿主机 IP |
| POST | `/api/v1/containers/{id}/port-mappings` | 添加端口映射 |
| PUT | `/api/v1/containers/{id}/port-mappings/{index}` | 更新端口映射 |
| DELETE | `/api/v1/containers/{id}/port-mappings/{index}` | 删除端口映射 |
+| GET | `/api/v1/containers/{id}/firewall` | 获取容器防火墙设置 |
+| PUT | `/api/v1/containers/{id}/firewall` | 更新容器防火墙设置 |
| GET | `/api/v1/snapshots` | 快照总览 |
| GET | `/api/v1/containers/{id}/snapshots` | 容器快照 |
| POST | `/api/v1/containers/{id}/snapshots` | 创建快照 |
@@ -191,6 +301,7 @@ print(resp.json())
| --- | --- | --- |
| GET | `/api/v1/templates` | 模板列表 |
| GET | `/api/v1/images` | 镜像管理列表 |
+| GET | `/api/v1/images/enabled` | 已启用且已下载的镜像;支持 `type=lxc\|kvm` |
| POST | `/api/v1/images/download` | 下载镜像 |
| POST | `/api/v1/images/cancel` | 取消镜像下载 |
| DELETE | `/api/v1/images/delete` | 删除镜像缓存 |
@@ -203,6 +314,12 @@ print(resp.json())
| PUT | `/api/v1/security/settings` | 更新安全设置 |
| GET | `/api/v1/swap` | Swap 信息 |
| POST | `/api/v1/swap` | 调整 Swap |
+| GET | `/api/v1/language` | 当前面板语言 |
+| POST/PUT | `/api/v1/language` | 更新面板语言 |
+| GET | `/api/v1/ssl` | SSL 设置(需管理员权限 / `admin:access`) |
+| PUT | `/api/v1/ssl` | 更新 SSL 设置(需管理员权限 / `admin:access`) |
+| GET | `/api/v1/webssh-origins` | WebSSH Origin 白名单(需管理员权限 / `admin:access`) |
+| PUT | `/api/v1/webssh-origins` | 更新 WebSSH Origin 白名单(需管理员权限 / `admin:access`) |
| POST | `/api/v1/batch-create` | 批量创建容器 |
| POST | `/api/v1/batch-action` | 批量开关机/删除/重装 |
| POST | `/api/v1/ssh-ticket` | 创建 WebSSH 票据 |
@@ -255,6 +372,16 @@ print(resp.json())
"load": { "load1": 0.01, "load5": 0.03, "load15": 0.01 }
}
},
+ "GET /api/v1/host-report": {
+ "success": true,
+ "data": {
+ "generated_at": "2026-06-12 10:00:00",
+ "summary": { "status": "ok", "warnings": 0 },
+ "host": { "hostname": "node-1", "kernel": "6.8.0" },
+ "resources": { "cpu_cores": 8, "ram_total_mb": 31825, "disk_total_gb": 1750.49 },
+ "network": { "public_ipv4": "203.0.113.10", "public_ipv6": "2001:db8:100::2" }
+ }
+ },
"GET /api/v1/routing": {
"success": true,
"data": {
@@ -331,6 +458,10 @@ print(resp.json())
"vcpu": 1,
"ram_mb": 512,
"disk_gb": 10,
+ "network_down_mbps": 100,
+ "network_up_mbps": 50,
+ "io_read_mbps": 120,
+ "io_write_mbps": 80,
"status": "running",
"ip": "10.0.0.10",
"ipv6": "2001:db8:100::1005",
@@ -343,6 +474,12 @@ print(resp.json())
}
]
},
+ "GET /api/v1/containers/list": {
+ "success": true,
+ "data": [
+ { "id": 5, "uuid": "00000000-0000-4000-8000-000000000005", "name": "example-vm", "status": "running", "ip": "10.0.0.10" }
+ ]
+ },
"POST /api/v1/containers/list": {
"success": true,
"data": [
@@ -410,7 +547,7 @@ print(resp.json())
"success": true,
"data": {
"mode": "total",
- "limit_gb": 0,
+ "limit_gb": 1024,
"in_limit_gb": 0,
"out_limit_gb": 0,
"total_used_bytes": 142082,
@@ -453,7 +590,7 @@ print(resp.json())
```json
{
- "GET /api/v1/containers/{id}/random-port": {
+ "GET /api/v1/containers/{id}/random-port?host_ip=203.0.113.10": {
"success": true,
"data": { "port": 61320 }
},
@@ -474,6 +611,21 @@ print(resp.json())
"success": true,
"data": []
},
+ "GET /api/v1/containers/{id}/firewall": {
+ "success": true,
+ "data": {
+ "enabled": true,
+ "default_action": "DROP",
+ "rules": [
+ { "id": "a1b2c3d4", "direction": "in", "protocol": "tcp", "action": "ACCEPT", "network": "ipv4", "source_ip": "203.0.113.0/24", "port": "22,80,443", "description": "allow admin and web" }
+ ]
+ }
+ },
+ "PUT /api/v1/containers/{id}/firewall": {
+ "success": true,
+ "message": "Firewall updated",
+ "data": { "enabled": true, "default_action": "DROP", "rules": [] }
+ },
"GET /api/v1/snapshots": {
"success": true,
"data": null
@@ -539,6 +691,12 @@ print(resp.json())
{ "id": "ubuntu-noble", "name": "Ubuntu 24.04", "type": "lxc", "downloaded": true, "enabled": true, "downloading": false, "progress": 0, "size_bytes": 135005452 }
]
},
+ "GET /api/v1/images/enabled?type=lxc": {
+ "success": true,
+ "data": [
+ { "id": "ubuntu-noble", "name": "Ubuntu 24.04", "distro": "ubuntu", "release": "noble", "arch": "amd64", "variant": "default", "description": "Ubuntu 24.04 LTS", "type": "lxc" }
+ ]
+ },
"POST /api/v1/images/download": {
"success": true,
"message": "Already downloaded"
@@ -588,6 +746,32 @@ print(resp.json())
"message": "SWAP 已调整为 16384 MB",
"data": { "total_mb": 16383, "used_mb": 0, "free_mb": 16383, "enabled": true, "swap_file": "/swapfile" }
},
+ "GET /api/v1/language": {
+ "success": true,
+ "data": { "language": "zh" }
+ },
+ "PUT /api/v1/language": {
+ "success": true,
+ "data": { "language": "en" }
+ },
+ "GET /api/v1/ssl": {
+ "success": true,
+ "data": { "enabled": true, "mode": "self-signed", "target": "panel.example.com", "detected_host": "panel.example.com", "needs_restart": false }
+ },
+ "PUT /api/v1/ssl": {
+ "success": true,
+ "message": "SSL settings saved",
+ "data": { "enabled": true, "mode": "self-signed", "target": "panel.example.com", "needs_restart": true }
+ },
+ "GET /api/v1/webssh-origins": {
+ "success": true,
+ "data": { "origins": ["https://panel.example.com"], "current_origin": "https://panel.example.com" }
+ },
+ "PUT /api/v1/webssh-origins": {
+ "success": true,
+ "message": "Origin allowlist saved",
+ "data": { "origins": ["https://panel.example.com"], "current_origin": "https://panel.example.com" }
+ },
"POST /api/v1/batch-create": {
"success": true,
"data": ["task-12"]
@@ -654,17 +838,17 @@ print(resp.json())
"GET /api/v1/api-keys": {
"success": true,
"data": [
- { "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "last_used_ip": "198.51.100.23" }
+ { "id": "c271023f", "name": "Test", "prefix": "clicd_sk_dd9d...", "ip_whitelist": "", "created_at": "2026-06-08 15:44:40", "last_used": "2026-06-08 15:46:10", "scopes": ["*"], "expires_at": "", "disabled": false, "container_uuids": [], "last_used_ip": "198.51.100.23" }
]
},
"POST /api/v1/api-keys": {
"success": true,
"message": "API key created. Save this key now - it won't be shown again.",
- "data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"] }
+ "data": { "id": "a1b2c3d4", "name": "Automation", "key": "clicd_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "prefix": "clicd_sk_xxxx...", "ip_whitelist": "198.51.100.23", "scopes": ["dashboard:read", "container:read"], "expires_at": "2026-12-31 23:59:59", "disabled": false, "container_uuids": ["00000000-0000-4000-8000-000000000005"] }
},
"PATCH /api/v1/api-keys/{id}": {
"success": true,
- "data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "disabled": false }
+ "data": { "id": "a1b2c3d4", "name": "Automation", "prefix": "clicd_sk_xxxx...", "scopes": ["dashboard:read", "container:read"], "expires_at": "2026-12-31 23:59:59", "disabled": false, "container_uuids": ["00000000-0000-4000-8000-000000000005"] }
},
"DELETE /api/v1/api-keys/{id}": {
"success": true,
diff --git a/frontend/package.json b/frontend/package.json
index edc348b..de64020 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "clicd-frontend",
"private": true,
- "version": "1.1.17",
+ "version": "1.1.19",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/frontend/src/components/ContainerCard.tsx b/frontend/src/components/ContainerCard.tsx
index c20f2ef..7085448 100644
--- a/frontend/src/components/ContainerCard.tsx
+++ b/frontend/src/components/ContainerCard.tsx
@@ -90,7 +90,7 @@ export default function ContainerCard({ container, onRefresh }: ContainerCardPro
- {container.network_bw_mbps} Mbps
+ {formatNetworkLimit(container)}
@@ -140,3 +140,10 @@ export default function ContainerCard({ container, onRefresh }: ContainerCardPro
)
}
+
+function formatNetworkLimit(container: { network_bw_mbps?: number; network_down_mbps?: number; network_up_mbps?: number }) {
+ const down = Math.max(0, Number(container.network_down_mbps || container.network_bw_mbps || 0))
+ const up = Math.max(0, Number(container.network_up_mbps || container.network_bw_mbps || 0))
+ if (down === 0 && up === 0) return '不限速'
+ return `下 ${down || '不限'} / 上 ${up || '不限'} Mbps`
+}
diff --git a/frontend/src/components/CreateContainerModal.tsx b/frontend/src/components/CreateContainerModal.tsx
index d78d7cd..fc4fcb8 100644
--- a/frontend/src/components/CreateContainerModal.tsx
+++ b/frontend/src/components/CreateContainerModal.tsx
@@ -21,11 +21,15 @@ const defaultForm: CreateContainerRequest = {
ram_mb: 512,
disk_gb: 10,
network_bw_mbps: 0,
+ network_down_mbps: 0,
+ network_up_mbps: 0,
monthly_traffic_gb: 0,
traffic_mode: 'total',
traffic_in_gb: 0,
traffic_out_gb: 0,
io_speed_mbps: 0,
+ io_read_mbps: 0,
+ io_write_mbps: 0,
extra_ports: [],
port_mapping_count: 2,
assign_nat: true,
@@ -498,7 +502,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist
-
+
{resourceErrors.disk_gb && {resourceErrors.disk_gb}
}
-
- setForm({ ...form, network_bw_mbps: value })} />
-
-
- setForm({ ...form, io_speed_mbps: value })} />
-
+
+
+ setForm({ ...form, network_down_mbps: value, network_bw_mbps: symmetricLimit(value, form.network_up_mbps) })} />
+
+
+ setForm({ ...form, network_up_mbps: value, network_bw_mbps: symmetricLimit(form.network_down_mbps, value) })} />
+
+
+ setForm({ ...form, io_read_mbps: value, io_speed_mbps: symmetricLimit(value, form.io_write_mbps) })} />
+
+
+ setForm({ ...form, io_write_mbps: value, io_speed_mbps: symmetricLimit(form.io_read_mbps, value) })} />
+
+
@@ -779,5 +791,14 @@ function formatNATPortCount(count: number, language: Language) {
: `将分配 ${count} 个 NAT 端口`
}
+function symmetricLimit(a: number, b: number) {
+ const left = Math.max(0, Number(a) || 0)
+ const right = Math.max(0, Number(b) || 0)
+ if (left === right) return left
+ if (left === 0) return right
+ if (right === 0) return left
+ return Math.min(left, right)
+}
+
const inputClass =
'w-full px-3 py-2 border border-gray-300 rounded-md text-sm text-black bg-white focus:outline-none focus:ring-2 focus:ring-black focus:border-black'
diff --git a/frontend/src/pages/ApiIntegration.tsx b/frontend/src/pages/ApiIntegration.tsx
index 2f70120..73e0f51 100644
--- a/frontend/src/pages/ApiIntegration.tsx
+++ b/frontend/src/pages/ApiIntegration.tsx
@@ -14,6 +14,7 @@ import {
X,
} from 'lucide-react'
import api, { APIResponse, Container } from '../services/api'
+import { useLanguage } from '../contexts/LanguageContext'
import { copyToClipboard } from '../utils/clipboard'
interface ApiKeyItem {
@@ -238,6 +239,7 @@ const emptyForm = (): ApiKeyForm => ({
})
export default function ApiIntegration() {
+ const { t } = useLanguage()
const [keys, setKeys] = useState
([])
const [containers, setContainers] = useState([])
const [loading, setLoading] = useState(true)
@@ -329,7 +331,7 @@ export default function ApiIntegration() {
}
const deleteKey = async (id: string) => {
- if (!window.confirm('确定删除这个 API Key 吗?')) return
+ if (!window.confirm(t('确定删除这个 API Key 吗?'))) return
try {
await api.delete(`/api-keys/${id}`)
setKeys(prev => prev.filter(k => k.id !== id))
@@ -730,11 +732,15 @@ const requestBodySamples: Record> = {
ram_mb: 512,
disk_gb: 10,
network_bw_mbps: 0,
+ network_down_mbps: 100,
+ network_up_mbps: 20,
monthly_traffic_gb: 0,
traffic_mode: 'total',
traffic_in_gb: 0,
traffic_out_gb: 0,
io_speed_mbps: 0,
+ io_read_mbps: 80,
+ io_write_mbps: 30,
extra_ports: [8080],
port_mapping_count: 2,
assign_nat: true,
@@ -765,8 +771,12 @@ const requestBodySamples: Record> = {
'PUT /api/v1/containers/{id}/resource-limit': {
vcpu: 1,
ram_mb: 512,
- io_speed_mbps: 0,
- network_bw_mbps: 0,
+ network_down_mbps: 100,
+ network_up_mbps: 20,
+ io_read_mbps: 80,
+ io_write_mbps: 30,
+ network_bw_mbps: 20,
+ io_speed_mbps: 30,
},
'PUT /api/v1/containers/{id}/expiry': { expires_at: '2026-12-31 23:59:59' },
'POST /api/v1/containers/{id}/reset-password': { password: 'NewPass123456' },
@@ -821,10 +831,11 @@ const requestBodySamples: Record> = {
'POST /api/v1/security/check': { container_name: 'example-vm' },
'PUT /api/v1/containers/{id}/firewall': {
enabled: true,
+ default_action: 'DROP',
rules: [
- { id: '', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH', enabled: true },
- { id: '', direction: 'in', protocol: 'tcp', port: '80,443', source_ip: '', action: 'ACCEPT', description: 'Allow HTTP/HTTPS', enabled: true },
- { id: '', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow all outbound TCP', enabled: true },
+ { id: '', network: 'ipv4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv4/NAT4', enabled: true },
+ { id: '', network: 'ipv6', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv6', enabled: true },
+ { id: '', network: 'all', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow outbound TCP', enabled: true },
],
},
'PUT /api/v1/security/settings': { auto_shutdown: false },
@@ -1039,10 +1050,11 @@ const responseSamples: Record = {
success: true,
data: {
enabled: true,
+ default_action: 'DROP',
rules: [
- { id: 'a1b2c3d4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH', enabled: true },
- { id: 'e5f6g7h8', direction: 'in', protocol: 'tcp', port: '80,443', source_ip: '', action: 'ACCEPT', description: 'Allow HTTP/HTTPS', enabled: true },
- { id: 'i9j0k1l2', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow all outbound TCP', enabled: true },
+ { id: 'a1b2c3d4', network: 'ipv4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv4/NAT4', enabled: true },
+ { id: 'e5f6g7h8', network: 'ipv6', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv6', enabled: true },
+ { id: 'i9j0k1l2', network: 'all', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow outbound TCP', enabled: true },
],
},
},
@@ -1051,10 +1063,11 @@ const responseSamples: Record = {
message: 'Firewall updated',
data: {
enabled: true,
+ default_action: 'DROP',
rules: [
- { id: 'a1b2c3d4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH', enabled: true },
- { id: 'e5f6g7h8', direction: 'in', protocol: 'tcp', port: '80,443', source_ip: '', action: 'ACCEPT', description: 'Allow HTTP/HTTPS', enabled: true },
- { id: 'i9j0k1l2', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow all outbound TCP', enabled: true },
+ { id: 'a1b2c3d4', network: 'ipv4', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv4/NAT4', enabled: true },
+ { id: 'e5f6g7h8', network: 'ipv6', direction: 'in', protocol: 'tcp', port: '22', source_ip: '', action: 'ACCEPT', description: 'Allow SSH over IPv6', enabled: true },
+ { id: 'i9j0k1l2', network: 'all', direction: 'out', protocol: 'tcp', port: '', source_ip: '', action: 'ACCEPT', description: 'Allow outbound TCP', enabled: true },
],
},
},
@@ -1095,11 +1108,11 @@ const responseSamples: Record = {
'GET /api/v1/security/settings': { success: true, data: { auto_shutdown: false } },
'PUT /api/v1/security/settings': { success: true, data: { auto_shutdown: false } },
'GET /api/v1/swap': { success: true, data: { total_mb: 16383, used_mb: 0, free_mb: 16383, enabled: true, swap_file: '/swapfile' } },
- 'POST /api/v1/swap': { success: true, message: 'SWAP 已调整为 16384 MB', data: { total_mb: 16383, used_mb: 0, free_mb: 16383, enabled: true, swap_file: '/swapfile' } },
+ 'POST /api/v1/swap': { success: true, message: 'SWAP adjusted to 16384 MB', data: { total_mb: 16383, used_mb: 0, free_mb: 16383, enabled: true, swap_file: '/swapfile' } },
'POST /api/v1/batch-create': { success: true, data: ['task-12'] },
'POST /api/v1/batch-action': { success: true, data: ['task-13'] },
- 'POST /api/v1/ssh-ticket': { success: true, data: { ticket: '***60秒有效票据***' } },
- 'POST /api/v1/vnc-ticket': { success: true, data: { ticket: '***60秒有效票据***' } },
+ 'POST /api/v1/ssh-ticket': { success: true, data: { ticket: '***60-second valid ticket***' } },
+ 'POST /api/v1/vnc-ticket': { success: true, data: { ticket: '***60-second valid ticket***' } },
'POST /api/v1/sub-user/create': {
success: true,
message: 'Sub-user created',
@@ -1164,29 +1177,33 @@ function examplePathFor(path: string) {
function endpointNoteFor(key: string) {
const notes: string[] = []
if (key === 'POST /api/v1/containers') {
- notes.push('Linux 创建支持 ssh_auth_mode=auto_password|password|key;公网 IPv4、IPv6 与 NAT 可通过 assign_nat、assign_ipv4、assign_ipv6 组合使用。')
+ notes.push('Linux container creation supports ssh_auth_mode=auto_password|password|key. Public IPv4, IPv6, and NAT can be configured with assign_nat, assign_ipv4, and assign_ipv6.')
+ notes.push('Supports independent upload/download bandwidth limits and read/write I/O limits. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases. New integrations should use network_down_mbps, network_up_mbps, io_read_mbps, and io_write_mbps.')
}
if (key === 'POST /api/v1/containers/{id}/reinstall') {
- notes.push('重装支持 ssh_auth_mode=keep|auto_password|password|key;keep 仅用于重装,未传 SSH 字段时保持原有行为。')
+ notes.push('Reinstall supports ssh_auth_mode=keep|auto_password|password|key. keep is only for reinstall requests; if SSH fields are omitted, the existing behavior is kept.')
}
if (key === 'POST /api/v1/batch-create') {
- notes.push('批量创建的单个 containers[] 项支持与 POST /api/v1/containers 相同的网络和 SSH 认证字段。')
+ notes.push('Each containers[] item in batch creation supports the same network and SSH authentication fields as POST /api/v1/containers.')
+ }
+ if (key === 'PUT /api/v1/containers/{id}/resource-limit') {
+ notes.push('Supports independent download/upload bandwidth limits and read/write I/O limits. Omitted fields keep their current values, and explicitly passing 0 makes that direction unlimited. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases.')
}
if (key === 'PUT /api/v1/containers/{id}/firewall') {
- notes.push('启用防火墙后默认拒绝所有 TCP/UDP 入站和出站流量,仅放行 rules 中定义的规则。direction: in=入站, out=出站。action: ACCEPT=放行, DROP=拒绝。port 支持单端口(22)、多端口(80,443)、范围(8000-9000)。')
+ notes.push('Backward compatible: default_action is optional; if omitted, the existing policy is kept. rule.network is optional; if omitted, it is treated as ipv4. default_action: DROP=deny unmatched traffic, ACCEPT=allow unmatched traffic. network: ipv4=IPv4 NAT/public IPv4, ipv6=IPv6, all=apply to both IPv4 and IPv6. For NAT inbound rules, port is the container internal port, not the host public port.')
}
if (key === 'POST /api/v1/batch-action') {
- notes.push('action=reinstall 时可追加 template_id、ssh_auth_mode、ssh_password、ssh_public_key;其他 action 会忽略这些重装字段。')
+ notes.push('When action=reinstall, you can include template_id, ssh_auth_mode, ssh_password, and ssh_public_key. Other actions ignore these reinstall fields.')
}
if (key === 'PUT /api/v1/routing') {
- notes.push('更新公网地址池需要 routing:write;已分配给容器的地址不能从池中移除。')
+ notes.push('Updating public address pools requires routing:write. Addresses already assigned to containers cannot be removed from the pool.')
}
if (key === 'POST /api/v1/routing/ipv4-scan') {
- notes.push('扫描公网 IPv4 段需要 routing:write;verify=true 时会尝试校验地址可用性。')
+ notes.push('Scanning public IPv4 prefixes requires routing:write. When verify=true, the API also attempts to check address availability.')
}
- if (key.includes('/vnc-ticket')) notes.push('WebVNC 仅适用于 KVM 虚拟机;LXC 容器会返回 VNC console is only available for KVM VMs。')
- if (key.includes('/containers/{id}/delete') || key.includes('/batch-action')) notes.push('该接口会进入任务队列,请随后调用 GET /api/v1/tasks 查看执行状态。')
- if (key.includes('/reset-password') || key.includes('/api-keys') || key.includes('/sub-user')) notes.push('样例中的密钥、密码和票据已脱敏;创建类接口的完整密钥只在创建响应中出现一次。')
+ if (key.includes('/vnc-ticket')) notes.push('WebVNC only applies to KVM VMs; LXC containers return "VNC console is only available for KVM VMs".')
+ if (key.includes('/containers/{id}/delete') || key.includes('/batch-action')) notes.push('This API enters the task queue. Call GET /api/v1/tasks afterward to check execution status.')
+ if (key.includes('/reset-password') || key.includes('/api-keys') || key.includes('/sub-user')) notes.push('Keys, passwords, and tickets in examples are masked. Full secrets from create APIs appear only once in the creation response.')
return notes.join(' ')
}
diff --git a/frontend/src/pages/ContainerDetail.tsx b/frontend/src/pages/ContainerDetail.tsx
index f498592..fef8614 100644
--- a/frontend/src/pages/ContainerDetail.tsx
+++ b/frontend/src/pages/ContainerDetail.tsx
@@ -46,6 +46,7 @@ import {
HostInfo,
TrafficInfo,
getEnabledImages,
+ getFirewall,
PortMapping,
FirewallRule,
reinstallContainer,
@@ -148,7 +149,7 @@ export default function ContainerDetail() {
const [trafficEdit, setTrafficEdit] = useState({ mode: 'total', monthly: 0, inGB: 0, outGB: 0 })
const [savingTraffic, setSavingTraffic] = useState(false)
const [showResourceEdit, setShowResourceEdit] = useState(false)
- const [resourceEdit, setResourceEdit] = useState({ vcpu: 1, ramMb: 512, ioMbps: 500, bwMbps: 100 })
+ const [resourceEdit, setResourceEdit] = useState({ vcpu: 1, ramMb: 512, networkDownMbps: 0, networkUpMbps: 0, ioReadMbps: 0, ioWriteMbps: 0 })
const [savingResource, setSavingResource] = useState(false)
const [showPassword, setShowPassword] = useState(false)
const [showResetPassword, setShowResetPassword] = useState(false)
@@ -166,8 +167,10 @@ export default function ContainerDetail() {
const [snapshotScheduleDraft, setSnapshotScheduleDraft] = useState({ intervalHours: 24, time: '03:00' })
const [showFirewall, setShowFirewall] = useState(false)
const [firewallEnabled, setFirewallEnabled] = useState(false)
+ const [firewallDefaultAction, setFirewallDefaultAction] = useState<'ACCEPT' | 'DROP'>('DROP')
const [firewallRules, setFirewallRules] = useState([])
const [firewallSaving, setFirewallSaving] = useState(false)
+ const [firewallMessage, setFirewallMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)
const [editingFirewallRule, setEditingFirewallRule] = useState(null)
const [showFirewallEditor, setShowFirewallEditor] = useState(false)
@@ -392,8 +395,10 @@ export default function ContainerDetail() {
setResourceEdit({
vcpu: container.vcpu,
ramMb: container.ram_mb,
- ioMbps: container.io_speed_mbps || 0,
- bwMbps: container.network_bw_mbps || 0,
+ networkDownMbps: resourceLimitValue(container.network_down_mbps, container.network_bw_mbps),
+ networkUpMbps: resourceLimitValue(container.network_up_mbps, container.network_bw_mbps),
+ ioReadMbps: resourceLimitValue(container.io_read_mbps, container.io_speed_mbps),
+ ioWriteMbps: resourceLimitValue(container.io_write_mbps, container.io_speed_mbps),
})
setShowResourceEdit(true)
}
@@ -405,8 +410,12 @@ export default function ContainerDetail() {
await updateResourceLimit(container.id, {
vcpu: resourceEdit.vcpu,
ram_mb: resourceEdit.ramMb,
- io_speed_mbps: resourceEdit.ioMbps,
- network_bw_mbps: resourceEdit.bwMbps,
+ network_down_mbps: resourceEdit.networkDownMbps,
+ network_up_mbps: resourceEdit.networkUpMbps,
+ network_bw_mbps: symmetricLimit(resourceEdit.networkDownMbps, resourceEdit.networkUpMbps),
+ io_read_mbps: resourceEdit.ioReadMbps,
+ io_write_mbps: resourceEdit.ioWriteMbps,
+ io_speed_mbps: symmetricLimit(resourceEdit.ioReadMbps, resourceEdit.ioWriteMbps),
})
setShowResourceEdit(false)
fetchContainer()
@@ -417,29 +426,59 @@ export default function ContainerDetail() {
}
}
- const openFirewall = () => {
+ const syncFirewallState = (enabled: boolean, defaultAction: 'ACCEPT' | 'DROP', rules: FirewallRule[]) => {
+ const nextRules = rules.map(r => ({ ...r }))
+ setFirewallEnabled(enabled)
+ setFirewallDefaultAction(defaultAction)
+ setFirewallRules(nextRules)
+ setContainer(prev => prev ? {
+ ...prev,
+ firewall_enabled: enabled,
+ firewall_default_action: defaultAction,
+ firewall_rules: nextRules.map(r => ({ ...r })),
+ } : prev)
+ }
+
+ const openFirewall = async () => {
if (!container) return
- setFirewallEnabled(container.firewall_enabled || false)
- setFirewallRules(container.firewall_rules ? [...container.firewall_rules.map(r => ({ ...r }))] : [])
+ syncFirewallState(container.firewall_enabled || false, container.firewall_default_action || 'DROP', container.firewall_rules || [])
+ setFirewallMessage(null)
setShowFirewall(true)
+ try {
+ const res = await getFirewall(container.id)
+ const data = res.data.data
+ if (data) syncFirewallState(data.enabled, data.default_action || 'DROP', data.rules || [])
+ } catch (err) {
+ console.error('Failed to load firewall:', err)
+ }
}
const saveFirewall = async () => {
if (!container) return
setFirewallSaving(true)
try {
- await updateFirewall(container.id, { enabled: firewallEnabled, rules: firewallRules })
+ const res = await updateFirewall(container.id, { enabled: firewallEnabled, default_action: firewallDefaultAction, rules: firewallRules })
+ const data = res.data.data
+ if (data) {
+ syncFirewallState(data.enabled, data.default_action || 'DROP', data.rules || [])
+ }
+ setFirewallMessage({ type: 'success', text: '防火墙设置已保存并应用' })
fetchContainer()
} catch (err: any) {
- dialog.alert('错误', err?.response?.data?.message || '保存防火墙设置失败')
+ const message = err?.response?.data?.message || '保存防火墙设置失败'
+ setFirewallMessage({ type: 'error', text: message })
+ dialog.alert('错误', message)
} finally {
setFirewallSaving(false)
}
}
const addFirewallRule = () => {
+ const hasIPv4Firewall = (container?.public_ipv4s?.length || 0) > 0 || Math.max(container?.port_mapping_limit || 0, container?.port_mappings?.length || 0) > 0
+ const hasIPv6Firewall = !!container?.ipv6 || (container?.ipv6_addresses?.length || 0) > 0
setEditingFirewallRule({
id: '',
+ network: hasIPv4Firewall ? 'ipv4' : hasIPv6Firewall ? 'ipv6' : 'ipv4',
direction: 'in',
protocol: 'tcp',
port: '',
@@ -870,12 +909,37 @@ export default function ContainerDetail() {
const diskPct = container.disk_gb > 0 ? clamp(((usage?.disk_usage_bytes || 0) / (container.disk_gb * 1024 * 1024 * 1024)) * 100) : 0
const networkBps = (usage?.network_rx_bps || 0) + (usage?.network_tx_bps || 0)
const rx = usage?.network_rx_bps || 0
- const netPct = Math.min(((usage?.network_rx_bps || 0) + (usage?.network_tx_bps || 0)) / (container.network_bw_mbps > 0 ? container.network_bw_mbps * 125000 : 125000000) * 100, 100)
+ const networkDownLimit = resourceLimitValue(container.network_down_mbps, container.network_bw_mbps)
+ const networkUpLimit = resourceLimitValue(container.network_up_mbps, container.network_bw_mbps)
+ const netPct = Math.max(
+ directionUsagePercent(usage?.network_rx_bps || 0, networkDownLimit, 125000, 125000000),
+ directionUsagePercent(usage?.network_tx_bps || 0, networkUpLimit, 125000, 125000000),
+ )
const diskIOBps = (usage?.disk_read_bps || 0) + (usage?.disk_write_bps || 0)
+ const ioReadLimit = resourceLimitValue(container.io_read_mbps, container.io_speed_mbps)
+ const ioWriteLimit = resourceLimitValue(container.io_write_mbps, container.io_speed_mbps)
+ const diskIOPct = Math.max(
+ directionUsagePercent(usage?.disk_read_bps || 0, ioReadLimit, 1024 * 1024, 1024 * 1024 * 1024),
+ directionUsagePercent(usage?.disk_write_bps || 0, ioWriteLimit, 1024 * 1024, 1024 * 1024 * 1024),
+ )
const mappingCount = container.port_mappings?.length || 0
const mappingLimit = Math.max(container.port_mapping_limit || 0, mappingCount)
const hasNATQuota = mappingLimit > 0
const canAddMapping = hasNATQuota && mappingCount < mappingLimit && !isSubUserPolicyBlocked
+ const hasFirewallIPv4 = hasIndependentIPv4 || hasNATQuota
+ const firewallNetworkOptions: Array<{ value: NonNullable; label: string }> = []
+ if (hasFirewallIPv4) {
+ firewallNetworkOptions.push({
+ value: 'ipv4',
+ label: hasIndependentIPv4 ? 'IPv4(公网 IPv4)' : 'IPv4(NAT)',
+ })
+ }
+ if (hasIndependentIPv6) {
+ firewallNetworkOptions.push({ value: 'ipv6', label: 'IPv6' })
+ }
+ if (hasFirewallIPv4 && hasIndependentIPv6) {
+ firewallNetworkOptions.push({ value: 'all', label: '全部网络' })
+ }
const managementUrl = subUser?.access_code
? `${window.location.origin}/login?code=${encodeURIComponent(subUser.access_code)}`
: ''
@@ -904,7 +968,7 @@ export default function ContainerDetail() {
current: networkBps,
points: toChartPoints(filtered, 'network'),
formatValue: formatRate,
- detail: `入 ${formatRate(usage?.network_rx_bps || 0)} / 出 ${formatRate(usage?.network_tx_bps || 0)},累计 ${formatBytes((usage?.network_rx_bytes || 0) + (usage?.network_tx_bytes || 0))}`,
+ detail: `入 ${formatRate(usage?.network_rx_bps || 0)} / 出 ${formatRate(usage?.network_tx_bps || 0)},限速占用 ${netPct.toFixed(1)}%,累计 ${formatBytes((usage?.network_rx_bytes || 0) + (usage?.network_tx_bytes || 0))}`,
},
{
title: '磁盘IO',
@@ -912,7 +976,7 @@ export default function ContainerDetail() {
current: diskIOBps,
points: toChartPoints(filtered, 'diskIO'),
formatValue: formatRate,
- detail: `读 ${formatRate(usage?.disk_read_bps || 0)} / 写 ${formatRate(usage?.disk_write_bps || 0)},累计 ${formatBytes((usage?.disk_read_bytes || 0) + (usage?.disk_write_bytes || 0))},容量 ${diskPct.toFixed(1)}%`,
+ detail: `读 ${formatRate(usage?.disk_read_bps || 0)} / 写 ${formatRate(usage?.disk_write_bps || 0)},限速占用 ${diskIOPct.toFixed(1)}%,累计 ${formatBytes((usage?.disk_read_bytes || 0) + (usage?.disk_write_bytes || 0))},容量 ${diskPct.toFixed(1)}%`,
},
]
@@ -997,7 +1061,7 @@ export default function ContainerDetail() {
IPv4 NAT 管理
)}
- setShowFirewall(true)} disabled={isSubUserPolicyBlocked}>
+
防火墙
@@ -1107,8 +1171,8 @@ export default function ContainerDetail() {
- 0 ? `${container.network_bw_mbps} Mbps` : '不限制'} />
- 0 ? `${container.io_speed_mbps} MB/s` : '不限制'} />
+
+
@@ -1511,7 +1575,12 @@ export default function ContainerDetail() {
{showFirewall && (
{ setShowFirewall(false); setShowFirewallEditor(false); setEditingFirewallRule(null) }} wide extra={
!isSubUser && (
-
-
CLICD v1.1.17
+
CLICD v1.1.19
)
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 0b01f07..b6a8003 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -47,6 +47,7 @@ export interface PortMapping {
export interface FirewallRule {
id: string
+ network?: 'ipv4' | 'ipv6' | 'all'
direction: 'in' | 'out'
protocol: 'tcp' | 'udp' | 'icmp' | 'all'
port: string
@@ -79,6 +80,8 @@ export interface Container {
ram_mb: number
disk_gb: number
network_bw_mbps: number
+ network_down_mbps: number
+ network_up_mbps: number
monthly_traffic_gb: number
traffic_mode: string
traffic_in_gb: number
@@ -87,6 +90,8 @@ export interface Container {
traffic_used_tx: number
traffic_reset_date: string
io_speed_mbps: number
+ io_read_mbps: number
+ io_write_mbps: number
status: string
ip: string
public_ipv4s?: PublicIPv4Assignment[]
@@ -100,6 +105,7 @@ export interface Container {
port_mappings: PortMapping[]
port_mapping_limit: number
firewall_enabled: boolean
+ firewall_default_action: 'ACCEPT' | 'DROP'
firewall_rules: FirewallRule[]
snapshot_limit: number
created_at: string
@@ -136,11 +142,15 @@ export interface CreateContainerRequest {
ram_mb: number
disk_gb: number
network_bw_mbps: number
+ network_down_mbps: number
+ network_up_mbps: number
monthly_traffic_gb: number
traffic_mode: string
traffic_in_gb: number
traffic_out_gb: number
io_speed_mbps: number
+ io_read_mbps: number
+ io_write_mbps: number
extra_ports: number[]
port_mapping_count: number
assign_nat?: boolean
@@ -486,8 +496,12 @@ export const updateTrafficLimit = (id: ContainerIdentifier, data: {
export const updateResourceLimit = (id: ContainerIdentifier, data: {
vcpu: number
ram_mb: number
- io_speed_mbps: number
- network_bw_mbps: number
+ io_speed_mbps?: number
+ io_read_mbps?: number
+ io_write_mbps?: number
+ network_bw_mbps?: number
+ network_down_mbps?: number
+ network_up_mbps?: number
}) =>
api.put(`/containers/${id}/resource-limit`, data)
@@ -501,10 +515,10 @@ export const deletePortMapping = (id: ContainerIdentifier, index: number) =>
api.delete>(`/containers/${id}/port-mappings/${index}`)
export const getFirewall = (id: ContainerIdentifier) =>
- api.get>(`/containers/${id}/firewall`)
+ api.get>(`/containers/${id}/firewall`)
-export const updateFirewall = (id: ContainerIdentifier, data: { enabled?: boolean; rules?: FirewallRule[] }) =>
- api.put>(`/containers/${id}/firewall`, data)
+export const updateFirewall = (id: ContainerIdentifier, data: { enabled?: boolean; default_action?: 'ACCEPT' | 'DROP'; rules?: FirewallRule[] }) =>
+ api.put>(`/containers/${id}/firewall`, data)
export const updateContainerExpiry = (id: ContainerIdentifier, expiresAt: string) =>
api.put(`/containers/${id}/expiry`, { expires_at: expiresAt })
diff --git a/frontend/src/utils/i18n.ts b/frontend/src/utils/i18n.ts
index ac4494b..1c650c7 100644
--- a/frontend/src/utils/i18n.ts
+++ b/frontend/src/utils/i18n.ts
@@ -92,6 +92,22 @@ const exact: Record = {
'创建时间': 'Created At',
'网络速率': 'Network Speed',
'IO 速度': 'IO Speed',
+ '下行带宽': 'Download Bandwidth',
+ '上行带宽': 'Upload Bandwidth',
+ '读取 IO': 'Read IO',
+ '写入 IO': 'Write IO',
+ '下行带宽 (Mbps)': 'Download Bandwidth (Mbps)',
+ '上行带宽 (Mbps)': 'Upload Bandwidth (Mbps)',
+ '读取 IO (MB/s)': 'Read IO (MB/s)',
+ '写入 IO (MB/s)': 'Write IO (MB/s)',
+ '下行带宽 (Mbps,0=不限制)': 'Download Bandwidth (Mbps, 0=unlimited)',
+ '上行带宽 (Mbps,0=不限制)': 'Upload Bandwidth (Mbps, 0=unlimited)',
+ '读取 IO (MB/s,0=不限制)': 'Read IO (MB/s, 0=unlimited)',
+ '写入 IO (MB/s,0=不限制)': 'Write IO (MB/s, 0=unlimited)',
+ '限速占用': 'Limit Usage',
+ '支持独立限制上行/下行带宽和读/写 I/O 操作。': 'Supports independent upload/download bandwidth limits and read/write I/O limits.',
+ '支持独立限制上行/下行带宽和读/写 I/O 操作。network_bw_mbps 与 io_speed_mbps 为旧版对称限制兼容别名,建议新对接使用 network_down_mbps、network_up_mbps、io_read_mbps、io_write_mbps。': 'Supports independent upload/download bandwidth limits and read/write I/O limits. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases. New integrations should use network_down_mbps, network_up_mbps, io_read_mbps, and io_write_mbps.',
+ '支持独立限制下行/上行带宽和读取/写入 I/O。未传字段保持原值,显式传 0 表示该方向不限速;network_bw_mbps 与 io_speed_mbps 为旧版对称限制兼容别名。': 'Supports independent download/upload bandwidth limits and read/write I/O limits. Omitted fields keep their current values, and explicitly passing 0 makes that direction unlimited. network_bw_mbps and io_speed_mbps are deprecated symmetric compatibility aliases.',
'月流量': 'Monthly Traffic',
'统计信息': 'Statistics',
'CPU 使用率': 'CPU Usage',
@@ -578,7 +594,11 @@ const exact: Record = {
'更新 Key': 'Update Key',
'删除 Key': 'Delete Key',
'总览': 'Overview',
+ 'NAT/IPv4/IPv6 路由': 'NAT / IPv4 / IPv6 Routing',
'NAT/IPv6 路由': 'NAT / IPv6 Routing',
+ '更新公网 IPv4/IPv6 池': 'Update Public IPv4 / IPv6 Pools',
+ '扫描公网 IPv4 段': 'Scan Public IPv4 Prefixes',
+ '公网 IPv4/IPv6 池': 'Public IPv4 / IPv6 Pools',
'任务队列': 'Task Queue',
'任务列表': 'Task List',
'操作记录': 'audit records',
@@ -588,6 +608,7 @@ const exact: Record = {
'管理员接口': 'Admin API',
'控制面板统计': 'Dashboard Stats',
'立即安全检查': 'Run Security Check',
+ '路由配置': 'Routing Configuration',
'返回响应样例': 'Response Example',
'请求参数': 'Request Parameters',
'响应字段': 'Response Fields',
@@ -616,11 +637,14 @@ const exact: Record = {
'添加端口映射': 'Add Port Mapping',
'更新端口映射': 'Update Port Mapping',
'删除端口映射': 'Delete Port Mapping',
+ '获取防火墙设置': 'Get Firewall Settings',
+ '更新防火墙设置': 'Update Firewall Settings',
'快照总览': 'Snapshot Overview',
'容器快照': 'Container Snapshots',
'计划快照': 'Scheduled Snapshots',
'快照配额': 'Snapshot Quota',
'模板列表': 'Template List',
+ '镜像管理列表': 'Image Management List',
'取消镜像下载': 'Cancel Image Download',
'启用/禁用镜像': 'Enable / Disable Image',
'安全连接日志': 'Security Connection Logs',
@@ -650,7 +674,6 @@ const exact: Record = {
'WebVNC 票据': 'WebVNC Ticket',
'容器列表(兼容 POST 写法)': 'Container List (compatible POST form)',
'调整到期时间': 'Adjust Expiration Time',
- '镜像管理列表': 'Image Management List',
'批量创建容器': 'Batch Create Containers',
'创建 WebSSH 票据': 'Create WebSSH Ticket',
'创建 WebVNC 票据': 'Create WebVNC Ticket',
@@ -677,6 +700,12 @@ const exact: Record = {
'CI/CD、计费系统、自动化脚本': 'CI/CD, billing systems, automation scripts',
'SWAP 已调整为 16384 MB': 'SWAP adjusted to 16384 MB',
'***60秒有效票据***': '***60-second valid ticket***',
+ 'Linux 创建支持 ssh_auth_mode=auto_password|password|key;公网 IPv4、IPv6 与 NAT 可通过 assign_nat、assign_ipv4、assign_ipv6 组合使用。': 'Linux container creation supports ssh_auth_mode=auto_password|password|key. Public IPv4, IPv6, and NAT can be configured with assign_nat, assign_ipv4, and assign_ipv6.',
+ '重装支持 ssh_auth_mode=keep|auto_password|password|key;keep 仅用于重装,未传 SSH 字段时保持原有行为。': 'Reinstall supports ssh_auth_mode=keep|auto_password|password|key. keep is only for reinstall requests; if SSH fields are omitted, the existing behavior is kept.',
+ '批量创建的单个 containers[] 项支持与 POST /api/v1/containers 相同的网络和 SSH 认证字段。': 'Each containers[] item in batch creation supports the same network and SSH authentication fields as POST /api/v1/containers.',
+ 'action=reinstall 时可追加 template_id、ssh_auth_mode、ssh_password、ssh_public_key;其他 action 会忽略这些重装字段。': 'When action=reinstall, you can include template_id, ssh_auth_mode, ssh_password, and ssh_public_key. Other actions ignore these reinstall fields.',
+ '更新公网地址池需要 routing:write;已分配给容器的地址不能从池中移除。': 'Updating public address pools requires routing:write. Addresses already assigned to containers cannot be removed from the pool.',
+ '扫描公网 IPv4 段需要 routing:write;verify=true 时会尝试校验地址可用性。': 'Scanning public IPv4 prefixes requires routing:write. When verify=true, the API also attempts to check address availability.',
'WebVNC 仅适用于 KVM 虚拟机;LXC 容器会返回 VNC console is only available for KVM VMs。': 'WebVNC only applies to KVM VMs; LXC containers return "VNC console is only available for KVM VMs".',
'该接口会进入任务队列,请随后调用 GET /api/v1/tasks 查看执行状态。': 'This API enters the task queue. Call GET /api/v1/tasks afterward to check execution status.',
'样例中的密钥、密码和票据已脱敏;创建类接口的完整密钥只在创建响应中出现一次。': 'Keys, passwords, and tickets in examples are masked. Full secrets from create APIs appear only once in the creation response.',
@@ -793,7 +822,32 @@ const exact: Record = {
'独立 IPv4': 'Dedicated IPv4',
'添加规则': 'Add Rule',
'启用后默认拒绝所有入站和出站流量,仅放行下方规则': 'When enabled, all inbound and outbound traffic is blocked by default. Only the rules below are allowed.',
+ '已启用,未匹配规则的流量将被拒绝': 'Enabled. Traffic that does not match a rule will be denied.',
+ '已启用,未匹配规则的流量将被放行': 'Enabled. Traffic that does not match a rule will be allowed.',
+ '未启用时不接管该容器流量': 'Disabled. Container traffic is not managed by this firewall.',
+ '默认动作': 'Default Action',
+ '没有命中下方规则时如何处理': 'How to handle traffic that does not match the rules below',
+ '未匹配拒绝': 'Deny unmatched',
+ '未匹配放行': 'Allow unmatched',
+ '网络范围': 'Network Scope',
+ '可配置:': 'Configurable: ',
+ '可配置:IPv4(公网 IPv4)。 IPv4 规则覆盖独立公网 IPv4。': 'Configurable: IPv4 (Public IPv4). IPv4 rules apply to the dedicated public IPv4.',
+ '可配置:IPv4(NAT)。 IPv4 规则覆盖IPv4 NAT 端口映射。 NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。': 'Configurable: IPv4 (NAT). IPv4 rules apply to IPv4 NAT port mappings. NAT inbound ports are matched by the container internal port, not the host public port.',
+ '可配置:IPv6。 IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'Configurable: IPv6. IPv6 rules apply to the IPv6 addresses assigned to this container.',
+ '可配置:IPv4(公网 IPv4)、IPv6。 IPv4 规则覆盖独立公网 IPv4。 IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'Configurable: IPv4 (Public IPv4), IPv6. IPv4 rules apply to the dedicated public IPv4. IPv6 rules apply to the IPv6 addresses assigned to this container.',
+ '可配置:IPv4(NAT)、IPv6。 IPv4 规则覆盖IPv4 NAT 端口映射。 NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。 IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'Configurable: IPv4 (NAT), IPv6. IPv4 rules apply to IPv4 NAT port mappings. NAT inbound ports are matched by the container internal port, not the host public port. IPv6 rules apply to the IPv6 addresses assigned to this container.',
+ '当前容器未分配 IPv4 NAT、独立公网 IPv4 或 IPv6,暂无可配置网络。': 'This container has no IPv4 NAT, dedicated public IPv4, or IPv6 assigned, so no firewall network can be configured.',
+ '当前容器没有可配置的 NAT、公网 IPv4 或 IPv6': 'This container has no configurable NAT, public IPv4, or IPv6',
+ '当前容器没有可配置网络': 'This container has no configurable network',
+ 'IPv4 规则覆盖独立公网 IPv4。': 'IPv4 rules apply to the dedicated public IPv4.',
+ 'IPv4 规则覆盖IPv4 NAT 端口映射。': 'IPv4 rules apply to IPv4 NAT port mappings.',
+ 'NAT 入站端口按容器内部端口匹配,不是宿主机公网端口。': 'NAT inbound ports are matched by the container internal port, not the host public port.',
+ 'IPv6 规则覆盖该容器已分配的 IPv6 地址。': 'IPv6 rules apply to the IPv6 addresses assigned to this container.',
+ 'IPv4(公网 IPv4)': 'IPv4 (Public IPv4)',
+ 'IPv4(NAT)': 'IPv4 (NAT)',
+ '全部网络': 'All Networks',
'方向': 'Direction',
+ '网络': 'Network',
'来源/目标 IP': 'Source / Destination IP',
'动作': 'Action',
'入站': 'Inbound',
@@ -802,18 +856,31 @@ const exact: Record = {
'放行': 'Allow',
'拒绝': 'Deny',
'暂无防火墙规则': 'No firewall rules',
+ '防火墙设置已保存并应用': 'Firewall settings saved and applied',
+ '保存防火墙设置失败': 'Failed to save firewall settings',
'编辑规则': 'Edit Rule',
'入站 (Inbound)': 'Inbound',
'出站 (Outbound)': 'Outbound',
'留空为全部端口,支持: 22 | 80,443 | 8000-9000': 'Leave empty for all ports. Supports: 22 | 80,443 | 8000-9000',
+ '入站填容器服务端口;留空为全部端口,支持: 22 | 80,443 | 8000-9000': 'For inbound rules, enter the container service port. Leave empty for all ports. Supports: 22 | 80,443 | 8000-9000',
+ '出站填远端目标端口;留空为全部端口,支持: 22 | 80,443 | 8000-9000': 'For outbound rules, enter the remote destination port. Leave empty for all ports. Supports: 22 | 80,443 | 8000-9000',
+ 'NAT 入站填容器内部端口,例如公网 22023 -> 容器 22,这里填 22': 'For NAT inbound rules, enter the container internal port. For example, public 22023 -> container 22 means enter 22 here.',
+ '端口仅适用于 TCP/UDP': 'Ports only apply to TCP/UDP',
'如: 22 或 80,443 或 8000-9000': 'e.g. 22 or 80,443 or 8000-9000',
+ '当前协议不使用端口': 'This protocol does not use ports',
'来源 IP': 'Source IP',
'目标 IP': 'Destination IP',
'留空为任意 IP,支持 CIDR: 192.168.1.0/24': 'Leave empty for any IP. Supports CIDR: 192.168.1.0/24',
+ '留空为任意 IPv4,支持 CIDR: 192.168.1.0/24': 'Leave empty for any IPv4. Supports CIDR: 192.168.1.0/24',
+ '留空为任意 IPv6,支持 CIDR: 2001:db8::/64': 'Leave empty for any IPv6. Supports CIDR: 2001:db8::/64',
+ '留空为任意 IP,支持 IPv4/IPv6 CIDR': 'Leave empty for any IP. Supports IPv4/IPv6 CIDR',
'如: 192.168.1.0/24': 'e.g. 192.168.1.0/24',
+ '如: 2001:db8::/64': 'e.g. 2001:db8::/64',
+ '如: 192.168.1.0/24 或 2001:db8::/64': 'e.g. 192.168.1.0/24 or 2001:db8::/64',
'放行 (ACCEPT)': 'Allow (ACCEPT)',
'拒绝 (DROP)': 'Deny (DROP)',
'规则描述': 'Rule description',
+ '兼容旧请求:default_action 可不传,不传时保留现有策略;rule.network 可不传,不传按 ipv4 处理。default_action: DROP=未命中规则时拒绝, ACCEPT=未命中规则时放行。network: ipv4=IPv4 NAT/公网 IPv4, ipv6=IPv6, all=同时应用到 IPv4 和 IPv6。NAT 入站规则的 port 填容器内端口,不是宿主机公网端口。': 'Backward compatible: default_action is optional; if omitted, the existing policy is kept. rule.network is optional; if omitted, it is treated as ipv4. default_action: DROP=deny unmatched traffic, ACCEPT=allow unmatched traffic. network: ipv4=IPv4 NAT/public IPv4, ipv6=IPv6, all=apply to both IPv4 and IPv6. For NAT inbound rules, port is the container internal port, not the host public port.',
'登录方式': 'SSH Auth Method',
'保留当前密码': 'Keep current password',
'生成新密码': 'Generate new password',
@@ -905,7 +972,12 @@ const replacements: Array<[RegExp, string]> = [
[/当前证书:/g, 'Current certificate: '],
[/第\s*(\d+)\s*页/g, 'Page $1'],
[/入\s*([^/,]+)\s*\/\s*出\s*([^,]+),累计\s*(.+)$/g, 'In $1 / Out $2, total $3'],
+ [/入\s*([^/,]+)\s*\/\s*出\s*([^,]+),限速占用\s*([^,]+),累计\s*(.+)$/g, 'In $1 / Out $2, limit usage $3, total $4'],
+ [/下\s*([^/]+)\s*\/\s*上\s*(.+)$/g, 'Down $1 / Up $2'],
+ [/下行\s*([^/]+)\s*\/\s*上行\s*(.+)$/g, 'Download $1 / Upload $2'],
+ [/读取\s*([^/]+)\s*\/\s*写入\s*(.+)$/g, 'Read $1 / Write $2'],
[/读\s*([^/,]+)\s*\/\s*写\s*([^,]+),累计\s*([^,]+),容量\s*(.+)$/g, 'Read $1 / Write $2, total $3, capacity $4'],
+ [/读\s*([^/,]+)\s*\/\s*写\s*([^,]+),限速占用\s*([^,]+),累计\s*([^,]+),容量\s*(.+)$/g, 'Read $1 / Write $2, limit usage $3, total $4, capacity $5'],
[/(.+?),筛选后\s*(\d+)\s*items/g, '$1, filtered $2 items'],
[/(.+?),已选\s*(\d+)\s*items/g, '$1, selected $2 items'],
[/将创建\s*(\d+)\s*个容器:(.+?)\s*至\s*(.+)$/g, 'Will create $1 containers: $2 to $3'],