From f2c14c01d34d4d2c5803529756b8f8b56117fc56 Mon Sep 17 00:00:00 2001 From: MengMengCode <227010654+MengMengCode@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:17:46 +0800 Subject: [PATCH 1/2] feat: add instance storage workflows and shadcn monitoring charts Add offline disk growth and managed data disks, portable full backups and restore, independent clones and batch instance templates, and local ISO and QCOW2 uploads. Persist task details and metric history in SQLite. Replace hand-drawn host and instance charts with shadcn/ui Chart and Recharts, keep numeric values and units together, and preserve responsive layouts, icons, time ranges and full-sample statistics. Validation: backend tests and vet; Linux KVM/LXC/API/config/server tests; frontend and documentation production builds; real disk, reinstall, backup, clone, upload, task-history and NAT tests; 37 cross-host restore checks; responsive chart checks and read-only deployed verification. Guest Windows restore behavior has not been tested on a running Windows VM. --- README.md | 12 +- backend/internal/api/backups.go | 519 ++++++++++++ backend/internal/api/backups_test.go | 152 ++++ backend/internal/api/container_metrics.go | 9 +- .../internal/api/container_response_test.go | 44 + backend/internal/api/disks.go | 261 ++++++ backend/internal/api/disks_test.go | 82 ++ backend/internal/api/disks_unicode_test.go | 36 + backend/internal/api/handlers.go | 26 +- backend/internal/api/host.go | 8 +- backend/internal/api/image_upload.go | 384 +++++++++ backend/internal/api/image_upload_test.go | 476 +++++++++++ backend/internal/api/images.go | 55 +- backend/internal/api/metric_history.go | 61 ++ backend/internal/api/operation_tasks.go | 107 +++ backend/internal/api/runtime.go | 4 +- backend/internal/api/snapshots.go | 19 +- backend/internal/api/snapshots_disks_test.go | 41 + backend/internal/api/subuser.go | 2 + backend/internal/api/task_history.go | 271 ++++++ backend/internal/api/task_history_test.go | 261 ++++++ backend/internal/api/taskqueue.go | 240 +++--- backend/internal/config/config.go | 7 +- backend/internal/config/disks.go | 124 +++ backend/internal/config/disks_test.go | 57 ++ backend/internal/config/history_store.go | 235 ++++++ backend/internal/config/history_store_test.go | 182 ++++ backend/internal/config/image_upload.go | 27 + backend/internal/config/image_upload_test.go | 58 ++ backend/internal/config/store_sqlite.go | 28 +- backend/internal/kvm/disks.go | 402 +++++++++ backend/internal/kvm/disks_test.go | 170 ++++ backend/internal/kvm/image_metadata.go | 25 + backend/internal/kvm/installation_media.go | 13 +- .../internal/kvm/installation_media_test.go | 18 + backend/internal/kvm/kvm.go | 69 +- backend/internal/kvm/templates.go | 9 + backend/internal/kvm/transfer.go | 469 +++++++++++ .../internal/kvm/transfer_root_mount_test.go | 146 ++++ backend/internal/kvm/transfer_test.go | 83 ++ backend/internal/lxc/disks.go | 700 +++++++++++++++ backend/internal/lxc/disks_test.go | 242 ++++++ backend/internal/lxc/lxc.go | 32 +- backend/internal/lxc/snapshot.go | 11 + backend/internal/lxc/transfer.go | 472 +++++++++++ .../internal/lxc/transfer_ownership_linux.go | 72 ++ .../internal/lxc/transfer_ownership_other.go | 14 + backend/internal/lxc/transfer_test.go | 53 ++ .../server/image_upload_access_test.go | 53 ++ backend/internal/server/server.go | 11 + backend/internal/transfer/artifact.go | 794 ++++++++++++++++++ backend/internal/transfer/artifact_test.go | 234 ++++++ docs/.vitepress/config.ts | 4 + docs/developer/architecture.md | 9 + docs/en/developer/architecture.md | 9 + docs/en/features/api.md | 31 + docs/en/features/containers.md | 2 + docs/en/features/dashboard.md | 2 + docs/en/features/images.md | 14 + docs/en/features/snapshots.md | 2 + docs/en/features/storage-backups.md | 85 ++ docs/en/features/tasks.md | 23 + docs/en/guide/configuration.md | 4 +- docs/en/guide/installation.md | 19 + docs/en/guide/introduction.md | 2 + docs/en/operations/deployment.md | 2 + docs/features/api.md | 31 + docs/features/containers.md | 2 + docs/features/dashboard.md | 2 + docs/features/images.md | 12 + docs/features/snapshots.md | 2 + docs/features/storage-backups.md | 85 ++ docs/features/tasks.md | 23 + docs/guide/configuration.md | 4 +- docs/guide/installation.md | 19 + docs/guide/introduction.md | 2 + docs/operations/deployment.md | 2 + frontend/package-lock.json | 400 +++++++++ frontend/package.json | 2 + frontend/src/App.tsx | 5 + .../src/components/CreateContainerModal.tsx | 19 +- frontend/src/components/DiskManagerModal.tsx | 94 +++ frontend/src/components/ImageUploadModal.tsx | 63 ++ .../src/components/InstanceTransferModal.tsx | 55 ++ frontend/src/components/KVMInstallMedia.tsx | 2 +- frontend/src/components/OperationTask.tsx | 55 ++ .../src/components/ResourceStatsPanel.tsx | 556 +++++------- frontend/src/components/Sidebar.tsx | 6 + frontend/src/components/ui/chart.tsx | 377 +++++++++ frontend/src/lib/chart-layout.ts | 99 --- frontend/src/lib/format-metrics.ts | 13 + frontend/src/pages/ContainerDetail.tsx | 36 +- frontend/src/pages/Dashboard.tsx | 21 +- frontend/src/pages/ImageManagement.tsx | 5 + frontend/src/pages/PortableLibrary.tsx | 108 +++ frontend/src/pages/Tasks.tsx | 65 ++ frontend/src/services/api.ts | 9 + frontend/src/services/operations.ts | 77 ++ frontend/src/utils/i18n.ts | 127 ++- install.sh | 27 + 100 files changed, 9816 insertions(+), 677 deletions(-) create mode 100644 backend/internal/api/backups.go create mode 100644 backend/internal/api/backups_test.go create mode 100644 backend/internal/api/container_response_test.go create mode 100644 backend/internal/api/disks.go create mode 100644 backend/internal/api/disks_test.go create mode 100644 backend/internal/api/disks_unicode_test.go create mode 100644 backend/internal/api/image_upload.go create mode 100644 backend/internal/api/image_upload_test.go create mode 100644 backend/internal/api/metric_history.go create mode 100644 backend/internal/api/operation_tasks.go create mode 100644 backend/internal/api/snapshots_disks_test.go create mode 100644 backend/internal/api/task_history.go create mode 100644 backend/internal/api/task_history_test.go create mode 100644 backend/internal/config/disks.go create mode 100644 backend/internal/config/disks_test.go create mode 100644 backend/internal/config/history_store.go create mode 100644 backend/internal/config/history_store_test.go create mode 100644 backend/internal/config/image_upload.go create mode 100644 backend/internal/config/image_upload_test.go create mode 100644 backend/internal/kvm/disks.go create mode 100644 backend/internal/kvm/disks_test.go create mode 100644 backend/internal/kvm/image_metadata.go create mode 100644 backend/internal/kvm/transfer.go create mode 100644 backend/internal/kvm/transfer_root_mount_test.go create mode 100644 backend/internal/kvm/transfer_test.go create mode 100644 backend/internal/lxc/disks.go create mode 100644 backend/internal/lxc/disks_test.go create mode 100644 backend/internal/lxc/transfer.go create mode 100644 backend/internal/lxc/transfer_ownership_linux.go create mode 100644 backend/internal/lxc/transfer_ownership_other.go create mode 100644 backend/internal/lxc/transfer_test.go create mode 100644 backend/internal/server/image_upload_access_test.go create mode 100644 backend/internal/transfer/artifact.go create mode 100644 backend/internal/transfer/artifact_test.go create mode 100644 docs/en/features/storage-backups.md create mode 100644 docs/en/features/tasks.md create mode 100644 docs/features/storage-backups.md create mode 100644 docs/features/tasks.md create mode 100644 frontend/src/components/DiskManagerModal.tsx create mode 100644 frontend/src/components/ImageUploadModal.tsx create mode 100644 frontend/src/components/InstanceTransferModal.tsx create mode 100644 frontend/src/components/OperationTask.tsx create mode 100644 frontend/src/components/ui/chart.tsx delete mode 100644 frontend/src/lib/chart-layout.ts create mode 100644 frontend/src/lib/format-metrics.ts create mode 100644 frontend/src/pages/PortableLibrary.tsx create mode 100644 frontend/src/pages/Tasks.tsx create mode 100644 frontend/src/services/operations.ts diff --git a/README.md b/README.md index f5149bb..c6a594f 100644 --- a/README.md +++ b/README.md @@ -54,13 +54,15 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | --- | --- | | Virtualization | Manage LXC containers and KVM virtual machines from one panel, including create, reinstall, start, stop, restart, delete, password reset, expiry control, and batch actions. | | Images and templates | Built-in template and image management for Ubuntu, Debian, Alpine, CentOS, Arch Linux, Fedora, Rocky Linux, and other common distributions. Images can be enabled, disabled, downloaded, cancelled, or removed from cache. | +| Local images | Upload validated ISO/QCOW2 files up to 32 GiB. Generic ISO installation uses WebVNC and persistent, removable installation media. | | Networking | NAT4 port quotas, random available port allocation, TCP/UDP port mappings, public IPv4 pool management, IPv6 prefix detection, IPv6 status checks, and per-container IPv6 assignment. | | Resource control | CPU, memory, disk, swap, bandwidth usage, traffic reset, traffic limit, and resource limit management, with automatic shutdown behavior for expired or over-quota containers. | | Console access | Browser-based WebSSH and WebVNC ticket access, so users can open terminals or consoles without manually exchanging credentials. | | Snapshots | Snapshot overview, per-container snapshots, create/delete/restore operations, scheduled snapshots, and quota controls. | +| Disks and portable backups | Offline disk growth, up to 8 managed data disks, full backups/download/import, independent full clones, and reusable installed-instance templates. Restore creates a stopped instance with a new identity and preserved guest accounts. | | Accounts and audit | Delegated sub-user links, sub-user password rotation, per-user container permissions, audit logs, login logs, and API key management. | | Automation | Versioned REST API under `/api/v1`, task queue endpoints, batch create/action endpoints, and a Mofang finance integration module packaged automatically by GitHub Actions. | -| Operations | Dashboard statistics, host resource overview, routing overview, swap management, CLI-only mode, and release artifacts generated by GitHub Actions. | +| Operations | Dashboard statistics, persisted metric history, durable task stages/errors, host resource overview, routing overview, swap management, CLI-only mode, and release artifacts generated by GitHub Actions. | ### 中文 @@ -68,13 +70,19 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/CLICD/main/install.sh | --- | --- | | 虚拟化管理 | 在同一个面板里管理 LXC 容器和 KVM 虚拟机,支持创建、重装、开机、关机、重启、删除、重置密码、到期时间和批量操作。 | | 镜像与模板 | 内置模板和镜像管理,支持 Ubuntu、Debian、Alpine、CentOS、Arch Linux、Fedora、Rocky Linux 等常见发行版,镜像可按需下载、取消、启用、禁用和清理缓存。 | +| 本地镜像 | 支持上传并校验最多 32 GiB 的 ISO/QCOW2;通用 ISO 可通过 WebVNC 手动安装,安装介质状态持久化并可弹出。 | | 网络能力 | 支持 NAT4 端口配额、随机可用端口、TCP/UDP 端口映射、公网 IPv4 池管理、IPv6 前缀检测、IPv6 状态检查和容器级 IPv6 分配。 | | 资源限制 | 支持 CPU、内存、磁盘、Swap、独立上行/下行带宽、读/写 I/O 限速、流量重置、流量限制和资源限制管理;容器到期或超额后可自动关机,避免资源和流量失控。 | | 远程控制 | 内置 WebSSH 和 WebVNC 票据访问,用户可以直接在浏览器打开终端或控制台,不需要手动复制连接信息。 | | 快照能力 | 支持快照总览、容器快照、创建快照、删除快照、恢复快照、计划快照和快照配额。 | +| 磁盘与完整备份 | 支持离线扩容、最多 8 块受管数据盘、完整备份下载/导入、独立完整克隆和已安装实例模板。恢复创建新身份的停止实例,保留客户机账户。 | | 账号与审计 | 支持子用户管理链接、子用户密码轮换、按容器授权、操作日志、登录日志和 API Key 管理,适合分发给下游用户或拼车用户。 | | 自动化接入 | 全量接口统一使用 `/api/v1`,覆盖任务队列、容器、镜像、网络、流量、批量创建和批量操作;同时提供魔方财务对接模块,并由 GitHub Actions 自动打包发布。 | -| 运维入口 | 提供总览统计、主机资源、路由概览、Swap 管理、CLI-only 模式和 GitHub Actions 自动发布产物,便于在小型节点上长期维护。 | +| 运维入口 | 提供总览统计、持久化历史指标、任务阶段/错误记录、主机资源、路由概览、Swap 管理、CLI-only 模式和 GitHub Actions 自动发布产物,便于在小型节点上长期维护。 | + +Disk growth is offline and never shrinks: KVM grows managed QCOW2 capacity while guest partitions/filesystems remain manual; LXC supports managed ext4 loop images. Instances with data disks use full backups instead of existing snapshots. Portable archives and their expanded disk payloads are each limited to 64 GiB; sparse KVM virtual capacity is a separate limit. KVM restore/clone requires `virt-customize` (`guestfs-tools` or distribution equivalent). See [storage and backup details](docs/en/features/storage-backups.md) and [task retention](docs/en/features/tasks.md). + +磁盘只支持离线增容:KVM 扩受管 QCOW2 容量,客户机分区/文件系统另行扩展;LXC 支持受管 ext4 loop 镜像。带数据盘实例使用完整备份,拒绝旧快照工作流;可移植归档和展开后的磁盘负载分别限制为 64 GiB,KVM 稀疏磁盘的虚拟容量另行计算。KVM 恢复/克隆需要 `virt-customize`(`guestfs-tools` 或发行版对应包),详见[磁盘与备份说明](docs/features/storage-backups.md)和[任务历史](docs/features/tasks.md)。 ## Technology Stack / 技术栈 diff --git a/backend/internal/api/backups.go b/backend/internal/api/backups.go new file mode 100644 index 0000000..8eafffc --- /dev/null +++ b/backend/internal/api/backups.go @@ -0,0 +1,519 @@ +package api + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "mime" + "net/http" + "os" + "strings" + "sync" + "time" + "unicode/utf8" + + "clicd/internal/config" + "clicd/internal/kvm" + "clicd/internal/lxc" + "clicd/internal/transfer" +) + +type transferRequest struct { + Name string `json:"name"` + StoragePoolID string `json:"storage_pool_id,omitempty"` + AssignNAT *bool `json:"assign_nat,omitempty"` + PortMappingCount int `json:"port_mapping_count,omitempty"` + ArtifactID string `json:"artifact_id,omitempty"` + Kind string `json:"kind,omitempty"` +} + +func init() { + RegisterOperationTask(TaskType("backup"), runCreateBackup) + RegisterOperationTask(TaskType("save-template"), runCreateTemplate) + RegisterOperationTask(TaskType("clone"), runFullClone) + RegisterOperationTask(TaskType("restore-backup"), runRestoreBackup) + RegisterOperationTask(TaskType("instantiate-template"), runInstantiateTemplate) +} + +func requireTransferAdmin(w http.ResponseWriter, r *http.Request) bool { + auth, ok := authContextFromRequest(r) + if !ok { + jsonResponse(w, 401, APIResponse{Success: false, Message: "Authentication required"}) + return false + } + if (auth.Type != authTypeAdmin && auth.Type != authTypeAPIKey) || auth.Type == authTypeAPIKey && (!scopeAllowed(auth.Scopes, "admin:access") || isAccessRestrictedRequest(r)) { + jsonResponse(w, 403, APIResponse{Success: false, Message: "Administrator permission required"}) + return false + } + return true +} + +func transferPath(r *http.Request, prefix string) []string { + path := strings.TrimPrefix(r.URL.Path, "/api/v1") + path = strings.TrimPrefix(path, "/api") + path = strings.TrimPrefix(path, prefix) + path = strings.Trim(path, "/") + if path == "" { + return nil + } + return strings.Split(path, "/") +} + +func HandleBackups(w http.ResponseWriter, r *http.Request) { + if !requireTransferAdmin(w, r) { + return + } + parts := transferPath(r, "/backups") + if len(parts) == 0 { + switch r.Method { + case http.MethodGet: + jsonResponse(w, 200, APIResponse{Success: true, Data: transfer.List("backup")}) + case http.MethodPost: + uploadPortableBackup(w, r) + default: + w.WriteHeader(405) + } + return + } + info, path, err := transfer.Resolve(parts[0]) + if err != nil || info.Kind != "backup" { + jsonResponse(w, 404, APIResponse{Success: false, Message: "Backup not found"}) + return + } + if len(parts) == 1 { + switch r.Method { + case http.MethodGet, http.MethodHead: + servePortableArtifact(w, r, info, path) + case http.MethodDelete: + if err = transfer.Delete(info.ID, "backup"); err != nil { + jsonResponse(w, 500, APIResponse{Success: false, Message: err.Error()}) + } else { + config.AddAuditLog("backup.delete", info.SourceName, info.ID, requestActor(r)) + jsonResponse(w, 200, APIResponse{Success: true}) + } + default: + w.WriteHeader(405) + } + return + } + if len(parts) == 2 && r.Method == http.MethodPost { + switch parts[1] { + case "restore": + enqueueArtifactRestore(w, r, info.ID, "backup") + return + case "download-ticket": + issueBackupTicket(w, r, info.ID) + return + } + } + http.NotFound(w, r) +} + +func HandleInstanceTemplates(w http.ResponseWriter, r *http.Request) { + if !requireTransferAdmin(w, r) { + return + } + parts := transferPath(r, "/instance-templates") + if len(parts) == 0 && r.Method == http.MethodGet { + jsonResponse(w, 200, APIResponse{Success: true, Data: transfer.List("template")}) + return + } + if len(parts) == 0 { + w.WriteHeader(405) + return + } + info, _, err := transfer.Resolve(parts[0]) + if err != nil || info.Kind != "template" { + jsonResponse(w, 404, APIResponse{Success: false, Message: "Template not found"}) + return + } + if len(parts) == 1 && r.Method == http.MethodDelete { + if err = transfer.Delete(info.ID, "template"); err != nil { + jsonResponse(w, 500, APIResponse{Success: false, Message: err.Error()}) + } else { + config.AddAuditLog("template.delete", info.SourceName, info.ID, requestActor(r)) + jsonResponse(w, 200, APIResponse{Success: true}) + } + return + } + if len(parts) == 2 && parts[1] == "instantiate" && r.Method == http.MethodPost { + enqueueArtifactRestore(w, r, info.ID, "template") + return + } + http.NotFound(w, r) +} + +func decodeTransferRequest(w http.ResponseWriter, r *http.Request) (transferRequest, bool) { + var request transferRequest + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&request); err != nil && err != io.EOF { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Invalid transfer request"}) + return request, false + } + var trailing interface{} + if err := decoder.Decode(&trailing); err != io.EOF { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Request must contain one JSON object"}) + return request, false + } + request.Name = strings.TrimSpace(request.Name) + request.StoragePoolID = strings.TrimSpace(request.StoragePoolID) + if request.PortMappingCount == 0 { + request.PortMappingCount = 2 + } + if request.PortMappingCount < 1 || request.PortMappingCount > 64 { + jsonResponse(w, 400, APIResponse{Success: false, Message: "port_mapping_count must be between 1 and 64"}) + return request, false + } + return request, true +} + +func HandleContainerTransfer(w http.ResponseWriter, r *http.Request, id int, action string) { + if !requireTransferAdmin(w, r) { + return + } + if r.Method != http.MethodPost { + w.WriteHeader(405) + return + } + c := config.FindContainer(id) + if c == nil { + jsonResponse(w, 404, APIResponse{Success: false, Message: "Instance not found"}) + return + } + request, ok := decodeTransferRequest(w, r) + if !ok { + return + } + kind := TaskType("backup") + additional := []string{} + switch action { + case "backup": + if request.Name == "" { + request.Name = c.Name + " " + time.Now().Format("2006-01-02 15:04") + } + case "template": + kind = TaskType("save-template") + case "clone": + kind = TaskType("clone") + if !validRestoreName(w, request.Name) { + return + } + additional = append(additional, request.Name) + default: + http.NotFound(w, r) + return + } + if request.Name == "" || utf8.RuneCountInString(request.Name) > 128 { + jsonResponse(w, 400, APIResponse{Success: false, Message: "A name of 1-128 characters is required"}) + return + } + payload, _ := json.Marshal(request) + task, err := EnqueueOperationWithAudit(id, c.Name, kind, payload, requestActor(r), clientIP(r), r.UserAgent(), additional...) + writeTransferTask(w, task, err) +} + +func validRestoreName(w http.ResponseWriter, name string) bool { + if !config.IsValidContainerName(name) || config.FindContainerByName(name) != nil { + jsonResponse(w, 409, APIResponse{Success: false, Message: "Invalid or already used instance name"}) + return false + } + return true +} + +func enqueueArtifactRestore(w http.ResponseWriter, r *http.Request, id, kind string) { + request, ok := decodeTransferRequest(w, r) + if !ok || !validRestoreName(w, request.Name) { + return + } + request.ArtifactID = id + request.Kind = kind + payload, _ := json.Marshal(request) + operation := TaskType("restore-backup") + if kind == "template" { + operation = TaskType("instantiate-template") + } + task, err := EnqueueOperationWithAudit(0, request.Name, operation, payload, requestActor(r), clientIP(r), r.UserAgent()) + writeTransferTask(w, task, err) +} + +func writeTransferTask(w http.ResponseWriter, task string, err error) { + if err != nil { + jsonResponse(w, 409, APIResponse{Success: false, Message: err.Error()}) + return + } + jsonResponse(w, 202, APIResponse{Success: true, Data: map[string]string{"task_id": task}}) +} + +func validatePortable(ctx context.Context, dir string, m *transfer.Manifest) error { + if m.Runtime == "kvm" { + return kvm.ValidateTransfer(ctx, dir, m) + } + return lxc.ValidateTransfer(ctx, dir, m) +} + +func exportPortable(ctx context.Context, sourceID int, request transferRequest, kind string, progress func(string, string)) (transfer.Info, error) { + c := config.FindContainer(sourceID) + if c == nil { + return transfer.Info{}, fmt.Errorf("source instance no longer exists") + } + source := *c + progress("cold_copy", "Stopping source, copying every disk, and restoring its original power state") + exporter := func(ctx context.Context, dir string, m *transfer.Manifest) error { + if source.IsKVM() { + return kvm.NewManagerForStoragePool(source.StoragePoolID).ExportTransfer(ctx, sourceID, dir, m) + } + return lxc.NewManager().ExportTransfer(ctx, sourceID, dir, m) + } + info, err := transfer.Create(ctx, request.StoragePoolID, request.Name, kind, source, exporter) + if err == nil { + progress("verified", "Self-contained disks and manifest checksums saved") + } + return info, err +} + +func runCreateBackup(ctx context.Context, id int, payload json.RawMessage, progress func(string, string)) error { + var request transferRequest + if err := json.Unmarshal(payload, &request); err != nil { + return err + } + info, err := exportPortable(ctx, id, request, "backup", progress) + if err != nil { + return err + } + return SetOperationTaskResult(ctx, map[string]interface{}{"artifact_id": info.ID, "artifact": info}) +} + +func runCreateTemplate(ctx context.Context, id int, payload json.RawMessage, progress func(string, string)) error { + var request transferRequest + if err := json.Unmarshal(payload, &request); err != nil { + return err + } + info, err := exportPortable(ctx, id, request, "template", progress) + if err != nil { + return err + } + return SetOperationTaskResult(ctx, map[string]interface{}{"artifact_id": info.ID, "artifact": info}) +} + +func restorePortable(ctx context.Context, request transferRequest, kind string, progress func(string, string)) (*config.Container, error) { + progress("verify", "Verifying manifest, architecture and every disk checksum") + manifest, dir, cleanup, err := transfer.OpenVerified(ctx, request.ArtifactID, kind, validatePortable) + if err != nil { + return nil, err + } + defer cleanup() + progress("restore", "Creating a stopped instance with a new identity and independent storage") + assignNAT := request.AssignNAT == nil || *request.AssignNAT + if manifest.Runtime == "kvm" { + return kvm.NewManager().RestoreTransfer(ctx, manifest, dir, request.Name, request.StoragePoolID, assignNAT, request.PortMappingCount) + } + return lxc.NewManager().RestoreTransfer(ctx, manifest, dir, request.Name, request.StoragePoolID, assignNAT, request.PortMappingCount) +} + +func containerTransferResult(ctx context.Context, c *config.Container) error { + return SetOperationTaskResult(ctx, map[string]interface{}{"container_id": c.ID, "container_uuid": c.UUID, "name": c.Name, "status": "stopped", "credentials_preserved": true}) +} + +func runRestoreBackup(ctx context.Context, _ int, payload json.RawMessage, progress func(string, string)) error { + var request transferRequest + if err := json.Unmarshal(payload, &request); err != nil { + return err + } + c, err := restorePortable(ctx, request, "backup", progress) + if err != nil { + return err + } + return containerTransferResult(ctx, c) +} + +func runInstantiateTemplate(ctx context.Context, _ int, payload json.RawMessage, progress func(string, string)) error { + var request transferRequest + if err := json.Unmarshal(payload, &request); err != nil { + return err + } + c, err := restorePortable(ctx, request, "template", progress) + if err != nil { + return err + } + return containerTransferResult(ctx, c) +} + +func runFullClone(ctx context.Context, id int, payload json.RawMessage, progress func(string, string)) error { + var request transferRequest + if err := json.Unmarshal(payload, &request); err != nil { + return err + } + archiveRequest := request + archiveRequest.StoragePoolID = "" + artifact, err := exportPortable(ctx, id, archiveRequest, "backup", progress) + if err != nil { + return err + } + defer transfer.Delete(artifact.ID, "backup") + request.ArtifactID = artifact.ID + c, err := restorePortable(ctx, request, "backup", progress) + if err != nil { + return err + } + return containerTransferResult(ctx, c) +} + +func uploadPortableBackup(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, transfer.MaxArchiveBytes+(4<<20)) + reader := io.Reader(r.Body) + pool, name := strings.TrimSpace(r.URL.Query().Get("storage_pool_id")), "" + if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") { + multipart, err := r.MultipartReader() + if err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Invalid multipart upload"}) + return + } + var upload *os.File + seen := map[string]bool{} + for { + part, e := multipart.NextPart() + if e == io.EOF { + break + } + if e != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Incomplete multipart upload"}) + return + } + field := part.FormName() + if seen[field] || (field != "file" && field != "name" && field != "storage_pool_id") { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Unexpected or duplicate upload field"}) + return + } + seen[field] = true + if field == "file" { + file, cleanup, e := transfer.SpoolUpload(r.Context(), part, pool) + if e != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: e.Error()}) + return + } + part.Close() + defer cleanup() + upload = file + } else { + data, e := io.ReadAll(io.LimitReader(part, 4097)) + part.Close() + if e != nil || len(data) > 4096 { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Upload field too large"}) + return + } + if field == "name" { + name = string(data) + } else { + requested := strings.TrimSpace(string(data)) + if pool != "" && requested != "" && pool != requested { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Conflicting storage_pool_id values"}) + return + } + if requested != "" { + pool = requested + } + } + } + } + if upload == nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Backup file field is required"}) + return + } + reader = upload + } + info, err := transfer.Import(r.Context(), pool, name, reader, validatePortable) + if err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: err.Error()}) + return + } + config.AddAuditLog("backup.import", info.SourceName, info.ID, requestActor(r)) + jsonResponse(w, 201, APIResponse{Success: true, Data: info}) +} + +func servePortableArtifact(w http.ResponseWriter, r *http.Request, info transfer.Info, path string) { + file, err := os.Open(path) + if err != nil { + http.NotFound(w, r) + return + } + defer file.Close() + stat, err := file.Stat() + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/gzip") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Cache-Control", "private, no-store") + w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": info.ID + ".clicd.tar.gz"})) + http.ServeContent(w, r, info.ID+".clicd.tar.gz", stat.ModTime(), file) +} + +type backupTicket struct { + ID string + Expires time.Time +} + +var backupTickets = struct { + sync.Mutex + Items map[string]backupTicket +}{Items: map[string]backupTicket{}} + +func issueBackupTicket(w http.ResponseWriter, r *http.Request, id string) { + var bytes [32]byte + if _, err := rand.Read(bytes[:]); err != nil { + jsonResponse(w, 500, APIResponse{Success: false, Message: "Cannot create download ticket"}) + return + } + token := hex.EncodeToString(bytes[:]) + expiry := time.Now().Add(2 * time.Minute) + backupTickets.Lock() + for key, ticket := range backupTickets.Items { + if time.Now().After(ticket.Expires) { + delete(backupTickets.Items, key) + } + } + if len(backupTickets.Items) >= 1024 { + backupTickets.Unlock() + jsonResponse(w, 429, APIResponse{Success: false, Message: "Too many pending download tickets"}) + return + } + backupTickets.Items[token] = backupTicket{ID: id, Expires: expiry} + backupTickets.Unlock() + jsonResponse(w, 200, APIResponse{Success: true, Data: map[string]string{"url": "/api/backup-download/" + token, "expires_at": expiry.UTC().Format(time.RFC3339)}}) +} + +// This route intentionally accepts only an opaque, short-lived scoped ticket. +// It streams through ServeContent (including Range), never exposing JWTs in URLs. +func HandleBackupDownload(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.WriteHeader(405) + return + } + parts := transferPath(r, "/backup-download") + if len(parts) != 1 || len(parts[0]) != 64 { + http.NotFound(w, r) + return + } + backupTickets.Lock() + ticket, ok := backupTickets.Items[parts[0]] + if ok && time.Now().After(ticket.Expires) { + delete(backupTickets.Items, parts[0]) + ok = false + } + backupTickets.Unlock() + if !ok { + http.NotFound(w, r) + return + } + info, path, err := transfer.Resolve(ticket.ID) + if err != nil || info.Kind != "backup" { + http.NotFound(w, r) + return + } + servePortableArtifact(w, r, info, path) +} diff --git a/backend/internal/api/backups_test.go b/backend/internal/api/backups_test.go new file mode 100644 index 0000000..f895da6 --- /dev/null +++ b/backend/internal/api/backups_test.go @@ -0,0 +1,152 @@ +package api + +import ( + "bytes" + "encoding/json" + "mime/multipart" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "clicd/internal/config" +) + +func setupDownloadArtifact(t *testing.T) string { + t.Helper() + pool := t.TempDir() + previous := config.AppConfig + config.AppConfig = &config.ClicdConfig{StoragePools: []config.StoragePool{{ID: "portable", Path: pool, ContentTypes: []string{config.StorageContentBackups}}}} + t.Cleanup(func() { config.AppConfig = previous }) + root := filepath.Join(pool, "backups", "instances") + if err := os.MkdirAll(root, 0700); err != nil { + t.Fatal(err) + } + id := "bk-" + strings.Repeat("a", 32) + if err := os.WriteFile(filepath.Join(root, id+".clicd.tar.gz"), []byte("streamed-test-backup"), 0600); err != nil { + t.Fatal(err) + } + metadata := map[string]interface{}{"id": id, "name": "portable", "kind": "backup", "format_version": 1, "runtime": "kvm", "arch": "amd64", "size_bytes": 20} + data, _ := json.Marshal(metadata) + if err := os.WriteFile(filepath.Join(root, id+".json"), data, 0600); err != nil { + t.Fatal(err) + } + return id +} + +func TestBackupAdminBoundaryAndScopedDownloadTicket(t *testing.T) { + id := setupDownloadArtifact(t) + for _, auth := range []AuthContext{{Type: authTypeSubUser}, {Type: authTypeAPIKey}, {Type: authTypeAPIKey, Scopes: []string{"admin:access"}, ContainerUUIDs: []string{"only-one-uuid"}}} { + request := withAuthContext(httptest.NewRequest(http.MethodGet, "/api/backups", nil), auth) + response := httptest.NewRecorder() + HandleBackups(response, request) + if response.Code != 403 { + t.Fatalf("nonadmin listed backup archives: %d", response.Code) + } + } + limited := AuthContext{Type: authTypeAPIKey, Scopes: []string{"admin:access"}, ContainerUUIDs: []string{"only-one-uuid"}} + for _, endpoint := range []struct { + method, path string + handler http.HandlerFunc + }{ + {http.MethodGet, "/api/backups/" + id, HandleBackups}, + {http.MethodPost, "/api/backups/" + id + "/download-ticket", HandleBackups}, + {http.MethodPost, "/api/backups/" + id + "/restore", HandleBackups}, + {http.MethodGet, "/api/instance-templates", HandleInstanceTemplates}, + } { + r := withAuthContext(httptest.NewRequest(endpoint.method, endpoint.path, nil), limited) + w := httptest.NewRecorder() + endpoint.handler(w, r) + if w.Code != 403 { + t.Fatalf("UUID-bound admin key reached %s: %d", endpoint.path, w.Code) + } + } + r := withAuthContext(httptest.NewRequest(http.MethodPost, "/api/containers/1/backup", nil), limited) + w := httptest.NewRecorder() + HandleContainerTransfer(w, r, 1, "backup") + if w.Code != 403 { + t.Fatal("restricted admin key created source backup") + } + unauth := httptest.NewRecorder() + HandleBackups(unauth, httptest.NewRequest(http.MethodGet, "/api/backups", nil)) + if unauth.Code != 401 { + t.Fatal("unauthenticated backup request accepted") + } + request := withAuthContext(httptest.NewRequest(http.MethodPost, "/api/backups/"+id+"/download-ticket", nil), AuthContext{Type: authTypeAdmin}) + response := httptest.NewRecorder() + HandleBackups(response, request) + if response.Code != 200 { + t.Fatal(response.Body.String()) + } + var data struct { + Data struct { + URL string `json:"url"` + Expires string `json:"expires_at"` + } `json:"data"` + } + if err := json.Unmarshal(response.Body.Bytes(), &data); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(data.Data.URL, "/api/backup-download/") || strings.Contains(data.Data.URL, "token=") { + t.Fatal("download leaks authentication token") + } + if len(strings.TrimPrefix(data.Data.URL, "/api/backup-download/")) != 64 { + t.Fatal("download ticket is not high entropy") + } + download := httptest.NewRecorder() + get := httptest.NewRequest(http.MethodGet, data.Data.URL, nil) + get.Header.Set("Range", "bytes=0-7") + HandleBackupDownload(download, get) + if download.Code != http.StatusPartialContent || download.Body.String() != "streamed" || download.Header().Get("X-Content-Type-Options") != "nosniff" || !strings.HasPrefix(download.Header().Get("Content-Disposition"), "attachment") { + t.Fatalf("streaming range download failed: code=%d", download.Code) + } + key := strings.TrimPrefix(data.Data.URL, "/api/backup-download/") + backupTickets.Lock() + ticket := backupTickets.Items[key] + ticket.Expires = time.Now().Add(-time.Minute) + backupTickets.Items[key] = ticket + backupTickets.Unlock() + expired := httptest.NewRecorder() + HandleBackupDownload(expired, httptest.NewRequest(http.MethodGet, data.Data.URL, nil)) + if expired.Code != 404 { + t.Fatal("expired scoped ticket accepted") + } + for _, path := range []string{"/api/backup-download/../config.db", "/api/backup-download/" + strings.Repeat("b", 64), "/api/backups/../../config.db"} { + rec := httptest.NewRecorder() + if strings.Contains(path, "backup-download") { + HandleBackupDownload(rec, httptest.NewRequest(http.MethodGet, path, nil)) + } else { + HandleBackups(rec, withAuthContext(httptest.NewRequest(http.MethodGet, path, nil), AuthContext{Type: authTypeAdmin})) + } + if rec.Code != 404 { + t.Fatalf("invalid artifact/ticket path accepted: %d", rec.Code) + } + } +} + +func TestTransferRequestRejectsHostPathAndInjectedSourceIdentity(t *testing.T) { + for _, body := range []string{`{"name":"copy","host_ip":"192.0.2.1"}`, `{"name":"copy","disk_image":"/etc/shadow"}`, `{"name":"copy","port_mapping_count":65}`} { + r := httptest.NewRequest(http.MethodPost, "/api/containers/1/clone", strings.NewReader(body)) + w := httptest.NewRecorder() + if _, ok := decodeTransferRequest(w, r); ok || w.Code != 400 { + t.Fatal("untrusted transfer fields accepted") + } + } +} + +func TestBackupUploadRejectsConflictingStorageSelection(t *testing.T) { + var body bytes.Buffer + multipart := multipart.NewWriter(&body) + multipart.WriteField("storage_pool_id", "body-pool") + multipart.Close() + r := withAuthContext(httptest.NewRequest(http.MethodPost, "/api/backups?storage_pool_id=query-pool", &body), AuthContext{Type: authTypeAdmin}) + r.Header.Set("Content-Type", multipart.FormDataContentType()) + w := httptest.NewRecorder() + HandleBackups(w, r) + if w.Code != 400 || !strings.Contains(w.Body.String(), "Conflicting storage_pool_id") { + t.Fatalf("conflicting query/multipart pool accepted: %d", w.Code) + } +} diff --git a/backend/internal/api/container_metrics.go b/backend/internal/api/container_metrics.go index f9b63ee..2fe69d1 100644 --- a/backend/internal/api/container_metrics.go +++ b/backend/internal/api/container_metrics.go @@ -36,6 +36,7 @@ const ( func StartContainerMetricSampler() { containerMetricSamplerOnce.Do(func() { + restoreContainerMetricHistory() go func() { sampleAllContainerMetrics() ticker := time.NewTicker(containerMetricSampleInterval) @@ -126,6 +127,7 @@ func appendContainerMetricPoint(c config.Container, usage map[string]interface{} DiskIO: diskRead + diskWrite, } cutoff := time.Now().Add(-hostMetricRetention).UnixMilli() + persistMetricPoint("container", key, point.TS, point) containerMetricMu.Lock() defer containerMetricMu.Unlock() @@ -139,7 +141,12 @@ func appendContainerMetricPoint(c config.Container, usage map[string]interface{} copy(history, history[keepFrom:]) history = history[:len(history)-keepFrom] } - containerMetricHistory[key] = append(history, point) + if len(history) > 0 && history[len(history)-1].TS/30_000 == point.TS/30_000 { + history[len(history)-1] = point + containerMetricHistory[key] = history + } else { + containerMetricHistory[key] = append(history, point) + } } func getContainerMetricHistory(c *config.Container) []ContainerMetricPoint { diff --git a/backend/internal/api/container_response_test.go b/backend/internal/api/container_response_test.go new file mode 100644 index 0000000..9a91195 --- /dev/null +++ b/backend/internal/api/container_response_test.go @@ -0,0 +1,44 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "clicd/internal/config" + "clicd/internal/transfer" +) + +func TestContainerResponsesHideDataDiskPathsWithoutChangingPersistence(t *testing.T) { + previous := config.AppConfig + t.Cleanup(func() { config.AppConfig = previous }) + t.Setenv("PATH", "") // No runtime tools or real instances participate. + const path = "/owned/data-disks/secret-owner/disk-one/disk.qcow2" + config.AppConfig = &config.ClicdConfig{Containers: []config.Container{{ID: 1, UUID: "disk-owner", Name: "guest", Virtualization: "kvm", Status: "stopped", DataDisks: []config.DataDisk{{ID: "disk-one", Name: "Data", Path: path, SizeGB: 1, Attached: true}}}}} + for _, test := range []struct { + name string + run func(http.ResponseWriter, *http.Request) + }{{"list", listContainers}, {"get", func(w http.ResponseWriter, r *http.Request) { getContainer(w, r, 1) }}} { + t.Run(test.name, func(t *testing.T) { + response := httptest.NewRecorder() + test.run(response, httptest.NewRequest(http.MethodGet, "/api/containers", nil)) + body := response.Body.String() + if response.Code != 200 || strings.Contains(body, path) || strings.Contains(body, `"path"`) || !strings.Contains(body, `"disk-one"`) { + t.Fatalf("unsafe or incomplete container response: %d %s", response.Code, body) + } + if config.AppConfig.Containers[0].DataDisks[0].Path != path { + t.Fatal("response redaction mutated the persistent configuration") + } + }) + } + data, err := json.Marshal(config.AppConfig.Containers[0].DataDisks) + if err != nil || !strings.Contains(string(data), path) { + t.Fatal("SQLite data_disks JSON lost its internal path", err) + } + manifest, err := json.Marshal(transfer.Manifest{Container: config.AppConfig.Containers[0]}) + if err != nil || !strings.Contains(string(manifest), path) { + t.Fatal("portable manifest lost its internal path", err) + } +} diff --git a/backend/internal/api/disks.go b/backend/internal/api/disks.go new file mode 100644 index 0000000..9a0c6b0 --- /dev/null +++ b/backend/internal/api/disks.go @@ -0,0 +1,261 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + "unicode/utf8" + + "clicd/internal/config" +) + +const ( + TaskDiskAdd TaskType = "disk-add" + TaskDiskResize TaskType = "disk-resize" + TaskDiskRemove TaskType = "disk-remove" + TaskDiskAttach TaskType = "disk-attach" +) + +type diskOperationPayload struct { + UUID string `json:"uuid"` + DiskID string `json:"disk_id,omitempty"` + Name string `json:"name,omitempty"` + SizeGB float64 `json:"size_gb,omitempty"` + StoragePoolID string `json:"storage_pool_id,omitempty"` + MountPath string `json:"mount_path,omitempty"` + Attached bool `json:"attached,omitempty"` +} + +func init() { + for _, kind := range []TaskType{TaskDiskAdd, TaskDiskResize, TaskDiskRemove, TaskDiskAttach} { + operation := kind + RegisterOperationTask(operation, func(ctx context.Context, id int, raw json.RawMessage, progress func(string, string)) error { + return runDiskOperation(ctx, id, operation, raw, progress) + }) + } +} +func diskInventory(ctx context.Context, c *config.Container) (config.DiskInventory, error) { + if c.IsKVM() { + return kvmManager.GetDisks(ctx, c.ID) + } + return lxcManager.GetDisks(ctx, c.ID) +} +func runDiskOperation(ctx context.Context, id int, kind TaskType, raw json.RawMessage, progress func(string, string)) error { + var payload diskOperationPayload + if err := json.Unmarshal(raw, &payload); err != nil { + return err + } + c := config.FindContainer(id) + if c == nil || c.UUID != payload.UUID { + return fmt.Errorf("operation target no longer exists") + } + isKVM := c.IsKVM() + progress("checking", "检查实例停止状态与受管磁盘") + switch kind { + case TaskDiskAdd: + progress("creating_disk", "创建数据盘并保存挂载配置") + var disk config.DataDisk + var err error + if isKVM { + if payload.MountPath != "" { + return fmt.Errorf("mount_path is only supported for LXC") + } + disk, err = kvmManager.AddDataDisk(ctx, id, payload.Name, payload.SizeGB, payload.StoragePoolID) + } else { + disk, err = lxcManager.AddDataDisk(ctx, id, payload.Name, payload.SizeGB, payload.StoragePoolID, payload.MountPath) + } + if err != nil { + return err + } + _ = SetOperationTaskResult(ctx, config.PublicDataDisk(disk)) + return nil + case TaskDiskResize: + progress("resizing_disk", "扩容受管磁盘;不会缩小磁盘或修改 KVM 客户机分区") + if isKVM { + return kvmManager.ResizeDisk(ctx, id, payload.DiskID, payload.SizeGB) + } + return lxcManager.ResizeDisk(ctx, id, payload.DiskID, payload.SizeGB) + case TaskDiskRemove: + progress("removing_disk", "移除数据盘配置并删除受管数据文件") + if isKVM { + return kvmManager.DeleteDataDisk(ctx, id, payload.DiskID) + } + return lxcManager.DeleteDataDisk(ctx, id, payload.DiskID) + case TaskDiskAttach: + progress("updating_disk", "保存数据盘连接状态") + if isKVM { + return kvmManager.SetDataDiskAttached(ctx, id, payload.DiskID, payload.Attached) + } + return lxcManager.SetDataDiskAttached(ctx, id, payload.DiskID, payload.Attached) + } + return fmt.Errorf("unsupported disk operation") +} + +// HandleContainerDisks is dispatched by HandleSingleContainer after ownership +// validation. Mutations require administrator resize privileges. +func HandleContainerDisks(w http.ResponseWriter, r *http.Request, id int, action string) { + c := config.FindContainer(id) + if c == nil { + jsonResponse(w, 404, APIResponse{Success: false, Message: "Container not found"}) + return + } + if !isContainerAllowedForRequest(r, c.UUID) { + jsonResponse(w, 403, APIResponse{Success: false, Message: "Access denied to this container"}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + if action == "disks" && r.Method == http.MethodGet { + if !requireScope(w, r, "container:read") { + return + } + inventory, err := diskInventory(ctx, c) + if err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: err.Error()}) + return + } + jsonResponse(w, 200, APIResponse{Success: true, Data: inventory}) + return + } + if isSubUserRequest(r) || isAccessRestrictedRequest(r) { + jsonResponse(w, 403, APIResponse{Success: false, Message: "Administrator permission required"}) + return + } + if !requireScope(w, r, "container:resize") { + return + } + var request struct { + Name string `json:"name"` + SizeGB *float64 `json:"size_gb"` + StoragePoolID string `json:"storage_pool_id"` + MountPath string `json:"mount_path"` + Attached *bool `json:"attached"` + DeleteData *bool `json:"delete_data"` + } + decoder := json.NewDecoder(io.LimitReader(r.Body, 8192)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&request); err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Invalid disk request"}) + return + } + if err := decoder.Decode(&struct{}{}); err != io.EOF { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Invalid disk request body"}) + return + } + payload := diskOperationPayload{UUID: c.UUID, Name: strings.TrimSpace(request.Name), StoragePoolID: request.StoragePoolID, MountPath: request.MountPath} + kind := TaskType("") + suffix := strings.TrimPrefix(action, "disks/") + switch { + case action == "disks" && r.Method == http.MethodPost: + kind = TaskDiskAdd + if c.SnapshotScheduleEnabled { + jsonResponse(w, 409, APIResponse{Success: false, Message: "Disable scheduled snapshots before adding data disks; use full backups to include all disks"}) + return + } + if payload.Name == "" || utf8.RuneCountInString(payload.Name) > 80 { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Disk name must contain 1 to 80 characters"}) + return + } + if !c.IsKVM() { + if err := config.ValidateGuestMountPath(payload.MountPath); err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: err.Error()}) + return + } + } else if payload.MountPath != "" { + jsonResponse(w, 400, APIResponse{Success: false, Message: "mount_path is only supported for LXC"}) + return + } + case strings.HasSuffix(suffix, "/attachment") && r.Method == http.MethodPut: + kind = TaskDiskAttach + payload.DiskID = strings.TrimSuffix(suffix, "/attachment") + if request.Attached == nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: "attached is required"}) + return + } + payload.Attached = *request.Attached + case action != "disks" && !strings.Contains(suffix, "/") && r.Method == http.MethodPut: + kind = TaskDiskResize + payload.DiskID = suffix + case action != "disks" && !strings.Contains(suffix, "/") && r.Method == http.MethodDelete: + kind = TaskDiskRemove + payload.DiskID = suffix + if request.DeleteData == nil || !*request.DeleteData { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Deleting a disk requires explicit delete_data: true"}) + return + } + default: + jsonResponse(w, 405, APIResponse{Success: false, Message: "Unsupported disk operation"}) + return + } + if kind == TaskDiskAdd || kind == TaskDiskResize { + if request.SizeGB == nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: "size_gb is required"}) + return + } + if _, err := config.DiskSizeBytes(*request.SizeGB); err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: err.Error()}) + return + } + payload.SizeGB = *request.SizeGB + } + if kind != TaskDiskAdd && payload.DiskID != "system" { + found := false + for _, disk := range c.DataDisks { + if disk.ID == payload.DiskID { + found = true + break + } + } + if !found { + jsonResponse(w, 404, APIResponse{Success: false, Message: "Data disk not found"}) + return + } + } + if payload.DiskID == "system" && kind != TaskDiskResize { + jsonResponse(w, 400, APIResponse{Success: false, Message: "System disks cannot be detached or deleted"}) + return + } + inventory, err := diskInventory(ctx, c) + if err != nil { + jsonResponse(w, 400, APIResponse{Success: false, Message: err.Error()}) + return + } + if !inventory.CanEdit { + jsonResponse(w, 409, APIResponse{Success: false, Message: inventory.Reason}) + return + } + if kind == TaskDiskAdd && len(c.DataDisks) >= config.MaxDataDisks { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Data disk limit reached"}) + return + } + if kind == TaskDiskResize { + info := inventory.System + if payload.DiskID != "system" { + for _, disk := range inventory.DataDisks { + if disk.ID == payload.DiskID { + info = disk + break + } + } + } + if !info.CanResize || info.Error != "" { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Disk cannot be resized: " + info.Error}) + return + } + if payload.SizeGB < info.SizeGB { + jsonResponse(w, 400, APIResponse{Success: false, Message: "Disk shrinking is not supported"}) + return + } + } + raw, _ := json.Marshal(payload) + taskID, err := EnqueueOperationWithAudit(id, c.Name, kind, raw, requestActor(r), clientIP(r), r.UserAgent()) + if err != nil { + jsonResponse(w, 409, APIResponse{Success: false, Message: err.Error()}) + return + } + jsonResponse(w, 202, APIResponse{Success: true, Message: "Disk operation queued", Data: map[string]interface{}{"task_id": taskID, "status": "pending"}}) +} diff --git a/backend/internal/api/disks_test.go b/backend/internal/api/disks_test.go new file mode 100644 index 0000000..df69efc --- /dev/null +++ b/backend/internal/api/disks_test.go @@ -0,0 +1,82 @@ +package api + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "clicd/internal/config" +) + +func diskAPIFixture(t *testing.T) *config.Container { + t.Helper() + previous := config.AppConfig + t.Cleanup(func() { config.AppConfig = previous }) + config.AppConfig = &config.ClicdConfig{Containers: []config.Container{{ID: 1, UUID: "disk-owner", Name: "guest", Virtualization: config.VirtualizationKVM, DataDisks: []config.DataDisk{{ID: "disk-one", Name: "Data", SizeGB: 1}}}}} + return &config.AppConfig.Containers[0] +} +func requestDisk(t *testing.T, method, action, body string, auth AuthContext) *httptest.ResponseRecorder { + t.Helper() + r := withAuthContext(httptest.NewRequest(method, "/api/containers/1/"+action, strings.NewReader(body)), auth) + w := httptest.NewRecorder() + HandleContainerDisks(w, r, 1, action) + return w +} +func TestDiskAPIRejectsUnsafeOrAmbiguousRequests(t *testing.T) { + diskAPIFixture(t) + admin := AuthContext{Type: authTypeAdmin} + for _, tc := range []struct { + method, action, body string + code int + }{ + {"POST", "disks", `{"name":"data","size_gb":1,"path":"/etc/passwd"}`, 400}, + {"POST", "disks", `{"name":"data","size_gb":1} {}`, 400}, + {"POST", "disks", `{"name":"data","size_gb":-1}`, 400}, + {"POST", "disks", `{"name":"data","size_gb":1,"mount_path":"/data"}`, 400}, + {"DELETE", "disks/disk-one", `{}`, 400}, + {"DELETE", "disks/disk-one", `{"delete_data":false}`, 400}, + {"DELETE", "disks/system", `{"delete_data":true}`, 400}, + {"PUT", "disks/system/attachment", `{"attached":false}`, 400}, + {"PUT", "disks/disk-one/attachment", `{}`, 400}, + {"PUT", "disks/unknown", `{"size_gb":2}`, 404}, + } { + got := requestDisk(t, tc.method, tc.action, tc.body, admin) + if got.Code != tc.code { + t.Fatalf("%s %s %s: %d %s", tc.method, tc.action, tc.body, got.Code, got.Body.String()) + } + } +} +func TestDiskAPIOwnershipAndAdministratorPrivileges(t *testing.T) { + diskAPIFixture(t) + for _, auth := range []AuthContext{ + {Type: authTypeSubUser, ContainerUUIDs: []string{"disk-owner"}}, + {Type: authTypeAPIKey, ContainerUUIDs: []string{"disk-owner"}, Scopes: []string{"*"}}, + {Type: authTypeAPIKey, Scopes: []string{"container:read"}}, + } { + got := requestDisk(t, http.MethodPost, "disks", `{"name":"data","size_gb":1}`, auth) + if got.Code != 403 { + t.Fatalf("mutation allowed to %+v: %d", auth, got.Code) + } + } + got := requestDisk(t, http.MethodGet, "disks", "", AuthContext{Type: authTypeSubUser, ContainerUUIDs: []string{"other-owner"}}) + if got.Code != 403 { + t.Fatalf("other owner inventory: %d", got.Code) + } + got = requestDisk(t, http.MethodGet, "disks", "", AuthContext{Type: authTypeSubUser, ContainerUUIDs: []string{"disk-owner"}}) + if got.Code != 200 { + t.Fatalf("own inventory: %d %s", got.Code, got.Body.String()) + } +} +func TestDiskAPIScheduledSnapshotAndStaleIdentityGuards(t *testing.T) { + c := diskAPIFixture(t) + c.SnapshotScheduleEnabled = true + got := requestDisk(t, http.MethodPost, "disks", `{"name":"data","size_gb":1}`, AuthContext{Type: authTypeAdmin}) + if got.Code != 409 || !strings.Contains(got.Body.String(), "scheduled snapshots") { + t.Fatal(got.Body.String()) + } + if err := runDiskOperation(context.Background(), c.ID, TaskDiskRemove, []byte(`{"uuid":"old-owner","disk_id":"disk-one"}`), func(string, string) {}); err == nil { + t.Fatal("stale identity operation executed") + } +} diff --git a/backend/internal/api/disks_unicode_test.go b/backend/internal/api/disks_unicode_test.go new file mode 100644 index 0000000..9bdf2b2 --- /dev/null +++ b/backend/internal/api/disks_unicode_test.go @@ -0,0 +1,36 @@ +package api + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +func TestDiskAPINameLimitCountsUnicodeCharacters(t *testing.T) { + diskAPIFixture(t) + for _, tc := range []struct { + name string + valid bool + }{ + {strings.Repeat("盘", 64), true}, + {strings.Repeat("盘", 80), true}, + {strings.Repeat("盘", 81), false}, + {strings.Repeat("x", 80), true}, + {strings.Repeat("x", 81), false}, + } { + // Deliberately omit size_gb: a valid display name must reach that + // independent required-field check without touching any runtime disk. + body, _ := json.Marshal(map[string]string{"name": tc.name}) + response := requestDisk(t, http.MethodPost, "disks", string(body), AuthContext{Type: authTypeAdmin}) + if response.Code != http.StatusBadRequest { + t.Fatalf("status=%d: %s", response.Code, response.Body.String()) + } + if tc.valid && !strings.Contains(response.Body.String(), "size_gb is required") { + t.Fatalf("valid Unicode name failed byte-length validation: %s", response.Body.String()) + } + if !tc.valid && !strings.Contains(response.Body.String(), "Disk name must contain") { + t.Fatalf("overlong display name was not rejected: %s", response.Body.String()) + } + } +} diff --git a/backend/internal/api/handlers.go b/backend/internal/api/handlers.go index d272471..721aab1 100644 --- a/backend/internal/api/handlers.go +++ b/backend/internal/api/handlers.go @@ -97,6 +97,10 @@ func HandleSingleContainer(w http.ResponseWriter, r *http.Request) { } switch { + case action == "disks" || strings.HasPrefix(action, "disks/"): + HandleContainerDisks(w, r, id, action) + case action == "backup" || action == "clone" || action == "template": + HandleContainerTransfer(w, r, id, action) case action == "installation-media": handleInstallationMedia(w, r, id) case action == "start" && r.Method == http.MethodPost: @@ -234,7 +238,20 @@ func HandleSingleContainer(w http.ResponseWriter, r *http.Request) { func listContainers(w http.ResponseWriter, r *http.Request) { containers, _ := listByRuntime() containers = filterContainersForRequest(r, containers) - jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: containers}) + public := make([]config.Container, len(containers)) + for i, c := range containers { + public[i] = containerResponse(c) + } + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: public}) +} + +// Disk paths belong to persistence and portable manifests, never public DTOs. +func containerResponse(c config.Container) config.Container { + c.DataDisks = append([]config.DataDisk(nil), c.DataDisks...) + for i := range c.DataDisks { + c.DataDisks[i].Path = "" + } + return c } func createContainer(w http.ResponseWriter, r *http.Request) { @@ -360,7 +377,7 @@ func getContainer(w http.ResponseWriter, r *http.Request, id int) { _, _ = kvmManager.RefreshVNCPort(c.ID) _, _ = kvmManager.RefreshNetwork(c.ID) } - jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: c}) + jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: containerResponse(*c)}) } func getUsage(w http.ResponseWriter, r *http.Request, id int) { @@ -438,6 +455,7 @@ func updateTrafficLimit(w http.ResponseWriter, r *http.Request, id int) { func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) { var req struct { + DiskGB *float64 `json:"disk_gb"` VCPU *float64 `json:"vcpu"` RAMMB *int `json:"ram_mb"` IOMBps *int `json:"io_speed_mbps"` @@ -456,6 +474,10 @@ func updateResourceLimit(w http.ResponseWriter, r *http.Request, id int) { jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"}) return } + if req.DiskGB != nil && *req.DiskGB != c.DiskGB { + jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "请通过磁盘管理接口离线扩容,资源设置不能修改磁盘容量"}) + return + } // Update config nextVCPU := c.VCPU diff --git a/backend/internal/api/host.go b/backend/internal/api/host.go index 1c33345..387eac6 100644 --- a/backend/internal/api/host.go +++ b/backend/internal/api/host.go @@ -302,6 +302,7 @@ func detectRuntimeProbeQuick() HostRuntimeProbe { func StartHostMetricSampler() { hostMetricSamplerOnce.Do(func() { + restoreHostMetricHistory() appendHostMetricPoint(getHostInfoWithNetworkDetails(false)) go func() { ticker := time.NewTicker(hostMetricSampleInterval) @@ -335,6 +336,7 @@ func appendHostMetricPoint(info HostInfo) { DiskUsagePct: diskUsagePct, } cutoff := time.Now().Add(-hostMetricRetention).UnixMilli() + persistMetricPoint("host", "host", point.TS, point) hostMetricMu.Lock() defer hostMetricMu.Unlock() @@ -347,7 +349,11 @@ func appendHostMetricPoint(info HostInfo) { copy(hostMetricHistory, hostMetricHistory[keepFrom:]) hostMetricHistory = hostMetricHistory[:len(hostMetricHistory)-keepFrom] } - hostMetricHistory = append(hostMetricHistory, point) + if len(hostMetricHistory) > 0 && hostMetricHistory[len(hostMetricHistory)-1].TS/30_000 == point.TS/30_000 { + hostMetricHistory[len(hostMetricHistory)-1] = point + } else { + hostMetricHistory = append(hostMetricHistory, point) + } } func getHostMetricHistory() []HostMetricPoint { diff --git a/backend/internal/api/image_upload.go b/backend/internal/api/image_upload.go new file mode 100644 index 0000000..8664d52 --- /dev/null +++ b/backend/internal/api/image_upload.go @@ -0,0 +1,384 @@ +package api + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + "unicode/utf8" + + "clicd/internal/config" + "clicd/internal/kvm" +) + +const maxLocalImageBytes int64 = 32 << 30 + +var errLocalImageTooLarge = errors.New("image exceeds upload limit") + +type uploadContextReader struct { + context.Context + io.Reader +} + +func (r uploadContextReader) Read(buffer []byte) (int, error) { + if err := r.Context.Err(); err != nil { + return 0, err + } + return r.Reader.Read(buffer) +} + +func copyImageUpload(ctx context.Context, dst io.Writer, src io.Reader, limit int64) (int64, error) { + n, err := io.Copy(dst, io.LimitReader(uploadContextReader{ctx, src}, limit+1)) + if n > limit { + return n, errLocalImageTooLarge + } + if err != nil { + return n, err + } + if err := ctx.Err(); err != nil { + return n, err + } + if n == 0 { + return 0, fmt.Errorf("empty image file") + } + return n, nil +} + +// HandleImageUpload streams into an unregistered temporary cache entry. Only a +// completely received, validated image is atomically published and registered. +func HandleImageUpload(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + jsonResponse(w, http.StatusMethodNotAllowed, APIResponse{Success: false, Message: "Method not allowed"}) + return + } + if !requireScope(w, r, "image:download") || !requireScope(w, r, "image:toggle") { + return + } + if isAccessRestrictedRequest(r) { + jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Administrator permission required"}) + return + } + if r.Context().Err() != nil { + jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "上传已取消"}) + return + } + if r.ContentLength > maxLocalImageBytes+(1<<20) { + jsonResponse(w, http.StatusRequestEntityTooLarge, APIResponse{Success: false, Message: "镜像文件不能超过 32 GiB"}) + return + } + r.Body = http.MaxBytesReader(w, r.Body, maxLocalImageBytes+(1<<20)) + reader, err := r.MultipartReader() + if err != nil { + jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "请使用 multipart/form-data 上传镜像"}) + return + } + requestedPool := strings.TrimSpace(r.URL.Query().Get("storage_pool_id")) + pool, err := config.SelectStoragePoolForContent(config.StorageContentImages, requestedPool, max64(r.ContentLength, 1<<20)) + if err != nil { + jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()}) + return + } + if requestedPool != "" && pool.ID != requestedPool { + jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: "选定的镜像存储不可用或空间不足,请重新选择"}) + return + } + dir := filepath.Join(pool.Path, "images", "kvm") + if err := os.MkdirAll(dir, 0755); err != nil { + jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "无法创建镜像缓存目录"}) + return + } + file, err := os.CreateTemp(dir, ".upload-*") + if err != nil { + jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "无法创建临时上传文件"}) + return + } + temporary := file.Name() + defer os.Remove(temporary) + defer file.Close() + fields := map[string]string{} + hash := sha256.New() + var received int64 + seenFile := false + fail := func(message string) { + jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: message}) + } + for { + if r.Context().Err() != nil { + fail("上传已取消") + return + } + part, nextErr := reader.NextPart() + if nextErr == io.EOF { + break + } + if nextErr != nil { + fail("上传未完成或请求超过大小限制") + return + } + if part.FileName() != "" { + if seenFile || part.FormName() != "file" { + fail("只允许上传一个 file 文件") + return + } + seenFile = true + received, err = copyImageUpload(r.Context(), io.MultiWriter(file, hash), part, maxLocalImageBytes) + if errors.Is(err, errLocalImageTooLarge) { + jsonResponse(w, http.StatusRequestEntityTooLarge, APIResponse{Success: false, Message: "镜像文件不能超过 32 GiB"}) + return + } + if err != nil { + fail("镜像上传失败、文件为空或超过 32 GiB") + return + } + part.Close() + } else { + name := part.FormName() + switch name { + case "name", "description", "arch", "sha256", "provisioner", "distro", "release": + default: + fail("不支持的上传字段") + return + } + data, readErr := io.ReadAll(io.LimitReader(part, 8193)) + if readErr != nil || len(data) > 8192 { + fail("上传字段过长") + return + } + part.Close() + if _, duplicate := fields[name]; duplicate { + fail("上传字段重复") + return + } + fields[name] = strings.TrimSpace(string(data)) + } + } + if !seenFile { + fail("请选择镜像文件") + return + } + if err := file.Sync(); err != nil { + fail("镜像写入失败,请检查剩余空间") + return + } + if err := file.Close(); err != nil { + fail("镜像写入失败") + return + } + name, description := fields["name"], fields["description"] + if name == "" || utf8.RuneCountInString(name) > 100 || utf8.RuneCountInString(description) > 500 { + fail("镜像名称为 1–100 字,备注最多 500 字") + return + } + if arch := fields["arch"]; arch != "" && arch != runtime.GOARCH { + fail("镜像架构必须与宿主机一致") + return + } + actualSHA := hex.EncodeToString(hash.Sum(nil)) + if expected := strings.ToLower(fields["sha256"]); expected != "" && expected != actualSHA { + fail("SHA-256 校验不匹配") + return + } + provisioner := fields["provisioner"] + format := "qcow2" + if kvm.ValidateISOFile(temporary) == nil { + format = "iso" + if provisioner == "" { + provisioner = config.KVMProvisionerManualISO + } + if provisioner != config.KVMProvisionerManualISO && provisioner != config.KVMProvisionerWindows10 && provisioner != config.KVMProvisionerWindows11 { + fail("ISO 请选择手动安装或 Windows 自动安装方式") + return + } + if provisioner != config.KVMProvisionerManualISO && runtime.GOARCH != "amd64" { + fail("Windows 自动安装只支持 amd64;其他 ISO 请使用手动安装") + return + } + } else { + if err := validateUploadedQCOW2(r.Context(), temporary); err != nil { + fail(err.Error()) + return + } + if provisioner == "" { + provisioner = "manual-disk" + } + if provisioner != "manual-disk" && provisioner != "linux-cloud-init" { + fail("QCOW2 请选择预装磁盘或 cloud-init 方式") + return + } + } + distro, release := fields["distro"], fields["release"] + if distro == "" { + distro = "generic" + } + if release == "" { + release = "local" + } + if provisioner == config.KVMProvisionerWindows10 || provisioner == config.KVMProvisionerWindows11 { + distro = "windows" + release = strings.TrimPrefix(provisioner, "windows-") + } + var random [8]byte + if _, err := rand.Read(random[:]); err != nil { + fail("无法生成镜像标识") + return + } + id := "custom-kvm-" + hex.EncodeToString(random[:]) + target := filepath.Join(dir, id+"."+format) + if err := os.Chmod(temporary, 0644); err != nil { + fail("无法设置镜像权限") + return + } + if r.Context().Err() != nil { + fail("上传已取消") + return + } + if err := os.Rename(temporary, target); err != nil { + fail("无法保存镜像") + return + } + registered := false + defer func() { + if !registered { + os.Remove(target) + } + }() + if r.Context().Err() != nil { + fail("上传已取消") + return + } + image := config.CustomKVMImage{ID: id, Name: name, Description: description, Distro: distro, Release: release, Arch: runtime.GOARCH, Provisioner: provisioner, SHA256: actualSHA, CreatedAt: time.Now().Format("2006-01-02 15:04:05")} + if err := config.AddUploadedKVMImage(image); err != nil { + fail("保存镜像信息失败: " + err.Error()) + return + } + registered = true + jsonResponse(w, http.StatusCreated, APIResponse{Success: true, Message: "本地镜像已上传、校验并启用", Data: map[string]interface{}{"id": id, "name": name, "format": format, "size_bytes": received, "sha256": actualSHA}}) +} + +func validateUploadedQCOW2(ctx context.Context, path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + var header [104]byte + n, _ := io.ReadFull(f, header[:]) + defer f.Close() + if err := validateQCOW2UploadHeader(header[:n]); err != nil { + return err + } + if err := validateQCOW2UploadExtensions(f, header[:n]); err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + output, err := exec.CommandContext(ctx, "qemu-img", "info", "--output=json", "-f", "qcow2", path).CombinedOutput() + if err != nil { + return fmt.Errorf("无法验证 QCOW2,请检查文件完整性及 qemu-img 是否可用") + } + var info struct { + Format string `json:"format"` + VirtualSize int64 `json:"virtual-size"` + Backing string `json:"backing-filename"` + FullBacking string `json:"full-backing-filename"` + DataFile string `json:"data-file"` + Encrypted bool `json:"encrypted"` + Snapshots []json.RawMessage `json:"snapshots"` + Specific json.RawMessage `json:"format-specific"` + } + if json.Unmarshal(output, &info) != nil || info.Format != "qcow2" || info.VirtualSize <= 0 || uint64(info.VirtualSize) != binary.BigEndian.Uint64(header[24:32]) || info.Backing != "" || info.FullBacking != "" || info.DataFile != "" || info.Encrypted || len(info.Snapshots) != 0 || strings.Contains(string(info.Specific), `"data-file"`) { + return fmt.Errorf("只支持独立完整的 QCOW2 磁盘,不允许外部 backing/data 文件") + } + if err := exec.CommandContext(ctx, "qemu-img", "check", "-f", "qcow2", path).Run(); err != nil { + return fmt.Errorf("QCOW2 一致性检查未通过") + } + return nil +} + +func validateQCOW2UploadHeader(header []byte) error { + if len(header) < 72 || string(header[:4]) != "QFI\xfb" { + return fmt.Errorf("文件不是有效 ISO 或 QCOW2 镜像") + } + version := binary.BigEndian.Uint32(header[4:8]) + if version != 2 && version != 3 { + return fmt.Errorf("不支持的 QCOW2 版本") + } + if binary.BigEndian.Uint64(header[8:16]) != 0 || binary.BigEndian.Uint32(header[16:20]) != 0 || binary.BigEndian.Uint32(header[32:36]) != 0 || binary.BigEndian.Uint32(header[60:64]) != 0 || binary.BigEndian.Uint64(header[64:72]) != 0 { + return fmt.Errorf("QCOW2 必须先展平:不允许 backing、加密或内部快照") + } + bits := binary.BigEndian.Uint32(header[20:24]) + virtualSize := binary.BigEndian.Uint64(header[24:32]) + if bits < 9 || bits > 21 || virtualSize == 0 || virtualSize > 16<<40 { + return fmt.Errorf("QCOW2 文件头或虚拟容量无效(最大 16 TiB)") + } + if version == 3 { + if len(header) < 104 { + return fmt.Errorf("QCOW2 文件头被截断") + } + features := binary.BigEndian.Uint64(header[72:80]) + length := binary.BigEndian.Uint32(header[100:104]) + if features & ^uint64(8|16) != 0 || binary.BigEndian.Uint64(header[88:96])&2 != 0 { + return fmt.Errorf("QCOW2 不允许外部 data 文件、脏数据或未知的不兼容特性") + } + if length < 104 || length%8 != 0 || uint64(length) > uint64(1)< 6 || features&16 != 0 && bits < 14 { + return fmt.Errorf("QCOW2 扩展文件头无效") + } + } + return nil +} + +// Header extensions live in the first cluster. Reject host-file references and +// encryption pointers before allowing qemu-img to parse any image metadata. +func validateQCOW2UploadExtensions(file *os.File, header []byte) error { + length := int64(72) + if binary.BigEndian.Uint32(header[4:8]) == 3 { + length = int64(binary.BigEndian.Uint32(header[100:104])) + } + info, err := file.Stat() + if err != nil { + return err + } + cluster := min(int64(1)< int64(len(data))-offset-8 { + return fmt.Errorf("QCOW2 文件头扩展越界或重复") + } + seen[kind] = true + offset += 8 + (size+7)/8*8 + } + return fmt.Errorf("QCOW2 文件头扩展被截断") +} + +func max64(a, b int64) int64 { + if a > b { + return a + } + return b +} diff --git a/backend/internal/api/image_upload_test.go b/backend/internal/api/image_upload_test.go new file mode 100644 index 0000000..5ac7f53 --- /dev/null +++ b/backend/internal/api/image_upload_test.go @@ -0,0 +1,476 @@ +package api + +import ( + "bytes" + "context" + "crypto/sha256" + "database/sql" + "encoding/binary" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "clicd/internal/config" +) + +// Reuse the test executable as a portable qemu-img stub. The real byte-level +// preflight still runs; only the external info/check commands are simulated. +func init() { + name := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe") + if os.Getenv("CLICD_UPLOAD_QEMU_HELPER") != "1" || name != "qemu-img" && name != "df" && name != "findmnt" { + return + } + if name == "df" { + fmt.Print("Filesystem 1B-blocks Used Available Use% MountedOn\nfixture 137438953472 0 137438953472 0% /\n") + os.Exit(0) + } + if name == "findmnt" { + fmt.Println(os.Getenv("CLICD_UPLOAD_MOUNT")) + os.Exit(0) + } + if log := os.Getenv("CLICD_UPLOAD_QEMU_LOG"); log != "" { + file, _ := os.OpenFile(log, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) + if file != nil { + fmt.Fprintln(file, strings.Join(os.Args[1:], " ")) + file.Close() + } + } + if os.Getenv("CLICD_UPLOAD_QEMU_BLOCK") == "1" { + time.Sleep(time.Minute) + } + if len(os.Args) > 1 && os.Args[1] == "info" { + if value := os.Getenv("CLICD_UPLOAD_QEMU_INFO"); value != "" { + fmt.Print(value) + } else { + fmt.Print(`{"format":"qcow2","virtual-size":4294967296}`) + } + } + if len(os.Args) > 1 && os.Args[1] == "check" && os.Getenv("CLICD_UPLOAD_QEMU_CHECK_FAIL") == "1" { + os.Exit(1) + } + os.Exit(0) +} + +type uploadPart struct { + name, filename, value string + data []byte +} + +func uploadRequest(t *testing.T, parts []uploadPart) *http.Request { + t.Helper() + var body bytes.Buffer + writer := multipart.NewWriter(&body) + for _, part := range parts { + if part.filename != "" { + file, err := writer.CreateFormFile(part.name, part.filename) + if err != nil { + t.Fatal(err) + } + if _, err := file.Write(part.data); err != nil { + t.Fatal(err) + } + } else if err := writer.WriteField(part.name, part.value); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "/api/v1/images/upload", bytes.NewReader(body.Bytes())) + request.Header.Set("Content-Type", writer.FormDataContentType()) + return withAuthContext(request, AuthContext{Type: authTypeAdmin, Username: "upload-test"}) +} + +func uploadISOFixture() []byte { + data := make([]byte, 17*2048) + copy(data[16*2048+1:], "CD001") + data[16*2048+6] = 1 + return data +} + +func uploadQCOWFixture(version uint32) []byte { + data := make([]byte, 512) + copy(data, "QFI\xfb") + binary.BigEndian.PutUint32(data[4:8], version) + binary.BigEndian.PutUint32(data[20:24], 9) + binary.BigEndian.PutUint64(data[24:32], 4<<30) + if version == 3 { + binary.BigEndian.PutUint32(data[96:100], 4) + binary.BigEndian.PutUint32(data[100:104], 104) + } + return data +} + +func TestQCOWUploadUnsafeHeadersNeverInvokeQEMU(t *testing.T) { + t.Setenv("PATH", "") + cases := []struct { + name string + edit func([]byte) + }{ + {"backing-offset", func(b []byte) { binary.BigEndian.PutUint64(b[8:16], 104) }}, + {"backing-size", func(b []byte) { binary.BigEndian.PutUint32(b[16:20], 12) }}, + {"encryption", func(b []byte) { binary.BigEndian.PutUint32(b[32:36], 2) }}, + {"snapshot-count", func(b []byte) { binary.BigEndian.PutUint32(b[60:64], 1) }}, + {"snapshot-offset-with-zero-count", func(b []byte) { binary.BigEndian.PutUint64(b[64:72], 512) }}, + {"external-data-bit", func(b []byte) { binary.BigEndian.PutUint64(b[72:80], 4) }}, + {"raw-data-bit", func(b []byte) { binary.BigEndian.PutUint64(b[88:96], 2) }}, + {"unknown-feature", func(b []byte) { binary.BigEndian.PutUint64(b[72:80], 1<<63) }}, + {"oversized-cluster", func(b []byte) { binary.BigEndian.PutUint32(b[20:24], 31) }}, + {"unaligned-header", func(b []byte) { binary.BigEndian.PutUint32(b[100:104], 105) }}, + {"header-past-cluster", func(b []byte) { binary.BigEndian.PutUint32(b[100:104], 1024) }}, + {"external-data-extension", func(b []byte) { binary.BigEndian.PutUint32(b[104:108], 0x44415441) }}, + {"backing-format-extension", func(b []byte) { binary.BigEndian.PutUint32(b[104:108], 0xe2792aca) }}, + {"crypto-pointer-extension", func(b []byte) { binary.BigEndian.PutUint32(b[104:108], 0x0537be77) }}, + {"oversized-extension", func(b []byte) { + binary.BigEndian.PutUint32(b[104:108], 0x6803f857) + binary.BigEndian.PutUint32(b[108:112], ^uint32(0)) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + data := uploadQCOWFixture(3) + tc.edit(data) + file := filepath.Join(t.TempDir(), "unsafe.qcow2") + if err := os.WriteFile(file, data, 0600); err != nil { + t.Fatal(err) + } + err := validateUploadedQCOW2(context.Background(), file) + if err == nil || strings.Contains(err.Error(), "qemu-img") { + t.Fatalf("unsafe header reached external qemu-img validation: %v", err) + } + }) + } +} + +func TestImageUploadStreamingLimitAndCancellation(t *testing.T) { + var destination bytes.Buffer + if n, err := copyImageUpload(context.Background(), &destination, strings.NewReader(strings.Repeat("x", 18)), 16); err != errLocalImageTooLarge || n != 17 || destination.Len() != 17 { + t.Fatalf("streaming byte limit not enforced: n=%d err=%v written=%d", n, err, destination.Len()) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + destination.Reset() + if n, err := copyImageUpload(ctx, &destination, strings.NewReader("image"), 16); err != context.Canceled || n != 0 || destination.Len() != 0 { + t.Fatalf("canceled stream was written: n=%d err=%v written=%d", n, err, destination.Len()) + } +} + +func TestImageUploadMultipartPublicationAndRollback(t *testing.T) { + const fixtureEnv = "CLICD_UPLOAD_FIXTURE_DIR" + dir := os.Getenv(fixtureEnv) + if dir == "" { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(executable, "-test.run=^TestImageUploadMultipartPublicationAndRollback$", "-test.v") + cmd.Env = append(os.Environ(), fixtureEnv+"="+t.TempDir()) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("isolated upload fixture: %v\n%s", err, output) + } else { + t.Log(string(output)) + } + return + } + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) + pool := filepath.Join(dir, "pool") + if err := os.MkdirAll(pool, 0755); err != nil { + t.Fatal(err) + } + cfg := config.ClicdConfig{AdminUser: "test", AdminPassHash: "hash", JWTSecret: "secret", Port: 8999, DataDir: dir, + StoragePools: []config.StoragePool{{ID: "upload", Name: "upload", Path: pool, MountPoint: filepath.VolumeName(pool) + string(os.PathSeparator), Enabled: true, ContentTypes: []string{config.StorageContentImages}, DefaultContents: []string{config.StorageContentImages}}}} + data, _ := json.Marshal(cfg) + if err := os.WriteFile(filepath.Join(dir, "config.json"), data, 0600); err != nil { + t.Fatal(err) + } + config.SetConfigPath(filepath.Join(dir, "config.json")) + if _, err := config.InitConfig(); err != nil { + t.Fatal(err) + } + // Production normalization maps mount points to their managed /clicd path. + // Keep this isolated fixture inside its temporary pool on every platform. + config.AppConfig.StoragePools = append([]config.StoragePool(nil), cfg.StoragePools...) + config.AppConfig.StoragePools[0].MountPoint = "" + tools := filepath.Join(dir, "tools") + if err := os.MkdirAll(tools, 0755); err != nil { + t.Fatal(err) + } + executable, _ := os.Executable() + source, err := os.Open(executable) + if err != nil { + t.Fatal(err) + } + tool := filepath.Join(tools, "qemu-img") + if runtime.GOOS == "windows" { + tool += ".exe" + } + dst, err := os.OpenFile(tool, os.O_CREATE|os.O_WRONLY, 0755) + if err != nil { + t.Fatal(err) + } + _, copyErr := io.Copy(dst, source) + source.Close() + dst.Close() + if copyErr != nil { + t.Fatal(copyErr) + } + for _, name := range []string{"df", "findmnt"} { + if runtime.GOOS == "windows" { + name += ".exe" + } + if err := os.Link(tool, filepath.Join(tools, name)); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", tools) + t.Setenv("CLICD_UPLOAD_QEMU_HELPER", "1") + t.Setenv("CLICD_UPLOAD_MOUNT", config.AppConfig.StoragePools[0].MountPoint) + if output, err := exec.Command("findmnt").CombinedOutput(); err != nil { + t.Fatalf("fixture findmnt: %v %s", err, output) + } + if output, err := exec.Command("df").CombinedOutput(); err != nil { + t.Fatalf("fixture df: %v %s", err, output) + } + log := filepath.Join(dir, "qemu.log") + t.Setenv("CLICD_UPLOAD_QEMU_LOG", log) + cache := filepath.Join(pool, "images", "kvm") + reset := func() { + t.Helper() + config.AppConfig.CustomKVMImages = nil + config.AppConfig.EnabledImages = nil + if err := config.SaveConfig(); err != nil { + t.Fatal(err) + } + entries, _ := os.ReadDir(cache) + for _, entry := range entries { + if err := os.Remove(filepath.Join(cache, entry.Name())); err != nil { + t.Fatal(err) + } + } + os.Remove(log) + } + assertEmpty := func() { + t.Helper() + entries, _ := os.ReadDir(cache) + if len(entries) != 0 || len(config.AppConfig.CustomKVMImages) != 0 || len(config.AppConfig.EnabledImages) != 0 { + t.Fatalf("failed upload left stage/cache/metadata: files=%v images=%+v enabled=%v", entries, config.AppConfig.CustomKVMImages, config.AppConfig.EnabledImages) + } + } + valid := []uploadPart{{name: "name", value: "Uploaded image"}, {name: "file", filename: "image.iso", data: uploadISOFixture()}} + for _, tc := range []struct { + name string + parts []uploadPart + }{ + {"no-file", valid[:1]}, + {"empty-file", []uploadPart{{name: "name", value: "Empty"}, {name: "file", filename: "empty.iso"}}}, + {"duplicate-file", append(append([]uploadPart{}, valid...), valid[1])}, + {"wrong-file-field", []uploadPart{{name: "name", value: "Wrong"}, {name: "image", filename: "image.iso", data: uploadISOFixture()}}}, + {"duplicate-field", append(append([]uploadPart{}, valid...), uploadPart{name: "name", value: "duplicate"})}, + {"unknown-field", append(append([]uploadPart{}, valid...), uploadPart{name: "path", value: "../../outside.iso"})}, + {"oversized-field", []uploadPart{{name: "name", value: strings.Repeat("n", 8193)}, {name: "file", filename: "image.iso", data: uploadISOFixture()}}}, + {"invalid-format", []uploadPart{{name: "name", value: "HTML"}, {name: "file", filename: "image.iso", data: []byte("not an image")}}}, + {"sha-mismatch", append(append([]uploadPart{}, valid...), uploadPart{name: "sha256", value: strings.Repeat("0", 64)})}, + } { + t.Run(tc.name, func(t *testing.T) { + reset() + response := httptest.NewRecorder() + HandleImageUpload(response, uploadRequest(t, tc.parts)) + if response.Code != http.StatusBadRequest { + t.Fatalf("status=%d: %s", response.Code, response.Body.String()) + } + if strings.Contains(response.Body.String(), "storage") { + t.Fatalf("test did not reach upload validation: %s", response.Body.String()) + } + assertEmpty() + }) + } + reset() + t.Run("explicit-pool-never-falls-back", func(t *testing.T) { + request := uploadRequest(t, valid) + request.URL.RawQuery = "storage_pool_id=missing-pool" + response := httptest.NewRecorder() + HandleImageUpload(response, request) + if response.Code != http.StatusBadRequest { + t.Fatalf("upload silently used a different pool: %d %s", response.Code, response.Body.String()) + } + assertEmpty() + }) + t.Run("content-length-limit", func(t *testing.T) { + request := uploadRequest(t, valid) + request.ContentLength = maxLocalImageBytes + (1 << 20) + 1 + response := httptest.NewRecorder() + HandleImageUpload(response, request) + if response.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status=%d", response.Code) + } + assertEmpty() + }) + t.Run("canceled-request", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + response := httptest.NewRecorder() + HandleImageUpload(response, uploadRequest(t, valid).WithContext(ctx)) + if response.Code != 400 { + t.Fatalf("status=%d", response.Code) + } + assertEmpty() + }) + for name, info := range map[string]string{ + "invalid-qemu-json": `{`, + "qemu-reported-backing": `{"format":"qcow2","virtual-size":4294967296,"backing-filename":"/host/private"}`, + "qemu-reported-full-backing": `{"format":"qcow2","virtual-size":4294967296,"full-backing-filename":"/host/private"}`, + "qemu-reported-nested-data": `{"format":"qcow2","virtual-size":4294967296,"format-specific":{"data":{"data-file":"/host/private"}}}`, + "qemu-reported-encryption": `{"format":"qcow2","virtual-size":4294967296,"encrypted":true}`, + "qemu-reported-snapshot": `{"format":"qcow2","virtual-size":4294967296,"snapshots":[{"id":"1"}]}`, + } { + t.Run(name, func(t *testing.T) { + reset() + t.Setenv("CLICD_UPLOAD_QEMU_INFO", info) + response := httptest.NewRecorder() + HandleImageUpload(response, uploadRequest(t, []uploadPart{{name: "name", value: "Disk"}, {name: "file", filename: "disk.qcow2", data: uploadQCOWFixture(3)}})) + if response.Code != 400 { + t.Fatalf("status=%d: %s", response.Code, response.Body.String()) + } + assertEmpty() + commands, _ := os.ReadFile(log) + if !strings.Contains(string(commands), "info ") || strings.Contains(string(commands), "check ") { + t.Fatalf("unsafe info result reached check: %s", commands) + } + }) + } + t.Run("qemu-consistency-failure", func(t *testing.T) { + reset() + t.Setenv("CLICD_UPLOAD_QEMU_CHECK_FAIL", "1") + response := httptest.NewRecorder() + HandleImageUpload(response, uploadRequest(t, []uploadPart{{name: "name", value: "Disk"}, {name: "file", filename: "disk.qcow2", data: uploadQCOWFixture(3)}})) + if response.Code != 400 { + t.Fatalf("status=%d: %s", response.Code, response.Body.String()) + } + assertEmpty() + commands, _ := os.ReadFile(log) + if !strings.Contains(string(commands), "check ") { + t.Fatal("consistency check was not exercised") + } + }) + t.Run("cancellation-during-qemu", func(t *testing.T) { + reset() + t.Setenv("CLICD_UPLOAD_QEMU_BLOCK", "1") + request := uploadRequest(t, []uploadPart{{name: "name", value: "Disk"}, {name: "file", filename: "disk.qcow2", data: uploadQCOWFixture(3)}}) + ctx, cancel := context.WithCancel(request.Context()) + defer cancel() + response := httptest.NewRecorder() + done := make(chan struct{}) + go func() { HandleImageUpload(response, request.WithContext(ctx)); close(done) }() + deadline := time.Now().Add(3 * time.Second) + for { + commands, _ := os.ReadFile(log) + if strings.Contains(string(commands), "info ") { + break + } + if time.Now().After(deadline) { + cancel() + <-done + t.Fatal("qemu validation never started") + } + time.Sleep(10 * time.Millisecond) + } + cancel() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("upload validator ignored context cancellation") + } + if response.Code != 400 { + t.Fatalf("status=%d", response.Code) + } + assertEmpty() + }) + for _, tc := range []struct { + name, provisioner, format string + bytes []byte + }{ + {"iso-path-traversal-filename", "", "iso", uploadISOFixture()}, + {"manual-disk-v2", "manual-disk", "qcow2", uploadQCOWFixture(2)}, + {"manual-disk-v3", "", "qcow2", uploadQCOWFixture(3)}, + {"cloud-init", "linux-cloud-init", "qcow2", uploadQCOWFixture(3)}, + {"windows10", "windows-10", "iso", uploadISOFixture()}, + {"windows11", "windows-11", "iso", uploadISOFixture()}, + } { + t.Run(tc.name, func(t *testing.T) { + reset() + sum := sha256.Sum256(tc.bytes) + sha := hex.EncodeToString(sum[:]) + parts := []uploadPart{{name: "name", value: "Local image"}, {name: "sha256", value: strings.ToUpper(sha)}, {name: "provisioner", value: tc.provisioner}, {name: "file", filename: "../../outside.iso", data: tc.bytes}} + response := httptest.NewRecorder() + HandleImageUpload(response, uploadRequest(t, parts)) + if strings.HasPrefix(tc.provisioner, "windows-") && runtime.GOARCH != "amd64" { + if response.Code != 400 { + t.Fatalf("automatic Windows installation accepted non-amd64 host: %d", response.Code) + } + assertEmpty() + return + } + if response.Code != 201 { + t.Fatalf("status=%d: %s", response.Code, response.Body.String()) + } + var result struct { + Data struct { + ID, Format string + SHA string `json:"sha256"` + Size int64 `json:"size_bytes"` + } `json:"data"` + } + if json.Unmarshal(response.Body.Bytes(), &result) != nil { + t.Fatal("invalid response") + } + image := config.AppConfig.CustomKVMImages[0] + if result.Data.ID != image.ID || result.Data.Format != tc.format || result.Data.SHA != sha || result.Data.Size != int64(len(tc.bytes)) { + t.Fatalf("incorrect upload receipt: %s", response.Body.String()) + } + entries, err := os.ReadDir(cache) + if err != nil || len(entries) != 1 || entries[0].Name() != image.ID+"."+tc.format || !strings.HasPrefix(image.ID, "custom-kvm-") || image.SHA256 != sha || len(config.AppConfig.EnabledImages) != 1 || config.AppConfig.EnabledImages[0] != image.ID { + t.Fatalf("upload was not atomically registered: %s files=%v image=%+v", response.Body.String(), entries, image) + } + if _, err := os.Stat(filepath.Join(pool, "outside.iso")); !os.IsNotExist(err) { + t.Fatal("client filename escaped cache") + } + if image.URL != "" { + t.Fatal("local upload acquired an external source URL") + } + }) + } + reset() + t.Run("publication-database-rollback", func(t *testing.T) { + db, err := sql.Open("sqlite", filepath.Join(dir, "config.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err = db.Exec(`CREATE TRIGGER reject_upload BEFORE INSERT ON enabled_images BEGIN SELECT RAISE(ABORT,'reject upload'); END`); err != nil { + t.Fatal(err) + } + defer db.Exec(`DROP TRIGGER reject_upload`) + response := httptest.NewRecorder() + HandleImageUpload(response, uploadRequest(t, valid)) + if response.Code != 400 { + t.Fatalf("status=%d: %s", response.Code, response.Body.String()) + } + assertEmpty() + var count int + if err = db.QueryRow(`SELECT COUNT(*) FROM enabled_images`).Scan(&count); err != nil || count != 0 { + t.Fatalf("partial enabled registration persisted: %d %v", count, err) + } + }) +} diff --git a/backend/internal/api/images.go b/backend/internal/api/images.go index e908976..cfdd437 100644 --- a/backend/internal/api/images.go +++ b/backend/internal/api/images.go @@ -24,30 +24,31 @@ import ( // ImageInfo represents a template image with its download/enable status. type ImageInfo struct { - ID string `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - Distro string `json:"distro"` - Release string `json:"release"` - Arch string `json:"arch"` - Description string `json:"description"` - Downloaded bool `json:"downloaded"` - Enabled bool `json:"enabled"` - Downloading bool `json:"downloading"` - Progress int `json:"progress"` - DownloadedBytes int64 `json:"downloaded_bytes"` - TotalBytes int64 `json:"total_bytes"` - Stage string `json:"stage,omitempty"` - Error string `json:"error,omitempty"` - SizeBytes int64 `json:"size_bytes"` - ManualPath string `json:"manual_path,omitempty"` - Desktop string `json:"desktop,omitempty"` - Provisioner string `json:"provisioner,omitempty"` - Format string `json:"format,omitempty"` - ManualInstall bool `json:"manual_install,omitempty"` - RequiresURL bool `json:"requires_url,omitempty"` - Custom bool `json:"custom,omitempty"` - SHA256 string `json:"sha256,omitempty"` + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Distro string `json:"distro"` + Release string `json:"release"` + Arch string `json:"arch"` + Description string `json:"description"` + Downloaded bool `json:"downloaded"` + Enabled bool `json:"enabled"` + Downloading bool `json:"downloading"` + Progress int `json:"progress"` + DownloadedBytes int64 `json:"downloaded_bytes"` + TotalBytes int64 `json:"total_bytes"` + Stage string `json:"stage,omitempty"` + Error string `json:"error,omitempty"` + SizeBytes int64 `json:"size_bytes"` + ManualPath string `json:"manual_path,omitempty"` + Desktop string `json:"desktop,omitempty"` + Provisioner string `json:"provisioner,omitempty"` + Format string `json:"format,omitempty"` + ManualInstall bool `json:"manual_install,omitempty"` + RequiresURL bool `json:"requires_url,omitempty"` + Custom bool `json:"custom,omitempty"` + SHA256 string `json:"sha256,omitempty"` + MinDiskGB float64 `json:"min_disk_gb,omitempty"` } var customImageFieldPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) @@ -491,7 +492,8 @@ func HandleImages(w http.ResponseWriter, r *http.Request) { Desktop: t.Desktop, Provisioner: t.EffectiveProvisioner(), Format: kvm.ImageFormat(t), - ManualInstall: t.IsManualISO(), + ManualInstall: t.IsManualISO() || t.IsManualDisk(), + MinDiskGB: kvm.GetKVMImageMinDiskGB(t.ID), RequiresURL: strings.TrimSpace(t.URL) == "", Custom: t.Custom, SHA256: t.SHA256, @@ -1211,7 +1213,8 @@ func HandleEnabledImages(w http.ResponseWriter, r *http.Request) { result = append(result, map[string]interface{}{ "id": t.ID, "name": t.Name, "distro": t.Distro, "release": t.Release, "arch": t.Arch, "description": t.Description, "type": config.VirtualizationKVM, "desktop": t.Desktop, - "provisioner": t.EffectiveProvisioner(), "format": kvm.ImageFormat(t), "manual_install": t.IsManualISO(), + "provisioner": t.EffectiveProvisioner(), "format": kvm.ImageFormat(t), "manual_install": t.IsManualISO() || t.IsManualDisk(), + "min_disk_gb": kvm.GetKVMImageMinDiskGB(t.ID), }) } } diff --git a/backend/internal/api/metric_history.go b/backend/internal/api/metric_history.go new file mode 100644 index 0000000..48c3590 --- /dev/null +++ b/backend/internal/api/metric_history.go @@ -0,0 +1,61 @@ +package api + +import ( + "encoding/json" + "fmt" + "time" + + "clicd/internal/config" +) + +func persistMetricPoint(kind, series string, sampledAt int64, point interface{}) { + data, err := json.Marshal(point) + if err == nil { + err = config.SaveMetricHistory(kind, series, sampledAt, data) + } + if err != nil && err != config.ErrHistoryStoreUnavailable { + fmt.Printf("Metric history persistence failed: %v\n", err) + } +} + +func restoreHostMetricHistory() { + records, err := config.LoadMetricHistory("host", "host") + if err != nil { + return + } + cutoff := time.Now().Add(-hostMetricRetention).UnixMilli() + var history []HostMetricPoint + for _, record := range records { + var point HostMetricPoint + if json.Unmarshal(record.Data, &point) == nil && point.TS >= cutoff { + history = append(history, point) + } + } + hostMetricMu.Lock() + hostMetricHistory = history + hostMetricMu.Unlock() +} + +func restoreContainerMetricHistory() { + records, err := config.LoadMetricHistory("container", "") + if err != nil { + return + } + valid := make(map[string]bool) + if config.AppConfig != nil { + for _, c := range config.AppConfig.Containers { + valid[containerMetricKey(c)] = true + } + } + cutoff := time.Now().Add(-hostMetricRetention).UnixMilli() + history := make(map[string][]ContainerMetricPoint) + for _, record := range records { + var point ContainerMetricPoint + if valid[record.Series] && json.Unmarshal(record.Data, &point) == nil && point.TS >= cutoff { + history[record.Series] = append(history[record.Series], point) + } + } + containerMetricMu.Lock() + containerMetricHistory = history + containerMetricMu.Unlock() +} diff --git a/backend/internal/api/operation_tasks.go b/backend/internal/api/operation_tasks.go new file mode 100644 index 0000000..6306080 --- /dev/null +++ b/backend/internal/api/operation_tasks.go @@ -0,0 +1,107 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "sync" + "time" + + "clicd/internal/config" +) + +type OperationTaskHandler func(context.Context, int, json.RawMessage, func(stage, detail string)) error + +var operationTasks = struct { + sync.RWMutex + handlers map[TaskType]OperationTaskHandler +}{handlers: make(map[TaskType]OperationTaskHandler)} + +func builtInTask(kind TaskType) bool { + switch kind { + case TaskCreate, TaskStart, TaskStop, TaskRestart, TaskDelete, TaskReinstall: + return true + } + return false +} + +// RegisterOperationTask is intended for package initialization. Operations share +// the same concurrency budget and instance locks as built-in lifecycle tasks. +func RegisterOperationTask(kind TaskType, handler OperationTaskHandler) { + if strings.TrimSpace(string(kind)) == "" || builtInTask(kind) || handler == nil { + panic("invalid operation task registration: " + string(kind)) + } + operationTasks.Lock() + defer operationTasks.Unlock() + if operationTasks.handlers[kind] != nil { + panic("duplicate operation task registration: " + string(kind)) + } + operationTasks.handlers[kind] = handler +} + +func operationHandler(kind TaskType) OperationTaskHandler { + operationTasks.RLock() + defer operationTasks.RUnlock() + return operationTasks.handlers[kind] +} + +func EnqueueOperationWithAudit(id int, name string, kind TaskType, payload json.RawMessage, user, ip, ua string, additionalTargets ...string) (string, error) { + return globalQueue.EnqueueOperationWithAudit(id, name, kind, payload, user, ip, ua, additionalTargets...) +} + +func (q *TaskQueue) EnqueueOperationWithAudit(id int, name string, kind TaskType, payload json.RawMessage, user, ip, ua string, additionalTargets ...string) (string, error) { + if operationHandler(kind) == nil || builtInTask(kind) { + return "", fmt.Errorf("unsupported operation task: %s", kind) + } + if !json.Valid(payload) || len(payload) > 64*1024 { + return "", fmt.Errorf("operation payload must be valid JSON of at most 64 KiB") + } + if id <= 0 && strings.TrimSpace(name) == "" { + return "", fmt.Errorf("operation target is required") + } + q.mu.Lock() + defer q.mu.Unlock() + sequence, err := config.ReserveTaskID(q.nextID) + if err != nil && err != config.ErrHistoryStoreUnavailable { + return "", fmt.Errorf("reserve task ID: %w", err) + } + if err == config.ErrHistoryStoreUnavailable { + sequence = q.nextID + } + q.nextID = sequence + 1 + task := &Task{ID: fmt.Sprintf("task-%d", sequence), Type: kind, ContainerID: id, ContainerName: name, + Status: "pending", Stage: "queued", StageDetail: "排队等待", CreatedAt: time.Now().Format(time.RFC3339Nano), + User: user, IP: ip, UserAgent: ua, Payload: append(json.RawMessage(nil), payload...), AdditionalTargets: append([]string(nil), additionalTargets...)} + q.enqueueTask(task) + if err := q.persistTasks(); err != nil && err != config.ErrHistoryStoreUnavailable { + delete(q.tasks, task.ID) + for i, queued := range q.opQueue { + if queued == task { + q.opQueue = append(q.opQueue[:i], q.opQueue[i+1:]...) + break + } + } + return "", fmt.Errorf("persist operation task: %w", err) + } + return task.ID, nil +} + +type operationResultKey struct{} + +// SetOperationTaskResult publishes safe result metadata, such as a new artifact +// or instance ID. Payloads and internal execution contexts are not API results. +func SetOperationTaskResult(ctx context.Context, result interface{}) error { + set, ok := ctx.Value(operationResultKey{}).(func(json.RawMessage) error) + if !ok { + return fmt.Errorf("not running in an operation task") + } + data, err := json.Marshal(result) + if err != nil { + return err + } + if len(data) > 64*1024 { + return fmt.Errorf("task result exceeds 64 KiB") + } + return set(data) +} diff --git a/backend/internal/api/runtime.go b/backend/internal/api/runtime.go index c7f1231..e935f9b 100644 --- a/backend/internal/api/runtime.go +++ b/backend/internal/api/runtime.go @@ -43,7 +43,7 @@ func createByRuntime(cfg lxc.ContainerConfig) error { } func validateCreateSSHAuth(cfg lxc.ContainerConfig) error { - if cfg.Virtualization == config.VirtualizationKVM && (kvm.IsWindowsImage(cfg.TemplateID) || kvm.IsManualISOImage(cfg.TemplateID)) { + if cfg.Virtualization == config.VirtualizationKVM && (kvm.IsWindowsImage(cfg.TemplateID) || kvm.IsManualISOImage(cfg.TemplateID) || kvm.IsManualDiskImage(cfg.TemplateID)) { return nil } _, err := lxc.ResolveCreateSSHAccess(cfg) @@ -51,7 +51,7 @@ func validateCreateSSHAuth(cfg lxc.ContainerConfig) error { } func validateReinstallSSHAuth(c *config.Container, templateID string, cfg lxc.ContainerConfig) error { - if c != nil && c.IsKVM() && (kvm.IsWindowsImage(templateID) || kvm.IsManualISOImage(templateID)) { + if c != nil && c.IsKVM() && (kvm.IsWindowsImage(templateID) || kvm.IsManualISOImage(templateID) || kvm.IsManualDiskImage(templateID)) { return nil } currentPassword := "" diff --git a/backend/internal/api/snapshots.go b/backend/internal/api/snapshots.go index d4ab70f..af1e319 100644 --- a/backend/internal/api/snapshots.go +++ b/backend/internal/api/snapshots.go @@ -88,6 +88,15 @@ func listContainerSnapshots(w http.ResponseWriter, r *http.Request, containerID } func createContainerSnapshot(w http.ResponseWriter, r *http.Request, containerID int) { + c := config.FindContainer(containerID) + if c == nil { + jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"}) + return + } + if len(c.DataDisks) > 0 { + jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Instances with data disks require full backup and restore; system-disk snapshots are unavailable"}) + return + } user := requestUser(r) var req struct { StoragePoolID string `json:"storage_pool_id"` @@ -104,7 +113,6 @@ func createContainerSnapshot(w http.ResponseWriter, r *http.Request, containerID return } if isSubUserRequest(r) { - c := config.FindContainer(containerID) limit := config.ContainerSnapshotLimit(c) if len(config.ContainerSnapshots(containerID)) >= limit { jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Snapshot quota reached. Delete an old snapshot first."}) @@ -219,6 +227,15 @@ func restoreContainerSnapshot(w http.ResponseWriter, r *http.Request, containerI jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Snapshot not found"}) return } + c := config.FindContainer(containerID) + if c == nil { + jsonResponse(w, http.StatusNotFound, APIResponse{Success: false, Message: "Container not found"}) + return + } + if len(c.DataDisks) > 0 { + jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "Instances with data disks require full backup and restore; system-disk snapshots are unavailable"}) + return + } user := requestUser(r) if err := restoreSnapshotByRuntime(snapshotID); err != nil { jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: err.Error()}) diff --git a/backend/internal/api/snapshots_disks_test.go b/backend/internal/api/snapshots_disks_test.go new file mode 100644 index 0000000..e57ccb2 --- /dev/null +++ b/backend/internal/api/snapshots_disks_test.go @@ -0,0 +1,41 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "clicd/internal/config" +) + +func TestSnapshotAPIReturnsConflictForInstancesWithDataDisks(t *testing.T) { + previous := config.AppConfig + t.Cleanup(func() { config.AppConfig = previous }) + t.Setenv("PATH", "") + for _, runtime := range []string{"lxc", "kvm"} { + for _, attached := range []bool{true, false} { + config.AppConfig = &config.ClicdConfig{Containers: []config.Container{{ID: 14, UUID: "with-data-disk", Name: "with-data-disk", Virtualization: runtime, Status: "stopped", DataDisks: []config.DataDisk{{ID: "disk-one", Attached: attached, SizeGB: 2}}}}, Snapshots: []config.Snapshot{{ID: "existing", ContainerID: 14, ContainerName: "with-data-disk"}}} + before, _ := json.Marshal(config.AppConfig) + for _, path := range []string{"/api/v1/containers/14/snapshots", "/api/v1/containers/14/snapshots/existing/restore"} { + request := withAuthContext(httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{}`)), AuthContext{Type: authTypeAdmin}) + response := httptest.NewRecorder() + HandleSingleContainer(response, request) + if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "full backup") { + t.Fatalf("runtime=%s attached=%v %s: %d %s", runtime, attached, path, response.Code, response.Body.String()) + } + request = withAuthContext(httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{}`)), AuthContext{Type: authTypeAPIKey, Scopes: []string{"container:read"}}) + response = httptest.NewRecorder() + HandleSingleContainer(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("data-disk check bypassed scope enforcement: %d", response.Code) + } + } + after, _ := json.Marshal(config.AppConfig) + if string(before) != string(after) { + t.Fatal("rejected snapshot operation modified instance or snapshot metadata") + } + } + } +} diff --git a/backend/internal/api/subuser.go b/backend/internal/api/subuser.go index 224b496..845002c 100644 --- a/backend/internal/api/subuser.go +++ b/backend/internal/api/subuser.go @@ -642,6 +642,8 @@ func isSubUserContainerActionAllowed(action string, method string) bool { return method == http.MethodGet } switch { + case action == "disks": + return method == http.MethodGet case action == "usage" || action == "traffic" || action == "history" || action == "random-port": return method == http.MethodGet case action == "firewall" || action == "installation-media": diff --git a/backend/internal/api/task_history.go b/backend/internal/api/task_history.go new file mode 100644 index 0000000..b51bd58 --- /dev/null +++ b/backend/internal/api/task_history.go @@ -0,0 +1,271 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "sort" + "strings" + "time" + + "clicd/internal/config" + "clicd/internal/lxc" +) + +const maxTaskEvents = 200 + +type TaskEvent struct { + Time string `json:"time"` + Stage string `json:"stage"` + Detail string `json:"detail"` +} + +type storedTask struct { + Task *Task `json:"task"` + Payload json.RawMessage `json:"payload,omitempty"` + AdditionalTargets []string `json:"additional_targets,omitempty"` +} + +func taskTime(value string) time.Time { + for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05"} { + if parsed, err := time.ParseInLocation(layout, value, time.Local); err == nil { + return parsed + } + } + return time.Time{} +} + +func addTaskEvent(task *Task, stage, detail string) { + if len(stage) > 128 { + stage = stage[:128] + } + if len(detail) > 4096 { + detail = detail[:4096] + } + task.Stage, task.StageDetail = stage, detail + if len(task.Logs) == 0 || task.Logs[len(task.Logs)-1].Stage != stage || task.Logs[len(task.Logs)-1].Detail != detail { + task.Logs = append(task.Logs, TaskEvent{Time: time.Now().Format(time.RFC3339Nano), Stage: stage, Detail: detail}) + if len(task.Logs) > maxTaskEvents { + task.Logs = append([]TaskEvent(nil), task.Logs[len(task.Logs)-maxTaskEvents:]...) + } + } + task.revision++ +} + +func taskConcurrencyKeys(task *Task) []string { + keys := []string{taskConcurrencyKey(task)} + for _, name := range task.AdditionalTargets { + key := "name:" + strings.ToLower(strings.TrimSpace(name)) + if key == "name:" { + continue + } + found := false + for _, existing := range keys { + found = found || existing == key + } + if !found { + keys = append(keys, key) + } + } + return keys +} + +func taskTargetsActive(task *Task, active map[string]bool) bool { + for _, key := range taskConcurrencyKeys(task) { + if active[key] { + return true + } + } + return false +} + +func (q *TaskQueue) allocateTaskID() int { + id, err := config.ReserveTaskID(q.nextID) + if err != nil { + id = q.nextID + if err != config.ErrHistoryStoreUnavailable { + fmt.Printf("Task sequence persistence failed: %v\n", err) + } + } + q.nextID = id + 1 + return id +} + +func (q *TaskQueue) pruneTaskMemory() { + var completed []*Task + cutoff := time.Now().Add(-config.TaskHistoryRetention) + for id, task := range q.tasks { + if task.Status != "done" && task.Status != "failed" { + continue + } + finished := taskTime(task.FinishedAt) + if finished.IsZero() { + finished = time.Now() + task.FinishedAt = finished.Format(time.RFC3339Nano) + task.revision++ + } + if !finished.IsZero() && finished.Before(cutoff) { + delete(q.tasks, id) + delete(q.historySaved, id) + } else { + completed = append(completed, task) + } + } + sort.Slice(completed, func(i, j int) bool { return parseIDNum(completed[i].ID) > parseIDNum(completed[j].ID) }) + for _, task := range completed[min(len(completed), config.TaskHistoryLimit):] { + delete(q.tasks, task.ID) + delete(q.historySaved, task.ID) + } +} + +func (q *TaskQueue) persistTaskState() error { + return q.persistTaskStateWithLegacy(true) +} + +func (q *TaskQueue) persistTaskHistoryOnly() error { + return q.persistTaskStateWithLegacy(false) +} + +func (q *TaskQueue) persistTaskStateWithLegacy(saveLegacy bool) error { + if q.historySaved == nil { + q.historySaved = make(map[string]uint64) + } + var records []config.TaskHistoryRecord + var changed []*Task + var pending []config.SavedTask + for _, task := range q.tasks { + // Legacy terminal rows may lack timestamps. Give them a durable finish + // marker before serialization so SQL retention cannot treat them as active. + if (task.Status == "done" || task.Status == "failed") && taskTime(task.FinishedAt).IsZero() { + task.FinishedAt = time.Now().Format(time.RFC3339Nano) + task.revision++ + } + if previous, ok := q.historySaved[task.ID]; !ok || previous != task.revision { + data, err := json.Marshal(storedTask{Task: task, Payload: task.Payload, AdditionalTargets: task.AdditionalTargets}) + if err != nil { + return err + } + finished := int64(0) + if parsed := taskTime(task.FinishedAt); !parsed.IsZero() { + finished = parsed.UnixMilli() + } + records = append(records, config.TaskHistoryRecord{ID: task.ID, Sequence: parseIDNum(task.ID), FinishedAt: finished, Data: data}) + changed = append(changed, task) + } + if task.Status == "pending" || task.Status == "running" { + cfgJSON, _ := json.Marshal(task.Config) + pending = append(pending, config.SavedTask{ID: task.ID, Type: string(task.Type), ContainerID: task.ContainerID, ContainerName: task.ContainerName, + Status: task.Status, Error: task.Error, CreatedAt: task.CreatedAt, TemplateID: task.TemplateID, Config: string(cfgJSON), User: task.User, IP: task.IP, UserAgent: task.UserAgent}) + } + } + err := config.SaveTaskHistory(records, q.nextID) + if err == nil { + for _, task := range changed { + q.historySaved[task.ID] = task.revision + } + // Persist terminal transitions before pruning memory. Otherwise a very + // old operation finishing at the limit could remain "running" on disk. + q.pruneTaskMemory() + } else if err != config.ErrHistoryStoreUnavailable { + fmt.Printf("Task history persistence failed: %v\n", err) + } + if saveLegacy && config.AppConfig != nil { + config.SaveTasks(pending) + } + return err +} + +func (q *TaskQueue) restoreTaskState() { + q.mu.Lock() + defer q.mu.Unlock() + restored := make(map[string]*Task) + for _, saved := range config.AppConfig.Tasks { + var cfg lxc.ContainerConfig + _ = json.Unmarshal([]byte(saved.Config), &cfg) + if saved.ContainerName == "" { + saved.ContainerName = cfg.Name + } + if cfg.Name == "" { + cfg.Name = saved.ContainerName + } + cfg.NormalizeResourceAliases() + restored[saved.ID] = &Task{ID: saved.ID, Type: TaskType(saved.Type), ContainerID: saved.ContainerID, ContainerName: saved.ContainerName, + Status: saved.Status, Error: saved.Error, CreatedAt: saved.CreatedAt, TemplateID: saved.TemplateID, Config: cfg, User: saved.User, IP: saved.IP, UserAgent: saved.UserAgent} + } + records, next, err := config.LoadTaskHistory() + if err != nil && err != config.ErrHistoryStoreUnavailable { + fmt.Printf("Load task history failed: %v\n", err) + } + if next > q.nextID { + q.nextID = next + } + for _, record := range records { + var stored storedTask + if json.Unmarshal(record.Data, &stored) == nil && stored.Task != nil { + stored.Task.Payload = stored.Payload + stored.Task.AdditionalTargets = stored.AdditionalTargets + restored[record.ID] = stored.Task + } + } + var ordered []*Task + for _, task := range restored { + if sequence := parseIDNum(task.ID); sequence >= q.nextID { + q.nextID = sequence + 1 + } + ordered = append(ordered, task) + } + sort.Slice(ordered, func(i, j int) bool { return parseIDNum(ordered[i].ID) < parseIDNum(ordered[j].ID) }) + for _, task := range ordered { + if task.Type == TaskStop && task.User == "system:security" { + continue + } + q.tasks[task.ID] = task + if task.Status != "pending" && task.Status != "running" { + if task.FinishedAt == "" { + task.FinishedAt = task.CreatedAt + } + continue + } + if !builtInTask(task.Type) && (task.Status == "running" || operationHandler(task.Type) == nil || !json.Valid(task.Payload)) { + task.Status = "failed" + task.Error = "operation interrupted by service restart or its handler is unavailable; inspect state before retrying" + task.FinishedAt = time.Now().Format(time.RFC3339Nano) + addTaskEvent(task, "interrupted", task.Error) + continue + } + task.Status = "pending" + task.StartedAt = "" + task.FinishedAt = "" + task.DurationMS = 0 + if task.ContainerID <= 0 && task.Type != TaskCreate && task.ContainerName != "" { + if c := config.FindContainerByName(task.ContainerName); c != nil { + task.ContainerID = c.ID + } + } + addTaskEvent(task, "queued", "服务重启后恢复排队") + q.enqueueTask(task) + } + q.persistTasks() + // The queue now owns recovery. Keep the compatibility field empty until its + // next transition, matching the old RestoreTasks contract. + config.SaveTasks([]config.SavedTask{}) +} + +func isHistoricalTaskAllowed(r *http.Request, task *Task) bool { + allowed, restricted := requestAllowedContainers(r) + if !restricted { + return true + } + if task == nil { + return false + } + if task.ContainerUUID != "" { + return allowed.uuids[task.ContainerUUID] + } + // Legacy records have no immutable owner identity. Only live matching + // containers can be authorized; never grant old history by name alone. + if task.Status != "pending" && task.Status != "running" { + return false + } + return isTaskAllowedForRequest(r, task) +} diff --git a/backend/internal/api/task_history_test.go b/backend/internal/api/task_history_test.go new file mode 100644 index 0000000..4c56b68 --- /dev/null +++ b/backend/internal/api/task_history_test.go @@ -0,0 +1,261 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "clicd/internal/config" +) + +func testOperationHandler(t *testing.T, kind TaskType, handler OperationTaskHandler) { + t.Helper() + RegisterOperationTask(kind, handler) + t.Cleanup(func() { operationTasks.Lock(); delete(operationTasks.handlers, kind); operationTasks.Unlock() }) +} + +func TestOperationTasksShareConcurrencyAndAllTargetLocks(t *testing.T) { + setupTaskQueueConfig(t) + config.AppConfig.Containers = []config.Container{{ID: 1, UUID: "source", Name: "source"}, {ID: 2, UUID: "destination", Name: "destination"}, {ID: 3, UUID: "other", Name: "other"}} + started := make(chan int, 3) + release := make(chan struct{}) + testOperationHandler(t, "qa-multiple-locks", func(ctx context.Context, id int, _ json.RawMessage, progress func(string, string)) error { + progress("copying", "copying a full disk") + started <- id + if id == 1 { + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } + } + return nil + }) + q := newTaskQueue(2) + startTaskQueueDispatchers(t, q) + first, err := q.EnqueueOperationWithAudit(1, "source", "qa-multiple-locks", json.RawMessage(`{}`), "admin", "", "", "destination") + if err != nil { + t.Fatal(err) + } + if id := <-started; id != 1 { + t.Fatalf("first operation = %d", id) + } + second, err := q.EnqueueOperationWithAudit(2, "destination", "qa-multiple-locks", json.RawMessage(`{}`), "admin", "", "") + if err != nil { + t.Fatal(err) + } + third, err := q.EnqueueOperationWithAudit(3, "other", "qa-multiple-locks", json.RawMessage(`{}`), "admin", "", "") + if err != nil { + t.Fatal(err) + } + select { + case id := <-started: + if id != 3 { + t.Fatalf("destination ran concurrently with its clone: %d", id) + } + case <-time.After(3 * time.Second): + t.Fatal("unrelated operation did not use available concurrency") + } + waitTaskQueueStatus(t, q, third, "done") + q.mu.Lock() + locked := q.tasks[second].Status == "pending" && q.activeTargets["name:source"] && q.activeTargets["name:destination"] + q.mu.Unlock() + if !locked { + t.Fatal("operation did not retain both target locks") + } + close(release) + select { + case id := <-started: + if id != 2 { + t.Fatalf("unexpected subsequent target: %d", id) + } + case <-time.After(3 * time.Second): + t.Fatal("destination lock was not released") + } + waitTaskQueueStatus(t, q, first, "done") + waitTaskQueueStatus(t, q, second, "done") +} + +func TestTaskHistoryAndMetricsAcrossProcessRestart(t *testing.T) { + const dirEnv, phaseEnv = "CLICD_TASK_HISTORY_TEST_DIR", "CLICD_TASK_HISTORY_TEST_PHASE" + dir, phase := os.Getenv(dirEnv), os.Getenv(phaseEnv) + if dir == "" { + dir = t.TempDir() + cfg := config.ClicdConfig{AdminUser: "test", AdminPassHash: "hash", JWTSecret: "secret", Port: 8999, DataDir: dir, + Containers: []config.Container{{ID: 1, UUID: "original-owner", Name: "guest", Status: "stopped", VCPU: 1, RAMMB: 512, DiskGB: 4}, {ID: 2, UUID: "other-owner", Name: "other", Status: "stopped", VCPU: 1, RAMMB: 512, DiskGB: 4}}} + data, _ := json.Marshal(cfg) + if err := os.WriteFile(filepath.Join(dir, "config.json"), data, 0600); err != nil { + t.Fatal(err) + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + for _, phase := range []string{"write", "read"} { + cmd := exec.Command(executable, "-test.run=^TestTaskHistoryAndMetricsAcrossProcessRestart$", "-test.v") + cmd.Env = append(os.Environ(), dirEnv+"="+dir, phaseEnv+"="+phase) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%s process: %v\n%s", phase, err, output) + } else { + t.Log(string(output)) + } + } + return + } + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) + t.Setenv("PATH", "") + config.SetConfigPath(filepath.Join(dir, "config.json")) + if _, err := config.InitConfig(); err != nil { + t.Fatal(err) + } + var calls int + testOperationHandler(t, "qa-history", func(ctx context.Context, _ int, payload json.RawMessage, progress func(string, string)) error { + calls++ + progress("copying", "copying disk contents") + if strings.Contains(string(payload), "failure") { + return errors.New("deliberate operation failure") + } + return SetOperationTaskResult(ctx, map[string]string{"artifact_id": "backup-example"}) + }) + q := newTaskQueue(4) + ids := map[string]string{} + enqueue := func(payload string) string { + t.Helper() + id, err := q.EnqueueOperationWithAudit(1, "guest", "qa-history", json.RawMessage(payload), "admin", "192.0.2.1", "test-agent") + if err != nil { + t.Fatal(err) + } + return id + } + if phase == "write" { + ids["done"] = enqueue(`{"note":"success"}`) + q.runOperationTask(q.takeNextTask(false)) + ids["failed"] = enqueue(`{"note":"failure"}`) + q.runOperationTask(q.takeNextTask(false)) + ids["builtin"] = q.Enqueue(2, "other", TaskStart, "", nil)[0] + q.takeNextTask(false) + ids["interrupted"] = enqueue(`{"note":"interrupted"}`) + q.takeNextTask(false) + ids["pending"] = enqueue(`{"note":"resume pending"}`) + unsupported := &Task{ID: "task-" + fmt.Sprint(q.allocateTaskID()), Type: "removed-operation", ContainerID: 1, ContainerUUID: "original-owner", ContainerName: "guest", Status: "pending", CreatedAt: time.Now().Format(time.RFC3339Nano), Payload: json.RawMessage(`{}`)} + ids["unsupported"] = unsupported.ID + q.tasks[unsupported.ID] = unsupported + legacy := &Task{ID: "task-" + fmt.Sprint(q.allocateTaskID()), Type: TaskStop, ContainerID: 1, ContainerUUID: "original-owner", ContainerName: "guest", Status: "done", CreatedAt: time.Now().Format(time.RFC3339Nano)} + ids["legacy-terminal"] = legacy.ID + q.tasks[legacy.ID] = legacy + if err := q.persistTaskHistoryOnly(); err != nil { + t.Fatal(err) + } + appendHostMetricPoint(HostInfo{}) + appendContainerMetricPoint(config.AppConfig.Containers[0], map[string]interface{}{"memory_total_bytes": 512, "memory_usage_bytes": 128, "network_rx_bps": 7, "network_tx_bps": 9}) + data, _ := json.Marshal(ids) + if err := os.WriteFile(filepath.Join(dir, "expected.json"), data, 0600); err != nil { + t.Fatal(err) + } + return + } + data, err := os.ReadFile(filepath.Join(dir, "expected.json")) + if err != nil || json.Unmarshal(data, &ids) != nil { + t.Fatal("missing writer expectations") + } + q.restoreTaskState() + for _, state := range []string{"done", "failed"} { + task := q.tasks[ids[state]] + if task == nil || task.Status != state || task.StartedAt == "" || task.FinishedAt == "" || len(task.Logs) < 3 || task.ContainerUUID != "original-owner" { + t.Fatalf("terminal task details did not survive restart: %+v", task) + } + } + if task := q.tasks[ids["done"]]; !strings.Contains(string(task.Result), "backup-example") { + t.Fatalf("operation result lost: %+v", task) + } + if task := q.tasks[ids["interrupted"]]; task.Status != "failed" || task.Stage != "interrupted" || !strings.Contains(task.Error, "restart") { + t.Fatalf("running destructive operation was replayed: %+v", task) + } + if q.tasks[ids["pending"]].Status != "pending" || q.tasks[ids["builtin"]].Status != "pending" { + t.Fatal("pending operation or built-in restart compatibility lost") + } + if task := q.tasks[ids["unsupported"]]; task.Status != "failed" || task.Stage != "interrupted" { + t.Fatalf("unregistered pending operation was replayed: %+v", task) + } + if task := q.tasks[ids["legacy-terminal"]]; task.Status != "done" || task.FinishedAt == "" { + t.Fatal("legacy terminal task lacks a durable retention timestamp") + } + q.runtime.start = func(context.Context, int) error { return nil } + q.runOperationTask(q.takeNextTask(false)) + q.runOperationTask(q.takeNextTask(false)) + if calls != 1 || q.tasks[ids["pending"]].Status != "done" || q.tasks[ids["builtin"]].Status != "done" { + t.Fatal("recovery did not execute precisely the safe pending operations") + } + newID := enqueue(`{}`) + for _, previous := range ids { + if parseIDNum(newID) <= parseIDNum(previous) { + t.Fatal("task ID was reused after restart") + } + } + restoreHostMetricHistory() + restoreContainerMetricHistory() + if len(getHostMetricHistory()) != 1 { + t.Fatal("host metrics did not survive process restart") + } + if history := getContainerMetricHistory(&config.AppConfig.Containers[0]); len(history) != 1 || history[0].NetworkRx != 7 || history[0].NetworkTx != 9 { + t.Fatalf("instance metrics did not survive process restart: %+v", history) + } + previousQueue := globalQueue + globalQueue = q + t.Cleanup(func() { globalQueue = previousQueue }) + // Reusing an ID and name must not grant a new owner the old task history. + config.AppConfig.Containers[0].UUID = "replacement-owner" + request := httptest.NewRequest(http.MethodGet, "/api/v1/tasks", nil) + request = withAuthContext(request, AuthContext{Type: authTypeAPIKey, Scopes: []string{"task:read"}, ContainerUUIDs: []string{"replacement-owner"}}) + response := httptest.NewRecorder() + HandleTasks(response, request) + var scoped struct { + Data []Task `json:"data"` + } + if err := json.Unmarshal(response.Body.Bytes(), &scoped); err != nil || response.Code != 200 || len(scoped.Data) != 0 { + t.Fatalf("old history leaked to a reused instance identity: %d %s", response.Code, response.Body.String()) + } + request = withAuthContext(httptest.NewRequest(http.MethodGet, "/api/v1/tasks", nil), AuthContext{Type: authTypeAdmin}) + response = httptest.NewRecorder() + HandleTasks(response, request) + if err := json.Unmarshal(response.Body.Bytes(), &scoped); err != nil || len(scoped.Data) < 6 || strings.Contains(response.Body.String(), `"payload"`) { + t.Fatalf("administrator history is incomplete or exposed operation payload: %s", response.Body.String()) + } + beforeCalls := calls + q.runOperationTask(q.takeNextTask(false)) + if calls != beforeCalls || q.tasks[newID].Status != "failed" || !strings.Contains(q.tasks[newID].Error, "identity changed") { + t.Fatal("queued operation executed against a reused instance identity") + } + // Completing an old running task at the retention limit must never leave + // its pre-completion "running" record behind to replay on the next boot. + oldID := q.Enqueue(2, "other", TaskStart, "", nil)[0] + oldTask := q.takeNextTask(false) + for i := 0; i < config.TaskHistoryLimit; i++ { + id := fmt.Sprintf("task-%d", 1000+i) + q.tasks[id] = &Task{ID: id, Type: TaskStop, Status: "done", CreatedAt: time.Now().Format(time.RFC3339Nano), FinishedAt: time.Now().Format(time.RFC3339Nano)} + } + q.nextID = 3000 + q.finishTask(oldTask, "done", nil) + records, _, err := config.LoadTaskHistory() + if err != nil { + t.Fatal(err) + } + for _, record := range records { + if record.ID == oldID { + var stored storedTask + if json.Unmarshal(record.Data, &stored) != nil || stored.Task.Status != "done" { + t.Fatal("retention discarded a completion and left a running record") + } + } + } +} diff --git a/backend/internal/api/taskqueue.go b/backend/internal/api/taskqueue.go index 8692aa5..9dcd45c 100644 --- a/backend/internal/api/taskqueue.go +++ b/backend/internal/api/taskqueue.go @@ -26,25 +26,35 @@ const ( ) type Task struct { - ID string `json:"id"` - Type TaskType `json:"type"` - ContainerID int `json:"container_id"` - ContainerName string `json:"container_name"` - Status string `json:"status"` - Error string `json:"error,omitempty"` - Stage string `json:"stage,omitempty"` - StageDetail string `json:"stage_detail,omitempty"` - CreatedAt string `json:"created_at"` - TemplateID string `json:"template_id,omitempty"` - Config lxc.ContainerConfig `json:"config,omitempty"` - Name string `json:"name,omitempty"` - User string `json:"user,omitempty"` // who created this task - IP string `json:"ip,omitempty"` - UserAgent string `json:"user_agent,omitempty"` - activeKey string - ctx context.Context - cancel context.CancelFunc - deleteRequested bool + ID string `json:"id"` + Type TaskType `json:"type"` + ContainerID int `json:"container_id"` + ContainerName string `json:"container_name"` + ContainerUUID string `json:"container_uuid,omitempty"` + Status string `json:"status"` + Error string `json:"error,omitempty"` + Stage string `json:"stage,omitempty"` + StageDetail string `json:"stage_detail,omitempty"` + CreatedAt string `json:"created_at"` + StartedAt string `json:"started_at,omitempty"` + FinishedAt string `json:"finished_at,omitempty"` + DurationMS int64 `json:"duration_ms,omitempty"` + Logs []TaskEvent `json:"logs,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Payload json.RawMessage `json:"-"` + AdditionalTargets []string `json:"-"` + TemplateID string `json:"template_id,omitempty"` + Config lxc.ContainerConfig `json:"config,omitempty"` + Name string `json:"name,omitempty"` + User string `json:"user,omitempty"` // who created this task + IP string `json:"ip,omitempty"` + UserAgent string `json:"user_agent,omitempty"` + activeKey string + activeKeys []string + revision uint64 + ctx context.Context + cancel context.CancelFunc + deleteRequested bool } type taskRuntime struct { @@ -67,6 +77,7 @@ type TaskQueue struct { runningTasks map[*Task]bool stop chan struct{} runtime taskRuntime + historySaved map[string]uint64 } type TaskQueueSettings struct { @@ -86,6 +97,7 @@ func init() { func newTaskQueue(concurrency int) *TaskQueue { q := &TaskQueue{ tasks: make(map[string]*Task), + historySaved: make(map[string]uint64), maxConcurrency: config.NormalizeTaskConcurrency(concurrency), activeTargets: make(map[string]bool), runningTasks: make(map[*Task]bool), @@ -131,10 +143,20 @@ func (q *TaskQueue) signalDispatchers() { func (q *TaskQueue) enqueueTask(task *Task) { if task.ContainerID > 0 && config.AppConfig != nil { if c := config.FindContainer(task.ContainerID); c != nil { + if task.ContainerUUID != "" && task.ContainerUUID != c.UUID { + task.Status = "failed" + task.Error = "operation target identity changed" + task.FinishedAt = time.Now().Format(time.RFC3339Nano) + addTaskEvent(task, "failed", task.Error) + q.tasks[task.ID] = task + return + } task.ContainerName = c.Name + task.ContainerUUID = c.UUID } } q.tasks[task.ID] = task + addTaskEvent(task, task.Stage, task.StageDetail) if task.Type == TaskDelete { q.cancelTasksForDelete(task) } else { @@ -182,6 +204,8 @@ func cancelPendingTaskForDelete(task *Task) { task.Error = "cancelled because container deletion was requested" task.Stage = "failed" task.StageDetail = "已取消,等待删除" + task.FinishedAt = time.Now().Format(time.RFC3339Nano) + addTaskEvent(task, task.Stage, task.Error) if task.Type == TaskCreate { name := task.Config.Name if name == "" { @@ -223,8 +247,7 @@ func (q *TaskQueue) EnqueueWithAudit(containerID int, containerName string, task q.mu.Lock() defer q.mu.Unlock() - id := q.nextID - q.nextID++ + id := q.allocateTaskID() task := &Task{ ID: fmt.Sprintf("task-%d", id), Type: taskType, @@ -307,8 +330,7 @@ func (q *TaskQueue) enqueueBatchCreateList(configs []lxc.ContainerConfig, user s for _, cfg := range configs { cfgCopy := cfg cfgCopy.NormalizeResourceAliases() - id := q.nextID - q.nextID++ + id := q.allocateTaskID() task := &Task{ ID: fmt.Sprintf("task-%d", id), Type: TaskCreate, @@ -339,8 +361,7 @@ func (q *TaskQueue) enqueueSingleWithUser(containerID int, containerName string, } func (q *TaskQueue) enqueueSingleWithAudit(containerID int, containerName string, taskType TaskType, templateID string, user string, ip string, userAgent string) string { - id := q.nextID - q.nextID++ + id := q.allocateTaskID() task := &Task{ ID: fmt.Sprintf("task-%d", id), Type: taskType, @@ -421,10 +442,15 @@ func (q *TaskQueue) takeNextTask(create bool) *Task { task.Error = "" task.Stage = "preparing" task.StageDetail = "准备初始化环境" + task.StartedAt = time.Now().Format(time.RFC3339Nano) + addTaskEvent(task, task.Stage, task.StageDetail) task.activeKey = taskConcurrencyKey(task) + task.activeKeys = taskConcurrencyKeys(task) task.ctx, task.cancel = context.WithCancel(context.Background()) q.runningTasks[task] = true - q.activeTargets[task.activeKey] = true + for _, key := range task.activeKeys { + q.activeTargets[key] = true + } q.activeTasks++ q.persistTasks() return task @@ -436,7 +462,7 @@ func (q *TaskQueue) takeNextTask(create bool) *Task { func runnableDeleteTaskIndex(queue []*Task, activeTargets map[string]bool) int { for index, task := range queue { - if task.Type == TaskDelete && !activeTargets[taskConcurrencyKey(task)] { + if task.Type == TaskDelete && !taskTargetsActive(task, activeTargets) { return index } } @@ -445,7 +471,7 @@ func runnableDeleteTaskIndex(queue []*Task, activeTargets map[string]bool) int { func runnableTaskIndex(queue []*Task, activeTargets map[string]bool) int { for index, task := range queue { - if !activeTargets[taskConcurrencyKey(task)] { + if !taskTargetsActive(task, activeTargets) { return index } } @@ -478,8 +504,15 @@ func (q *TaskQueue) finishTask(task *Task, status string, taskErr error) { task.cancel = nil } task.Status = status + task.FinishedAt = time.Now().Format(time.RFC3339Nano) + if started := taskTime(task.StartedAt); !started.IsZero() { + task.DurationMS = max(0, time.Since(started).Milliseconds()) + } if taskErr != nil { task.Error = taskErr.Error() + if len(task.Error) > 8192 { + task.Error = task.Error[:8192] + } if task.Type == TaskCreate { task.Stage = "failed" task.StageDetail = "初始化失败" @@ -491,6 +524,20 @@ func (q *TaskQueue) finishTask(task *Task, status string, taskErr error) { task.StageDetail = "初始化完成" } } + if status == "failed" { + task.Stage = "failed" + if taskErr != nil { + task.StageDetail = taskErr.Error() + } + } else { + task.Stage = "completed" + task.StageDetail = "操作完成" + } + addTaskEvent(task, task.Stage, task.StageDetail) + for _, key := range task.activeKeys { + delete(q.activeTargets, key) + } + task.activeKeys = nil if task.activeKey != "" { delete(q.activeTargets, task.activeKey) task.activeKey = "" @@ -506,8 +553,8 @@ func (q *TaskQueue) finishTask(task *Task, status string, taskErr error) { func (q *TaskQueue) updateTaskStage(task *Task, stage, detail string) { q.mu.Lock() - task.Stage = stage - task.StageDetail = detail + addTaskEvent(task, stage, detail) + q.persistTaskHistoryOnly() q.mu.Unlock() } @@ -561,10 +608,11 @@ func (q *TaskQueue) runCreateTask(task *Task) { // FindContainer returns a slice-backed pointer. Another container's removal // can shift that slice while startup waits, so never retain it for cleanup. - containerID, containerName := c.ID, c.Name + containerID, containerName, containerUUID := c.ID, c.Name, c.UUID q.mu.Lock() task.ContainerID = containerID task.ContainerName = containerName + task.ContainerUUID = containerUUID q.mu.Unlock() startDetail := "启动容器并等待网络就绪" if strings.EqualFold(cfg.Virtualization, config.VirtualizationKVM) { @@ -588,7 +636,10 @@ func (q *TaskQueue) runCreateTask(task *Task) { func (q *TaskQueue) runOperationTask(task *Task) { q.mu.Lock() - err := resolveTaskContainer(task) + var err error + if builtInTask(task.Type) || task.ContainerID > 0 { + err = resolveTaskContainer(task) + } ctx := task.ctx if ctx == nil { ctx = context.Background() @@ -626,6 +677,19 @@ func (q *TaskQueue) runOperationTask(task *Task) { } else { err = reinstallByRuntime(task.ContainerID, task.TemplateID) } + default: + if handler := operationHandler(task.Type); handler != nil { + ctx = context.WithValue(ctx, operationResultKey{}, func(result json.RawMessage) error { + q.mu.Lock() + defer q.mu.Unlock() + task.Result = append(json.RawMessage(nil), result...) + task.revision++ + return q.persistTaskHistoryOnly() + }) + err = handler(ctx, task.ContainerID, task.Payload, func(stage, detail string) { q.updateTaskStage(task, stage, detail) }) + } else { + err = fmt.Errorf("operation handler unavailable: %s", task.Type) + } } } @@ -656,12 +720,18 @@ func resolveTaskContainer(task *Task) error { } if task.ContainerID > 0 { if c := config.FindContainer(task.ContainerID); c != nil { + if task.ContainerUUID != "" && c.UUID != task.ContainerUUID { + return fmt.Errorf("container identity changed: %d", task.ContainerID) + } if task.ContainerName == "" { task.ContainerName = c.Name } return nil } } + if task.ContainerUUID != "" { + return fmt.Errorf("container no longer exists: %s", task.ContainerUUID) + } if task.ContainerName != "" { if c := config.FindContainerByName(task.ContainerName); c != nil { task.ContainerID = c.ID @@ -673,31 +743,8 @@ func resolveTaskContainer(task *Task) error { return fmt.Errorf("container not found: %d", task.ContainerID) } -func (q *TaskQueue) persistTasks() { - saved := make([]config.SavedTask, 0) - for _, t := range q.tasks { - // Only persist pending and running tasks to avoid - // re-queuing already completed/failed tasks after restart. - if t.Status != "pending" && t.Status != "running" { - continue - } - cfgJSON, _ := json.Marshal(t.Config) - saved = append(saved, config.SavedTask{ - ID: t.ID, - Type: string(t.Type), - ContainerID: t.ContainerID, - ContainerName: t.ContainerName, - Status: t.Status, - Error: t.Error, - CreatedAt: t.CreatedAt, - TemplateID: t.TemplateID, - Config: string(cfgJSON), - User: t.User, - IP: t.IP, - UserAgent: t.UserAgent, - }) - } - config.SaveTasks(saved) +func (q *TaskQueue) persistTasks() error { + return q.persistTaskState() } func (q *TaskQueue) GetTasks() []*Task { @@ -707,6 +754,11 @@ func (q *TaskQueue) GetTasks() []*Task { // Collect all task IDs, sort by creation time (extracted from ID number) for _, t := range q.tasks { copyTask := *t + copyTask.Logs = append([]TaskEvent(nil), t.Logs...) + copyTask.Result = append(json.RawMessage(nil), t.Result...) + if t.Status == "running" && !taskTime(t.StartedAt).IsZero() { + copyTask.DurationMS = max(0, time.Since(taskTime(t.StartedAt)).Milliseconds()) + } result = append(result, ©Task) } // Stable sort by ID number (task-N where N is sequential) @@ -1070,12 +1122,23 @@ func HandleTaskDelete(w http.ResponseWriter, r *http.Request) { } globalQueue.mu.Lock() task := globalQueue.tasks[taskID] - if task != nil && !isTaskAllowedForRequest(r, task) { + if task != nil && !isHistoricalTaskAllowed(r, task) { globalQueue.mu.Unlock() jsonResponse(w, http.StatusForbidden, APIResponse{Success: false, Message: "Access denied to this task"}) return } + if task != nil && task.Status == "running" { + globalQueue.mu.Unlock() + jsonResponse(w, http.StatusConflict, APIResponse{Success: false, Message: "A running task cannot be removed"}) + return + } + if err := config.DeleteTaskHistory(taskID); err != nil && err != config.ErrHistoryStoreUnavailable { + globalQueue.mu.Unlock() + jsonResponse(w, http.StatusInternalServerError, APIResponse{Success: false, Message: "Failed to remove task history"}) + return + } delete(globalQueue.tasks, taskID) + delete(globalQueue.historySaved, taskID) // Also remove from both queues if pending newCreate := make([]*Task, 0, len(globalQueue.createQueue)) for _, t := range globalQueue.createQueue { @@ -1109,64 +1172,19 @@ func HandleTasks(w http.ResponseWriter, r *http.Request) { return } tasks := globalQueue.GetTasks() - tasks = filterTasksForRequest(r, tasks) + filtered := make([]*Task, 0, len(tasks)) + for _, task := range tasks { + if isHistoricalTaskAllowed(r, task) { + filtered = append(filtered, task) + } + } + tasks = filtered jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: tasks}) } // RestoreTasks restores task queue from config func RestoreTasks() { - globalQueue.mu.Lock() - defer globalQueue.mu.Unlock() - for _, st := range config.AppConfig.Tasks { - // Retired alert automation must not replay shutdowns saved by older versions. - if st.Type == string(TaskStop) && st.User == "system:security" { - continue - } - var cfg lxc.ContainerConfig - if st.Config != "" { - json.Unmarshal([]byte(st.Config), &cfg) - } - containerName := st.ContainerName - if containerName == "" { - containerName = cfg.Name - } - if cfg.Name == "" { - cfg.Name = containerName - } - cfg.NormalizeResourceAliases() - containerID := st.ContainerID - if containerID <= 0 && containerName != "" { - if c := config.FindContainerByName(containerName); c != nil { - containerID = c.ID - } - } - globalQueue.tasks[st.ID] = &Task{ - ID: st.ID, - Type: TaskType(st.Type), - ContainerID: containerID, - ContainerName: containerName, - Status: st.Status, - Error: st.Error, - Stage: "queued", - StageDetail: "排队等待", - CreatedAt: st.CreatedAt, - TemplateID: st.TemplateID, - Config: cfg, - User: st.User, - IP: st.IP, - UserAgent: st.UserAgent, - } - if st.Status == "pending" || st.Status == "running" { - // Reset running tasks back to pending so they get retried - globalQueue.tasks[st.ID].Status = "pending" - globalQueue.enqueueTask(globalQueue.tasks[st.ID]) - } - if num := parseIDNum(st.ID); num >= globalQueue.nextID { - globalQueue.nextID = num + 1 - } - } - // Clear persisted tasks from disk (they're now in memory) - config.SaveTasks([]config.SavedTask{}) + globalQueue.restoreTaskState() } func parseIDNum(id string) int { diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index bc18d9f..d8dbafa 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -112,7 +112,9 @@ type Container struct { LXCName string `json:"lxc_name,omitempty"` KVMName string `json:"kvm_name,omitempty"` DiskImage string `json:"disk_image,omitempty"` + DataDisks []DataDisk `json:"data_disks"` ManualInstall bool `json:"manual_install,omitempty"` + Standalone bool `json:"standalone,omitempty"` InstallationMediaImageID string `json:"installation_media_image_id,omitempty"` InstallationMediaBoot string `json:"installation_media_boot,omitempty"` StoragePoolID string `json:"storage_pool_id,omitempty"` @@ -2012,8 +2014,9 @@ func AddAuditLogFull(action, target, detail, user, ip, userAgent string, success // SaveTasks persists the task queue to config func SaveTasks(tasks []SavedTask) { - AppConfig.Tasks = tasks - SaveConfig() + if err := saveTaskQueueCompatibility(tasks); err != nil && err != ErrHistoryStoreUnavailable { + fmt.Printf("Task queue persistence failed: %v\n", err) + } } // AddLoginLog persists a login log entry diff --git a/backend/internal/config/disks.go b/backend/internal/config/disks.go new file mode 100644 index 0000000..f64c868 --- /dev/null +++ b/backend/internal/config/disks.go @@ -0,0 +1,124 @@ +package config + +import ( + "fmt" + "math" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "unicode" +) + +const MaxDataDisks = 8 + +type DataDisk struct { + ID string `json:"id"` + Name string `json:"name"` + SizeGB float64 `json:"size_gb"` + StoragePoolID string `json:"storage_pool_id"` + Path string `json:"path,omitempty"` + Format string `json:"format"` + Target string `json:"target"` + Bus string `json:"bus,omitempty"` + MountPath string `json:"mount_path,omitempty"` + Attached bool `json:"attached"` + CreatedAt string `json:"created_at"` +} + +var diskComponent = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$`) + +func NewDataDiskID() string { return "disk-" + generateUUIDString() } + +func DiskSizeBytes(sizeGB float64) (int64, error) { + if math.IsNaN(sizeGB) || math.IsInf(sizeGB, 0) || sizeGB < 0.125 || sizeGB > 16384 { + return 0, fmt.Errorf("disk size must be between 0.125 and 16384 GB") + } + return int64(math.Ceil(sizeGB*1024)) * 1024 * 1024, nil +} + +// DataDiskPath derives ownership from pool, workload UUID and disk ID. Persisted +// paths must match exactly; no API accepts a host path. +func DataDiskPath(c *Container, d DataDisk) (string, error) { + if c == nil || !diskComponent.MatchString(c.UUID) || !diskComponent.MatchString(d.ID) { + return "", fmt.Errorf("invalid workload or disk identity") + } + pool := StoragePoolByID(d.StoragePoolID) + if pool == nil || pool.Path == "" { + return "", fmt.Errorf("data disk storage pool is unavailable") + } + extension := "disk.img" + if c.IsKVM() { + extension = "disk.qcow2" + } + expected := filepath.Join(pool.Path, "data-disks", c.Runtime(), c.UUID, d.ID, extension) + if d.Path != "" && filepath.Clean(d.Path) != filepath.Clean(expected) { + return "", fmt.Errorf("data disk path is outside its managed owner directory") + } + // A guest must never be able to replace a managed host component by a symlink. + relative, _ := filepath.Rel(pool.Path, expected) + cursor := filepath.Clean(pool.Path) + for _, part := range strings.Split(relative, string(os.PathSeparator)) { + cursor = filepath.Join(cursor, part) + info, err := os.Lstat(cursor) + if os.IsNotExist(err) { + continue + } + if err != nil { + return "", err + } + if info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("managed disk paths cannot contain symlinks") + } + if cursor == expected && !info.Mode().IsRegular() { + return "", fmt.Errorf("managed disk must be a regular file") + } + } + return expected, nil +} + +func ValidateGuestMountPath(value string) error { + if value == "" || value != path.Clean(value) || !strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || strings.IndexFunc(value, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 { + return fmt.Errorf("mount_path must be a clean absolute guest path without spaces") + } + allowed := false + for _, base := range []string{"/data", "/mnt", "/srv"} { + if value == base || strings.HasPrefix(value, base+"/") { + allowed = true + } + } + if !allowed { + return fmt.Errorf("managed data disks must mount below /data, /mnt or /srv") + } + return nil +} + +// DiskInfo is the public inventory. Host paths deliberately stay out of this API. +type DiskInfo struct { + ID string `json:"id"` + Name string `json:"name"` + SizeGB float64 `json:"size_gb"` + AllocatedBytes int64 `json:"allocated_bytes"` + Format string `json:"format"` + Target string `json:"target"` + Bus string `json:"bus,omitempty"` + MountPath string `json:"mount_path,omitempty"` + StoragePoolID string `json:"storage_pool_id"` + Attached bool `json:"attached"` + CanResize bool `json:"can_resize"` + Error string `json:"error,omitempty"` +} +type DiskInventory struct { + System DiskInfo `json:"system"` + DataDisks []DiskInfo `json:"data_disks"` + CanEdit bool `json:"can_edit"` + Reason string `json:"reason,omitempty"` + Limits struct { + MaxDataDisks int `json:"max_data_disks"` + } `json:"limits"` +} + +func PublicDataDisk(d DataDisk) DiskInfo { + return DiskInfo{ID: d.ID, Name: d.Name, SizeGB: d.SizeGB, Format: d.Format, Target: d.Target, Bus: d.Bus, MountPath: d.MountPath, StoragePoolID: d.StoragePoolID, Attached: d.Attached, CanResize: true} +} diff --git a/backend/internal/config/disks_test.go b/backend/internal/config/disks_test.go new file mode 100644 index 0000000..5ebb8c8 --- /dev/null +++ b/backend/internal/config/disks_test.go @@ -0,0 +1,57 @@ +package config + +import ( + "math" + "os" + "path/filepath" + "testing" +) + +func TestManagedDiskOwnershipAndSizeValidation(t *testing.T) { + old := AppConfig + t.Cleanup(func() { AppConfig = old }) + pool := t.TempDir() + AppConfig = &ClicdConfig{StoragePools: []StoragePool{{ID: "p", Path: pool, Enabled: true}}} + c := &Container{UUID: "owner-one", Virtualization: VirtualizationKVM} + d := DataDisk{ID: "disk-one", StoragePoolID: "p"} + path, err := DataDiskPath(c, d) + if err != nil { + t.Fatal(err) + } + d.Path = path + if _, err = DataDiskPath(&Container{UUID: "owner-two", Virtualization: VirtualizationKVM}, d); err == nil { + t.Fatal("accepted another workload's disk") + } + d.ID = "../outside" + if _, err = DataDiskPath(c, d); err == nil { + t.Fatal("accepted traversal") + } + for _, size := range []float64{0, -1, math.NaN(), math.Inf(1), 16385} { + if _, err := DiskSizeBytes(size); err == nil { + t.Fatalf("accepted size %v", size) + } + } + if got, err := DiskSizeBytes(.125); err != nil || got != 128*1024*1024 { + t.Fatalf("size=%d err=%v", got, err) + } + target := filepath.Join(pool, "data-disks") + if err := os.Symlink(t.TempDir(), target); err == nil { + d.ID = "disk-one" + d.Path = "" + if _, err := DataDiskPath(c, d); err == nil { + t.Fatal("accepted symlink-owned disk") + } + } +} +func TestGuestMountPathValidation(t *testing.T) { + for _, path := range []string{"/", "/etc/config", "/proc/x", "/mnt/../etc", "/mnt//a", "relative", "/data/a b", "/srv/a\nvalue", "/mnt/a\\b"} { + if ValidateGuestMountPath(path) == nil { + t.Fatalf("accepted unsafe mount %q", path) + } + } + for _, path := range []string{"/data", "/mnt/database", "/srv/app/data"} { + if err := ValidateGuestMountPath(path); err != nil { + t.Fatal(err) + } + } +} diff --git a/backend/internal/config/history_store.go b/backend/internal/config/history_store.go new file mode 100644 index 0000000..89c862d --- /dev/null +++ b/backend/internal/config/history_store.go @@ -0,0 +1,235 @@ +package config + +import ( + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" +) + +const ( + TaskHistoryRetention = 30 * 24 * time.Hour + TaskHistoryLimit = 1000 + MetricHistoryRetention = 7 * 24 * time.Hour + metricBucketMillis = int64(30_000) +) + +var ErrHistoryStoreUnavailable = errors.New("sqlite history store is not initialized") + +// Queue transitions only rewrite their legacy compatibility tables. In +// particular they must not replace unrelated instance or image metadata. +func saveTaskQueueCompatibility(tasks []SavedTask) error { + dbMu.Lock() + defer dbMu.Unlock() + if AppConfig == nil { + return ErrHistoryStoreUnavailable + } + AppConfig.Tasks = tasks + if db == nil { + return ErrHistoryStoreUnavailable + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + for _, table := range []string{"task_extra_ports", "task_nat_port_mappings", "tasks"} { + if _, err := tx.Exec("DELETE FROM " + table); err != nil { + return err + } + } + if err := saveTasksDB(tx); err != nil { + return err + } + return tx.Commit() +} + +// History tables are deliberately independent of SaveConfig's replace-all tables. +func ensureHistorySchema() error { + for _, stmt := range []string{ + `CREATE TABLE IF NOT EXISTS history_state (key TEXT PRIMARY KEY, value INTEGER NOT NULL)`, + `CREATE TABLE IF NOT EXISTS task_history (id TEXT PRIMARY KEY, sequence INTEGER NOT NULL, updated_at INTEGER NOT NULL, finished_at INTEGER NOT NULL DEFAULT 0, data TEXT NOT NULL)`, + `CREATE INDEX IF NOT EXISTS task_history_finished ON task_history(finished_at, sequence)`, + `CREATE TABLE IF NOT EXISTS metric_history (kind TEXT NOT NULL, series TEXT NOT NULL, sampled_at INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY(kind, series, sampled_at))`, + `CREATE INDEX IF NOT EXISTS metric_history_time ON metric_history(sampled_at)`, + } { + if _, err := db.Exec(stmt); err != nil { + return fmt.Errorf("initialize history schema: %w", err) + } + } + return nil +} + +type TaskHistoryRecord struct { + ID string + Sequence int + FinishedAt int64 + Data json.RawMessage +} + +// ReserveTaskID never lowers its high-water mark, including after history purge. +func ReserveTaskID(minimum int) (int, error) { + dbMu.Lock() + defer dbMu.Unlock() + if db == nil { + return 0, ErrHistoryStoreUnavailable + } + tx, err := db.Begin() + if err != nil { + return 0, err + } + defer tx.Rollback() + var next int + if err := tx.QueryRow(`SELECT value FROM history_state WHERE key = 'next_task_id'`).Scan(&next); err != nil && err != sql.ErrNoRows { + return 0, err + } + if next < minimum { + next = minimum + } + if _, err := tx.Exec(`INSERT INTO history_state(key,value) VALUES ('next_task_id',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, next+1); err != nil { + return 0, err + } + return next, tx.Commit() +} + +func SaveTaskHistory(records []TaskHistoryRecord, nextID int) error { + dbMu.Lock() + defer dbMu.Unlock() + if db == nil { + return ErrHistoryStoreUnavailable + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + for _, record := range records { + if !json.Valid(record.Data) { + return fmt.Errorf("invalid task history JSON for %s", record.ID) + } + if _, err := tx.Exec(`INSERT INTO task_history(id,sequence,updated_at,finished_at,data) VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET sequence=excluded.sequence,updated_at=excluded.updated_at,finished_at=excluded.finished_at,data=excluded.data`, record.ID, record.Sequence, time.Now().UnixMilli(), record.FinishedAt, string(record.Data)); err != nil { + return err + } + } + if _, err := tx.Exec(`INSERT INTO history_state(key,value) VALUES ('next_task_id',?) ON CONFLICT(key) DO UPDATE SET value=MAX(value,excluded.value)`, nextID); err != nil { + return err + } + if err := purgeTaskHistory(tx, time.Now()); err != nil { + return err + } + return tx.Commit() +} + +func purgeTaskHistory(tx *sql.Tx, now time.Time) error { + if _, err := tx.Exec(`DELETE FROM task_history WHERE finished_at > 0 AND finished_at < ?`, now.Add(-TaskHistoryRetention).UnixMilli()); err != nil { + return err + } + _, err := tx.Exec(`DELETE FROM task_history WHERE finished_at > 0 AND id NOT IN (SELECT id FROM task_history WHERE finished_at > 0 ORDER BY sequence DESC LIMIT ?)`, TaskHistoryLimit) + return err +} + +func LoadTaskHistory() ([]TaskHistoryRecord, int, error) { + dbMu.Lock() + defer dbMu.Unlock() + if db == nil { + return nil, 0, ErrHistoryStoreUnavailable + } + rows, err := db.Query(`SELECT id,sequence,finished_at,data FROM task_history ORDER BY sequence`) + if err != nil { + return nil, 0, err + } + var records []TaskHistoryRecord + for rows.Next() { + var record TaskHistoryRecord + var data string + if err := rows.Scan(&record.ID, &record.Sequence, &record.FinishedAt, &data); err != nil { + rows.Close() + return nil, 0, err + } + record.Data = json.RawMessage(data) + records = append(records, record) + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, 0, err + } + rows.Close() + var next int + if err := db.QueryRow(`SELECT value FROM history_state WHERE key = 'next_task_id'`).Scan(&next); err != nil && err != sql.ErrNoRows { + return nil, 0, err + } + return records, next, nil +} + +func DeleteTaskHistory(id string) error { + dbMu.Lock() + defer dbMu.Unlock() + if db == nil { + return ErrHistoryStoreUnavailable + } + _, err := db.Exec(`DELETE FROM task_history WHERE id = ?`, id) + return err +} + +type MetricHistoryRecord struct { + Series string + Data json.RawMessage +} + +// A 30s bucket bounds each series to approximately 20,161 records per week, +// including repeated service starts and duplicate samples within one interval. +func SaveMetricHistory(kind, series string, sampledAt int64, data json.RawMessage) error { + if kind != "host" && kind != "container" || series == "" || !json.Valid(data) { + return fmt.Errorf("invalid metric history record") + } + dbMu.Lock() + defer dbMu.Unlock() + if db == nil { + return ErrHistoryStoreUnavailable + } + bucket := sampledAt / metricBucketMillis * metricBucketMillis + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.Exec(`INSERT INTO metric_history(kind,series,sampled_at,data) VALUES (?,?,?,?) ON CONFLICT(kind,series,sampled_at) DO UPDATE SET data=excluded.data`, kind, series, bucket, string(data)); err != nil { + return err + } + // The indexed time delete is small: expired rows are removed on each sample. + if _, err := tx.Exec(`DELETE FROM metric_history WHERE sampled_at < ?`, time.Now().Add(-MetricHistoryRetention).UnixMilli()-metricBucketMillis); err != nil { + return err + } + return tx.Commit() +} + +func LoadMetricHistory(kind, series string) ([]MetricHistoryRecord, error) { + dbMu.Lock() + defer dbMu.Unlock() + if db == nil { + return nil, ErrHistoryStoreUnavailable + } + query := `SELECT series,data FROM metric_history WHERE kind=? AND sampled_at>=?` + args := []interface{}{kind, time.Now().Add(-MetricHistoryRetention).UnixMilli() - metricBucketMillis} + if series != "" { + query += ` AND series=?` + args = append(args, series) + } + rows, err := db.Query(query+` ORDER BY sampled_at`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var records []MetricHistoryRecord + for rows.Next() { + var record MetricHistoryRecord + var data string + if err := rows.Scan(&record.Series, &data); err != nil { + return nil, err + } + record.Data = json.RawMessage(data) + records = append(records, record) + } + return records, rows.Err() +} diff --git a/backend/internal/config/history_store_test.go b/backend/internal/config/history_store_test.go new file mode 100644 index 0000000..4158c8b --- /dev/null +++ b/backend/internal/config/history_store_test.go @@ -0,0 +1,182 @@ +package config + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "sync" + "testing" + "time" +) + +func setupHistoryStore(t *testing.T) string { + t.Helper() + resetConfigStoreForTest(t) + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) + t.Cleanup(func() { resetConfigStoreForTest(t) }) + path := filepath.Join(dir, "config.json") + data, err := json.Marshal(ClicdConfig{AdminUser: "test", AdminPassHash: "hash", JWTSecret: "secret", Port: 8999, DataDir: dir}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + SetConfigPath(path) + if _, err := InitConfig(); err != nil { + t.Fatal(err) + } + return path +} + +func TestHistoryTablesSurviveConfigSaveAndReopen(t *testing.T) { + path := setupHistoryStore(t) + id, err := ReserveTaskID(71) + if err != nil || id != 71 { + t.Fatalf("reserve = %d %v", id, err) + } + task := TaskHistoryRecord{ID: "task-71", Sequence: 71, FinishedAt: time.Now().UnixMilli(), Data: json.RawMessage(`{"status":"done","logs":[{"stage":"completed"}]}`)} + if err := SaveTaskHistory([]TaskHistoryRecord{task}, 72); err != nil { + t.Fatal(err) + } + metric := json.RawMessage(`{"ts":123,"cpu":12.5}`) + if err := SaveMetricHistory("host", "host", time.Now().UnixMilli(), metric); err != nil { + t.Fatal(err) + } + if err := SaveConfig(); err != nil { + t.Fatal(err) + } + resetConfigStoreForTest(t) + SetConfigPath(path) + if _, err := InitConfig(); err != nil { + t.Fatal(err) + } + records, next, err := LoadTaskHistory() + if err != nil || len(records) != 1 || next != 72 || string(records[0].Data) != string(task.Data) { + t.Fatalf("reopened task history = %+v next=%d err=%v", records, next, err) + } + metrics, err := LoadMetricHistory("host", "host") + if err != nil || len(metrics) != 1 || string(metrics[0].Data) != string(metric) { + t.Fatalf("reopened metrics = %+v %v", metrics, err) + } + if err := DeleteTaskHistory(task.ID); err != nil { + t.Fatal(err) + } + if id, err := ReserveTaskID(0); err != nil || id != 72 { + t.Fatalf("deleted history reused its ID: %d %v", id, err) + } +} + +func TestHistoryRetentionAndMetricBucketsAreBounded(t *testing.T) { + setupHistoryStore(t) + now := time.Now() + records := []TaskHistoryRecord{{ID: "task-old", Sequence: 1, FinishedAt: now.Add(-TaskHistoryRetention - time.Hour).UnixMilli(), Data: json.RawMessage(`{}`)}, {ID: "task-active", Sequence: 2, Data: json.RawMessage(`{}`)}} + for i := 0; i < TaskHistoryLimit+3; i++ { + records = append(records, TaskHistoryRecord{ID: fmt.Sprintf("task-%d", i+3), Sequence: i + 3, FinishedAt: now.UnixMilli(), Data: json.RawMessage(`{}`)}) + } + if err := SaveTaskHistory(records, 5000); err != nil { + t.Fatal(err) + } + got, next, err := LoadTaskHistory() + if err != nil || len(got) != TaskHistoryLimit+1 || next != 5000 { + t.Fatalf("bounded history = %d next=%d err=%v", len(got), next, err) + } + for _, record := range got { + if record.ID == "task-old" || record.ID == "task-3" || record.ID == "task-4" || record.ID == "task-5" { + t.Fatalf("expired/excess task retained: %s", record.ID) + } + } + if id, err := ReserveTaskID(0); err != nil || id != 5000 { + t.Fatalf("purge reset task sequence: %d %v", id, err) + } + for _, timestamp := range []int64{now.Add(-8 * 24 * time.Hour).UnixMilli(), now.UnixMilli() / metricBucketMillis * metricBucketMillis, now.UnixMilli()/metricBucketMillis*metricBucketMillis + 1} { + if err := SaveMetricHistory("container", "uuid:guest", timestamp, json.RawMessage(fmt.Sprintf(`{"ts":%d}`, timestamp))); err != nil { + t.Fatal(err) + } + } + metrics, err := LoadMetricHistory("container", "uuid:guest") + if err != nil || len(metrics) != 1 { + t.Fatalf("expired or duplicate metric retained: %+v %v", metrics, err) + } + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM metric_history").Scan(&count); err != nil || count != 1 { + t.Fatalf("expired metric not physically purged: %d %v", count, err) + } +} + +func TestHistoryWriteRollbackAndConfigWritesDoNotInterfere(t *testing.T) { + setupHistoryStore(t) + if err := SaveTaskHistory([]TaskHistoryRecord{{ID: "good", Sequence: 1, Data: json.RawMessage(`{}`)}, {ID: "bad", Sequence: 2, Data: json.RawMessage(`{`)}}, 10); err == nil { + t.Fatal("invalid JSON was accepted") + } + if records, next, err := LoadTaskHistory(); err != nil || len(records) != 0 || next != 0 { + t.Fatalf("partially committed history: %+v %d %v", records, next, err) + } + var wg sync.WaitGroup + errors := make(chan error, 30) + for i := 0; i < 10; i++ { + wg.Add(3) + go func() { defer wg.Done(); errors <- SaveConfig() }() + go func(i int) { + defer wg.Done() + errors <- SaveTaskHistory([]TaskHistoryRecord{{ID: fmt.Sprint(i), Sequence: i, Data: json.RawMessage(`{}`)}}, 20) + }(i) + go func(i int) { + defer wg.Done() + errors <- SaveMetricHistory("container", fmt.Sprint(i), time.Now().UnixMilli(), json.RawMessage(`{}`)) + }(i) + } + wg.Wait() + close(errors) + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + if records, _, err := LoadTaskHistory(); err != nil || len(records) != 10 { + t.Fatalf("config replacement lost task history: %d %v", len(records), err) + } + if records, err := LoadMetricHistory("container", ""); err != nil || len(records) != 10 { + t.Fatalf("config replacement lost metric history: %d %v", len(records), err) + } +} + +func TestDataDiskAndStandaloneMigrationRoundTrip(t *testing.T) { + path := setupHistoryStore(t) + AppConfig.Containers = []Container{{ID: 1, UUID: "legacy", Name: "guest", Status: "stopped", VCPU: 1, RAMMB: 512, DiskGB: 4}} + if err := SaveConfig(); err != nil { + t.Fatal(err) + } + for _, column := range []string{"data_disks", "standalone"} { + if _, err := db.Exec("ALTER TABLE containers DROP COLUMN " + column); err != nil { + t.Fatal(err) + } + } + resetConfigStoreForTest(t) + SetConfigPath(path) + if _, err := InitConfig(); err != nil { + t.Fatal(err) + } + c := &AppConfig.Containers[0] + if c.Standalone || len(c.DataDisks) != 0 || c.Status != "stopped" || c.UUID != "legacy" { + t.Fatalf("migration changed legacy instance behavior: %+v", c) + } + c.Standalone = true + c.DataDisks = []DataDisk{{ID: "disk-example", Name: "data", SizeGB: 12.5, StoragePoolID: "pool", Path: "/pool/disks/data.qcow2", Format: "qcow2", Target: "vdb", Bus: "virtio", MountPath: "/data", Attached: true, CreatedAt: "2026-11-03T10:00:00Z"}} + want := append([]DataDisk(nil), c.DataDisks...) + if err := SaveConfig(); err != nil { + t.Fatal(err) + } + resetConfigStoreForTest(t) + SetConfigPath(path) + if _, err := InitConfig(); err != nil { + t.Fatal(err) + } + if c := AppConfig.Containers[0]; !c.Standalone || !reflect.DeepEqual(c.DataDisks, want) { + t.Fatalf("disk metadata did not survive restart: %+v", c) + } +} diff --git a/backend/internal/config/image_upload.go b/backend/internal/config/image_upload.go new file mode 100644 index 0000000..dc4c0ff --- /dev/null +++ b/backend/internal/config/image_upload.go @@ -0,0 +1,27 @@ +package config + +import "fmt" + +// AddUploadedKVMImage publishes image metadata and its enabled flag together. +func AddUploadedKVMImage(image CustomKVMImage) error { + allocationMu.Lock() + defer allocationMu.Unlock() + if AppConfig == nil { + return fmt.Errorf("configuration is not loaded") + } + for _, existing := range AppConfig.CustomKVMImages { + if existing.ID == image.ID { + return fmt.Errorf("image already exists") + } + } + previousImages := AppConfig.CustomKVMImages + previousEnabled := AppConfig.EnabledImages + AppConfig.CustomKVMImages = append(append([]CustomKVMImage(nil), previousImages...), image) + AppConfig.EnabledImages = append(append([]string(nil), previousEnabled...), image.ID) + if err := SaveConfig(); err != nil { + AppConfig.CustomKVMImages = previousImages + AppConfig.EnabledImages = previousEnabled + return err + } + return nil +} diff --git a/backend/internal/config/image_upload_test.go b/backend/internal/config/image_upload_test.go new file mode 100644 index 0000000..853545c --- /dev/null +++ b/backend/internal/config/image_upload_test.go @@ -0,0 +1,58 @@ +package config + +import ( + "encoding/json" + "reflect" + "testing" +) + +func TestUploadedImageMetadataAndEnabledPublishAtomically(t *testing.T) { + setupHistoryStore(t) + previous := CustomKVMImage{ID: "custom-kvm-existing", Name: "Existing", Arch: "amd64", Provisioner: KVMProvisionerManualISO} + AppConfig.CustomKVMImages = []CustomKVMImage{previous} + AppConfig.EnabledImages = []string{previous.ID} + if err := SaveConfig(); err != nil { + t.Fatal(err) + } + image := CustomKVMImage{ID: "custom-kvm-new", Name: "Uploaded", Arch: "amd64", Provisioner: KVMProvisionerManualISO, SHA256: "sha"} + if _, err := db.Exec(`CREATE TRIGGER reject_uploaded BEFORE INSERT ON enabled_images WHEN NEW.image_id = 'custom-kvm-new' BEGIN SELECT RAISE(ABORT,'forced failure'); END`); err != nil { + t.Fatal(err) + } + if err := AddUploadedKVMImage(image); err == nil { + t.Fatal("forced metadata failure was accepted") + } + if !reflect.DeepEqual(AppConfig.CustomKVMImages, []CustomKVMImage{previous}) || !reflect.DeepEqual(AppConfig.EnabledImages, []string{previous.ID}) { + t.Fatal("failed registration changed in-memory images or enabled flags") + } + var raw string + if err := db.QueryRow(`SELECT value FROM app_meta WHERE key = 'custom_kvm_images'`).Scan(&raw); err != nil { + t.Fatal(err) + } + var persisted []CustomKVMImage + if err := json.Unmarshal([]byte(raw), &persisted); err != nil || !reflect.DeepEqual(persisted, []CustomKVMImage{previous}) { + t.Fatalf("failed image metadata escaped transaction: %s %v", raw, err) + } + var count int + if err := db.QueryRow(`SELECT COUNT(*) FROM enabled_images`).Scan(&count); err != nil || count != 1 { + t.Fatalf("failed registration changed stored flags: %d %v", count, err) + } + if _, err := db.Exec(`DROP TRIGGER reject_uploaded`); err != nil { + t.Fatal(err) + } + if err := AddUploadedKVMImage(image); err != nil { + t.Fatal(err) + } + if len(AppConfig.CustomKVMImages) != 2 || len(AppConfig.EnabledImages) != 2 { + t.Fatal("successful registration did not publish both lists") + } + loaded, ok, err := loadConfigFromDB() + if err != nil || !ok || !reflect.DeepEqual(loaded.CustomKVMImages, []CustomKVMImage{previous, image}) || !reflect.DeepEqual(loaded.EnabledImages, []string{previous.ID, image.ID}) { + t.Fatalf("successful metadata and enabled flags did not both persist: %+v %v", loaded, err) + } + if err := AddUploadedKVMImage(image); err == nil || len(AppConfig.CustomKVMImages) != 2 || len(AppConfig.EnabledImages) != 2 { + t.Fatal("duplicate image registration changed existing state") + } + if err := db.QueryRow(`SELECT COUNT(*) FROM enabled_images WHERE image_id = 'custom-kvm-new'`).Scan(&count); err != nil || count != 1 { + t.Fatalf("success did not persist enabled flag: %d %v", count, err) + } +} diff --git a/backend/internal/config/store_sqlite.go b/backend/internal/config/store_sqlite.go index c59d087..3e5d1b4 100644 --- a/backend/internal/config/store_sqlite.go +++ b/backend/internal/config/store_sqlite.go @@ -419,7 +419,10 @@ func ensureSchema() error { return fmt.Errorf("failed to create sqlite schema: %v", err) } } - return ensureSchemaMigrations() + if err := ensureSchemaMigrations(); err != nil { + return err + } + return ensureHistorySchema() } func ensureSchemaMigrations() error { @@ -475,6 +478,8 @@ func ensureSchemaMigrations() error { {"containers", "manual_install", "INTEGER NOT NULL DEFAULT 0"}, {"containers", "installation_media_image_id", "TEXT NOT NULL DEFAULT ''"}, {"containers", "installation_media_boot", "TEXT NOT NULL DEFAULT ''"}, + {"containers", "data_disks", "TEXT NOT NULL DEFAULT '[]'"}, + {"containers", "standalone", "INTEGER NOT NULL DEFAULT 0"}, {"containers", "storage_pool_id", "TEXT"}, {"containers", "storage_path", "TEXT"}, {"containers", "lan_ipv4_mode", "TEXT"}, @@ -792,6 +797,10 @@ func saveContainers(tx *sql.Tx) error { for _, c := range AppConfig.Containers { NormalizeContainerResourceAliases(&c) allowedImageIDs := encodeStringSlice(c.AllowedImageIDs) + dataDisks, err := json.Marshal(c.DataDisks) + if err != nil { + return err + } if _, err := tx.Exec(`INSERT INTO containers ( id, uuid, name, virtualization, lxc_name, kvm_name, disk_image, storage_pool_id, storage_path, mac_address, template, vcpu, ram_mb, disk_gb, network_bw_mbps, network_down_mbps, network_up_mbps, @@ -805,8 +814,8 @@ func saveContainers(tx *sql.Tx) error { snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by, firewall_enabled, firewall_default_action, firewall_rules, allowed_image_ids, image_limit_configured, ipv6_nat_address, ipv6_port_mappings, ipv6_nat_sync_ipv4, ipv6_port_mapping_limit, - manual_install, installation_media_image_id, installation_media_boot - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + manual_install, installation_media_image_id, installation_media_boot, data_disks, standalone + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, c.ID, c.UUID, c.Name, c.Virtualization, c.LXCName, c.KVMName, c.DiskImage, c.StoragePoolID, c.StoragePath, c.MACAddress, c.Template, c.VCPU, c.RAMMB, c.DiskGB, c.NetworkBWMbps, c.NetworkDownMbps, c.NetworkUpMbps, c.MonthlyTrafficGB, c.TrafficMode, c.TrafficInGB, @@ -819,7 +828,7 @@ func saveContainers(tx *sql.Tx) error { c.SnapshotScheduleLastRun, c.SnapshotScheduleNextRun, c.SnapshotScheduleCreatedBy, boolInt(c.FirewallEnabled), normalizeFirewallDefaultAction(c.FirewallDefaultAction), marshalFirewallRules(c.FirewallRules), allowedImageIDs, boolInt(c.ImageLimitConfigured), c.IPv6NATAddress, marshalIPv6PortMappings(c.IPv6PortMappings), boolPtrInt(c.IPv6NATSyncIPv4), c.IPv6PortMappingLimit, - boolInt(c.ManualInstall), c.InstallationMediaImageID, c.InstallationMediaBoot, + boolInt(c.ManualInstall), c.InstallationMediaImageID, c.InstallationMediaBoot, string(dataDisks), boolInt(c.Standalone), ); err != nil { return err } @@ -985,7 +994,7 @@ func loadContainers() ([]Container, error) { snapshot_schedule_last_run, snapshot_schedule_next_run, snapshot_schedule_created_by, firewall_enabled, firewall_default_action, firewall_rules, allowed_image_ids, image_limit_configured, ipv6_nat_address, ipv6_port_mappings, ipv6_nat_sync_ipv4, ipv6_port_mapping_limit, - manual_install, installation_media_image_id, installation_media_boot + manual_install, installation_media_image_id, installation_media_boot, data_disks, standalone FROM containers ORDER BY id`) if err != nil { return nil, err @@ -995,7 +1004,8 @@ func loadContainers() ([]Container, error) { result := []Container{} for rows.Next() { var c Container - var scheduleEnabled, firewallEnabled, imageLimitConfigured, restoreOnHostBoot, manualInstall int + var scheduleEnabled, firewallEnabled, imageLimitConfigured, restoreOnHostBoot, manualInstall, standalone int + var dataDisksJSON string var firewallDefaultAction string var firewallRulesJSON, allowedImageIDs, ipv6PortMappingsJSON sql.NullString var ipv6NATSyncIPv4 sql.NullInt64 @@ -1016,7 +1026,7 @@ func loadContainers() ([]Container, error) { &c.SnapshotScheduleLastRun, &c.SnapshotScheduleNextRun, &c.SnapshotScheduleCreatedBy, &firewallEnabled, &firewallDefaultAction, &firewallRulesJSON, &allowedImageIDs, &imageLimitConfigured, &c.IPv6NATAddress, &ipv6PortMappingsJSON, &ipv6NATSyncIPv4, &c.IPv6PortMappingLimit, - &manualInstall, &c.InstallationMediaImageID, &c.InstallationMediaBoot, + &manualInstall, &c.InstallationMediaImageID, &c.InstallationMediaBoot, &dataDisksJSON, &standalone, ); err != nil { return nil, err } @@ -1038,6 +1048,10 @@ func loadContainers() ([]Container, error) { c.LANIPv4Gateway = lanIPv4Gateway.String c.SnapshotScheduleEnabled = scheduleEnabled != 0 c.ManualInstall = manualInstall != 0 + c.Standalone = standalone != 0 + if err := json.Unmarshal([]byte(dataDisksJSON), &c.DataDisks); err != nil { + return nil, fmt.Errorf("invalid data disks for container %d: %w", c.ID, err) + } c.RestoreOnHostBoot = restoreOnHostBoot != 0 c.FirewallEnabled = firewallEnabled != 0 c.FirewallDefaultAction = normalizeFirewallDefaultAction(firewallDefaultAction) diff --git a/backend/internal/kvm/disks.go b/backend/internal/kvm/disks.go new file mode 100644 index 0000000..2583715 --- /dev/null +++ b/backend/internal/kvm/disks.go @@ -0,0 +1,402 @@ +package kvm + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "time" + "unicode/utf8" + + "clicd/internal/config" +) + +func diskCommand(ctx context.Context, name string, args ...string) error { + out, err := exec.CommandContext(ctx, name, args...).CombinedOutput() + if err != nil { + return fmt.Errorf("%s failed: %w: %s", name, err, strings.TrimSpace(string(out))) + } + return nil +} +func qcowDiskInfo(ctx context.Context, path string) (int64, int64, error) { + out, err := exec.CommandContext(ctx, "qemu-img", "info", "-U", "--output=json", path).CombinedOutput() + if err != nil { + return 0, 0, fmt.Errorf("inspect disk: %w: %s", err, strings.TrimSpace(string(out))) + } + var info struct { + VirtualSize int64 `json:"virtual-size"` + ActualSize int64 `json:"actual-size"` + Format string `json:"format"` + } + if err := json.Unmarshal(out, &info); err != nil { + return 0, 0, err + } + if info.Format != "qcow2" || info.VirtualSize <= 0 { + return 0, 0, fmt.Errorf("only managed QCOW2 disks can be resized") + } + return info.VirtualSize, info.ActualSize, nil +} +func (m *Manager) requireDiskStopped(c *config.Container) error { + state, err := m.GetContainerStatus(c.VirshName()) + if err != nil { + return fmt.Errorf("cannot inspect VM state: %w", err) + } + if state != "stopped" { + return fmt.Errorf("VM must be fully shut down before changing disks (state %s)", state) + } + return nil +} +func (m *Manager) systemDiskPath(c *config.Container) (string, error) { + expected := filepath.Join(NewManagerForStoragePool(c.StoragePoolID).BasePath, "instances", c.VirshName(), "disk.qcow2") + if filepath.Clean(c.DiskImage) != filepath.Clean(expected) { + return "", fmt.Errorf("this system disk is not in its managed instance directory") + } + if err := rejectDiskSymlinks(expected); err != nil { + return "", err + } + return expected, nil +} +func rejectDiskSymlinks(path string) error { + for cursor := filepath.Clean(path); ; cursor = filepath.Dir(cursor) { + if info, err := os.Lstat(cursor); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("disk paths cannot contain symlinks") + } + } else if !os.IsNotExist(err) { + return err + } + if filepath.Dir(cursor) == cursor { + break + } + } + return nil +} +func (m *Manager) GetDisks(ctx context.Context, id int) (config.DiskInventory, error) { + stored := config.FindContainer(id) + if stored == nil || !stored.IsKVM() { + return config.DiskInventory{}, fmt.Errorf("KVM VM not found") + } + c := *stored + result := config.DiskInventory{System: config.DiskInfo{ID: "system", Name: "System disk", SizeGB: c.DiskGB, Format: "qcow2", Target: "system", StoragePoolID: c.StoragePoolID, Attached: true, CanResize: true}, DataDisks: []config.DiskInfo{}} + result.Limits.MaxDataDisks = config.MaxDataDisks + if err := m.requireDiskStopped(&c); err != nil { + result.Reason = err.Error() + } else { + result.CanEdit = true + } + path, err := m.systemDiskPath(&c) + if err != nil { + result.System.CanResize = false + result.System.Error = err.Error() + } else if size, allocated, err := qcowDiskInfo(ctx, path); err == nil { + result.System.SizeGB = float64(size) / (1 << 30) + result.System.AllocatedBytes = allocated + } else { + result.System.Error = err.Error() + result.System.CanResize = false + } + for _, d := range c.DataDisks { + entry := config.PublicDataDisk(d) + path, err := config.DataDiskPath(&c, d) + if err == nil { + var size, allocated int64 + size, allocated, err = qcowDiskInfo(ctx, path) + entry.SizeGB = float64(size) / (1 << 30) + entry.AllocatedBytes = allocated + } + if err != nil { + entry.Error = err.Error() + entry.CanResize = false + } + result.DataDisks = append(result.DataDisks, entry) + } + return result, nil +} +func (m *Manager) persistDataDisks(previous, next config.Container) error { + if err := m.ensureDomainDefinition(&next); err != nil { + return err + } + current := config.FindContainer(next.ID) + if current == nil { + return fmt.Errorf("VM disappeared") + } + old := current.DataDisks + current.DataDisks = next.DataDisks + if err := config.SaveConfig(); err != nil { + current.DataDisks = old + rollback := m.ensureDomainDefinition(&previous) + return fmt.Errorf("save disk configuration: %v (domain rollback: %v)", err, rollback) + } + return nil +} +func (m *Manager) AddDataDisk(ctx context.Context, id int, name string, sizeGB float64, poolID string) (config.DataDisk, error) { + installationMediaMu.Lock() + defer installationMediaMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || !stored.IsKVM() { + return config.DataDisk{}, fmt.Errorf("KVM VM not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return config.DataDisk{}, err + } + if len(c.DataDisks) >= config.MaxDataDisks { + return config.DataDisk{}, fmt.Errorf("data disk limit is %d", config.MaxDataDisks) + } + if c.SnapshotScheduleEnabled { + return config.DataDisk{}, fmt.Errorf("disable scheduled snapshots before adding data disks; use full backups to include all disks") + } + bytes, err := config.DiskSizeBytes(sizeGB) + if err != nil { + return config.DataDisk{}, err + } + name = strings.TrimSpace(name) + if name == "" || utf8.RuneCountInString(name) > 80 { + return config.DataDisk{}, fmt.Errorf("disk name must contain 1 to 80 characters") + } + poolID = strings.TrimSpace(poolID) + pool, err := config.SelectStoragePoolForContent(config.StorageContentKVM, poolID, bytes) + if err != nil { + return config.DataDisk{}, err + } + if poolID != "" && pool.ID != poolID { + return config.DataDisk{}, fmt.Errorf("requested data disk storage pool is unavailable or lacks capacity") + } + bus, prefix := "virtio", "vd" + offset := 1 + if runtime.GOARCH == "amd64" && (c.ManualInstall || IsWindowsImage(c.Template) || strings.Contains(c.Template, "windows")) { + bus, prefix, offset = "sata", "sd", 2 + } + used := map[string]bool{} + for _, d := range c.DataDisks { + used[d.Target] = true + } + target := "" + for i := offset; i < 26; i++ { + candidate := prefix + string(rune('a'+i)) + if !used[candidate] { + target = candidate + break + } + } + if target == "" { + return config.DataDisk{}, fmt.Errorf("no disk target is available") + } + d := config.DataDisk{ID: config.NewDataDiskID(), Name: name, SizeGB: float64(bytes) / (1 << 30), StoragePoolID: pool.ID, Format: "qcow2", Target: target, Bus: bus, Attached: true, CreatedAt: time.Now().Format(time.RFC3339)} + d.Path, err = config.DataDiskPath(&c, d) + if err != nil { + return d, err + } + if err = os.MkdirAll(filepath.Dir(d.Path), 0755); err != nil { + return d, err + } + if _, err := os.Lstat(d.Path); !os.IsNotExist(err) { + return d, fmt.Errorf("new data disk path already exists") + } + if err = diskCommand(ctx, "qemu-img", "create", "-f", "qcow2", d.Path, fmt.Sprintf("%dM", bytes/(1<<20))); err != nil { + _ = os.Remove(d.Path) + return d, err + } + _ = os.Chmod(d.Path, 0644) + next := c + next.DataDisks = append(append([]config.DataDisk(nil), c.DataDisks...), d) + if err = m.persistDataDisks(c, next); err != nil { + if rollback := m.ensureDomainDefinition(&c); rollback != nil { + return d, fmt.Errorf("%w; new disk file retained because domain rollback failed: %v", err, rollback) + } + _ = os.Remove(d.Path) + return d, err + } + return d, nil +} +func (m *Manager) ResizeDisk(ctx context.Context, id int, diskID string, sizeGB float64) error { + installationMediaMu.Lock() + defer installationMediaMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || !stored.IsKVM() { + return fmt.Errorf("KVM VM not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return err + } + bytes, err := config.DiskSizeBytes(sizeGB) + if err != nil { + return err + } + path := "" + index := -1 + if diskID == "system" { + path, err = m.systemDiskPath(&c) + } else { + for i, d := range c.DataDisks { + if d.ID == diskID { + index = i + path, err = config.DataDiskPath(&c, d) + break + } + } + if index < 0 { + return fmt.Errorf("data disk not found") + } + } + if err != nil { + return err + } + actual, _, err := qcowDiskInfo(ctx, path) + if err != nil { + return err + } + if bytes < actual { + return fmt.Errorf("disk shrinking is not supported; current size is %.3f GB", float64(actual)/(1<<30)) + } + if bytes > actual { + poolID := c.StoragePoolID + if index >= 0 { + poolID = c.DataDisks[index].StoragePoolID + } + pool, err := config.SelectStoragePoolForContent(config.StorageContentKVM, poolID, bytes-actual) + if err != nil { + return err + } + if poolID != "" && pool.ID != poolID { + return fmt.Errorf("disk storage pool is unavailable or lacks capacity") + } + if err = diskCommand(ctx, "qemu-img", "resize", path, fmt.Sprintf("%dM", bytes/(1<<20))); err != nil { + return err + } + } + current := config.FindContainer(id) + if current == nil { + return fmt.Errorf("VM disappeared") + } + if index < 0 { + current.DiskGB = float64(bytes) / (1 << 30) + } else { + for i := range current.DataDisks { + if current.DataDisks[i].ID == diskID { + current.DataDisks[i].SizeGB = float64(bytes) / (1 << 30) + } + } + } + if err = config.SaveConfig(); err != nil { + return fmt.Errorf("disk was expanded but metadata could not be persisted: %w", err) + } + return nil +} +func (m *Manager) SetDataDiskAttached(ctx context.Context, id int, diskID string, attached bool) error { + installationMediaMu.Lock() + defer installationMediaMu.Unlock() + stored := config.FindContainer(id) + if stored == nil { + return fmt.Errorf("VM not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return err + } + next := c + next.DataDisks = append([]config.DataDisk(nil), c.DataDisks...) + for i, d := range next.DataDisks { + if d.ID == diskID { + if _, err := config.DataDiskPath(&c, d); err != nil { + return err + } + next.DataDisks[i].Attached = attached + return m.persistDataDisks(c, next) + } + } + return fmt.Errorf("data disk not found") +} +func (m *Manager) DeleteDataDisk(ctx context.Context, id int, diskID string) error { + installationMediaMu.Lock() + defer installationMediaMu.Unlock() + stored := config.FindContainer(id) + if stored == nil { + return fmt.Errorf("VM not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return err + } + for index, d := range c.DataDisks { + if d.ID == diskID { + path, err := config.DataDiskPath(&c, d) + if err != nil { + return err + } + next := c + next.DataDisks = append(append([]config.DataDisk(nil), c.DataDisks[:index]...), c.DataDisks[index+1:]...) + if err = m.persistDataDisks(c, next); err != nil { + return err + } + if err = os.Remove(path); err != nil && !os.IsNotExist(err) { + d.Attached = false + current := config.FindContainer(id) + current.DataDisks = append(current.DataDisks, d) + _ = config.SaveConfig() + return fmt.Errorf("disk detached but file deletion failed: %w", err) + } + _ = os.Remove(filepath.Dir(path)) + return nil + } + } + return fmt.Errorf("data disk not found") +} + +var dataDiskTarget = regexp.MustCompile(`^(vd[b-z]|sd[c-z])$`) + +func attachDataDisksXML(xml string, c *config.Container) (string, error) { + seen := map[string]bool{} + if len(c.DataDisks) > config.MaxDataDisks { + return "", fmt.Errorf("too many data disks") + } + for _, d := range c.DataDisks { + if !d.Attached { + continue + } + if !dataDiskTarget.MatchString(d.Target) || (d.Bus != "virtio" && d.Bus != "sata") || (d.Bus == "virtio" && !strings.HasPrefix(d.Target, "vd")) || (d.Bus == "sata" && !strings.HasPrefix(d.Target, "sd")) || seen[d.Target] { + return "", fmt.Errorf("invalid or duplicate data disk target") + } + seen[d.Target] = true + path, err := config.DataDiskPath(c, d) + if err != nil { + return "", err + } + if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() { + return "", fmt.Errorf("data disk %s is unavailable", d.ID) + } + disk := fmt.Sprintf("%s\n", xmlEscape(path), d.Target, d.Bus, xmlEscape(d.ID)) + xml = strings.Replace(xml, " ", " "+disk+" ", 1) + } + return xml, nil +} +func (m *Manager) containerDomainXML(c *config.Container) (string, error) { + xml, err := m.baseContainerDomainXML(c) + if err != nil { + return "", err + } + return attachDataDisksXML(xml, c) +} +func (m *Manager) CleanupDataDisks(c *config.Container) error { + paths := []string{} + for _, d := range c.DataDisks { + path, err := config.DataDiskPath(c, d) + if err != nil { + return err + } + paths = append(paths, path) + } + for _, path := range paths { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + _ = os.Remove(filepath.Dir(path)) + } + return nil +} diff --git a/backend/internal/kvm/disks_test.go b/backend/internal/kvm/disks_test.go new file mode 100644 index 0000000..2b8f45c --- /dev/null +++ b/backend/internal/kvm/disks_test.go @@ -0,0 +1,170 @@ +package kvm + +import ( + "clicd/internal/config" + "context" + "encoding/xml" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestDataDiskXMLIncludesAttachedOwnedDisksOnly(t *testing.T) { + _, c := manualISOFixture(t) + c.UUID = "test-owner" + d := config.DataDisk{ID: "disk-data", Name: "Data", StoragePoolID: "test", Format: "qcow2", Target: "sdc", Bus: "sata", Attached: true} + var err error + d.Path, err = config.DataDiskPath(c, d) + if err != nil { + t.Fatal(err) + } + if err = os.MkdirAll(filepath.Dir(d.Path), 0755); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(d.Path, []byte("QFI\xfb"), 0644); err != nil { + t.Fatal(err) + } + c.DataDisks = []config.DataDisk{d} + text, err := NewManager().containerDomainXML(c) + if err != nil { + t.Fatal(err) + } + var doc struct { + Disks []struct { + Source struct { + File string `xml:"file,attr"` + } `xml:"source"` + } `xml:"devices>disk"` + } + if err = xml.Unmarshal([]byte(text), &doc); err != nil { + t.Fatal(err) + } + if len(doc.Disks) != 3 || doc.Disks[2].Source.File != d.Path { + t.Fatalf("data disk missing: %s", text) + } + c.DataDisks[0].Attached = false + text, err = NewManager().containerDomainXML(c) + if err != nil || strings.Contains(text, d.Path) { + t.Fatal("detached disk is still in XML") + } + c.DataDisks[0].Attached = true + c.DataDisks = append(c.DataDisks, d) + if _, err = NewManager().containerDomainXML(c); err == nil { + t.Fatal("duplicate target accepted") + } +} +func TestDataDiskCleanupValidatesAllOwnersBeforeDeleting(t *testing.T) { + _, c := manualISOFixture(t) + c.UUID = "test-owner" + good := config.DataDisk{ID: "disk-owned", StoragePoolID: "test"} + good.Path, _ = config.DataDiskPath(c, good) + _ = os.MkdirAll(filepath.Dir(good.Path), 0755) + _ = os.WriteFile(good.Path, []byte("data"), 0600) + bad := good + bad.ID = "disk-other" + bad.Path = filepath.Join(t.TempDir(), "important") + c.DataDisks = []config.DataDisk{good, bad} + if NewManager().CleanupDataDisks(c) == nil { + t.Fatal("unowned path accepted") + } + if _, err := os.Stat(good.Path); err != nil { + t.Fatal("deleted an owned file before validating the complete set") + } +} +func TestDiskResizeRejectsActualRunningAndShrinking(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake hypervisor uses POSIX commands") + } + _, c := manualISOFixture(t) + c.UUID = "test-owner" + c.StoragePoolID = "test" + m := NewManagerForStoragePool("test") + c.DiskImage = filepath.Join(m.instancesDir(), c.VirshName(), "disk.qcow2") + _ = os.MkdirAll(filepath.Dir(c.DiskImage), 0755) + _ = os.WriteFile(c.DiskImage, []byte("QFI\xfb"), 0600) + config.AppConfig.Containers = []config.Container{*c} + commands := t.TempDir() + log := filepath.Join(commands, "resize.log") + writeKVMTestCommand(t, commands, "virsh", "echo \"$KVM_TEST_STATE\"\n") + writeKVMTestCommand(t, commands, "qemu-img", "case \"$1\" in info) echo '{\"format\":\"qcow2\",\"virtual-size\":4294967296,\"actual-size\":4096}' ;; resize) echo resized >> \"$KVM_COMMAND_LOG\" ;; esac\n") + t.Setenv("PATH", commands+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("KVM_COMMAND_LOG", log) + for _, state := range []string{"running", "paused", "in shutdown"} { + t.Setenv("KVM_TEST_STATE", state) + if err := m.ResizeDisk(context.Background(), c.ID, "system", 8); err == nil { + t.Fatal("resized active VM") + } + } + t.Setenv("KVM_TEST_STATE", "shut off") + if err := m.ResizeDisk(context.Background(), c.ID, "system", 2); err == nil || !strings.Contains(err.Error(), "shrinking") { + t.Fatalf("shrink: %v", err) + } + if _, err := os.Stat(log); !os.IsNotExist(err) { + t.Fatal("unsafe qemu resize executed") + } +} + +func TestDataDiskSnapshotSafetyGuards(t *testing.T) { + _, c := manualISOFixture(t) + c.DataDisks = []config.DataDisk{{ID: "disk-existing", Attached: false}} + config.AppConfig.Containers = []config.Container{*c} + if _, err := NewManager().CreateSnapshot(c.ID, "admin", false, 0); err == nil || !strings.Contains(err.Error(), "full backup") { + t.Fatalf("snapshot ignored data disk: %v", err) + } + if _, err := NewManager().SetSnapshotSchedule(c.ID, true, 24, "03:00", "admin"); err == nil || !strings.Contains(err.Error(), "full backups") { + t.Fatalf("scheduled snapshot accepted: %v", err) + } + config.AppConfig.DataDir = t.TempDir() + path := filepath.Join(config.AppConfig.DataDir, "snapshots", "legacy") + _ = os.MkdirAll(path, 0700) + config.AppConfig.Snapshots = []config.Snapshot{{ID: "legacy", ContainerID: c.ID, Path: path}} + if err := NewManager().RestoreSnapshot("legacy"); err == nil || !strings.Contains(err.Error(), "full backup") { + t.Fatalf("old snapshot restored over data disk inventory: %v", err) + } +} + +func TestDataDiskRejectsExplicitPoolFallbackBeforeCreatingOrResizing(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake hypervisor uses POSIX commands") + } + _, c := manualISOFixture(t) + c.UUID = "pool-test-owner" + disabled := config.AppConfig.StoragePools[0] + disabled.ID, disabled.Path, disabled.Enabled = "disabled", t.TempDir(), false + config.AppConfig.StoragePools = append(config.AppConfig.StoragePools, disabled) + config.AppConfig.Containers = []config.Container{*c} + commands := t.TempDir() + log := filepath.Join(commands, "unsafe.log") + writeKVMTestCommand(t, commands, "virsh", "echo 'shut off'\n") + writeKVMTestCommand(t, commands, "df", "printf 'Filesystem 1B-blocks Used Available Use%% Mounted\\nfake 107374182400 0 107374182400 0%% /\\n'\n") + writeKVMTestCommand(t, commands, "qemu-img", "if [ \"$1\" = info ]; then echo '{\"format\":\"qcow2\",\"virtual-size\":134217728,\"actual-size\":4096}'; else echo unsafe >> \"$KVM_COMMAND_LOG\"; exit 88; fi\n") + t.Setenv("PATH", commands+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("KVM_COMMAND_LOG", log) + if pool, err := config.SelectStoragePoolForContent("kvm", "missing", 128<<20); err != nil || pool.ID != "test" { + t.Fatalf("fallback precondition: %v %v", pool, err) + } + for _, requested := range []string{"missing", "disabled"} { + if _, err := NewManager().AddDataDisk(context.Background(), c.ID, "data", .125, requested); err == nil || !strings.Contains(err.Error(), "requested data disk storage pool") { + t.Fatalf("explicit %s pool was not rejected: %v", requested, err) + } + } + if len(config.FindContainer(c.ID).DataDisks) != 0 { + t.Fatal("failed addition mutated disk metadata") + } + d := config.DataDisk{ID: "disk-disabled", StoragePoolID: "disabled", SizeGB: .125} + d.Path, _ = config.DataDiskPath(c, d) + _ = os.MkdirAll(filepath.Dir(d.Path), 0755) + _ = os.WriteFile(d.Path, []byte("QFI\xfb"), 0600) + config.FindContainer(c.ID).DataDisks = []config.DataDisk{d} + if err := NewManager().ResizeDisk(context.Background(), c.ID, d.ID, .25); err == nil || !strings.Contains(err.Error(), "disk storage pool") { + t.Fatalf("resize checked capacity on another pool: %v", err) + } + if config.FindContainer(c.ID).DataDisks[0].SizeGB != .125 { + t.Fatal("failed resize mutated disk metadata") + } + if _, err := os.Stat(log); !os.IsNotExist(err) { + t.Fatal("created or resized a disk in an unintended pool") + } +} diff --git a/backend/internal/kvm/image_metadata.go b/backend/internal/kvm/image_metadata.go new file mode 100644 index 0000000..4af609a --- /dev/null +++ b/backend/internal/kvm/image_metadata.go @@ -0,0 +1,25 @@ +package kvm + +import ( + "encoding/binary" + "math" + "os" +) + +// ImageVirtualDiskGB reads only the QCOW2 header without opening backing files. +func ImageVirtualDiskGB(id string) float64 { + f, err := os.Open(ImagePath(id)) + if err != nil { + return 0 + } + defer f.Close() + var header [32]byte + if _, err := f.ReadAt(header[:], 0); err != nil || string(header[:4]) != "QFI\xfb" { + return 0 + } + version := binary.BigEndian.Uint32(header[4:8]) + if version != 2 && version != 3 { + return 0 + } + return math.Ceil(float64(binary.BigEndian.Uint64(header[24:32])) / float64(1<<30)) +} diff --git a/backend/internal/kvm/installation_media.go b/backend/internal/kvm/installation_media.go index 89d4c95..1fa1e5d 100644 --- a/backend/internal/kvm/installation_media.go +++ b/backend/internal/kvm/installation_media.go @@ -128,7 +128,17 @@ func withInstallationMedia(xml, iso, boot string) string { return xml } -func (m *Manager) containerDomainXML(c *config.Container) (string, error) { +func (m *Manager) baseContainerDomainXML(c *config.Container) (string, error) { + if c.Standalone { + switch c.Template { + case "standalone-windows": + return withInstallationMedia(windowsDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, "", "", c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps), "", "disk"), nil + case "standalone-manual": + return manualDomainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, "", c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps, "disk"), nil + default: + return withInstallationMedia(domainXML(c.VirshName(), int(c.VCPU), c.RAMMB, c.DiskImage, "", c.MACAddress, c.IOReadMBps, c.IOWriteMBps, c.NetworkDownMbps, c.NetworkUpMbps, false), "", "disk"), nil + } + } imageID, boot := InstallationMedia(c) iso := "" if imageID != "" { @@ -213,6 +223,7 @@ func (m *Manager) SetInstallationMedia(id int, imageID, boot string) error { // and resource updates keep the existing media selection (including eject). func resetReinstalledMedia(current, next *config.Container) { current.Template = next.Template + current.Standalone = next.Standalone current.ManualInstall = next.ManualInstall current.InstallationMediaImageID = next.InstallationMediaImageID current.InstallationMediaBoot = next.InstallationMediaBoot diff --git a/backend/internal/kvm/installation_media_test.go b/backend/internal/kvm/installation_media_test.go index 9530d48..2af2185 100644 --- a/backend/internal/kvm/installation_media_test.go +++ b/backend/internal/kvm/installation_media_test.go @@ -227,6 +227,24 @@ func TestExplicitReinstallUsesNewTemplateMediaAfterEjectOrRescueMount(t *testing } } +func TestReinstallReplacesStandaloneProvisioningMode(t *testing.T) { + _, original := manualISOFixture(t) + current := *original + current.Template, current.Standalone, current.ManualInstall = "standalone-linux", true, false + next := config.Container{Template: "kvm-debian-12"} + resetReinstalledMedia(¤t, &next) + xml, err := NewManager().containerDomainXML(¤t) + if err != nil || current.Standalone || !strings.Contains(xml, "seed.iso") { + t.Fatalf("reinstall of a restored VM lost its new cloud-init medium: %v", err) + } + next = config.Container{Template: "manual-test", Standalone: true, ManualInstall: true, InstallationMediaBoot: "disk"} + resetReinstalledMedia(¤t, &next) + xml, err = NewManager().containerDomainXML(¤t) + if err != nil || !current.Standalone || strings.Contains(xml, "seed.iso") { + t.Fatalf("preinstalled disk reinstall inherited a provisioning medium: %v", err) + } +} + func TestPersistedManualModeDoesNotRequireSourceRegistryOrCloudTools(t *testing.T) { _, c := manualISOFixture(t) c.InstallationMediaImageID = "" diff --git a/backend/internal/kvm/kvm.go b/backend/internal/kvm/kvm.go index fceb4ed..2d365be 100644 --- a/backend/internal/kvm/kvm.go +++ b/backend/internal/kvm/kvm.go @@ -453,7 +453,7 @@ func (m *Manager) CreateContainer(cfg lxc.ContainerConfig) error { if cfg.VCPU < 1 || cfg.VCPU != float64(int(cfg.VCPU)) { return fmt.Errorf("KVM vCPU must be a whole number and at least 1") } - if IsWindowsImage(image.ID) && cfg.DiskGB < 30 { + if !image.IsManualDisk() && IsWindowsImage(image.ID) && cfg.DiskGB < 30 { cfg.DiskGB = 30 } else if image.Desktop != "" && cfg.DiskGB < 20 { cfg.DiskGB = 20 @@ -523,7 +523,7 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig sshPassword := "" sshPublicKey := "" sshAuthMode := "" - if !IsWindowsImage(image.ID) && !image.IsManualISO() { + if !IsWindowsImage(image.ID) && !image.IsManualISO() && !image.IsManualDisk() { sshAccess, err := lxc.ResolveCreateSSHAccess(cfg) if err != nil { return nil, err @@ -553,7 +553,20 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig var xml string winAdminPassword := "" - if image.IsManualISO() { + if image.IsManualDisk() { + cfg.ReportProgress("disk", "Copy independent preinstalled disk") + if err := flattenTransferDisk(context.Background(), ImagePath(image.ID), diskPath); err != nil { + return nil, err + } + if output, err := exec.Command("qemu-img", "resize", diskPath, fmt.Sprintf("%dM", int64(math.Ceil(cfg.DiskGB*1024)))).CombinedOutput(); err != nil { + return nil, fmt.Errorf("grow copied preinstalled disk: %w: %s", err, strings.TrimSpace(string(output))) + } + if image.IsWindows() { + xml = withInstallationMedia(windowsDomainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, "", "", mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps), "", "disk") + } else { + xml = withInstallationMedia(domainXML(vmName, int(cfg.VCPU), cfg.RAMMB, diskPath, "", mac, cfg.IOReadMBps, cfg.IOWriteMBps, cfg.NetworkDownMbps, cfg.NetworkUpMbps, false), "", "disk") + } + } else if image.IsManualISO() { cfg.ReportProgress("disk", "Create blank KVM disk") if err := createEmptyDisk(diskPath, cfg.DiskGB); err != nil { return nil, err @@ -710,7 +723,15 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig CreatedAt: now, ExpiresAt: cfg.ExpiresAt, } - if image.IsManualISO() { + if image.IsManualDisk() { + container.Standalone = true + container.ManualInstall = true + container.InstallationMediaBoot = "disk" + container.Template = "standalone-linux" + if image.IsWindows() { + container.Template = "standalone-windows" + } + } else if image.IsManualISO() { container.ManualInstall = true container.InstallationMediaImageID = image.ID container.InstallationMediaBoot = "cdrom" @@ -737,7 +758,7 @@ func (m *Manager) StartContainerContext(ctx context.Context, id int) error { // Config deletion compacts the container slice. Never keep its element // pointer across guest polling or external commands. c := *stored - if err := m.validateHost(c.Template, c.ManualInstall); err != nil { + if err := m.validateHost(c.Template, c.ManualInstall || c.Standalone); err != nil { return err } lxc.EnsureAssignedPublicIPv4s(c.PublicIPv4s) @@ -761,7 +782,7 @@ func (m *Manager) StartContainerContext(ctx context.Context, id int) error { } _ = exec.CommandContext(ctx, "virsh", "dommemstat", name, "--period", "10", "--live").Run() _ = exec.CommandContext(ctx, "virsh", "dommemstat", name, "--period", "10", "--config").Run() - if c.ManualInstall || IsManualISOImage(c.Template) || c.InstallationMediaBoot == "cdrom" { + if c.ManualInstall || c.Standalone || IsManualISOImage(c.Template) || c.InstallationMediaBoot == "cdrom" { if err := ctx.Err(); err != nil { return err } @@ -1024,6 +1045,9 @@ func (m *Manager) DestroyContainer(id int) error { return fmt.Errorf("failed to undefine KVM VM %s: %w", name, err) } } + if err := m.CleanupDataDisks(&container); err != nil { + return err + } removeKVMIPv6Runtime(&container) if err := os.RemoveAll(instanceDir); err != nil { return err @@ -1246,6 +1270,9 @@ func (m *Manager) CreateSnapshot(id int, createdBy string, scheduled bool, rotat if !c.IsKVM() { return config.Snapshot{}, fmt.Errorf("container is not a KVM VM: %d", id) } + if len(c.DataDisks) > 0 { + return config.Snapshot{}, fmt.Errorf("snapshots with data disks are not supported; use a full backup to include all disks") + } if scheduled && rotateLimit > 0 { for { existing := config.ContainerSnapshots(id) @@ -1369,6 +1396,9 @@ func (m *Manager) RestoreSnapshot(id string) error { if !c.IsKVM() { return fmt.Errorf("container is not a KVM VM: %d", c.ID) } + if len(c.DataDisks) > 0 { + return fmt.Errorf("snapshots with data disks are not supported; use a full backup to include all disks") + } name := c.VirshName() instanceDir := m.instanceDir(name) instanceParent := filepath.Dir(instanceDir) @@ -1412,10 +1442,15 @@ func (m *Manager) RestoreSnapshot(id string) error { } func (m *Manager) SetSnapshotSchedule(id int, enabled bool, intervalHours int, scheduleTime string, createdBy string) (*config.Container, error) { + installationMediaMu.Lock() + defer installationMediaMu.Unlock() c := config.FindContainer(id) if c == nil { return nil, fmt.Errorf("container not found: %d", id) } + if enabled && len(c.DataDisks) > 0 { + return nil, fmt.Errorf("scheduled snapshots with data disks are not supported; use full backups to include all disks") + } if intervalHours < 24 { return nil, fmt.Errorf("snapshot schedule interval cannot be less than 24 hours") } @@ -1887,7 +1922,7 @@ func (m *Manager) validateHost(imageID string, manualInstall ...bool) error { } func validateProvisioningTools(imageID string, manualInstall bool) error { - if manualInstall || IsManualISOImage(imageID) { + if manualInstall || IsManualISOImage(imageID) || IsManualDiskImage(imageID) { // Manual installation needs no seed or unattended ISO tools. } else if IsWindowsImage(imageID) { if runtime.GOARCH != "amd64" { @@ -2212,20 +2247,24 @@ func windowsMinimumResources(imageID string) (float64, int, int) { // GetKVMImageMinDiskGB returns the minimum required disk size in GB for a KVM image. func GetKVMImageMinDiskGB(imageID string) float64 { - if IsManualISOImage(imageID) { - return 1 - } - if IsWindowsImage(imageID) { + minimum := float64(5) + if IsManualISOImage(imageID) || IsManualDiskImage(imageID) { + minimum = 1 + } else if IsWindowsImage(imageID) { if IsWindows11Image(imageID) { - return 64 + minimum = 64 + } else { + minimum = 30 } - return 30 } img := FindImage(imageID) if img != nil && img.Desktop != "" { - return 20 + minimum = 20 } - return 5 + if virtualGB := ImageVirtualDiskGB(imageID); virtualGB > minimum { + minimum = virtualGB + } + return minimum } func sanitizeWindowsComputerName(name string) string { diff --git a/backend/internal/kvm/templates.go b/backend/internal/kvm/templates.go index 27270cb..1f97a61 100644 --- a/backend/internal/kvm/templates.go +++ b/backend/internal/kvm/templates.go @@ -254,6 +254,15 @@ func (image Image) IsManualISO() bool { return strings.EqualFold(strings.TrimSpace(image.Provisioner), config.KVMProvisionerManualISO) } +func (image Image) IsManualDisk() bool { + return strings.EqualFold(strings.TrimSpace(image.Provisioner), "manual-disk") +} + +func IsManualDiskImage(id string) bool { + image := FindImage(id) + return image != nil && image.IsManualDisk() +} + func IsManualISOImage(id string) bool { image := FindImage(id) return image != nil && image.IsManualISO() diff --git a/backend/internal/kvm/transfer.go b/backend/internal/kvm/transfer.go new file mode 100644 index 0000000..3217e84 --- /dev/null +++ b/backend/internal/kvm/transfer.go @@ -0,0 +1,469 @@ +package kvm + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/hex" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" + + "clicd/internal/config" + "clicd/internal/lxc" + "clicd/internal/transfer" +) + +func flattenTransferDisk(ctx context.Context, source, target string) error { + if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil { + return err + } + if output, err := exec.CommandContext(ctx, "qemu-img", "convert", "-O", "qcow2", source, target).CombinedOutput(); err != nil { + return fmt.Errorf("flatten disk: %w: %s", err, strings.TrimSpace(string(output))) + } + if err := os.Chmod(target, 0644); err != nil { + return err + } + return validateTransferDisk(ctx, target) +} + +func validateTransferDisk(ctx context.Context, p string) error { + output, err := exec.CommandContext(ctx, "qemu-img", "info", "--output=json", p).CombinedOutput() + if err != nil { + return fmt.Errorf("inspect portable disk: %w: %s", err, strings.TrimSpace(string(output))) + } + var info struct { + Format string `json:"format"` + Virtual int64 `json:"virtual-size"` + Backing string `json:"backing-filename"` + FullBacking string `json:"full-backing-filename"` + Specific json.RawMessage `json:"format-specific"` + } + if err = json.Unmarshal(output, &info); err != nil { + return err + } + if info.Format != "qcow2" || info.Virtual <= 0 || info.Virtual > transfer.MaxVirtualDiskBytes || info.Backing != "" || info.FullBacking != "" || strings.Contains(string(info.Specific), `"data-file"`) { + return fmt.Errorf("backup disks must be bounded standalone QCOW2 without backing/external data files") + } + if output, err = exec.CommandContext(ctx, "qemu-img", "check", "-q", p).CombinedOutput(); err != nil { + return fmt.Errorf("portable disk consistency check: %w: %s", err, strings.TrimSpace(string(output))) + } + return nil +} + +func ValidateTransfer(ctx context.Context, dir string, m *transfer.Manifest) error { + if m.Runtime != "kvm" { + return fmt.Errorf("not a KVM backup") + } + for _, file := range m.Files { + if err := validateTransferDisk(ctx, filepath.Join(dir, filepath.FromSlash(file.Name))); err != nil { + return err + } + } + return nil +} + +func (m *Manager) ExportTransfer(ctx context.Context, id int, dir string, manifest *transfer.Manifest) (err error) { + installationMediaMu.Lock() + defer installationMediaMu.Unlock() + kvmSnapshotMu.Lock() + defer kvmSnapshotMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || !stored.IsKVM() { + return fmt.Errorf("KVM VM not found") + } + c := *stored + state, err := m.GetContainerStatus(c.VirshName()) + if err != nil { + return err + } + if state != "running" && state != "stopped" { + return fmt.Errorf("VM must be running or fully stopped for backup") + } + if state == "running" { + if err = m.StopContainer(id); err != nil { + return err + } + defer func() { + restoreErr := m.StartContainer(id) + if restoreErr == nil { + config.UpdateContainerStatusAndRestore(id, "running", c.RestoreOnHostBoot) + } + err = errors.Join(err, restoreErr) + }() + } + if state, err = m.GetContainerStatus(c.VirshName()); err != nil || state != "stopped" { + return fmt.Errorf("cannot confirm stopped VM before copying") + } + var measured int64 + sources := []string{c.DiskImage} + for _, disk := range c.DataDisks { + p, e := config.DataDiskPath(&c, disk) + if e != nil { + return e + } + sources = append(sources, p) + } + for _, source := range sources { + size, e := measureTransferDisk(ctx, source) + if e != nil { + return e + } + measured += size + if measured > transfer.MaxExpandedBytes { + return fmt.Errorf("flattened QCOW2 payload exceeds 64 GiB archive limit") + } + } + if err = transfer.EnsureSpace(dir, measured*2); err != nil { + return err + } + manifest.BootProfile = "linux" + if c.Template == "standalone-windows" || IsWindowsImage(c.Template) { + manifest.BootProfile = "windows" + } else if c.ManualInstall || c.Template == "standalone-manual" { + manifest.BootProfile = "manual" + } + manifest.Files = []transfer.File{{Name: "disks/system.qcow2", Role: "system", Format: "qcow2"}} + if err = flattenTransferDisk(ctx, c.DiskImage, filepath.Join(dir, "disks", "system.qcow2")); err != nil { + return err + } + for index, d := range c.DataDisks { + p, e := config.DataDiskPath(&c, d) + if e != nil { + return e + } + name := fmt.Sprintf("disks/data-%d.qcow2", index) + if err = flattenTransferDisk(ctx, p, filepath.Join(dir, filepath.FromSlash(name))); err != nil { + return err + } + manifest.Files = append(manifest.Files, transfer.File{Name: name, Role: "data", DiskID: d.ID, Format: "qcow2"}) + } + return nil +} + +func measureTransferDisk(ctx context.Context, p string) (int64, error) { + output, err := exec.CommandContext(ctx, "qemu-img", "measure", "--output=json", "-O", "qcow2", p).CombinedOutput() + if err != nil { + return 0, fmt.Errorf("measure flattened disk capacity: %w: %s", err, strings.TrimSpace(string(output))) + } + var measured struct { + Required int64 `json:"required"` + } + if err = json.Unmarshal(output, &measured); err != nil { + return 0, err + } + if measured.Required <= 0 { + return 0, fmt.Errorf("invalid flattened disk capacity estimate") + } + return measured.Required, nil +} + +// Reset both cloud and manually installed Linux network identity offline. A +// fresh MAC alone is insufficient for netplan files matching the old MAC. +// libguestfs runs inside its appliance; guest links cannot escape to the host. +func resetTransferGuest(ctx context.Context, c *config.Container, name string) (result error) { + if _, err := exec.LookPath("virt-customize"); err != nil { + return fmt.Errorf("virt-customize (libguestfs-tools) is required to reset cloned guest network identity") + } + disks := []string{"--format=qcow2", "-a", c.DiskImage} + for _, d := range c.DataDisks { + if d.Attached { + disks = append(disks, "-a", d.Path) + } + } + inspectionArgs := append([]string{"--no-applications", "--no-icon"}, disks...) + output, err := exec.CommandContext(ctx, "virt-inspector", inspectionArgs...).CombinedOutput() + if err != nil { + return fmt.Errorf("inspect cloned guest OS: %w: %s", err, strings.TrimSpace(string(output))) + } + var inspected struct { + Systems []struct { + Name string `xml:"name"` + Root string `xml:"root"` + Mountpoints []struct { + Path string `xml:",chardata"` + } `xml:"mountpoints>mountpoint"` + } `xml:"operatingsystem"` + } + if err = xml.Unmarshal(output, &inspected); err != nil || len(inspected.Systems) != 1 { + return fmt.Errorf("backup must contain one inspectable Linux or Windows installation") + } + operatingSystem := inspected.Systems[0].Name + if operatingSystem != "linux" && operatingSystem != "windows" { + return fmt.Errorf("unsupported cloned guest OS: %s", operatingSystem) + } + if operatingSystem == "linux" { + rootMounted := false + for _, mount := range inspected.Systems[0].Mountpoints { + rootMounted = rootMounted || strings.TrimSpace(mount.Path) == "/" + } + if !rootMounted { + restore, err := prepareTransferRootMount(ctx, disks, inspected.Systems[0].Root) + if restore != nil { + defer func() { result = errors.Join(result, restore()) }() + } + if err != nil { + return err + } + } + } + args := append(disks, "--no-network") + if operatingSystem == "windows" { + command := `powershell -NoProfile -ExecutionPolicy Bypass -Command "Get-NetAdapter | ForEach-Object { Get-NetIPAddress -InterfaceIndex $_.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object PrefixOrigin -eq 'Manual' | Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue; Set-NetIPInterface -InterfaceIndex $_.ifIndex -Dhcp Enabled -ErrorAction Stop; Set-DnsClientServerAddress -InterfaceIndex $_.ifIndex -ResetServerAddresses -ErrorAction Stop }"` + args = append(args, "--firstboot-command", command) + } else { + script := `set -eu +rm -rf /var/lib/cloud/instances /var/lib/cloud/instance /var/lib/cloud/data /var/lib/dhcp/* /var/lib/NetworkManager/*lease* +rm -rf /var/lib/dhclient/* /var/lib/systemd/network/* +rm -f /etc/dhcpcd.duid /var/lib/dhcpcd/duid /var/lib/NetworkManager/secret_key +rm -f /etc/ssh/ssh_host_* /etc/udev/rules.d/70-persistent-net.rules +: > /etc/machine-id +rm -f /var/lib/dbus/machine-id +mkdir -p /etc/network/interfaces.d /etc/systemd/network +printf 'auto lo\niface lo inet loopback\nauto eth0\niface eth0 inet dhcp\n' > /etc/network/interfaces +find /etc/network/interfaces.d -maxdepth 1 -type f -delete +find /etc/systemd/network -maxdepth 1 -type f -delete +if [ -d /etc/sysconfig/network-scripts ]; then find /etc/sysconfig/network-scripts -maxdepth 1 -type f -name 'ifcfg-*' ! -name 'ifcfg-lo' -delete; fi +printf '[Match]\nName=eth* en*\n[Network]\nDHCP=ipv4\n' > /etc/systemd/network/10-clicd-clone.network +if [ -d /etc/netplan ]; then rm -f /etc/netplan/*.yaml /etc/netplan/*.yml; printf 'network:\n version: 2\n ethernets:\n clicd:\n match:\n name: "en*"\n dhcp4: true\n eth:\n match:\n name: "eth*"\n dhcp4: true\n' > /etc/netplan/99-clicd-clone.yaml; chmod 600 /etc/netplan/99-clicd-clone.yaml; fi +if [ -d /etc/NetworkManager/system-connections ]; then rm -f /etc/NetworkManager/system-connections/*; printf '[connection]\nid=clicd-clone\ntype=ethernet\nautoconnect=true\n[ipv4]\nmethod=auto\n[ipv6]\nmethod=disabled\n' > /etc/NetworkManager/system-connections/clicd-clone.nmconnection; chmod 600 /etc/NetworkManager/system-connections/clicd-clone.nmconnection; fi +mkdir -p /etc/cloud/cloud.cfg.d +printf 'network: {config: disabled}\n' > /etc/cloud/cloud.cfg.d/99-clicd-clone-network.cfg +touch /etc/cloud/cloud-init.disabled +if command -v ssh-keygen >/dev/null 2>&1; then ssh-keygen -A; fi +` + args = append(args, "--hostname", name, "--run-command", script) + } + output, err = exec.CommandContext(ctx, "virt-customize", args...).CombinedOutput() + if err != nil { + return fmt.Errorf("reset guest identity before restore: %w: %s", err, strings.TrimSpace(string(output))) + } + return nil +} + +// Old libguestfs releases can identify a PARTUUID-rooted Linux installation but +// omit / from its mount list. Edit only the new clone through explicit appliance +// mounts, then restore its original fstab even if customization is interrupted. +func prepareTransferRootMount(ctx context.Context, disks []string, root string) (func() error, error) { + if !regexp.MustCompile(`^/dev/[a-zA-Z0-9_./+-]+$`).MatchString(root) || strings.Contains(root, "..") { + return nil, fmt.Errorf("unsupported inspected guest root device") + } + for _, tool := range []string{"virt-filesystems", "virt-cat", "virt-edit"} { + if _, err := exec.LookPath(tool); err != nil { + return nil, fmt.Errorf("%s (libguestfs tools) is required to mount this cloned guest root", tool) + } + } + args := append(append([]string(nil), disks...), "--filesystems", "--long", "--uuid", "--csv") + output, err := transferCommandOutput(ctx, "virt-filesystems", args, 1<<20) + if err != nil { + return nil, err + } + uuid, err := transferRootUUID(output, root) + if err != nil { + return nil, err + } + mountArgs := append(append([]string(nil), disks...), "-m", root+":/") + read := func(ctx context.Context) ([]byte, error) { + return transferCommandOutput(ctx, "virt-cat", append(append([]string(nil), mountArgs...), "/etc/fstab"), 16<<10) + } + original, err := read(ctx) + if err != nil { + return nil, err + } + if len(original) == 0 || bytes.IndexByte(original, 0) >= 0 { + return nil, fmt.Errorf("cloned guest fstab is empty or invalid; cannot safely repair its root mount") + } + edit := func(ctx context.Context, expression string) error { + _, err := transferCommandOutput(ctx, "virt-edit", append(append([]string(nil), mountArgs...), "/etc/fstab", "-e", expression), 16<<10) + return err + } + restore := func() error { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute) + defer cancel() + if err := edit(cleanupCtx, `$_ = $. == 1 ? pack("H*","`+hex.EncodeToString(original)+`") : ""`); err != nil { + return fmt.Errorf("restore cloned guest fstab: %w", err) + } + actual, err := read(cleanupCtx) + if err != nil || !bytes.Equal(actual, original) { + return fmt.Errorf("cloned guest fstab was not restored exactly: %v", err) + } + return nil + } + prefix := "# CLICD temporary appliance root mount\nUUID=" + uuid + " / auto defaults 0 0\n" + err = edit(ctx, `$_ = pack("H*","`+hex.EncodeToString([]byte(prefix))+`") . $_ if $. == 1`) + return restore, err +} + +func transferRootUUID(output []byte, root string) (string, error) { + rows, err := csv.NewReader(bytes.NewReader(output)).ReadAll() + if err != nil || len(rows) < 2 { + return "", fmt.Errorf("cannot read cloned guest filesystem UUIDs") + } + nameColumn, uuidColumn := -1, -1 + for i, name := range rows[0] { + if name == "Name" { + nameColumn = i + } + if name == "UUID" { + uuidColumn = i + } + } + if nameColumn >= 0 && uuidColumn >= 0 { + for _, row := range rows[1:] { + if row[nameColumn] == root && regexp.MustCompile(`^[a-zA-Z0-9-]{1,128}$`).MatchString(row[uuidColumn]) { + return row[uuidColumn], nil + } + } + } + return "", fmt.Errorf("inspected guest root has no usable filesystem UUID") +} + +func transferCommandOutput(ctx context.Context, tool string, args []string, limit int64) ([]byte, error) { + command := exec.CommandContext(ctx, tool, args...) + var stderr bytes.Buffer + command.Stderr = &stderr + stdout, err := command.StdoutPipe() + if err != nil { + return nil, err + } + if err = command.Start(); err != nil { + return nil, err + } + output, readErr := io.ReadAll(io.LimitReader(stdout, limit+1)) + if readErr != nil || int64(len(output)) > limit { + _ = command.Process.Kill() + _ = command.Wait() + return nil, fmt.Errorf("%s output is invalid or exceeds the safety limit", tool) + } + if err = command.Wait(); err != nil { + return nil, fmt.Errorf("%s: %w: %s", tool, err, strings.TrimSpace(stderr.String())) + } + return output, nil +} + +func (m *Manager) RestoreTransfer(ctx context.Context, manifest *transfer.Manifest, dir, name, poolID string, assignNAT bool, portCount int) (_ *config.Container, err error) { + transfer.CreationMu.Lock() + defer transfer.CreationMu.Unlock() + if err = transfer.ValidateManifest(manifest); err != nil { + return nil, err + } + if err = ValidateTransfer(ctx, dir, manifest); err != nil { + return nil, err + } + if !config.IsValidContainerName(name) || config.FindContainerByName(name) != nil { + return nil, fmt.Errorf("invalid or already used instance name") + } + var required int64 + for _, f := range manifest.Files { + required += f.Size + } + pool, err := config.SelectStoragePoolForContent(config.StorageContentKVM, poolID, required) + if err != nil { + return nil, err + } + if poolID != "" && pool.ID != poolID { + return nil, fmt.Errorf("requested KVM storage pool is unavailable or lacks capacity") + } + c := transfer.NewIdentity(manifest.Container, name, pool.ID) + sourceDataDisks := c.DataDisks + c.DataDisks = nil + c.KVMName = fmt.Sprintf("vm-%d", c.ID) + c.MACAddress = randomMAC() + c.Template = "standalone-" + manifest.BootProfile + c.ManualInstall = manifest.BootProfile == "manual" + c.InstallationMediaImageID = "" + c.InstallationMediaBoot = "disk" + m = NewManagerForStoragePool(pool.ID) + c.StoragePath = m.instanceDir(c.KVMName) + c.DiskImage = filepath.Join(c.StoragePath, "disk.qcow2") + if _, e := os.Lstat(c.StoragePath); !os.IsNotExist(e) { + return nil, fmt.Errorf("new instance storage path already exists") + } + if err = os.MkdirAll(c.StoragePath, 0755); err != nil { + return nil, err + } + committed := false + defer func() { + if !committed { + _ = undefineDomain(c.KVMName) + _ = os.RemoveAll(c.StoragePath) + _ = m.CleanupDataDisks(&c) + } + }() + for _, file := range manifest.Files { + if file.Role == "system" { + if err = flattenTransferDisk(ctx, filepath.Join(dir, filepath.FromSlash(file.Name)), c.DiskImage); err != nil { + return nil, err + } + } + } + for _, sourceDisk := range sourceDataDisks { + oldID := sourceDisk.ID + d := sourceDisk + d.ID = config.NewDataDiskID() + d.StoragePoolID = pool.ID + d.Path = "" + d.Format = "qcow2" + d.CreatedAt = time.Now().UTC().Format(time.RFC3339) + p, e := config.DataDiskPath(&c, d) + if e != nil { + return nil, e + } + d.Path = p + c.DataDisks = append(c.DataDisks, d) + for _, file := range manifest.Files { + if file.Role == "data" && file.DiskID == oldID { + if err = flattenTransferDisk(ctx, filepath.Join(dir, filepath.FromSlash(file.Name)), p); err != nil { + return nil, err + } + } + } + } + if err = resetTransferGuest(ctx, &c, name); err != nil { + return nil, err + } + if err = m.validateHost(c.Template, true); err != nil { + return nil, err + } + if assignNAT { + if portCount < 1 || portCount > 64 { + return nil, fmt.Errorf("port mapping quota must be between 1 and 64") + } + cfg := lxc.ContainerConfig{Name: name, Virtualization: "kvm", PortMappingCount: portCount} + port, release, e := lxc.ReserveCreateNATPorts(cfg) + if e != nil { + return nil, e + } + defer release() + c.SSHPort = port + c.PortMappingLimit = portCount + c.PortMappings = lxc.SetupDefaultPortMappings(port) + if manifest.BootProfile == "windows" { + c.PortMappings[0].ContainerPort = 3389 + c.PortMappings[0].Description = "RDP" + } + } else { + c.PortMappingLimit = 0 + } + if err = m.ensureDomainDefinition(&c); err != nil { + return nil, err + } + if err = ctx.Err(); err != nil { + return nil, err + } + config.AddContainer(c) + if err = config.SaveConfig(); err != nil { + config.RemoveContainer(c.ID) + return nil, err + } + committed = true + return &c, nil +} diff --git a/backend/internal/kvm/transfer_root_mount_test.go b/backend/internal/kvm/transfer_root_mount_test.go new file mode 100644 index 0000000..9def07f --- /dev/null +++ b/backend/internal/kvm/transfer_root_mount_test.go @@ -0,0 +1,146 @@ +package kvm + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "clicd/internal/config" +) + +func TestTransferRootUUIDHandlesCSVAndRejectsUnsafeOrMissingRoot(t *testing.T) { + valid := "Name,Type,VFS,Label,Size,Parent,UUID\n/dev/sdb,filesystem,ext4,\"label,with-comma\",42,,data-uuid\n/dev/sda1,filesystem,ext4,,42,,root-uuid\n" + if uuid, err := transferRootUUID([]byte(valid), "/dev/sda1"); err != nil || uuid != "root-uuid" { + t.Fatalf("root UUID: %q %v", uuid, err) + } + for _, invalid := range []string{strings.ReplaceAll(valid, "root-uuid", "bad uuid"), "Name,UUID\n/dev/sda1\n", "Name,UUID\n/dev/sdb,data-uuid\n"} { + if _, err := transferRootUUID([]byte(invalid), "/dev/sda1"); err == nil { + t.Fatal("accepted missing or unsafe root UUID") + } + } +} + +func resetTransferFixture(t *testing.T, osName string, rootMapped bool) (config.Container, string, string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("fake libguestfs tools use POSIX executables") + } + if _, err := exec.LookPath("python3"); err != nil { + t.Skip("python3 is needed for fake libguestfs tools") + } + dir := t.TempDir() + fstab := filepath.Join(dir, "fstab") + if err := os.WriteFile(fstab, []byte("PARTUUID=original / ext4 defaults 0 1\nUUID=data /data/qa ext4 defaults,nofail 0 2\n"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("KVM_FSTAB", fstab) + t.Setenv("KVM_EDIT_LOG", filepath.Join(dir, "edit.log")) + t.Setenv("KVM_CUSTOMIZE_LOG", filepath.Join(dir, "customize.log")) + t.Setenv("KVM_CUSTOMIZE_STARTED", filepath.Join(dir, "started")) + t.Setenv("KVM_EXPECT_TEMP_ROOT", "1") + if rootMapped || osName == "windows" { + t.Setenv("KVM_EXPECT_TEMP_ROOT", "0") + } + mountpoints := "/data/qa" + if rootMapped { + mountpoints += "/" + } + writeKVMTestCommand(t, dir, "virt-inspector", "printf '%s' \"$KVM_INSPECTION\"\n") + t.Setenv("KVM_INSPECTION", "/dev/sda1"+osName+""+mountpoints+"") + writeKVMTestCommand(t, dir, "virt-filesystems", "printf 'Name,Type,VFS,Label,Size,Parent,UUID\\n/dev/sda1,filesystem,ext4,,42,,root-uuid\\n'\n") + writeKVMTestCommand(t, dir, "virt-cat", "cat \"$KVM_FSTAB\"\n") + for name, script := range map[string]string{ + "virt-edit": `import os,sys,re,pathlib +p=pathlib.Path(os.environ['KVM_FSTAB']) +log=pathlib.Path(os.environ['KVM_EDIT_LOG']) +count=len(log.read_text().splitlines()) if log.exists() else 0 +with log.open('a') as f:f.write(repr(sys.argv[1:])+'\n') +if count and os.environ.get('KVM_RESTORE_FAIL')=='1':sys.exit(21) +expression=sys.argv[sys.argv.index('-e')+1] +data=bytes.fromhex(re.search(r'pack\("H\*","([0-9a-f]+)"\)',expression).group(1)) +p.write_bytes(data+p.read_bytes() if ' . $_ if' in expression else data) +`, + "virt-customize": `import os,sys,pathlib,time +pathlib.Path(os.environ['KVM_CUSTOMIZE_LOG']).write_text(repr(sys.argv[1:])) +if os.environ['KVM_EXPECT_TEMP_ROOT']=='1': + assert b'UUID=root-uuid / auto defaults 0 0\n' in pathlib.Path(os.environ['KVM_FSTAB']).read_bytes() +pathlib.Path(os.environ['KVM_CUSTOMIZE_STARTED']).touch() +mode=os.environ.get('KVM_CUSTOMIZE_MODE','pass') +if mode=='wait':time.sleep(30) +if mode=='fail':print('simulated customization failure',file=sys.stderr);sys.exit(37) +`, + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte("#!/usr/bin/env python3\n"+script), 0755); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + c := config.Container{DiskImage: filepath.Join(dir, "system.qcow2"), DataDisks: []config.DataDisk{{Path: filepath.Join(dir, "attached.qcow2"), Attached: true}, {Path: filepath.Join(dir, "detached.qcow2")}}} + return c, fstab, dir +} + +func TestResetTransferGuestRestoresPARTUUIDFstabAfterSuccessFailureAndCancellation(t *testing.T) { + for _, mode := range []string{"pass", "fail", "wait"} { + t.Run(mode, func(t *testing.T) { + c, fstab, dir := resetTransferFixture(t, "linux", false) + original, _ := os.ReadFile(fstab) + t.Setenv("KVM_CUSTOMIZE_MODE", mode) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if mode == "wait" { + go func() { + for ctx.Err() == nil { + if _, err := os.Stat(filepath.Join(dir, "started")); err == nil { + cancel() + return + } + time.Sleep(5 * time.Millisecond) + } + }() + } + err := resetTransferGuest(ctx, &c, "new-name") + if (err == nil) != (mode == "pass") { + t.Fatalf("customization %s: %v", mode, err) + } + restored, _ := os.ReadFile(fstab) + if string(restored) != string(original) { + t.Fatal("original fstab was not restored exactly") + } + edits, _ := os.ReadFile(filepath.Join(dir, "edit.log")) + if strings.Count(string(edits), "\n") != 2 || !strings.Contains(string(edits), "'/dev/sda1:/'") { + t.Fatal("repair/restore did not use explicit appliance root mounts") + } + command, _ := os.ReadFile(filepath.Join(dir, "customize.log")) + if !strings.Contains(string(command), "attached.qcow2") || strings.Contains(string(command), "detached.qcow2") { + t.Fatal("customization attached an incorrect data disk inventory") + } + }) + } +} + +func TestResetTransferGuestWindowsAndMappedLinuxDoNotEditFstab(t *testing.T) { + for _, osName := range []string{"linux", "windows"} { + t.Run(osName, func(t *testing.T) { + c, _, dir := resetTransferFixture(t, osName, true) + if err := resetTransferGuest(context.Background(), &c, "new-name"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "edit.log")); !os.IsNotExist(err) { + t.Fatal("edited fstab although an explicit repair was unnecessary") + } + }) + } +} + +func TestResetTransferGuestCannotSucceedAfterFstabRestorationFailure(t *testing.T) { + c, _, _ := resetTransferFixture(t, "linux", false) + t.Setenv("KVM_RESTORE_FAIL", "1") + if err := resetTransferGuest(context.Background(), &c, "new-name"); err == nil || !strings.Contains(err.Error(), "restore cloned guest fstab") { + t.Fatalf("failed restoration was reported as success: %v", err) + } +} diff --git a/backend/internal/kvm/transfer_test.go b/backend/internal/kvm/transfer_test.go new file mode 100644 index 0000000..0e01c5c --- /dev/null +++ b/backend/internal/kvm/transfer_test.go @@ -0,0 +1,83 @@ +package kvm + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "clicd/internal/config" +) + +func TestStandaloneDomainDoesNotRequireDeletedTemplateOrSeed(t *testing.T) { + previous := config.AppConfig + config.AppConfig = &config.ClicdConfig{} + defer func() { config.AppConfig = previous }() + for _, profile := range []string{"linux", "manual", "windows"} { + t.Run(profile, func(t *testing.T) { + c := config.Container{ID: 77, UUID: "independent-77", KVMName: "vm-77", Virtualization: "kvm", Standalone: true, Template: "standalone-" + profile, DiskImage: "/owned/independent/disk.qcow2", MACAddress: "52:54:00:00:11:22", VCPU: 1, RAMMB: 512, DiskGB: 4} + xml, err := NewManager().containerDomainXML(&c) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(xml, c.DiskImage) || strings.Contains(xml, "seed.iso") || strings.Contains(xml, "unattend.iso") || strings.Contains(xml, "device='cdrom'") { + t.Fatal("standalone domain still references provisioning media") + } + if err = validateProvisioningTools(c.Template, true); err != nil { + t.Fatal("standalone still requires original provisioning tools") + } + }) + } +} + +func TestFlattenedBackupSurvivesRemovalOfQCOWBackingFile(t *testing.T) { + if _, err := exec.LookPath("qemu-img"); err != nil { + t.Skip("qemu-img integration runs on Linux validation host") + } + ctx := context.Background() + dir := t.TempDir() + base := filepath.Join(dir, "base.qcow2") + source := filepath.Join(dir, "source.qcow2") + flat := filepath.Join(dir, "independent.qcow2") + run := func(name string, args ...string) { + t.Helper() + if output, err := exec.Command(name, args...).CombinedOutput(); err != nil { + t.Fatalf("%s: %v %s", name, err, output) + } + } + run("qemu-img", "create", "-f", "qcow2", base, "128G") + if _, err := exec.LookPath("qemu-io"); err == nil { + run("qemu-io", "-c", "write -P 0x5a 0 4096", base) + } + run("qemu-img", "create", "-f", "qcow2", "-F", "qcow2", "-b", base, source) + if required, err := measureTransferDisk(ctx, source); err != nil || required >= 1<<30 { + t.Fatalf("sparse 128GB disk confused with physical capacity: required=%d err=%v", required, err) + } + if err := validateTransferDisk(ctx, source); err == nil { + t.Fatal("portable disk validation accepted external backing dependency") + } + if err := flattenTransferDisk(ctx, source, flat); err != nil { + t.Fatal(err) + } + if err := os.Remove(base); err != nil { + t.Fatal(err) + } + if err := os.Remove(source); err != nil { + t.Fatal(err) + } + if err := validateTransferDisk(ctx, flat); err != nil { + t.Fatal("flattened disk depends on deleted source", err) + } + if _, err := exec.LookPath("qemu-io"); err == nil { + run("qemu-io", "-r", "-c", "read -P 0x5a 0 4096", flat) + } +} + +func TestManualDiskTakesExplicitProvisioningMode(t *testing.T) { + image := Image{ID: "custom-preinstalled", Distro: "windows", Provisioner: "manual-disk"} + if !image.IsManualDisk() || image.IsManualISO() { + t.Fatal("manual preinstalled disk metadata lost") + } +} diff --git a/backend/internal/lxc/disks.go b/backend/internal/lxc/disks.go new file mode 100644 index 0000000..ca6f146 --- /dev/null +++ b/backend/internal/lxc/disks.go @@ -0,0 +1,700 @@ +package lxc + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "clicd/internal/config" +) + +var dataDiskMu sync.Mutex + +const dataDiskMarker = "# clicd data disk " + +func runDiskCommand(ctx context.Context, name string, args ...string) error { + out, err := exec.CommandContext(ctx, name, args...).CombinedOutput() + if err != nil { + return fmt.Errorf("%s failed: %w: %s", name, err, strings.TrimSpace(string(out))) + } + return nil +} +func (m *Manager) requireDiskStopped(c *config.Container) error { + out, err := exec.Command("lxc-info", "-n", c.LxcName(), "-sH").Output() + if err != nil { + return fmt.Errorf("cannot inspect container state: %w", err) + } + if strings.TrimSpace(string(out)) != "STOPPED" { + return fmt.Errorf("container must be fully stopped before changing disks (state %s)", strings.TrimSpace(string(out))) + } + return nil +} +func validateExt4Image(path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + var magic [2]byte + if _, err = f.ReadAt(magic[:], 1080); err != nil { + return err + } + if magic != [2]byte{0x53, 0xef} { + return fmt.Errorf("only managed ext4 loop images are supported") + } + return nil +} +func (m *Manager) systemDiskPath(c *config.Container) (string, error) { + dir := filepath.Join(m.LxcPath, c.LxcName()) + resolved, err := filepath.EvalSymlinks(dir) + if err != nil { + return "", err + } + base, _ := filepath.Abs(m.LxcPath) + abs, _ := filepath.Abs(resolved) + relative, _ := filepath.Rel(base, abs) + if (relative == "." || strings.HasPrefix(relative, "..") || filepath.IsAbs(relative)) && !lxcStorageTargetAllowed(abs) { + return "", fmt.Errorf("rootfs is not in managed storage") + } + image := filepath.Join(resolved, "rootfs.img") + info, err := os.Lstat(image) + if err != nil { + return "", fmt.Errorf("rootfs layout has no managed loop image; quota/directory resizing is not supported: %w", err) + } + if !info.Mode().IsRegular() { + return "", fmt.Errorf("rootfs image must be a regular file") + } + if err = validateExt4Image(image); err != nil { + return "", err + } + return image, nil +} +func rawDiskInfo(path string) (float64, int64, error) { + info, err := os.Stat(path) + if err != nil { + return 0, 0, err + } + if !info.Mode().IsRegular() { + return 0, 0, fmt.Errorf("disk must be a regular file") + } + out, err := exec.Command("du", "-B1", "--", path).Output() + if err != nil { + return 0, 0, err + } + fields := strings.Fields(string(out)) + if len(fields) == 0 { + return 0, 0, fmt.Errorf("cannot inspect allocated disk space") + } + allocated, err := strconv.ParseInt(fields[0], 10, 64) + return float64(info.Size()) / (1 << 30), allocated, err +} +func (m *Manager) GetDisks(ctx context.Context, id int) (config.DiskInventory, error) { + stored := config.FindContainer(id) + if stored == nil || stored.IsKVM() { + return config.DiskInventory{}, fmt.Errorf("LXC container not found") + } + c := *stored + result := config.DiskInventory{System: config.DiskInfo{ID: "system", Name: "Root filesystem", SizeGB: c.DiskGB, Format: "raw/ext4", Target: "rootfs", StoragePoolID: c.StoragePoolID, Attached: true, CanResize: true}, DataDisks: []config.DiskInfo{}} + result.Limits.MaxDataDisks = config.MaxDataDisks + if err := m.requireDiskStopped(&c); err != nil { + result.Reason = err.Error() + } else { + result.CanEdit = true + } + path, err := m.systemDiskPath(&c) + if err != nil { + result.System.CanResize = false + result.System.Error = err.Error() + } else { + result.System.SizeGB, result.System.AllocatedBytes, err = rawDiskInfo(path) + if err != nil { + result.System.Error = err.Error() + } + } + for _, d := range c.DataDisks { + entry := config.PublicDataDisk(d) + path, err := config.DataDiskPath(&c, d) + if err == nil { + entry.SizeGB, entry.AllocatedBytes, err = rawDiskInfo(path) + } + if err != nil { + entry.Error = err.Error() + entry.CanResize = false + } + result.DataDisks = append(result.DataDisks, entry) + } + return result, nil +} +func diskMountPoint(path string) string { return path + ".mount" } + +// LXC resolves bind sources after entering an unprivileged user namespace. +// Permit traversal of managed ancestors without exposing directory listings or +// the raw image (0600). Never change the storage pool or its parent directories. +func prepareDataDiskDirectories(c *config.Container, d config.DataDisk) (string, error) { + image, err := config.DataDiskPath(c, d) + if err != nil { + return "", err + } + pool := config.StoragePoolByID(d.StoragePoolID) + relative, err := filepath.Rel(pool.Path, filepath.Dir(image)) + if err != nil || relative == "." || strings.HasPrefix(relative, "..") || filepath.IsAbs(relative) { + return "", fmt.Errorf("invalid managed data disk directory") + } + cursor := pool.Path + for _, part := range strings.Split(relative, string(os.PathSeparator)) { + cursor = filepath.Join(cursor, part) + if err = os.Mkdir(cursor, 0711); err != nil && !os.IsExist(err) { + return "", err + } + info, err := os.Lstat(cursor) + if err != nil { + return "", err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("managed disk directories cannot contain symlinks") + } + if _, uid, _, ok := fileStatFields(info); ok && uid != os.Geteuid() { + return "", fmt.Errorf("managed disk directory is owned by another host user") + } + if err = os.Chmod(cursor, 0711); err != nil { + return "", err + } + } + return image, nil +} + +func imageMountedAt(image, target string) (bool, error) { + if info, err := os.Lstat(target); os.IsNotExist(err) { + return false, nil + } else if err != nil { + return false, err + } else if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return false, fmt.Errorf("disk mountpoint must be a managed directory without symlinks") + } + targetValue, err := findmntValue(target, "TARGET") + if err != nil { + return false, err + } + if !sameFilesystemPath(targetValue, target) { + return false, nil + } + source, err := findmntValue(target, "SOURCE") + if err != nil { + return false, err + } + source = strings.Split(source, "[")[0] + backing, err := exec.Command("losetup", "-n", "-O", "BACK-FILE", source).Output() + if err != nil { + return false, fmt.Errorf("cannot verify loop-device ownership") + } + if !sameFilesystemPath(strings.TrimSpace(string(backing)), image) { + return false, fmt.Errorf("mountpoint is occupied by a different filesystem") + } + return true, nil +} +func unmountOwnedImage(ctx context.Context, image, target string) error { + mounted, err := imageMountedAt(image, target) + if err != nil { + return err + } + if mounted { + return runDiskCommand(ctx, "umount", target) + } + return nil +} +func requireImageNotAttached(ctx context.Context, path string) error { + out, err := exec.CommandContext(ctx, "losetup", "-j", path).Output() + if err != nil { + return fmt.Errorf("cannot inspect loop-device ownership: %w", err) + } + if strings.TrimSpace(string(out)) != "" { + return fmt.Errorf("disk image is still attached to a loop device; unmount it before changing or deleting it") + } + return nil +} +func safeDataGuestDirectory(root, guest string) error { + if err := config.ValidateGuestMountPath(guest); err != nil { + return err + } + cursor := root + for _, part := range strings.Split(strings.TrimPrefix(guest, "/"), "/") { + cursor = filepath.Join(cursor, part) + info, err := os.Lstat(cursor) + if os.IsNotExist(err) { + if err = os.Mkdir(cursor, 0755); err != nil { + return err + } + continue + } + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("guest mount path cannot cross symlinks or non-directories") + } + } + entries, err := os.ReadDir(cursor) + if err != nil { + return err + } + if len(entries) > 0 { + return fmt.Errorf("guest mount path %s is not empty; refusing to hide existing data", guest) + } + return nil +} +func (m *Manager) syncDataDiskConfig(c *config.Container) error { + filename := filepath.Join(m.LxcPath, c.LxcName(), "config") + content, err := os.ReadFile(filename) + if err != nil { + return err + } + next := []string{} + skip := false + for _, line := range strings.Split(string(content), "\n") { + if strings.HasPrefix(strings.TrimSpace(line), dataDiskMarker) { + skip = true + continue + } + if skip && strings.HasPrefix(strings.TrimSpace(line), "lxc.mount.entry") { + skip = false + continue + } + skip = false + next = append(next, line) + } + for _, d := range c.DataDisks { + if !d.Attached { + continue + } + if err := config.ValidateGuestMountPath(d.MountPath); err != nil { + return err + } + path, err := config.DataDiskPath(c, d) + if err != nil { + return err + } + source := diskMountPoint(path) + if strings.ContainsAny(source, " \t\n\r") { + return fmt.Errorf("data disk storage paths cannot contain whitespace") + } + next = append(next, dataDiskMarker+d.ID, fmt.Sprintf("lxc.mount.entry = %s %s none bind,create=dir 0 0", source, strings.TrimPrefix(d.MountPath, "/"))) + } + return os.WriteFile(filename, []byte(strings.Join(next, "\n")), 0644) +} + +// PrepareDataDisks mounts sources outside rootfs and only bind-mounts empty, +// symlink-free guest targets. It is also used by full backup restore. +func (m *Manager) PrepareDataDisks(c *config.Container) error { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + return m.prepareDataDisks(c) +} +func (m *Manager) prepareDataDisks(c *config.Container) (result error) { + if len(c.DataDisks) == 0 { + return nil + } + root := filepath.Join(m.LxcPath, c.LxcName(), "rootfs") + newMounts := []string{} + defer func() { + if result != nil { + for i := len(newMounts) - 1; i >= 0; i-- { + _ = unmountOwnedImage(context.Background(), newMounts[i], diskMountPoint(newMounts[i])) + } + } + }() + for _, d := range c.DataDisks { + if !d.Attached { + continue + } + path, err := prepareDataDiskDirectories(c, d) + if err != nil { + return err + } + if err = validateExt4Image(path); err != nil { + return err + } + if err = safeDataGuestDirectory(root, d.MountPath); err != nil { + return err + } + target := diskMountPoint(path) + if err = os.MkdirAll(target, 0700); err != nil { + return err + } + mounted, err := imageMountedAt(path, target) + if err != nil { + return err + } + if !mounted { + if err = runDiskCommand(context.Background(), "mount", "-t", "ext4", "-o", "loop,nodev,nosuid", path, target); err != nil { + return err + } + newMounts = append(newMounts, path) + } + } + return m.syncDataDiskConfig(c) +} +func (m *Manager) UnmountDataDisks(c *config.Container) error { + if len(c.DataDisks) == 0 { + return nil + } + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + if err := m.requireDiskStopped(c); err != nil { + return err + } + return m.unmountDataDisks(c) +} +func (m *Manager) unmountDataDisks(c *config.Container) error { + for _, d := range c.DataDisks { + path, err := config.DataDiskPath(c, d) + if err != nil { + return err + } + if err = unmountOwnedImage(context.Background(), path, diskMountPoint(path)); err != nil { + return err + } + } + return nil +} +func (m *Manager) persistDataDisks(previous, next config.Container) error { + filename := filepath.Join(m.LxcPath, previous.LxcName(), "config") + oldConfig, err := os.ReadFile(filename) + if err != nil { + return err + } + if err = m.syncDataDiskConfig(&next); err != nil { + return err + } + current := config.FindContainer(next.ID) + if current == nil { + return fmt.Errorf("container disappeared") + } + old := current.DataDisks + current.DataDisks = next.DataDisks + if err = config.SaveConfig(); err != nil { + current.DataDisks = old + _ = os.WriteFile(filename, oldConfig, 0644) + return err + } + return nil +} +func (m *Manager) AddDataDisk(ctx context.Context, id int, name string, sizeGB float64, poolID, mountPath string) (config.DataDisk, error) { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || stored.IsKVM() { + return config.DataDisk{}, fmt.Errorf("LXC container not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return config.DataDisk{}, err + } + if len(c.DataDisks) >= config.MaxDataDisks { + return config.DataDisk{}, fmt.Errorf("data disk limit is %d", config.MaxDataDisks) + } + if c.SnapshotScheduleEnabled { + return config.DataDisk{}, fmt.Errorf("disable scheduled snapshots before adding data disks; use full backups to include all disks") + } + bytes, err := config.DiskSizeBytes(sizeGB) + if err != nil { + return config.DataDisk{}, err + } + name = strings.TrimSpace(name) + if name == "" || utf8.RuneCountInString(name) > 80 { + return config.DataDisk{}, fmt.Errorf("disk name must contain 1 to 80 characters") + } + if err = config.ValidateGuestMountPath(mountPath); err != nil { + return config.DataDisk{}, err + } + for _, d := range c.DataDisks { + if d.MountPath == mountPath || strings.HasPrefix(d.MountPath, mountPath+"/") || strings.HasPrefix(mountPath, d.MountPath+"/") { + return config.DataDisk{}, fmt.Errorf("guest mount paths cannot overlap") + } + } + poolID = strings.TrimSpace(poolID) + pool, err := config.SelectStoragePoolForContent(config.StorageContentLXC, poolID, bytes) + if err != nil { + return config.DataDisk{}, err + } + if poolID != "" && pool.ID != poolID { + return config.DataDisk{}, fmt.Errorf("requested data disk storage pool is unavailable or lacks capacity") + } + if err = m.ensureDiskImageMounted(c.LxcName()); err != nil { + return config.DataDisk{}, err + } + if err = safeDataGuestDirectory(filepath.Join(m.LxcPath, c.LxcName(), "rootfs"), mountPath); err != nil { + return config.DataDisk{}, err + } + d := config.DataDisk{ID: config.NewDataDiskID(), Name: name, SizeGB: float64(bytes) / (1 << 30), StoragePoolID: pool.ID, Format: "raw", Target: mountPath, MountPath: mountPath, Attached: true, CreatedAt: time.Now().Format(time.RFC3339)} + d.Path, err = prepareDataDiskDirectories(&c, d) + if err != nil { + return d, err + } + f, err := os.OpenFile(d.Path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) + if err != nil { + return d, err + } + err = f.Truncate(bytes) + _ = f.Close() + if err != nil { + _ = os.Remove(d.Path) + return d, err + } + cleanup := true + defer func() { + if cleanup { + if err := unmountOwnedImage(context.Background(), d.Path, diskMountPoint(d.Path)); err == nil { + _ = os.Remove(d.Path) + } + } + }() + if err = runDiskCommand(ctx, "mkfs.ext4", "-F", d.Path); err != nil { + return d, err + } + target := diskMountPoint(d.Path) + if err = os.MkdirAll(target, 0700); err != nil { + return d, err + } + if mounted, err := imageMountedAt(d.Path, target); err != nil || mounted { + return d, fmt.Errorf("new disk mountpoint is occupied or unsafe: %v", err) + } + if err = runDiskCommand(ctx, "mount", "-t", "ext4", "-o", "loop,nodev,nosuid", d.Path, target); err != nil { + return d, err + } + uid, gid, err := unprivilegedIDMap() + if err != nil { + return d, err + } + if err = os.Chown(target, uid, gid); err != nil { + return d, err + } + if err = os.Chmod(target, 0755); err != nil { + return d, err + } + if err = unmountOwnedImage(ctx, d.Path, target); err != nil { + return d, err + } + next := c + next.DataDisks = append(append([]config.DataDisk(nil), c.DataDisks...), d) + if err = m.persistDataDisks(c, next); err != nil { + return d, err + } + cleanup = false + return d, nil +} +func growExt4Image(ctx context.Context, path string, bytes int64) error { + if err := validateExt4Image(path); err != nil { + return err + } + info, err := os.Stat(path) + if err != nil { + return err + } + if bytes < info.Size() { + return fmt.Errorf("disk shrinking is not supported; current size is %.3f GB", float64(info.Size())/(1<<30)) + } + if err = requireImageNotAttached(ctx, path); err != nil { + return err + } + out, err := exec.CommandContext(ctx, "e2fsck", "-f", "-p", path).CombinedOutput() + if err != nil { + exit, ok := err.(*exec.ExitError) + if !ok || exit.ExitCode() != 1 { + return fmt.Errorf("filesystem check failed: %v: %s", err, out) + } + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return err + } + err = f.Truncate(bytes) + _ = f.Close() + if err != nil { + return err + } + if err = runDiskCommand(ctx, "resize2fs", path); err != nil { + return fmt.Errorf("image expanded but filesystem resize failed; retry to finish safely: %w", err) + } + return nil +} +func (m *Manager) ResizeDisk(ctx context.Context, id int, diskID string, sizeGB float64) error { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || stored.IsKVM() { + return fmt.Errorf("LXC container not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return err + } + bytes, err := config.DiskSizeBytes(sizeGB) + if err != nil { + return err + } + if err = m.unmountDataDisks(&c); err != nil { + return err + } + path := "" + index := -1 + poolID := c.StoragePoolID + if diskID == "system" { + path, err = m.systemDiskPath(&c) + if err == nil { + err = unmountOwnedImage(ctx, path, filepath.Join(m.LxcPath, c.LxcName(), "rootfs")) + } + } else { + for i, d := range c.DataDisks { + if d.ID == diskID { + index = i + poolID = d.StoragePoolID + path, err = config.DataDiskPath(&c, d) + break + } + } + if index < 0 { + return fmt.Errorf("data disk not found") + } + } + if err != nil { + return err + } + info, err := os.Stat(path) + if err != nil { + return err + } + if bytes < info.Size() { + return fmt.Errorf("disk shrinking is not supported") + } + pool, err := config.SelectStoragePoolForContent(config.StorageContentLXC, poolID, bytes-info.Size()) + if err != nil { + return err + } + if poolID != "" && pool.ID != poolID { + return fmt.Errorf("disk storage pool is unavailable or lacks capacity") + } + if err = growExt4Image(ctx, path, bytes); err != nil { + return err + } + current := config.FindContainer(id) + if current == nil { + return fmt.Errorf("container disappeared") + } + if index < 0 { + current.DiskGB = float64(bytes) / (1 << 30) + } else { + for i := range current.DataDisks { + if current.DataDisks[i].ID == diskID { + current.DataDisks[i].SizeGB = float64(bytes) / (1 << 30) + } + } + } + if err = config.SaveConfig(); err != nil { + return fmt.Errorf("disk expanded but metadata save failed: %w", err) + } + return nil +} +func (m *Manager) SetDataDiskAttached(ctx context.Context, id int, diskID string, attached bool) error { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || stored.IsKVM() { + return fmt.Errorf("LXC container not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return err + } + if err := m.unmountDataDisks(&c); err != nil { + return err + } + next := c + next.DataDisks = append([]config.DataDisk(nil), c.DataDisks...) + for i, d := range next.DataDisks { + if d.ID == diskID { + if _, err := config.DataDiskPath(&c, d); err != nil { + return err + } + next.DataDisks[i].Attached = attached + return m.persistDataDisks(c, next) + } + } + return fmt.Errorf("data disk not found") +} +func (m *Manager) DeleteDataDisk(ctx context.Context, id int, diskID string) error { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || stored.IsKVM() { + return fmt.Errorf("LXC container not found") + } + c := *stored + if err := m.requireDiskStopped(&c); err != nil { + return err + } + if err := m.unmountDataDisks(&c); err != nil { + return err + } + for i, d := range c.DataDisks { + if d.ID == diskID { + path, err := config.DataDiskPath(&c, d) + if err != nil { + return err + } + if err = requireImageNotAttached(ctx, path); err != nil { + return err + } + next := c + next.DataDisks = append(append([]config.DataDisk(nil), c.DataDisks[:i]...), c.DataDisks[i+1:]...) + if err = m.persistDataDisks(c, next); err != nil { + return err + } + if err = os.Remove(path); err != nil && !os.IsNotExist(err) { + d.Attached = false + current := config.FindContainer(id) + current.DataDisks = append(current.DataDisks, d) + _ = config.SaveConfig() + return fmt.Errorf("disk detached but file deletion failed: %w", err) + } + _ = os.Remove(diskMountPoint(path)) + _ = os.Remove(filepath.Dir(path)) + return nil + } + } + return fmt.Errorf("data disk not found") +} +func (m *Manager) CleanupDataDisks(c *config.Container) error { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() + if err := m.unmountDataDisks(c); err != nil { + return err + } + paths := []string{} + for _, d := range c.DataDisks { + path, err := config.DataDiskPath(c, d) + if err != nil { + return err + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + if err = requireImageNotAttached(context.Background(), path); err != nil { + return err + } + } + paths = append(paths, path) + } + for _, path := range paths { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return err + } + _ = os.Remove(diskMountPoint(path)) + _ = os.Remove(filepath.Dir(path)) + } + return nil +} diff --git a/backend/internal/lxc/disks_test.go b/backend/internal/lxc/disks_test.go new file mode 100644 index 0000000..66f113a --- /dev/null +++ b/backend/internal/lxc/disks_test.go @@ -0,0 +1,242 @@ +package lxc + +import ( + "clicd/internal/config" + "context" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestDataMountRefusesGuestSymlinkAndNonEmptyDirectory(t *testing.T) { + root := t.TempDir() + if err := safeDataGuestDirectory(root, "/mnt/data"); err != nil { + t.Fatal(err) + } + file := filepath.Join(root, "mnt", "data", "existing") + _ = os.WriteFile(file, []byte("keep"), 0600) + if safeDataGuestDirectory(root, "/mnt/data") == nil { + t.Fatal("hid existing guest data") + } + if err := os.Symlink(t.TempDir(), filepath.Join(root, "srv")); err == nil { + if safeDataGuestDirectory(root, "/srv/escape") == nil { + t.Fatal("followed guest symlink") + } + } +} +func TestLXCStrictDiskStopAndImageShrinkGuard(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake runtime uses POSIX commands") + } + commands := t.TempDir() + _ = os.WriteFile(filepath.Join(commands, "lxc-info"), []byte("#!/bin/sh\necho FROZEN\n"), 0755) + t.Setenv("PATH", commands+string(os.PathListSeparator)+os.Getenv("PATH")) + m := NewManager() + if m.requireDiskStopped(&config.Container{ID: 1, Name: "guest"}) == nil { + t.Fatal("frozen guest was treated as stopped") + } + image := filepath.Join(t.TempDir(), "disk.img") + f, _ := os.OpenFile(image, os.O_CREATE|os.O_RDWR, 0600) + _ = f.Truncate(256 * 1024 * 1024) + _, _ = f.WriteAt([]byte{0x53, 0xef}, 1080) + _ = f.Close() + if err := growExt4Image(context.Background(), image, 128*1024*1024); err == nil || !strings.Contains(err.Error(), "shrinking") { + t.Fatalf("shrink: %v", err) + } + info, _ := os.Stat(image) + if info.Size() != 256*1024*1024 { + t.Fatal("shrink touched image") + } +} +func TestDataDiskConfigOnlyChangesManagedMountEntries(t *testing.T) { + old := config.AppConfig + t.Cleanup(func() { config.AppConfig = old }) + pool := t.TempDir() + config.AppConfig = &config.ClicdConfig{StoragePools: []config.StoragePool{{ID: "p", Path: pool, Enabled: true}}} + m := &Manager{LxcPath: t.TempDir()} + c := &config.Container{ID: 1, UUID: "test-owner", LXCName: "guest", Virtualization: config.VirtualizationLXC} + dir := filepath.Join(m.LxcPath, "guest") + _ = os.MkdirAll(dir, 0755) + file := filepath.Join(dir, "config") + original := "lxc.net.0.type = veth\nlxc.mount.entry = /host/existing srv/existing none bind 0 0\n" + _ = os.WriteFile(file, []byte(original), 0644) + d := config.DataDisk{ID: "disk-data", StoragePoolID: "p", MountPath: "/mnt/data", Attached: true} + c.DataDisks = []config.DataDisk{d} + if err := m.syncDataDiskConfig(c); err != nil { + t.Fatal(err) + } + text, _ := os.ReadFile(file) + if !strings.Contains(string(text), original) || !strings.Contains(string(text), "mnt/data none bind,create=dir") { + t.Fatal(string(text)) + } + c.DataDisks[0].Attached = false + if err := m.syncDataDiskConfig(c); err != nil { + t.Fatal(err) + } + text, _ = os.ReadFile(file) + if strings.Contains(string(text), "clicd data disk") || !strings.Contains(string(text), "/host/existing") { + t.Fatal("detach changed unrelated mounts") + } +} + +func TestDataDiskSnapshotSafetyGuards(t *testing.T) { + old := config.AppConfig + t.Cleanup(func() { config.AppConfig = old }) + config.AppConfig = &config.ClicdConfig{Containers: []config.Container{{ID: 1, UUID: "disk-owner", DataDisks: []config.DataDisk{{ID: "disk-existing", Attached: false}}}}} + m := NewManager() + if _, err := m.CreateSnapshot(1, "admin", false, 0); err == nil || !strings.Contains(err.Error(), "full backup") { + t.Fatalf("snapshot ignored data disk: %v", err) + } + if _, err := m.SetSnapshotSchedule(1, true, 24, "03:00", "admin"); err == nil || !strings.Contains(err.Error(), "full backups") { + t.Fatalf("scheduled snapshot accepted: %v", err) + } + config.AppConfig.DataDir = t.TempDir() + path := filepath.Join(config.AppConfig.DataDir, "snapshots", "legacy") + _ = os.MkdirAll(path, 0700) + config.AppConfig.Snapshots = []config.Snapshot{{ID: "legacy", ContainerID: 1, Path: path}} + if err := m.RestoreSnapshot("legacy"); err == nil || !strings.Contains(err.Error(), "full backup") { + t.Fatalf("old snapshot restored over data disk inventory: %v", err) + } +} +func TestDataImageStillAttachedCannotBeDeleted(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake runtime uses POSIX commands") + } + commands := t.TempDir() + _ = os.WriteFile(filepath.Join(commands, "losetup"), []byte("#!/bin/sh\necho '/dev/loop123: [1]:2 (/other/mount/disk.img)'\n"), 0755) + t.Setenv("PATH", commands+string(os.PathListSeparator)+os.Getenv("PATH")) + if err := requireImageNotAttached(context.Background(), "/owned/disk.img"); err == nil { + t.Fatal("accepted an attached image") + } +} + +func TestDataDiskDirectoriesAllowUserNamespaceTraversalWithoutExposingImages(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix permission bits are required") + } + old := config.AppConfig + t.Cleanup(func() { config.AppConfig = old }) + pool := t.TempDir() + if err := os.Chmod(pool, 0700); err != nil { + t.Fatal(err) + } + config.AppConfig = &config.ClicdConfig{StoragePools: []config.StoragePool{{ID: "p", Path: pool, Enabled: true}}} + c := &config.Container{UUID: "disk-owner", Virtualization: config.VirtualizationLXC} + d := config.DataDisk{ID: "disk-one", StoragePoolID: "p"} + image, err := prepareDataDiskDirectories(c, d) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(image, []byte("private raw image"), 0600); err != nil { + t.Fatal(err) + } + d.Path = image + parents := []string{} + for dir := filepath.Dir(image); dir != pool; dir = filepath.Dir(dir) { + parents = append(parents, dir) + if err = os.Chmod(dir, 0700); err != nil { + t.Fatal(err) + } + } + // Repair legacy Add and imported backup directories before the next start. + if _, err = prepareDataDiskDirectories(c, d); err != nil { + t.Fatal(err) + } + for _, dir := range parents { + info, err := os.Stat(dir) + if err != nil || info.Mode().Perm() != 0711 { + t.Fatalf("user namespace cannot traverse %s: %v %v", dir, info, err) + } + } + info, _ := os.Stat(image) + if info.Mode().Perm() != 0600 { + t.Fatal("raw disk contents became readable") + } + info, _ = os.Stat(pool) + if info.Mode().Perm() != 0700 { + t.Fatal("modified storage pool permissions") + } + outside := t.TempDir() + if err = os.Chmod(outside, 0700); err != nil { + t.Fatal(err) + } + d.ID, d.Path = "disk-symlink", "" + link := filepath.Join(filepath.Dir(filepath.Dir(image)), d.ID) + if err = os.Symlink(outside, link); err != nil { + t.Fatal(err) + } + if _, err = prepareDataDiskDirectories(c, d); err == nil { + t.Fatal("followed a symlink while repairing traversal permissions") + } + info, _ = os.Stat(outside) + if info.Mode().Perm() != 0700 { + t.Fatal("changed permissions outside the managed owner tree") + } +} + +func TestDataDiskRejectsExplicitPoolFallbackBeforeCreatingOrResizing(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake runtime uses POSIX commands") + } + old := config.AppConfig + t.Cleanup(func() { config.AppConfig = old }) + available, disabled := t.TempDir(), t.TempDir() + c := config.Container{ID: 1, UUID: "pool-test-owner", LXCName: "ct-fixture", DiskGB: 2} + config.AppConfig = &config.ClicdConfig{Containers: []config.Container{c}, StoragePools: []config.StoragePool{ + {ID: "available", Path: available, Enabled: true, ContentTypes: []string{"lxc"}}, + {ID: "disabled", Path: disabled, Enabled: false, ContentTypes: []string{"lxc"}}, + }} + commands := t.TempDir() + log := filepath.Join(commands, "unsafe.log") + write := func(name, script string) { + t.Helper() + if err := os.WriteFile(filepath.Join(commands, name), []byte("#!/bin/sh\n"+script), 0755); err != nil { + t.Fatal(err) + } + } + write("lxc-info", "echo STOPPED\n") + write("df", "printf 'Filesystem 1B-blocks Used Available Use%% Mounted\\nfake 107374182400 0 107374182400 0%% /\\n'\n") + for _, name := range []string{"mkfs.ext4", "e2fsck", "resize2fs", "mount"} { + write(name, "echo unsafe >> \"$LXC_DISK_TEST_LOG\"; exit 88\n") + } + t.Setenv("PATH", commands+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("LXC_DISK_TEST_LOG", log) + if pool, err := config.SelectStoragePoolForContent("lxc", "missing", 128<<20); err != nil || pool.ID != "available" { + t.Fatalf("fallback precondition: %v %v", pool, err) + } + m := &Manager{LxcPath: t.TempDir()} + for _, requested := range []string{"missing", "disabled"} { + if _, err := m.AddDataDisk(context.Background(), c.ID, "data", .125, requested, "/data/qa"); err == nil || !strings.Contains(err.Error(), "requested data disk storage pool") { + t.Fatalf("explicit %s pool was not rejected: %v", requested, err) + } + } + if len(config.FindContainer(c.ID).DataDisks) != 0 { + t.Fatal("failed addition mutated disk metadata") + } + if _, err := os.Stat(filepath.Join(m.LxcPath, c.LxcName())); !os.IsNotExist(err) { + t.Fatal("invalid selection touched the guest rootfs") + } + d := config.DataDisk{ID: "disk-disabled", StoragePoolID: "disabled", SizeGB: .125} + d.Path, _ = config.DataDiskPath(&c, d) + _ = os.MkdirAll(filepath.Dir(d.Path), 0755) + f, err := os.OpenFile(d.Path, os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + t.Fatal(err) + } + _ = f.Truncate(128 << 20) + _, _ = f.WriteAt([]byte{0x53, 0xef}, 1080) + _ = f.Close() + config.FindContainer(c.ID).DataDisks = []config.DataDisk{d} + if err := m.ResizeDisk(context.Background(), c.ID, d.ID, .25); err == nil || !strings.Contains(err.Error(), "disk storage pool") { + t.Fatalf("resize checked capacity on another pool: %v", err) + } + info, _ := os.Stat(d.Path) + if info.Size() != 128<<20 || config.FindContainer(c.ID).DataDisks[0].SizeGB != .125 { + t.Fatal("failed resize changed the image or metadata") + } + if _, err := os.Stat(log); !os.IsNotExist(err) { + t.Fatal("formatted, mounted or resized a disk in an unintended pool") + } +} diff --git a/backend/internal/lxc/lxc.go b/backend/internal/lxc/lxc.go index b090aa6..ca938e4 100644 --- a/backend/internal/lxc/lxc.go +++ b/backend/internal/lxc/lxc.go @@ -2178,6 +2178,9 @@ func (m *Manager) StartContainer(id int) error { } EnsureAssignedPublicIPv4s(c.PublicIPv4s) + if err := m.PrepareDataDisks(&initialIPv6); err != nil { + return err + } logFile, consoleLog, output, err := m.startLXCContainerDaemon(lxcName) if err != nil { config.UpdateContainerStatus(id, "stopped") @@ -2412,6 +2415,9 @@ func (m *Manager) StopContainer(id int) error { m.CleanPortMappings(id) CleanFirewallRules(id) m.cleanupBandwidthLimit(lxcName) + if err := m.UnmountDataDisks(&ipv6Snapshot); err != nil { + return err + } return m.cleanupIPv6NAT(&ipv6Snapshot) } @@ -2424,6 +2430,9 @@ func (m *Manager) StopContainer(id int) error { if err != nil { if strings.Contains(string(output), "not running") { config.UpdateContainerStatusAndRestore(id, "stopped", false) + if err := m.UnmountDataDisks(&ipv6Snapshot); err != nil { + return err + } return m.cleanupIPv6NAT(&ipv6Snapshot) } return fmt.Errorf("failed to stop container: %v, output: %s", err, string(output)) @@ -2431,6 +2440,9 @@ func (m *Manager) StopContainer(id int) error { config.UpdateContainerStatusAndRestore(id, "stopped", false) fmt.Printf("Container %d (%s) stopped\n", id, c.Name) + if err := m.UnmountDataDisks(&ipv6Snapshot); err != nil { + return err + } return m.cleanupIPv6NAT(&ipv6Snapshot) } @@ -2599,6 +2611,7 @@ func (m *Manager) DestroyContainer(id int) error { return fmt.Errorf("container not found: %d", id) } lxcName := c.LxcName() + diskSnapshot := *c if hasLXCIPv6(c) { c.NormalizeNetworkAssignments() for _, assignment := range c.IPv6Addresses { @@ -2672,6 +2685,9 @@ func (m *Manager) DestroyContainer(id int) error { } } + if err := m.CleanupDataDisks(&diskSnapshot); err != nil { + return err + } if !config.RemoveContainer(id) { return fmt.Errorf("container destroyed but config entry was not removed: %d", id) } @@ -3638,11 +3654,22 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co } lxcName := c.LxcName() + dataDiskSnapshot := *c // Stop the container first status, _ := m.GetContainerStatus(lxcName) if status == "running" { - m.StopContainer(id) + if err := m.StopContainer(id); err != nil { + return err + } + } + if len(c.DataDisks) > 0 { + if err := m.requireDiskStopped(c); err != nil { + return err + } + if err := m.UnmountDataDisks(c); err != nil { + return err + } } // Clean port mappings temporarily @@ -3724,6 +3751,9 @@ func (m *Manager) ReinstallContainer(id int, templateID string, authConfig ...Co config.SaveConfig() return err } + if err := m.PrepareDataDisks(&dataDiskSnapshot); err != nil { + return err + } logFile, consoleLog, output, err := m.startLXCContainerDaemon(lxcName) if err != nil { fmt.Printf("Warning: failed to start container after reinstall: %v\n", err) diff --git a/backend/internal/lxc/snapshot.go b/backend/internal/lxc/snapshot.go index 7bb884e..8767c3d 100644 --- a/backend/internal/lxc/snapshot.go +++ b/backend/internal/lxc/snapshot.go @@ -24,6 +24,9 @@ func (m *Manager) CreateSnapshot(id int, createdBy string, scheduled bool, rotat if c == nil { return config.Snapshot{}, fmt.Errorf("container not found: %d", id) } + if len(c.DataDisks) > 0 { + return config.Snapshot{}, fmt.Errorf("snapshots with data disks are not supported; use a full backup to include all disks") + } if scheduled && rotateLimit > 0 { for { existing := config.ContainerSnapshots(id) @@ -142,6 +145,9 @@ func (m *Manager) RestoreSnapshot(id string) error { if c == nil { return fmt.Errorf("container not found: %d", snapshot.ContainerID) } + if len(c.DataDisks) > 0 { + return fmt.Errorf("snapshots with data disks are not supported; use a full backup to include all disks") + } lxcName := c.LxcName() containerDir := filepath.Join(m.LxcPath, lxcName) if err := safePathUnder(containerDir, m.LxcPath); err != nil { @@ -176,10 +182,15 @@ func (m *Manager) RestoreSnapshot(id string) error { } func (m *Manager) SetSnapshotSchedule(id int, enabled bool, intervalHours int, scheduleTime string, createdBy string) (*config.Container, error) { + dataDiskMu.Lock() + defer dataDiskMu.Unlock() c := config.FindContainer(id) if c == nil { return nil, fmt.Errorf("container not found: %d", id) } + if enabled && len(c.DataDisks) > 0 { + return nil, fmt.Errorf("scheduled snapshots with data disks are not supported; use full backups to include all disks") + } if intervalHours < 24 { return nil, fmt.Errorf("snapshot schedule interval cannot be less than 24 hours") } diff --git a/backend/internal/lxc/transfer.go b/backend/internal/lxc/transfer.go new file mode 100644 index 0000000..4e249c9 --- /dev/null +++ b/backend/internal/lxc/transfer.go @@ -0,0 +1,472 @@ +package lxc + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" + + "clicd/internal/config" + "clicd/internal/transfer" +) + +func copyTransferRaw(ctx context.Context, source, target string) error { + if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil { + return err + } + output, err := exec.CommandContext(ctx, "cp", "--sparse=always", "--reflink=auto", source, target).CombinedOutput() + if err != nil { + return fmt.Errorf("copy portable filesystem: %w: %s", err, strings.TrimSpace(string(output))) + } + return validateExt4Image(target) +} + +func ValidateTransfer(ctx context.Context, dir string, manifest *transfer.Manifest) error { + if manifest.Runtime != "lxc" { + return fmt.Errorf("not an LXC backup") + } + for _, file := range manifest.Files { + if err := ctx.Err(); err != nil { + return err + } + if err := validateExt4Image(filepath.Join(dir, filepath.FromSlash(file.Name))); err != nil { + return err + } + } + return nil +} + +func (m *Manager) ExportTransfer(ctx context.Context, id int, dir string, manifest *transfer.Manifest) (err error) { + snapshotMu.Lock() + defer snapshotMu.Unlock() + stored := config.FindContainer(id) + if stored == nil || stored.IsKVM() { + return fmt.Errorf("LXC container not found") + } + c := *stored + state, err := m.GetContainerStatus(c.LxcName()) + if err != nil { + return err + } + if state != "running" && state != "stopped" { + return fmt.Errorf("container must be running or fully stopped for backup") + } + if state == "running" { + if err = m.StopContainer(id); err != nil { + return err + } + defer func() { + restartErr := m.StartContainer(id) + if restartErr == nil { + config.UpdateContainerStatusAndRestore(id, "running", c.RestoreOnHostBoot) + } + err = errors.Join(err, restartErr) + }() + } + if state, err = m.GetContainerStatus(c.LxcName()); err != nil || state != "stopped" { + return fmt.Errorf("cannot confirm stopped LXC before copying") + } + if err = m.UnmountDataDisks(&c); err != nil { + return err + } + containerDir := filepath.Join(m.LxcPath, c.LxcName()) + if _, err = m.prepareContainerForColdCopy(id, c.LxcName(), containerDir); err != nil { + return err + } + configuration, _ := os.ReadFile(filepath.Join(containerDir, "config")) + for _, item := range []struct { + kind string + destination *uint32 + }{{"u", &manifest.RootUIDBase}, {"g", &manifest.RootGIDBase}} { + expression := regexp.MustCompile(`(?m)^\s*lxc\.idmap\s*=\s*` + item.kind + `\s+0\s+(\d+)\s+`) + match := expression.FindSubmatch(configuration) + if len(match) > 1 { + value, _ := strconv.ParseUint(string(match[1]), 10, 32) + *item.destination = uint32(value) + } + } + manifest.BootProfile = "linux" + manifest.Files = []transfer.File{{Name: "disks/system.img", Role: "system", Format: "raw"}} + image := filepath.Join(containerDir, "rootfs.img") + target := filepath.Join(dir, "disks", "system.img") + if _, statErr := os.Stat(image); statErr == nil { + if err = copyTransferRaw(ctx, image, target); err != nil { + return err + } + } else if !os.IsNotExist(statErr) { + return statErr + } else { + if err = os.MkdirAll(filepath.Dir(target), 0700); err != nil { + return err + } + file, e := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if e != nil { + return e + } + e = file.Truncate(int64(c.DiskGB * (1 << 30))) + file.Close() + if e != nil { + return e + } + output, e := exec.CommandContext(ctx, "mkfs.ext4", "-F", "-d", filepath.Join(containerDir, "rootfs"), target).CombinedOutput() + if e != nil { + return fmt.Errorf("capture directory rootfs: %w: %s", e, strings.TrimSpace(string(output))) + } + } + for index, d := range c.DataDisks { + p, e := config.DataDiskPath(&c, d) + if e != nil { + return e + } + name := fmt.Sprintf("disks/data-%d.img", index) + if err = copyTransferRaw(ctx, p, filepath.Join(dir, filepath.FromSlash(name))); err != nil { + return err + } + manifest.Files = append(manifest.Files, transfer.File{Name: name, Role: "data", DiskID: d.ID, Format: "raw"}) + } + return nil +} + +func safeTransferWrite(root, name, value string, uid, gid int) error { + name = strings.TrimPrefix(name, "/") + parent := filepath.Dir(name) + cursor := root + for _, part := range strings.Split(parent, string(os.PathSeparator)) { + if part == "." { + continue + } + cursor = filepath.Join(cursor, part) + st, err := os.Lstat(cursor) + if os.IsNotExist(err) { + if err = os.Mkdir(cursor, 0755); err != nil { + return err + } + if err = os.Chown(cursor, uid, gid); err != nil { + return err + } + continue + } + if err != nil { + return err + } + if !st.IsDir() || st.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("guest configuration parent cannot be a symlink") + } + } + p := filepath.Join(root, name) + if st, err := os.Lstat(p); err == nil && st.Mode()&os.ModeSymlink != 0 { + if err = os.Remove(p); err != nil { + return err + } + } + if err := os.WriteFile(p, []byte(value), 0644); err != nil { + return err + } + return os.Chown(p, uid, gid) +} + +func rewriteTransferIDs(ctx context.Context, root string, oldUID, oldGID uint32, newUID, newGID int) error { + seen := map[[2]uint64]bool{} + return filepath.WalkDir(root, func(p string, _ os.DirEntry, e error) error { + if err := ctx.Err(); err != nil { + return err + } + if e != nil { + return e + } + st, e := os.Lstat(p) + if e != nil { + return e + } + if key, ok := transferFileID(st); ok { + if seen[key] { + return nil + } + seen[key] = true + } + _, uid, gid, ok := fileStatFields(st) + if !ok { + return fmt.Errorf("cannot inspect guest filesystem ownership") + } + originalUID, originalGID := uid, gid + if oldUID > 0 && uid >= int(oldUID) && uid < int(oldUID)+65536 { + uid = uid - int(oldUID) + newUID + } else if uid >= 0 && uid < 65536 { + uid += newUID + } + if oldGID > 0 && gid >= int(oldGID) && gid < int(oldGID)+65536 { + gid = gid - int(oldGID) + newGID + } else if gid >= 0 && gid < 65536 { + gid += newGID + } + if uid == originalUID && gid == originalGID { + return nil + } + return remapTransferOwnership(p, st, uid, gid, oldUID, oldGID, newUID, newGID) + }) +} + +func rewriteTransferDataImage(ctx context.Context, p string, oldUID, oldGID uint32, newUID, newGID int) (err error) { + if int(oldUID) == newUID && int(oldGID) == newGID { + return nil + } + root, err := os.MkdirTemp(filepath.Dir(p), ".identity-") + if err != nil { + return err + } + mounted := false + defer func() { + if mounted { + if unmountErr := exec.Command("umount", root).Run(); unmountErr != nil { + err = errors.Join(err, unmountErr) + return + } + } + _ = os.Remove(root) + }() + if output, e := exec.CommandContext(ctx, "mount", "-t", "ext4", "-o", "loop,nodev,nosuid,noexec", p, root).CombinedOutput(); e != nil { + return fmt.Errorf("mount data disk for ownership mapping: %w: %s", e, strings.TrimSpace(string(output))) + } + mounted = true + return rewriteTransferIDs(ctx, root, oldUID, oldGID, newUID, newGID) +} + +func resetTransferRoot(root, name string, uid, gid int) error { + for _, pattern := range []string{"etc/ssh/ssh_host_*", "etc/network/interfaces.d/*", "etc/netplan/*.yaml", "etc/netplan/*.yml", "etc/systemd/network/*", "etc/NetworkManager/system-connections/*", "var/lib/cloud/instances", "var/lib/cloud/instance", "var/lib/cloud/data", "var/lib/dhcp/*", "etc/udev/rules.d/70-persistent-net.rules"} { + // Resolve the parent first. Guest symlinks must never direct host file IO. + parent := filepath.Dir(filepath.Join(root, pattern)) + resolved, e := filepath.EvalSymlinks(parent) + if os.IsNotExist(e) { + continue + } + if e != nil { + return e + } + if e = safePathUnder(resolved, root); e != nil { + return e + } + matches, _ := filepath.Glob(filepath.Join(root, pattern)) + for _, p := range matches { + if e = os.RemoveAll(p); e != nil { + return e + } + } + } + files := map[string]string{ + "etc/hostname": name + "\n", "etc/machine-id": "", "etc/hosts": "127.0.0.1 localhost\n127.0.1.1 " + name + "\n", + "etc/network/interfaces": "auto lo\niface lo inet loopback\nauto eth0\niface eth0 inet dhcp\n", + "etc/systemd/network/10-clicd-clone.network": "[Match]\nName=eth* en*\n[Network]\nDHCP=ipv4\n", + "etc/cloud/cloud.cfg.d/99-clicd-clone-network.cfg": "network: {config: disabled}\n", + "etc/cloud/cloud-init.disabled": "", + ".clicd-unprivileged-shifted": "1\n", + } + if st, e := os.Stat(filepath.Join(root, "etc/netplan")); e == nil && st.IsDir() { + files["etc/netplan/99-clicd-clone.yaml"] = "network:\n version: 2\n ethernets:\n eth0:\n dhcp4: true\n" + } + if st, e := os.Stat(filepath.Join(root, "etc/NetworkManager/system-connections")); e == nil && st.IsDir() { + files["etc/NetworkManager/system-connections/clicd-clone.nmconnection"] = "[connection]\nid=clicd-clone\ntype=ethernet\ninterface-name=eth0\nautoconnect=true\n[ipv4]\nmethod=auto\n[ipv6]\nmethod=disabled\n" + } + for path, content := range files { + if err := safeTransferWrite(root, path, content, uid, gid); err != nil { + return err + } + if strings.Contains(path, ".nmconnection") || strings.HasPrefix(path, "etc/netplan/") { + if err := os.Chmod(filepath.Join(root, path), 0600); err != nil { + return err + } + } + } + if st, e := os.Stat(filepath.Join(root, "etc/ssh")); e == nil && st.IsDir() { + if err := safeTransferWrite(root, "etc/ssh/.clicd-key-parent-check", "", uid, gid); err != nil { + return err + } + _ = os.Remove(filepath.Join(root, "etc/ssh/.clicd-key-parent-check")) + for _, kind := range []string{"ed25519", "rsa"} { + p := filepath.Join(root, "etc/ssh/ssh_host_"+kind+"_key") + output, e := exec.Command("ssh-keygen", "-q", "-t", kind, "-N", "", "-C", "", "-f", p).CombinedOutput() + if e != nil { + return fmt.Errorf("generate independent guest SSH host keys: %w: %s", e, strings.TrimSpace(string(output))) + } + if e = os.Chown(p, uid, gid); e != nil { + return e + } + if e = os.Chown(p+".pub", uid, gid); e != nil { + return e + } + } + } + return nil +} + +func (m *Manager) RestoreTransfer(ctx context.Context, manifest *transfer.Manifest, dir, name, poolID string, assignNAT bool, portCount int) (_ *config.Container, err error) { + transfer.CreationMu.Lock() + defer transfer.CreationMu.Unlock() + if err = transfer.ValidateManifest(manifest); err != nil { + return nil, err + } + if err = ValidateTransfer(ctx, dir, manifest); err != nil { + return nil, err + } + if !config.IsValidContainerName(name) || config.FindContainerByName(name) != nil { + return nil, fmt.Errorf("invalid or already used instance name") + } + var required int64 + for _, f := range manifest.Files { + required += f.Size + } + pool, err := config.SelectStoragePoolForContent(config.StorageContentLXC, poolID, required) + if err != nil { + return nil, err + } + if poolID != "" && pool.ID != poolID { + return nil, fmt.Errorf("requested LXC storage pool is unavailable or lacks capacity") + } + c := transfer.NewIdentity(manifest.Container, name, pool.ID) + sourceDataDisks := c.DataDisks + c.DataDisks = nil + c.LXCName = fmt.Sprintf("ct-%d", c.ID) + c.StoragePath = filepath.Join(pool.Path, "lxc", c.LXCName) + c.MACAddress = transferMAC() + c.InstallationMediaImageID = "" + c.InstallationMediaBoot = "" + if _, e := os.Lstat(c.StoragePath); !os.IsNotExist(e) { + return nil, fmt.Errorf("new instance storage path already exists") + } + link := filepath.Join(m.LxcPath, c.LXCName) + separateLink := filepath.Clean(link) != filepath.Clean(c.StoragePath) + if separateLink { + if _, e := os.Lstat(link); !os.IsNotExist(e) { + return nil, fmt.Errorf("new LXC name already has unmanaged storage") + } + } + if err = os.MkdirAll(m.LxcPath, 0755); err != nil { + return nil, err + } + if err = os.MkdirAll(c.StoragePath, 0755); err != nil { + return nil, err + } + committed := false + linked := false + defer func() { + if !committed { + _ = m.UnmountDataDisks(&c) + _ = m.CleanupDataDisks(&c) + if linked { + _ = os.Remove(link) + } + _ = os.RemoveAll(c.StoragePath) + } + }() + if separateLink { + if err = os.Symlink(c.StoragePath, link); err != nil { + return nil, err + } + linked = true + } + root := filepath.Join(c.StoragePath, "rootfs") + if err = os.MkdirAll(root, 0755); err != nil { + return nil, err + } + image := filepath.Join(c.StoragePath, "rootfs.img") + for _, f := range manifest.Files { + if f.Role == "system" { + if err = copyTransferRaw(ctx, filepath.Join(dir, filepath.FromSlash(f.Name)), image); err != nil { + return nil, err + } + } + } + if output, e := exec.CommandContext(ctx, "mount", "-t", "ext4", "-o", "loop,nodev,nosuid,noexec", image, root).CombinedOutput(); e != nil { + return nil, fmt.Errorf("mount restored rootfs for identity reset: %w: %s", e, strings.TrimSpace(string(output))) + } + mounted := true + defer func() { + if mounted { + _ = exec.Command("umount", root).Run() + } + }() + uid, gid, err := unprivilegedIDMap() + if err != nil { + return nil, err + } + if err = rewriteTransferIDs(ctx, root, manifest.RootUIDBase, manifest.RootGIDBase, uid, gid); err != nil { + return nil, err + } + if err = resetTransferRoot(root, name, uid, gid); err != nil { + return nil, err + } + if output, e := exec.Command("umount", root).CombinedOutput(); e != nil { + return nil, fmt.Errorf("unmount restored rootfs: %w: %s", e, strings.TrimSpace(string(output))) + } + mounted = false + configuration := fmt.Sprintf("lxc.include = /usr/share/lxc/config/common.conf\nlxc.uts.name = %s\nlxc.rootfs.path = dir:%s\nlxc.net.0.type = veth\nlxc.net.0.link = lxcbr0\nlxc.net.0.flags = up\nlxc.net.0.name = eth0\nlxc.net.0.hwaddr = %s\n", name, root, c.MACAddress) + if err = os.WriteFile(filepath.Join(c.StoragePath, "config"), []byte(configuration), 0600); err != nil { + return nil, err + } + if err = m.applyResourceLimits(c.LxcName(), ContainerConfig{Name: name, TemplateID: c.Template, VCPU: c.VCPU, RAMMB: c.RAMMB, DiskGB: c.DiskGB, IOReadMBps: c.IOReadMBps, IOWriteMBps: c.IOWriteMBps, NetworkDownMbps: c.NetworkDownMbps, NetworkUpMbps: c.NetworkUpMbps}); err != nil { + return nil, err + } + for _, sourceDisk := range sourceDataDisks { + oldID := sourceDisk.ID + if err = config.ValidateGuestMountPath(sourceDisk.MountPath); err != nil { + return nil, err + } + d := sourceDisk + d.ID = config.NewDataDiskID() + d.Path = "" + d.StoragePoolID = pool.ID + d.Format = "raw" + d.CreatedAt = time.Now().UTC().Format(time.RFC3339) + p, e := config.DataDiskPath(&c, d) + if e != nil { + return nil, e + } + d.Path = p + c.DataDisks = append(c.DataDisks, d) + for _, f := range manifest.Files { + if f.Role == "data" && f.DiskID == oldID { + if err = copyTransferRaw(ctx, filepath.Join(dir, filepath.FromSlash(f.Name)), p); err != nil { + return nil, err + } + if err = rewriteTransferDataImage(ctx, p, manifest.RootUIDBase, manifest.RootGIDBase, uid, gid); err != nil { + return nil, err + } + } + } + } + if assignNAT { + if portCount < 1 || portCount > 64 { + return nil, fmt.Errorf("invalid port mapping quota") + } + port, release, e := ReserveCreateNATPorts(ContainerConfig{Name: name, Virtualization: "lxc", PortMappingCount: portCount}) + if e != nil { + return nil, e + } + defer release() + c.SSHPort = port + c.PortMappingLimit = portCount + c.PortMappings = SetupDefaultPortMappings(port) + } else { + c.PortMappingLimit = 0 + } + if err = ctx.Err(); err != nil { + return nil, err + } + config.AddContainer(c) + if err = config.SaveConfig(); err != nil { + config.RemoveContainer(c.ID) + return nil, err + } + committed = true + return &c, nil +} + +func transferMAC() string { + id := strings.ReplaceAll(config.NewContainerUUID(), "-", "") + return fmt.Sprintf("00:16:3e:%s:%s:%s", id[:2], id[2:4], id[4:6]) +} diff --git a/backend/internal/lxc/transfer_ownership_linux.go b/backend/internal/lxc/transfer_ownership_linux.go new file mode 100644 index 0000000..746a697 --- /dev/null +++ b/backend/internal/lxc/transfer_ownership_linux.go @@ -0,0 +1,72 @@ +//go:build linux + +package lxc + +import ( + "encoding/binary" + "errors" + "os" + "syscall" + + "golang.org/x/sys/unix" +) + +func transferFileID(info os.FileInfo) ([2]uint64, bool) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return [2]uint64{}, false + } + return [2]uint64{uint64(st.Dev), st.Ino}, true +} + +// chown clears set-ID bits and file capabilities even when cloning an ext4 +// image. Preserve them while translating the subordinate-UID root ID. +func remapTransferOwnership(path string, st os.FileInfo, uid, gid int, oldUID, oldGID uint32, newUID, newGID int) error { + xattrs := map[string][]byte{} + for _, name := range []string{"security.capability", "system.posix_acl_access", "system.posix_acl_default"} { + size, err := unix.Lgetxattr(path, name, nil) + if errors.Is(err, unix.ENODATA) || errors.Is(err, unix.ENOTSUP) { + continue + } + if err != nil { + return err + } + value := make([]byte, size) + if _, err = unix.Lgetxattr(path, name, value); err != nil { + return err + } + if name == "security.capability" && len(value) == 24 && binary.LittleEndian.Uint32(value[:4])&0xff000000 == 0x03000000 { + root := binary.LittleEndian.Uint32(value[20:]) + if oldUID > 0 && root >= oldUID && root < oldUID+65536 { + binary.LittleEndian.PutUint32(value[20:], root-oldUID+uint32(newUID)) + } + } + if name != "security.capability" && len(value) >= 4 { + for offset := 4; offset+8 <= len(value); offset += 8 { + tag := binary.LittleEndian.Uint16(value[offset:]) + id := binary.LittleEndian.Uint32(value[offset+4:]) + if tag == 0x02 && oldUID > 0 && id >= oldUID && id < oldUID+65536 { + binary.LittleEndian.PutUint32(value[offset+4:], id-oldUID+uint32(newUID)) + } + if tag == 0x08 && oldGID > 0 && id >= oldGID && id < oldGID+65536 { + binary.LittleEndian.PutUint32(value[offset+4:], id-oldGID+uint32(newGID)) + } + } + } + xattrs[name] = value + } + if err := os.Lchown(path, uid, gid); err != nil { + return err + } + if st.Mode()&os.ModeSymlink == 0 { + if err := os.Chmod(path, st.Mode()); err != nil { + return err + } + } + for name, value := range xattrs { + if err := unix.Lsetxattr(path, name, value, 0); err != nil { + return err + } + } + return nil +} diff --git a/backend/internal/lxc/transfer_ownership_other.go b/backend/internal/lxc/transfer_ownership_other.go new file mode 100644 index 0000000..4335723 --- /dev/null +++ b/backend/internal/lxc/transfer_ownership_other.go @@ -0,0 +1,14 @@ +//go:build !linux + +package lxc + +import ( + "fmt" + "os" +) + +func transferFileID(os.FileInfo) ([2]uint64, bool) { return [2]uint64{}, false } + +func remapTransferOwnership(string, os.FileInfo, int, int, uint32, uint32, int, int) error { + return fmt.Errorf("LXC filesystem ownership restore requires Linux") +} diff --git a/backend/internal/lxc/transfer_test.go b/backend/internal/lxc/transfer_test.go new file mode 100644 index 0000000..e5850d6 --- /dev/null +++ b/backend/internal/lxc/transfer_test.go @@ -0,0 +1,53 @@ +package lxc + +import ( + "context" + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestTransferIdentityWritesCannotEscapeGuestRoot(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("LXC restore is Linux only") + } + root, outside := t.TempDir(), t.TempDir() + if err := os.Symlink(outside, filepath.Join(root, "etc")); err != nil { + t.Fatal(err) + } + if err := safeTransferWrite(root, "etc/hostname", "new-name\n", os.Getuid(), os.Getgid()); err == nil { + t.Fatal("guest parent symlink escaped root") + } + entries, _ := os.ReadDir(outside) + if len(entries) != 0 { + t.Fatal("modified host path outside restored guest") + } +} + +func TestOwnershipRewriteHonorsCancellationAndPreservesUnchangedSetID(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("Linux ownership semantics") + } + root := t.TempDir() + file := filepath.Join(root, "owned") + if err := os.WriteFile(file, []byte("data"), 0755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(file, 0755|os.ModeSetuid); err != nil { + t.Fatal(err) + } + before, _ := os.Stat(file) + if err := rewriteTransferIDs(context.Background(), root, 0, 0, 0, 0); err != nil { + t.Fatal(err) + } + after, _ := os.Stat(file) + if before.Mode() != after.Mode() { + t.Fatal("unchanged ownership cleared guest set-ID bits") + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := rewriteTransferIDs(ctx, root, 0, 0, 0, 0); err != context.Canceled { + t.Fatal("ownership pass ignored cancellation") + } +} diff --git a/backend/internal/server/image_upload_access_test.go b/backend/internal/server/image_upload_access_test.go new file mode 100644 index 0000000..9295188 --- /dev/null +++ b/backend/internal/server/image_upload_access_test.go @@ -0,0 +1,53 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "clicd/internal/config" +) + +func TestLocalImageUploadRoutesRequireAdministratorAndBothScopes(t *testing.T) { + previous := config.AppConfig + t.Cleanup(func() { config.AppConfig = previous }) + config.AppConfig = &config.ClicdConfig{JWTSecret: "upload-permission-test", SubUsers: []config.SubUser{{Username: "tenant"}}, ApiKeys: []config.ApiKeyConfig{{ID: "upload-key", KeyHash: "636c6963645f736b5f73656375726974795f626f756e646172795f7465737400"}}} + mux := http.NewServeMux() + setupRoutes(mux) + for _, path := range []string{"/api/images/upload", "/api/v1/images/upload"} { + for _, tc := range []struct { + name, token string + scopes []string + containers []string + key bool + want int + }{ + {name: "anonymous", want: 401}, + {name: "tenant", token: imageAccessToken(t, "tenant"), want: 403}, + {name: "image-scopes-without-admin", key: true, scopes: []string{"image:download", "image:toggle"}, want: 403}, + {name: "admin-missing-download", key: true, scopes: []string{"admin:access", "image:toggle"}, want: 403}, + {name: "admin-missing-toggle", key: true, scopes: []string{"admin:access", "image:download"}, want: 403}, + {name: "container-bound-wildcard-key", key: true, scopes: []string{"*"}, containers: []string{"only-this-container"}, want: 403}, + {name: "admin-both-scopes", key: true, scopes: []string{"admin:access", "image:download", "image:toggle"}, want: 400}, + {name: "admin-session", token: imageAccessToken(t, ""), want: 400}, + } { + t.Run(path+"/"+tc.name, func(t *testing.T) { + config.AppConfig.ApiKeys[0].Scopes = tc.scopes + config.AppConfig.ApiKeys[0].ContainerUUIDs = tc.containers + request := httptest.NewRequest(http.MethodPost, path, strings.NewReader("{}")) + if tc.key { + request.Header.Set("X-API-Key", "clicd_sk_security_boundary_test") + } + if tc.token != "" { + request.Header.Set("Authorization", "Bearer "+tc.token) + } + response := httptest.NewRecorder() + mux.ServeHTTP(response, request) + if response.Code != tc.want { + t.Fatalf("status=%d want=%d: %s", response.Code, tc.want, response.Body.String()) + } + }) + } + } +} diff --git a/backend/internal/server/server.go b/backend/internal/server/server.go index 626f43c..69378a8 100644 --- a/backend/internal/server/server.go +++ b/backend/internal/server/server.go @@ -56,6 +56,12 @@ func setupRoutes(mux *http.ServeMux) { mux.HandleFunc("/api/templates", corsMiddleware(api.AuthMiddleware(api.HandleTemplates))) mux.HandleFunc("/api/images", corsMiddleware(api.AdminMiddleware(api.HandleImages))) mux.HandleFunc("/api/images/custom", corsMiddleware(api.AdminMiddleware(api.HandleCustomKVMImages))) + mux.HandleFunc("/api/images/upload", corsMiddleware(api.AdminMiddleware(api.HandleImageUpload))) + mux.HandleFunc("/api/backups", corsMiddleware(api.AdminMiddleware(api.HandleBackups))) + mux.HandleFunc("/api/backups/", corsMiddleware(api.AdminMiddleware(api.HandleBackups))) + mux.HandleFunc("/api/instance-templates", corsMiddleware(api.AdminMiddleware(api.HandleInstanceTemplates))) + mux.HandleFunc("/api/instance-templates/", corsMiddleware(api.AdminMiddleware(api.HandleInstanceTemplates))) + mux.HandleFunc("/api/backup-download/", corsMiddleware(api.HandleBackupDownload)) mux.HandleFunc("/api/images/download", corsMiddleware(api.AdminMiddleware(api.HandleImageDownload))) mux.HandleFunc("/api/images/cancel", corsMiddleware(api.AdminMiddleware(api.HandleImageCancel))) mux.HandleFunc("/api/images/delete", corsMiddleware(api.AdminMiddleware(api.HandleImageDelete))) @@ -100,6 +106,11 @@ func setupRoutes(mux *http.ServeMux) { mux.HandleFunc("/api/v1/templates", corsMiddleware(api.AuthMiddleware(api.HandleTemplates))) mux.HandleFunc("/api/v1/images", corsMiddleware(api.AuthMiddleware(api.HandleImages))) mux.HandleFunc("/api/v1/images/custom", corsMiddleware(api.AdminMiddleware(api.HandleCustomKVMImages))) + mux.HandleFunc("/api/v1/images/upload", corsMiddleware(api.AdminMiddleware(api.HandleImageUpload))) + mux.HandleFunc("/api/v1/backups", corsMiddleware(api.AdminMiddleware(api.HandleBackups))) + mux.HandleFunc("/api/v1/backups/", corsMiddleware(api.AdminMiddleware(api.HandleBackups))) + mux.HandleFunc("/api/v1/instance-templates", corsMiddleware(api.AdminMiddleware(api.HandleInstanceTemplates))) + mux.HandleFunc("/api/v1/instance-templates/", corsMiddleware(api.AdminMiddleware(api.HandleInstanceTemplates))) mux.HandleFunc("/api/v1/images/download", corsMiddleware(api.AdminMiddleware(api.HandleImageDownload))) mux.HandleFunc("/api/v1/images/cancel", corsMiddleware(api.AdminMiddleware(api.HandleImageCancel))) mux.HandleFunc("/api/v1/images/delete", corsMiddleware(api.AdminMiddleware(api.HandleImageDelete))) diff --git a/backend/internal/transfer/artifact.go b/backend/internal/transfer/artifact.go new file mode 100644 index 0000000..294b772 --- /dev/null +++ b/backend/internal/transfer/artifact.go @@ -0,0 +1,794 @@ +// Package transfer stores portable, versioned instance backups. The outer +// archive contains only regular disk files; guest filesystem links/devices +// remain inside the filesystem image and are never extracted onto the host. +package transfer + +import ( + "archive/tar" + "compress/gzip" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path" + "path/filepath" + "regexp" + "runtime" + "sort" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "clicd/internal/config" + "clicd/internal/version" +) + +const FormatVersion = 1 +const MaxExpandedBytes int64 = 64 << 30 +const MaxArchiveBytes int64 = 64 << 30 +const MaxVirtualDiskBytes int64 = 16384 << 30 +const maxManifestBytes int64 = 4 << 20 + +var idPattern = regexp.MustCompile(`^(bk|tpl)-[a-f0-9]{32}$`) +var payloadPattern = regexp.MustCompile(`^disks/[a-z0-9-]+\.(qcow2|img)$`) +var mutationMu sync.Mutex +var selectBackupRoot = selectRoot +var allocateIdentityID = config.AllocateContainerID + +var checkSpace = func(directory string, required int64) error { + if runtime.GOOS != "linux" { + return nil + } + out, err := exec.Command("df", "-B1", "--output=avail", directory).Output() + if err != nil { + return fmt.Errorf("cannot check backup free space: %w", err) + } + fields := strings.Fields(string(out)) + if len(fields) < 2 { + return fmt.Errorf("invalid backup free-space response") + } + available, err := strconv.ParseInt(fields[len(fields)-1], 10, 64) + if err != nil { + return err + } + if available < required+(256<<20) { + return fmt.Errorf("backup storage has insufficient space (256 MiB reserve required)") + } + return nil +} + +// CreationMu protects the final name check, ID/network reservation and commit +// of all transfer-created instances. It is never acquired under a queue mutex. +var CreationMu sync.Mutex + +type File struct { + Name string `json:"name"` + Role string `json:"role"` + DiskID string `json:"disk_id,omitempty"` + Format string `json:"format"` + Size int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` +} + +type Manifest struct { + Version int `json:"format_version"` + AppVersion string `json:"app_version"` + Runtime string `json:"runtime"` + Arch string `json:"arch"` + BootProfile string `json:"boot_profile"` + CreatedAt string `json:"created_at"` + Container config.Container `json:"container"` + Files []File `json:"files"` + RootUIDBase uint32 `json:"root_uid_base,omitempty"` + RootGIDBase uint32 `json:"root_gid_base,omitempty"` +} + +type Info struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + Runtime string `json:"runtime"` + Arch string `json:"arch"` + CreatedAt string `json:"created_at"` + SourceName string `json:"source_name"` + SizeBytes int64 `json:"size_bytes"` + DiskCount int `json:"disk_count"` + FormatVersion int `json:"format_version"` + SHA256 string `json:"sha256"` + CredentialsPreserved bool `json:"credentials_preserved"` + ColdCopy bool `json:"cold_copy"` +} + +type record struct { + Info + Manifest Manifest `json:"manifest"` +} +type Exporter func(context.Context, string, *Manifest) error +type Validator func(context.Context, string, *Manifest) error + +func NewID(prefix string) string { + var bytes [16]byte + if _, err := rand.Read(bytes[:]); err != nil { + panic(err) + } + return prefix + "-" + hex.EncodeToString(bytes[:]) +} + +func ValidateManifest(m *Manifest) error { + if m.Version != FormatVersion { + return fmt.Errorf("unsupported backup format version") + } + if m.Arch != runtime.GOARCH { + return fmt.Errorf("backup architecture %q does not match %s", m.Arch, runtime.GOARCH) + } + if m.Runtime != "kvm" && m.Runtime != "lxc" { + return fmt.Errorf("invalid backup runtime") + } + maxDiskGB := float64(64) + if m.Runtime == "kvm" { + maxDiskGB = 16384 + } + if m.Container.Runtime() != m.Runtime || m.Container.VCPU <= 0 || m.Container.VCPU > 1024 || m.Container.RAMMB < 128 || m.Container.RAMMB > 1048576 || m.Container.DiskGB <= 0 || m.Container.DiskGB > maxDiskGB || len(m.Container.DataDisks) > config.MaxDataDisks { + return fmt.Errorf("invalid instance resources") + } + if m.BootProfile != "linux" && m.BootProfile != "windows" && m.BootProfile != "manual" { + return fmt.Errorf("invalid boot profile") + } + if m.RootUIDBase > 0x7fff0000 || m.RootGIDBase > 0x7fff0000 { + return fmt.Errorf("invalid subordinate ID range") + } + if m.Runtime == "kvm" && (m.Container.VCPU < 1 || m.Container.VCPU != float64(int(m.Container.VCPU))) { + return fmt.Errorf("KVM backup requires integral vCPU count") + } + if len(m.Files) == 0 || len(m.Files) > 65 { + return fmt.Errorf("invalid disk inventory") + } + seen := map[string]bool{} + ids := map[string]bool{} + var total int64 + systems := 0 + for _, f := range m.Files { + if !payloadPattern.MatchString(f.Name) || seen[f.Name] || f.Size <= 0 || f.Size > MaxExpandedBytes || len(f.SHA256) != 64 { + return fmt.Errorf("invalid backup file entry") + } + if _, err := hex.DecodeString(f.SHA256); err != nil { + return fmt.Errorf("invalid file checksum") + } + seen[f.Name] = true + total += f.Size + if total > MaxExpandedBytes { + return fmt.Errorf("backup expands beyond 64 GiB limit") + } + if m.Runtime == "kvm" && f.Format != "qcow2" || m.Runtime == "lxc" && f.Format != "raw" { + return fmt.Errorf("invalid disk format") + } + if f.Role == "system" { + systems++ + } else if f.Role == "data" && f.DiskID != "" && !ids[f.DiskID] { + ids[f.DiskID] = true + } else { + return fmt.Errorf("invalid disk role") + } + } + if systems != 1 || len(ids) != len(m.Container.DataDisks) { + return fmt.Errorf("backup does not contain every instance disk") + } + for _, d := range m.Container.DataDisks { + if !ids[d.ID] { + return fmt.Errorf("missing data disk") + } + if _, err := config.DiskSizeBytes(d.SizeGB); err != nil { + return err + } + if m.Runtime == "lxc" { + if err := config.ValidateGuestMountPath(d.MountPath); err != nil { + return err + } + } + } + return nil +} + +func roots() []string { + var result []string + if config.AppConfig == nil { + return result + } + for _, p := range config.AppConfig.StoragePools { + for _, content := range p.ContentTypes { + if content == config.StorageContentBackups { + result = append(result, filepath.Join(p.Path, "backups", "instances")) + break + } + } + } + return result +} + +func selectRoot(poolID string, required int64) (string, error) { + pool, err := config.SelectStoragePoolForContent(config.StorageContentBackups, poolID, required) + if err != nil { + return "", err + } + if poolID != "" && pool.ID != poolID { + return "", fmt.Errorf("requested backup storage pool is unavailable or lacks capacity") + } + root := filepath.Join(pool.Path, "backups", "instances") + if err = os.MkdirAll(root, 0700); err != nil { + return "", err + } + return root, nil +} + +func List(kind string) []Info { + result := []Info{} + for _, root := range roots() { + entries, _ := os.ReadDir(root) + for _, entry := range entries { + if !strings.HasSuffix(entry.Name(), ".json") || entry.IsDir() { + continue + } + id := strings.TrimSuffix(entry.Name(), ".json") + if !idPattern.MatchString(id) { + continue + } + r, _, err := loadAt(root, id) + if err == nil && (kind == "" || r.Kind == kind) { + result = append(result, r.Info) + } + } + } + sort.Slice(result, func(i, j int) bool { return result[i].CreatedAt > result[j].CreatedAt }) + return result +} + +func loadAt(root, id string) (*record, string, error) { + archive := filepath.Join(root, id+".clicd.tar.gz") + for _, p := range []string{filepath.Join(root, id+".json"), archive} { + st, e := os.Lstat(p) + if e != nil { + return nil, "", e + } + if !st.Mode().IsRegular() { + return nil, "", fmt.Errorf("artifact is not a regular file") + } + } + data, err := os.ReadFile(filepath.Join(root, id+".json")) + if err != nil { + return nil, "", err + } + if len(data) > int(maxManifestBytes) { + return nil, "", fmt.Errorf("artifact metadata too large") + } + var r record + if err = json.Unmarshal(data, &r); err != nil { + return nil, "", err + } + if r.ID != id || r.FormatVersion != FormatVersion { + return nil, "", fmt.Errorf("invalid artifact record") + } + return &r, archive, nil +} + +func Resolve(id string) (Info, string, error) { + if !idPattern.MatchString(id) { + return Info{}, "", fmt.Errorf("invalid artifact ID") + } + for _, root := range roots() { + r, p, e := loadAt(root, id) + if e == nil { + return r.Info, p, nil + } + } + return Info{}, "", os.ErrNotExist +} + +func Delete(id, kind string) error { + mutationMu.Lock() + defer mutationMu.Unlock() + info, p, err := Resolve(id) + if err != nil { + return err + } + if info.Kind != kind { + return os.ErrNotExist + } + if err = os.Remove(p); err != nil { + return err + } + return os.Remove(filepath.Join(filepath.Dir(p), id+".json")) +} + +func Create(ctx context.Context, poolID, name, kind string, c config.Container, export Exporter) (Info, error) { + if kind != "backup" && kind != "template" { + return Info{}, fmt.Errorf("invalid artifact kind") + } + if strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 128 { + return Info{}, fmt.Errorf("artifact name must contain 1-128 characters") + } + required := int64(0) + if !c.IsKVM() { + required = int64(c.DiskGB * (1 << 30)) + for _, d := range c.DataDisks { + required += int64(d.SizeGB * (1 << 30)) + } + if required <= 0 || required > MaxExpandedBytes { + return Info{}, fmt.Errorf("LXC raw filesystem payload exceeds 64 GiB backup limit") + } + } + // QCOW2 logical capacity is deliberately not an archive byte count. Its + // exporter measures the flattened files after the guest is safely stopped. + root, err := selectBackupRoot(poolID, required) + if err != nil { + return Info{}, err + } + stage, err := os.MkdirTemp(root, ".building-") + if err != nil { + return Info{}, err + } + defer os.RemoveAll(stage) + // Container contains slices. Sanitizing portable metadata must never mutate + // the live source's DataDisks or other backing arrays. + encoded, err := json.Marshal(c) + if err != nil { + return Info{}, err + } + var copied config.Container + if err = json.Unmarshal(encoded, &copied); err != nil { + return Info{}, err + } + m := Manifest{Version: FormatVersion, AppVersion: version.Current(), Runtime: c.Runtime(), Arch: runtime.GOARCH, CreatedAt: time.Now().UTC().Format(time.RFC3339), Container: copied, BootProfile: "linux"} + if err = export(ctx, stage, &m); err != nil { + return Info{}, err + } + for i := range m.Files { + p := filepath.Join(stage, filepath.FromSlash(m.Files[i].Name)) + st, e := os.Lstat(p) + if e != nil { + return Info{}, e + } + if !st.Mode().IsRegular() { + return Info{}, fmt.Errorf("payload is not a regular disk file") + } + m.Files[i].Size = st.Size() + m.Files[i].SHA256, err = HashFile(ctx, p) + if err != nil { + return Info{}, err + } + } + // Host paths are neither needed for restore nor disclosed in the portable metadata. + m.Container.DiskImage = "" + m.Container.StoragePath = "" + m.Container.StoragePoolID = "" + for i := range m.Container.DataDisks { + m.Container.DataDisks[i].Path = "" + m.Container.DataDisks[i].StoragePoolID = "" + } + if err = ValidateManifest(&m); err != nil { + return Info{}, err + } + return pack(ctx, root, name, kind, stage, m) +} + +func pack(ctx context.Context, root, name, kind, stage string, m Manifest) (Info, error) { + id := NewID(map[string]string{"backup": "bk", "template": "tpl"}[kind]) + temp, err := os.CreateTemp(root, ".archive-") + if err != nil { + return Info{}, err + } + tmp := temp.Name() + defer os.Remove(tmp) + compressed, _ := gzip.NewWriterLevel(temp, gzip.BestSpeed) + writer := tar.NewWriter(compressed) + data, err := json.Marshal(m) + if err != nil { + temp.Close() + return Info{}, err + } + if err = writer.WriteHeader(&tar.Header{Name: "manifest.json", Mode: 0600, Size: int64(len(data)), Typeflag: tar.TypeReg}); err == nil { + _, err = writer.Write(data) + } + for _, file := range m.Files { + if err != nil { + break + } + err = writer.WriteHeader(&tar.Header{Name: file.Name, Mode: 0600, Size: file.Size, Typeflag: tar.TypeReg}) + if err != nil { + break + } + source, e := os.Open(filepath.Join(stage, filepath.FromSlash(file.Name))) + if e != nil { + err = e + break + } + _, err = Copy(ctx, writer, source) + source.Close() + } + err = errors.Join(err, writer.Close(), compressed.Close(), temp.Sync(), temp.Close()) + if err != nil { + return Info{}, err + } + archive := filepath.Join(root, id+".clicd.tar.gz") + if err = os.Rename(tmp, archive); err != nil { + return Info{}, err + } + info, err := saveRecord(ctx, archive, id, name, kind, m) + if err != nil { + os.Remove(archive) + } + return info, err +} + +func saveRecord(ctx context.Context, archive, id, name, kind string, m Manifest) (Info, error) { + st, err := os.Stat(archive) + if err != nil { + return Info{}, err + } + digest, err := HashFile(ctx, archive) + if err != nil { + return Info{}, err + } + info := Info{ID: id, Name: name, Kind: kind, Runtime: m.Runtime, Arch: m.Arch, CreatedAt: time.Now().UTC().Format(time.RFC3339), SourceName: m.Container.Name, SizeBytes: st.Size(), DiskCount: len(m.Files), FormatVersion: FormatVersion, SHA256: digest, CredentialsPreserved: true, ColdCopy: true} + bytes, err := json.Marshal(record{Info: info, Manifest: m}) + if err != nil { + return Info{}, err + } + p := filepath.Join(filepath.Dir(archive), id+".json") + if err = os.WriteFile(p+".tmp", bytes, 0600); err != nil { + return Info{}, err + } + err = os.Rename(p+".tmp", p) + return info, err +} + +// Extract validates every byte against a strict regular-file allowlist. There +// are no tar symlink/hardlink/device entries, duplicate names, absolute paths, +// parent traversal, optional arbitrary payloads or unbounded decompression. +func Extract(ctx context.Context, reader io.Reader, destination string) (*Manifest, error) { + compressed, err := gzip.NewReader(io.LimitReader(reader, MaxArchiveBytes+1)) + if err != nil { + return nil, err + } + defer compressed.Close() + limited := &io.LimitedReader{R: compressed, N: MaxExpandedBytes + maxManifestBytes + (1 << 20) + 1} + archive := tar.NewReader(limited) + var m *Manifest + seen := map[string]bool{} + var total int64 + count := 0 + for { + h, e := archive.Next() + if e == io.EOF { + break + } + if e != nil { + return nil, e + } + count++ + if count > 66 { + return nil, fmt.Errorf("too many archive entries") + } + if h.Typeflag != tar.TypeReg && h.Typeflag != tar.TypeRegA || h.Linkname != "" || h.Size < 0 || h.Size > MaxExpandedBytes || h.Name != path.Clean(h.Name) || strings.Contains(h.Name, "\\") || strings.Contains(h.Name, ":") || path.IsAbs(h.Name) || seen[h.Name] { + return nil, fmt.Errorf("unsafe archive entry") + } + seen[h.Name] = true + if h.Name == "manifest.json" { + if m != nil || h.Size > maxManifestBytes { + return nil, fmt.Errorf("invalid manifest") + } + data, e := io.ReadAll(io.LimitReader(archive, maxManifestBytes+1)) + if e != nil { + return nil, e + } + var next Manifest + if e = json.Unmarshal(data, &next); e != nil { + return nil, e + } + if e = ValidateManifest(&next); e != nil { + return nil, e + } + m = &next + var required int64 + for _, file := range m.Files { + required += file.Size + } + if e = checkSpace(destination, required); e != nil { + return nil, e + } + continue + } + if m == nil { + return nil, fmt.Errorf("manifest must be the first archive entry") + } + var expected *File + for i := range m.Files { + if m.Files[i].Name == h.Name { + expected = &m.Files[i] + break + } + } + if expected == nil || !payloadPattern.MatchString(h.Name) || h.Size != expected.Size { + return nil, fmt.Errorf("unexpected disk payload") + } + total += h.Size + if total > MaxExpandedBytes { + return nil, fmt.Errorf("archive expansion limit exceeded") + } + p := filepath.Join(destination, filepath.FromSlash(h.Name)) + if st, e := os.Lstat(filepath.Join(destination, "disks")); e == nil && (!st.IsDir() || st.Mode()&os.ModeSymlink != 0) { + return nil, fmt.Errorf("payload directory cannot be a symlink") + } + if e = os.MkdirAll(filepath.Dir(p), 0700); e != nil { + return nil, e + } + file, e := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if e != nil { + return nil, e + } + digest := sha256.New() + n, copyErr := Copy(ctx, io.MultiWriter(file, digest), archive) + closeErr := file.Close() + if copyErr != nil || closeErr != nil { + return nil, errors.Join(copyErr, closeErr) + } + if n != h.Size || hex.EncodeToString(digest.Sum(nil)) != expected.SHA256 { + return nil, fmt.Errorf("disk checksum or length mismatch") + } + } + if m == nil || len(seen) != len(m.Files)+1 { + return nil, fmt.Errorf("incomplete backup archive") + } + if limited.N <= 0 { + return nil, fmt.Errorf("archive expansion limit exceeded") + } + var tail [1]byte + if n, e := compressed.Read(tail[:]); n != 0 || e != io.EOF { + return nil, fmt.Errorf("unexpected trailing archive data") + } + return m, nil +} + +func Import(ctx context.Context, poolID, name string, reader io.Reader, validate Validator) (Info, error) { + root, err := selectBackupRoot(poolID, 0) + if err != nil { + return Info{}, err + } + stage, err := os.MkdirTemp(root, ".import-") + if err != nil { + return Info{}, err + } + defer os.RemoveAll(stage) + spool, err := os.CreateTemp(root, ".upload-") + if err != nil { + return Info{}, err + } + defer os.Remove(spool.Name()) + n, err := Copy(ctx, &spaceWriter{File: spool, Directory: root}, io.LimitReader(reader, MaxArchiveBytes+1)) + if err != nil { + spool.Close() + return Info{}, err + } + if n > MaxArchiveBytes { + spool.Close() + return Info{}, fmt.Errorf("upload exceeds 64 GiB limit") + } + if _, err = spool.Seek(0, 0); err != nil { + spool.Close() + return Info{}, err + } + m, err := Extract(ctx, spool, stage) + spool.Close() + if err != nil { + return Info{}, err + } + if validate != nil { + if err = validate(ctx, stage, m); err != nil { + return Info{}, err + } + } + if strings.TrimSpace(name) == "" { + name = m.Container.Name + } + if utf8.RuneCountInString(name) > 128 { + return Info{}, fmt.Errorf("invalid artifact name") + } + id := NewID("bk") + archive := filepath.Join(root, id+".clicd.tar.gz") + if err = os.Rename(spool.Name(), archive); err != nil { + return Info{}, err + } + info, err := saveRecord(ctx, archive, id, name, "backup", *m) + if err != nil { + os.Remove(archive) + } + return info, err +} + +type spaceWriter struct { + File *os.File + Directory string + untilCheck int64 +} + +func (w *spaceWriter) Write(bytes []byte) (int, error) { + if w.untilCheck <= 0 { + if err := checkSpace(w.Directory, 32<<20); err != nil { + return 0, err + } + w.untilCheck = 32 << 20 + } + n, err := w.File.Write(bytes) + w.untilCheck -= int64(n) + return n, err +} + +// SpoolUpload streams multipart content into a configured backup pool rather +// than net/http's system TEMP directory, preserving a free-space reserve. +func SpoolUpload(ctx context.Context, reader io.Reader, poolIDs ...string) (*os.File, func(), error) { + poolID := "" + if len(poolIDs) > 0 { + poolID = poolIDs[0] + } + root, err := selectBackupRoot(poolID, 0) + if err != nil { + return nil, nil, err + } + file, err := os.CreateTemp(root, ".incoming-") + if err != nil { + return nil, nil, err + } + cleanup := func() { file.Close(); os.Remove(file.Name()) } + n, err := Copy(ctx, &spaceWriter{File: file, Directory: root}, io.LimitReader(reader, MaxArchiveBytes+1)) + if err == nil && n > MaxArchiveBytes { + err = fmt.Errorf("upload exceeds 64 GiB limit") + } + if err == nil { + _, err = file.Seek(0, 0) + } + if err != nil { + cleanup() + return nil, nil, err + } + return file, cleanup, nil +} + +// OpenVerified creates an isolated staging tree and revalidates disk checksums +// on every restore, including artifacts that were created on this host. +func OpenVerified(ctx context.Context, id, kind string, validate Validator) (*Manifest, string, func(), error) { + info, p, err := Resolve(id) + if err != nil { + return nil, "", nil, err + } + if info.Kind != kind { + return nil, "", nil, os.ErrNotExist + } + digest, err := HashFile(ctx, p) + if err != nil { + return nil, "", nil, err + } + if digest != info.SHA256 { + return nil, "", nil, fmt.Errorf("archive checksum mismatch") + } + file, err := os.Open(p) + if err != nil { + return nil, "", nil, err + } + defer file.Close() + stage, err := os.MkdirTemp(filepath.Dir(p), ".restore-") + if err != nil { + return nil, "", nil, err + } + cleanup := func() { os.RemoveAll(stage) } + m, err := Extract(ctx, file, stage) + if err == nil && validate != nil { + err = validate(ctx, stage, m) + } + if err != nil { + cleanup() + return nil, "", nil, err + } + return m, stage, cleanup, nil +} + +func HashFile(ctx context.Context, p string) (string, error) { + file, err := os.Open(p) + if err != nil { + return "", err + } + defer file.Close() + h := sha256.New() + _, err = Copy(ctx, h, file) + return hex.EncodeToString(h.Sum(nil)), err +} + +func Copy(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) { + buf := make([]byte, 256<<10) + var total int64 + for { + if err := ctx.Err(); err != nil { + return total, err + } + n, e := src.Read(buf) + if n > 0 { + written, err := dst.Write(buf[:n]) + total += int64(written) + if err != nil { + return total, err + } + if written != n { + return total, io.ErrShortWrite + } + } + if e == io.EOF { + return total, nil + } + if e != nil { + return total, e + } + } +} + +func EnsureSpace(directory string, required int64) error { return checkSpace(directory, required) } + +// NewIdentity intentionally preserves guest accounts but removes all host-side +// addresses, schedules, ownership grants, media references and port mappings. +func NewIdentity(source config.Container, name, poolID string) config.Container { + c := source + c.ID = allocateIdentityID() + c.UUID = config.NewContainerUUID() + c.Name = name + c.Standalone = true + c.LXCName = "" + c.KVMName = "" + c.StoragePath = "" + c.StoragePoolID = poolID + c.DiskImage = "" + c.MACAddress = "" + c.Status = "stopped" + c.RestoreOnHostBoot = false + c.IP = "" + c.LANIPv4Mode = "" + c.LANInterface = "" + c.LANIPv4Address = "" + c.LANIPv4PrefixLen = 0 + c.LANIPv4Gateway = "" + c.PublicIPv4s = nil + c.IPv6 = "" + c.IPv6Addresses = nil + c.IPv6NATAddress = "" + c.IPv6PortMappings = nil + c.IPv6PortMappingLimit = 0 + c.IPv6NATSyncIPv4 = nil + c.IPv6PrefixLen = 0 + c.IPv6Interface = "" + c.VNCPort = 0 + c.SSHPort = 0 + c.PortMappings = nil + c.SSHHostKey = "" + c.AllowedImageIDs = nil + c.ImageLimitConfigured = true + c.FirewallEnabled = false + c.FirewallRules = nil + c.FirewallDefaultAction = "DROP" + c.SnapshotScheduleEnabled = false + c.SnapshotScheduleLastRun = "" + c.SnapshotScheduleNextRun = "" + c.SnapshotScheduleCreatedBy = "" + c.SnapshotScheduleIntervalHours = 0 + c.SnapshotScheduleTime = "" + c.TrafficUsedRX = 0 + c.TrafficUsedTX = 0 + c.TrafficResetDate = time.Now().Format("2006-01") + c.ExpiresAt = "" + c.CreatedAt = time.Now().Format("2006-01-02 15:04:05") + c.DataDisks = append([]config.DataDisk(nil), source.DataDisks...) + return c +} diff --git a/backend/internal/transfer/artifact_test.go b/backend/internal/transfer/artifact_test.go new file mode 100644 index 0000000..a04646d --- /dev/null +++ b/backend/internal/transfer/artifact_test.go @@ -0,0 +1,234 @@ +package transfer + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "clicd/internal/config" +) + +func smallManifest() Manifest { + digest := sha256.Sum256([]byte("disk payload")) + return Manifest{Version: FormatVersion, Runtime: "kvm", Arch: runtime.GOARCH, BootProfile: "linux", Container: config.Container{Name: "source", Virtualization: "kvm", VCPU: 1, RAMMB: 512, DiskGB: 1}, Files: []File{{Name: "disks/system.qcow2", Role: "system", Format: "qcow2", Size: 12, SHA256: hex.EncodeToString(digest[:])}}} +} + +func archiveFor(t *testing.T, m Manifest, headers []*tar.Header, payloads []string) []byte { + t.Helper() + var result bytes.Buffer + compressed := gzip.NewWriter(&result) + writer := tar.NewWriter(compressed) + data, _ := json.Marshal(m) + if err := writer.WriteHeader(&tar.Header{Name: "manifest.json", Mode: 0600, Size: int64(len(data)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + writer.Write(data) + for i, h := range headers { + if err := writer.WriteHeader(h); err != nil { + t.Fatal(err) + } + if i < len(payloads) { + writer.Write([]byte(payloads[i])) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := compressed.Close(); err != nil { + t.Fatal(err) + } + return result.Bytes() +} + +func TestPortableArchiveValidatesEveryDiskAndRejectsUnsafeEntries(t *testing.T) { + m := smallManifest() + ctx := context.Background() + for _, test := range []struct { + name string + header tar.Header + body string + valid bool + }{ + {"regular", tar.Header{Name: m.Files[0].Name, Size: 12, Typeflag: tar.TypeReg}, "disk payload", true}, + {"parent traversal", tar.Header{Name: "../outside", Size: 12, Typeflag: tar.TypeReg}, "disk payload", false}, + {"absolute", tar.Header{Name: "/outside", Size: 12, Typeflag: tar.TypeReg}, "disk payload", false}, + {"windows drive", tar.Header{Name: "C:/outside", Size: 12, Typeflag: tar.TypeReg}, "disk payload", false}, + {"backslash", tar.Header{Name: `disks\system.qcow2`, Size: 12, Typeflag: tar.TypeReg}, "disk payload", false}, + {"symlink", tar.Header{Name: m.Files[0].Name, Typeflag: tar.TypeSymlink, Linkname: "/etc/shadow"}, "", false}, + {"hardlink", tar.Header{Name: m.Files[0].Name, Typeflag: tar.TypeLink, Linkname: "../outside"}, "", false}, + {"device", tar.Header{Name: m.Files[0].Name, Typeflag: tar.TypeChar, Devmajor: 1, Devminor: 3}, "", false}, + {"wrong checksum", tar.Header{Name: m.Files[0].Name, Size: 12, Typeflag: tar.TypeReg}, "bad payload!", false}, + {"wrong length", tar.Header{Name: m.Files[0].Name, Size: 1, Typeflag: tar.TypeReg}, "x", false}, + {"unlisted file", tar.Header{Name: "disks/extra.qcow2", Size: 12, Typeflag: tar.TypeReg}, "disk payload", false}, + } { + t.Run(test.name, func(t *testing.T) { + data := archiveFor(t, m, []*tar.Header{&test.header}, []string{test.body}) + _, err := Extract(ctx, bytes.NewReader(data), t.TempDir()) + if (err == nil) != test.valid { + t.Fatalf("valid=%v err=%v", test.valid, err) + } + }) + } + t.Run("duplicate", func(t *testing.T) { + h := &tar.Header{Name: m.Files[0].Name, Size: 12, Typeflag: tar.TypeReg} + _, err := Extract(ctx, bytes.NewReader(archiveFor(t, m, []*tar.Header{h, h}, []string{"disk payload", "disk payload"})), t.TempDir()) + if err == nil { + t.Fatal("duplicate accepted") + } + }) + t.Run("missing disk", func(t *testing.T) { + _, err := Extract(ctx, bytes.NewReader(archiveFor(t, m, nil, nil)), t.TempDir()) + if err == nil { + t.Fatal("missing disk accepted") + } + }) + t.Run("gzip corruption", func(t *testing.T) { + h := &tar.Header{Name: m.Files[0].Name, Size: 12, Typeflag: tar.TypeReg} + data := archiveFor(t, m, []*tar.Header{h}, []string{"disk payload"}) + data[len(data)-4] ^= 0xff + _, err := Extract(ctx, bytes.NewReader(data), t.TempDir()) + if err == nil { + t.Fatal("corrupt compressed archive accepted") + } + }) +} + +func TestManifestRejectsUnsupportedArchitectureVersionAndExpansionBomb(t *testing.T) { + for _, change := range []func(*Manifest){func(m *Manifest) { m.Version++ }, func(m *Manifest) { m.Arch = "different-arch" }, func(m *Manifest) { m.Files[0].Size = MaxExpandedBytes + 1 }, func(m *Manifest) { m.Files[0].Name = "../disk" }, func(m *Manifest) { m.Container.DataDisks = []config.DataDisk{{ID: "missing", SizeGB: 1}} }, func(m *Manifest) { m.Runtime = "unsupported" }} { + m := smallManifest() + change(&m) + if err := ValidateManifest(&m); err == nil { + t.Fatal("invalid manifest accepted") + } + } +} + +func TestSparseKVMVirtualCapacityIsIndependentOfArchiveExpansionLimit(t *testing.T) { + m := smallManifest() + m.Container.DiskGB = 128 + if err := ValidateManifest(&m); err != nil { + t.Fatal("128GB sparse QCOW logical disk rejected", err) + } + m.Container.DiskGB = 16385 + if err := ValidateManifest(&m); err == nil { + t.Fatal("logical disk beyond 16TiB accepted") + } + m.Container.DiskGB = 128 + m.Files[0].Size = MaxExpandedBytes + 1 + if err := ValidateManifest(&m); err == nil { + t.Fatal("physical payload expansion limit disabled") + } +} + +func TestArchiveCannotFollowPreexistingPayloadDirectorySymlink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink privileges vary on Windows") + } + root, other := t.TempDir(), t.TempDir() + if err := os.Symlink(other, filepath.Join(root, "disks")); err != nil { + t.Fatal(err) + } + m := smallManifest() + h := &tar.Header{Name: m.Files[0].Name, Size: 12, Typeflag: tar.TypeReg} + if _, err := Extract(context.Background(), bytes.NewReader(archiveFor(t, m, []*tar.Header{h}, []string{"disk payload"})), root); err == nil { + t.Fatal("payload symlink followed") + } + entries, _ := os.ReadDir(other) + if len(entries) != 0 { + t.Fatal("wrote outside staging root") + } +} + +func TestArtifactSurvivesReloadAndDoesNotMutateSourceDiskOwnership(t *testing.T) { + pool := t.TempDir() + root := filepath.Join(pool, "backups", "instances") + oldRoot, oldConfig := selectBackupRoot, config.AppConfig + selectBackupRoot = func(string, int64) (string, error) { return root, nil } + defer func() { selectBackupRoot = oldRoot; config.AppConfig = oldConfig }() + if err := os.MkdirAll(root, 0700); err != nil { + t.Fatal(err) + } + config.AppConfig = &config.ClicdConfig{StoragePools: []config.StoragePool{{ID: "test", Path: pool, ContentTypes: []string{config.StorageContentBackups}}}} + source := smallManifest().Container + source.DataDisks = []config.DataDisk{{ID: "source-data", Path: "/source-owned/disk.qcow2", StoragePoolID: "original", SizeGB: 1, Format: "qcow2", Attached: false}} + info, err := Create(context.Background(), "test", "portable test", "backup", source, func(_ context.Context, dir string, m *Manifest) error { + os.MkdirAll(filepath.Join(dir, "disks"), 0700) + os.WriteFile(filepath.Join(dir, "disks/system.qcow2"), []byte("disk payload"), 0600) + os.WriteFile(filepath.Join(dir, "disks/data-0.qcow2"), []byte("data payload"), 0600) + m.Files = []File{{Name: "disks/system.qcow2", Role: "system", Format: "qcow2"}, {Name: "disks/data-0.qcow2", Role: "data", DiskID: "source-data", Format: "qcow2"}} + return nil + }) + if err != nil { + t.Fatal(err) + } + if source.DataDisks[0].Path != "/source-owned/disk.qcow2" || source.DataDisks[0].StoragePoolID != "original" { + t.Fatal("export mutated live source disk descriptors") + } + if got := List("backup"); len(got) != 1 || got[0].ID != info.ID { + t.Fatalf("disk index not discovered after reconstructing registry: %+v", got) + } + m, dir, cleanup, err := OpenVerified(context.Background(), info.ID, "backup", nil) + if err != nil { + t.Fatal(err) + } + defer cleanup() + if len(m.Files) != 2 || m.Container.DataDisks[0].Attached || m.Container.DataDisks[0].Path != "" { + t.Fatal("detached disk missing or host path exported") + } + if _, err = os.Stat(filepath.Join(dir, "disks/data-0.qcow2")); err != nil { + t.Fatal(err) + } + _, p, err := Resolve(info.ID) + if err != nil { + t.Fatal(err) + } + file, _ := os.OpenFile(p, os.O_WRONLY, 0600) + file.WriteAt([]byte("x"), 12) + file.Close() + if _, _, _, err = OpenVerified(context.Background(), info.ID, "backup", nil); err == nil { + t.Fatal("archive checksum corruption not detected") + } +} + +func TestNewIdentityRetainsAccountsButNeverNetworkSchedulesOrDiskOwnership(t *testing.T) { + oldConfig := config.AppConfig + config.AppConfig = &config.ClicdConfig{} + defer func() { config.AppConfig = oldConfig }() + previous := allocateIdentityID + allocateIdentityID = func() int { return 99 } + defer func() { allocateIdentityID = previous }() + source := smallManifest().Container + source.ID = 1 + source.UUID = "source-id" + source.SSHPassword = "test-account-kept" + source.MACAddress = "52:54:00:01:02:03" + source.IP = "192.0.2.5" + source.PortMappings = []config.PortMapping{{HostPort: 20022, ContainerPort: 22}} + source.SnapshotScheduleEnabled = true + source.RestoreOnHostBoot = true + source.Status = "running" + source.DataDisks = []config.DataDisk{{ID: "old-data", Path: "/old/data"}} + c := NewIdentity(source, "restored", "new-pool") + if c.ID == source.ID || c.UUID == source.UUID || c.UUID == "" || c.IP != "" || c.MACAddress != "" || len(c.PortMappings) != 0 || c.Status != "stopped" || c.RestoreOnHostBoot || c.SnapshotScheduleEnabled || !c.Standalone || c.SSHPassword != source.SSHPassword { + t.Fatal("identity was not safely isolated") + } + c.DataDisks[0].Path = "new" + if source.DataDisks[0].Path != "/old/data" { + t.Fatal("clone shares mutable disk descriptor slice") + } + if _, _, err := Resolve("../../etc/shadow"); err == nil { + t.Fatal("invalid artifact lookup accepted") + } + if strings.Contains(c.UUID, "/") { + t.Fatal("unsafe UUID") + } +} diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 33dbb16..d39b186 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -33,6 +33,8 @@ const zhSidebar = [ { text: '镜像管理', link: '/features/images' }, { text: '网络与路由', link: '/features/networking' }, { text: '快照管理', link: '/features/snapshots' }, + { text: '磁盘、备份与克隆', link: '/features/storage-backups' }, + { text: '任务与历史指标', link: '/features/tasks' }, { text: '子用户', link: '/features/sub-users' }, { text: 'API 集成', link: '/features/api' }, { text: '主机报告', link: '/features/host-report' }, @@ -75,6 +77,8 @@ const enSidebar = [ { text: 'Images', link: '/en/features/images' }, { text: 'Networking & Routing', link: '/en/features/networking' }, { text: 'Snapshots', link: '/en/features/snapshots' }, + { text: 'Disks, Backups & Clones', link: '/en/features/storage-backups' }, + { text: 'Tasks & Metric History', link: '/en/features/tasks' }, { text: 'Sub-users', link: '/en/features/sub-users' }, { text: 'API Integration', link: '/en/features/api' }, { text: 'Host Report', link: '/en/features/host-report' }, diff --git a/docs/developer/architecture.md b/docs/developer/architecture.md index e90a493..04dc766 100644 --- a/docs/developer/architecture.md +++ b/docs/developer/architecture.md @@ -10,6 +10,7 @@ CLICD 由 Go 后端、React 前端和宿主机虚拟化能力组成。 - `internal/config`:配置和 SQLite 存储。 - `internal/lxc`:LXC 容器管理。 - `internal/kvm`:KVM/libvirt 虚拟机管理。 +- `internal/transfer`:全盘归档、校验、可移植备份和实例模板。 - `internal/cli`:命令行管理入口。 - `internal/server`:静态前端嵌入和 HTTP 服务。 - `internal/version`:版本号。 @@ -25,6 +26,8 @@ CLICD 由 Go 后端、React 前端和宿主机虚拟化能力组成。 - 容器详情:`ContainerDetail.tsx` - 镜像管理:`ImageManagement.tsx` - 快照管理:`Snapshots.tsx` +- 任务历史:`Tasks.tsx` +- 完整备份与实例模板:`PortableLibrary.tsx`(`/backups`、`/instance-templates`) - 路由管理:`Routing.tsx` - API 集成:`ApiIntegration.tsx` - 主机报告:`HostReport.tsx` @@ -39,3 +42,9 @@ CLICD 由 Go 后端、React 前端和宿主机虚拟化能力组成。 - `/api/*`:Web 面板和兼容接口。 - `/api/v1/*`:推荐给外部自动化系统使用的版本化接口。 - WebSSH 和 WebVNC 使用短期票据后建立 WebSocket 连接。 + +## 任务与存储状态 + +磁盘、备份、恢复、克隆和模板任务复用同实例队列锁。SQLite 独立历史表保存任务事件/结果及约 30 秒粒度的指标;通用运行中任务遇服务重启会记录为中断失败,待执行任务恢复排队。容器表同时持久化数据盘清单、独立系统盘模式和安装介质状态。 + +KVM 数据盘以受管 QCOW2 文件写入域 XML。LXC 数据盘使用 rootfs 外的 ext4 镜像挂载点和受管 `lxc.mount.entry`,避免冷复制 rootfs 时混入数据盘。完整归档逐盘校验并独立复制;旧快照在存在数据盘时拒绝创建和恢复。详见[存储边界](../features/storage-backups)和[任务历史](../features/tasks)。 diff --git a/docs/en/developer/architecture.md b/docs/en/developer/architecture.md index eb9f856..7e1caee 100644 --- a/docs/en/developer/architecture.md +++ b/docs/en/developer/architecture.md @@ -10,6 +10,7 @@ The backend entry point is `backend/main.go`, and HTTP routes are centralized in - `internal/config`: configuration and SQLite storage. - `internal/lxc`: LXC container management. - `internal/kvm`: KVM/libvirt virtual machine management. +- `internal/transfer`: complete disk archives, validation, portable backups and instance templates. - `internal/cli`: command-line management entry point. - `internal/server`: embedded frontend assets and HTTP service. - `internal/version`: version number. @@ -25,6 +26,8 @@ Main pages: - Container details: `ContainerDetail.tsx` - Image Management: `ImageManagement.tsx` - Snapshot Management: `Snapshots.tsx` +- Task history: `Tasks.tsx` +- Full backups and instance templates: `PortableLibrary.tsx` (`/backups`, `/instance-templates`) - Routing Management: `Routing.tsx` - API Integration: `ApiIntegration.tsx` - Host Report: `HostReport.tsx` @@ -39,3 +42,9 @@ For production builds, frontend artifacts are placed in `backend/internal/server - `/api/*`: web panel and compatibility APIs. - `/api/v1/*`: versioned APIs recommended for external automation. - WebSSH and WebVNC use short-lived tickets before opening WebSocket connections. + +## Task and Storage State + +Disk, backup, restore, clone and template tasks share per-instance queue locks. Independent SQLite history tables store task events/results and metrics sampled about every 30 seconds. Running generic operations become interrupted failures after service restart; pending operations return to the queue. Container metadata also persists data disks, standalone system disks and installation-media state. + +KVM data disks are managed QCOW2 files included in domain XML. LXC uses ext4 images mounted outside rootfs with managed `lxc.mount.entry` records, keeping data disks out of rootfs cold copies. Full archives validate and independently copy every disk. Existing snapshots reject instances with data disks. See [storage limits](../features/storage-backups) and [task history](../features/tasks). diff --git a/docs/en/features/api.md b/docs/en/features/api.md index ec3a2b6..1425468 100644 --- a/docs/en/features/api.md +++ b/docs/en/features/api.md @@ -289,6 +289,9 @@ print(resp.json()) | POST | `/api/v1/containers/{id}/reinstall` | Reinstall | | DELETE | `/api/v1/containers/{id}/delete` | Delete | | GET | `/api/v1/containers/{id}/usage` | Resource usage | +| GET | `/api/v1/containers/{id}/history` | Persisted resource history, up to 7 days | +| GET | `/api/v1/containers/{id}/installation-media` | KVM media, boot mode and available ISOs | +| PUT | `/api/v1/containers/{id}/installation-media` | Mount/change/eject ISO and set boot mode while stopped | | GET | `/api/v1/containers/{id}/traffic` | Traffic statistics | | POST | `/api/v1/containers/{id}/traffic-reset` | Reset traffic | | PUT | `/api/v1/containers/{id}/traffic-limit` | Update traffic limits | @@ -315,6 +318,32 @@ print(resp.json()) | POST | `/api/v1/containers/{id}/snapshots/schedule` | Schedule snapshots | | PUT | `/api/v1/containers/{id}/snapshots/quota` | Snapshot quota | +### Disks, Full Backups and Instance Templates + +Disk mutations require administrator access and `container:resize`; sub-users can only read their assigned instances' disk inventory. Full backup, restore, clone and template endpoints require administrator access (`admin:access` for external API keys). See [storage limits and request examples](./storage-backups). + +| Method | Path | Description | +| --- | --- | --- | +| GET | `/api/v1/containers/{id}/disks` | Actual capacity, allocated space and editing capabilities | +| POST | `/api/v1/containers/{id}/disks` | Add a managed data disk | +| PUT | `/api/v1/containers/{id}/disks/system` | Grow the system disk offline; no shrinking | +| PUT | `/api/v1/containers/{id}/disks/{disk_id}` | Grow a data disk offline | +| PUT | `/api/v1/containers/{id}/disks/{disk_id}/attachment` | Attach/detach a data disk | +| DELETE | `/api/v1/containers/{id}/disks/{disk_id}` | Permanently delete a data disk; requires `delete_data: true` | +| POST | `/api/v1/containers/{id}/backup` | Create a full backup | +| POST | `/api/v1/containers/{id}/clone` | Full clone to a new stopped instance | +| POST | `/api/v1/containers/{id}/template` | Save an installed-instance template | +| GET | `/api/v1/backups` | List full backups | +| POST | `/api/v1/backups` | Upload a `.clicd.tar.gz` full backup | +| GET | `/api/v1/backups/{artifact_id}` | Download a full backup | +| DELETE | `/api/v1/backups/{artifact_id}` | Delete a backup artifact | +| POST | `/api/v1/backups/{artifact_id}/restore` | Restore a new stopped instance | +| GET | `/api/v1/instance-templates` | List installed-instance templates | +| DELETE | `/api/v1/instance-templates/{artifact_id}` | Delete an instance template | +| POST | `/api/v1/instance-templates/{artifact_id}/instantiate` | Create a new stopped instance from a template | + +Disk mutations and backup/restore/clone/template operations return `202` with `data.task_id`. Poll `GET /api/v1/tasks` for final status, stage logs and results. A backup upload itself returns `201` and does not start a restore. Scheduled snapshots and instances with data disks are mutually exclusive workflows. + ### Platform Management | Method | Path | Description | @@ -328,6 +357,8 @@ print(resp.json()) | POST | `/api/v1/images/cancel` | Cancel image download | | DELETE | `/api/v1/images/delete` | Delete image cache | | PUT | `/api/v1/images/toggle` | Enable or disable image | +| POST | `/api/v1/images/upload` | Local ISO/QCOW2 upload, `multipart/form-data`, at most 32 GiB | +| GET | `/api/v1/host-history` | Persisted host metrics, up to 7 days | | GET | `/api/v1/swap` | Swap information | | POST | `/api/v1/swap` | Adjust Swap | | GET | `/api/v1/language` | Current panel language | diff --git a/docs/en/features/containers.md b/docs/en/features/containers.md index 26b70fb..a393a28 100644 --- a/docs/en/features/containers.md +++ b/docs/en/features/containers.md @@ -51,6 +51,8 @@ When reinstalling a Linux system, you may pass `ssh_auth_mode`, `ssh_password`, The container details page supports resource usage, traffic limit changes, resource limit changes, and expiration changes. +Use disk management in instance details for system-disk growth and data disks while the instance is stopped. See [Disks, Backups and Clones](./storage-backups) for full backup, restore, full clone and instance templates, and [Tasks](./tasks) for progress and errors. + ```http GET /api/v1/containers/{id}/usage GET /api/v1/containers/{id}/traffic diff --git a/docs/en/features/dashboard.md b/docs/en/features/dashboard.md index ba2cb51..e65086e 100644 --- a/docs/en/features/dashboard.md +++ b/docs/en/features/dashboard.md @@ -1,5 +1,7 @@ # Dashboard +Host and instance metric history is sampled about every 30 seconds and persisted in SQLite for up to 7 days across service restarts. Task records and stage logs are persisted too; see [Tasks and Metric History](./tasks). + The dashboard shows the overall state of the host and virtualization resources. ## Metrics diff --git a/docs/en/features/images.md b/docs/en/features/images.md index 9c4d95c..14d0578 100644 --- a/docs/en/features/images.md +++ b/docs/en/features/images.md @@ -2,6 +2,8 @@ Image Management maintains templates used to create containers or virtual machines. +The main page shows downloaded/downloading images; open the download dialog for the preset catalog. Upload local ISO/QCOW2 files as KVM images or maintain third-party download sources. + ## Supported Template Types The project includes common Linux distribution templates such as Debian, Ubuntu, Alpine, CentOS, Fedora, Arch Linux, and Rocky Linux. KVM templates use the corresponding distribution cloud image resources. @@ -15,6 +17,7 @@ POST /api/v1/images/download POST /api/v1/images/cancel DELETE /api/v1/images/delete PUT /api/v1/images/toggle +POST /api/v1/images/upload ``` - `templates` returns available template definitions. @@ -23,6 +26,17 @@ PUT /api/v1/images/toggle - `cancel` cancels a download task. - `delete` removes the local image cache. - `toggle` controls whether a template can be used during creation. +- `upload` accepts `multipart/form-data` with `file`, optionally adding `name`, `description`, `arch`, `sha256`, `provisioner`, `distro` and `release`. A file can be at most **32 GiB**; select a storage pool with the `storage_pool_id` query parameter. + +Image mutations require administrator permission. External API keys also need `admin:access` and the corresponding `image:*` scopes. + +## Local Images and Generic ISO Installation + +Uploads validate file content, optional SHA-256 and disk structure. A filename extension alone is insufficient. QCOW2 files must be independent, without external backing/data files, encryption or internal snapshots. Images are registered only after the full upload and validation succeed. + +`provisioner=manual-iso` supports manual Linux, Windows and other OS installation: create an empty system disk, attach the ISO and install through WebVNC. It does not require a Windows unattended image or wait for SSH. The KVM installation-media button in instance details opens a dialog to select a downloaded ISO, choose CD/disk boot or eject the media while the VM is stopped. Arbitrary host paths are not accepted. Media and ejection state persist across power operations and resource changes. An explicit reinstall prepares media from the newly selected template. + +Preinstalled QCOW2 defaults to `manual-disk`, preserving its accounts and network settings. Linux images with cloud-init can explicitly use `linux-cloud-init`. Uploaded images must match the host CPU architecture. For installed-instance templates including data disks, use [full backups and clones](./storage-backups). ## Windows Images diff --git a/docs/en/features/snapshots.md b/docs/en/features/snapshots.md index 8397c65..954ccb4 100644 --- a/docs/en/features/snapshots.md +++ b/docs/en/features/snapshots.md @@ -1,5 +1,7 @@ # Snapshot Management +Instances with data disks cannot create/restore existing snapshots or enable scheduled snapshots. Detached disks count too. Disable an active snapshot schedule before adding a data disk. Use [full backups](./storage-backups) for rollback, migration or cloning that includes the system disk and all data disks. + Snapshots save the current state of a container so it can be rolled back before upgrades, configuration changes, or delivery. ## Global Overview diff --git a/docs/en/features/storage-backups.md b/docs/en/features/storage-backups.md new file mode 100644 index 0000000..0dc14bd --- /dev/null +++ b/docs/en/features/storage-backups.md @@ -0,0 +1,85 @@ +# Disks, Full Backups and Clones + +Administrators manage disks and backups from instance details. Sub-users can read disk information for their assigned instances. Long operations return a `task_id` through the [task queue](./tasks); wait for completion before the next disk or lifecycle operation. + +## Grow a System Disk + +Shut down the instance first. The backend checks the actual LXC/libvirt state; running, paused and frozen instances cannot change disks. + +| Runtime | Supported operation | After growing | +| --- | --- | --- | +| KVM | Offline growth of managed QCOW2 system/data disks; shrinking is rejected. | Extend partitions, LVM and filesystems inside the guest yourself. CLICD only enlarges the virtual disk. | +| LXC | Offline growth of managed ext4 loop images, including a filesystem check and `resize2fs`. | Start the container after success. Directory rootfs layouts, other filesystems and quota backends do not have a general resize implementation. | + +Disk inventory reports the actual image capacity and allocated host space. These can differ for sparse files. Resource limits do not replace a real disk resize. + +## Data Disks + +Each instance supports up to 8 managed data disks. Select a name, capacity and optional storage pool. LXC also needs a guest mount path. + +- KVM uses independent QCOW2 files. Partition, format and configure persistent mounts inside the guest. +- LXC uses independent ext4 images mounted outside rootfs and bind-mounted into the guest. Paths must be `/data`, `/mnt`, `/srv`, or their descendants. Paths cannot overlap, cross symlinks or hide an existing non-empty directory. +- Add, grow, attach, detach and delete require a stopped instance. Detach keeps the file. Delete requires explicit `delete_data: true` and permanently removes the managed data file. +- Power operations and system reinstallation preserve data disks. Full backups include every managed disk, including detached disks. + +## Full Backups + +A full backup contains the system disk, all data disks and necessary instance settings. Download it as `.clicd.tar.gz` and import it on a CLICD node with a compatible CPU architecture. KVM disks become independent QCOW2 files without the original backing image. LXC stores independent ext4 images. + +Backup creation, full cloning and saving an instance template use cold copies. A running source is temporarily stopped, and CLICD attempts to restore its prior running state afterward. Allow for downtime and sufficient disk space. + +Current portable format limits: + +- The archive and its expanded disk-file payload each have a **64 GiB** limit. LXC raw images count their full logical capacity toward the payload. Sparse KVM QCOW2 virtual capacities can exceed 64 GiB, with a 16 TiB virtual-capacity limit per disk. +- Import/restore checks the format version, CPU architecture, complete disk inventory and every file's SHA-256. Archives missing a data disk are rejected. +- Compression does not bypass the expanded-payload limit. After shutdown, KVM estimates the flattened QCOW2 file size and checks temporary copy space. Creation, extraction and restore still need additional capacity. + +Archives preserve guest accounts, passwords and disk contents, and can contain saved SSH login information. Handle downloaded archives as sensitive data. + +## Restore, Full Clone and Instance Templates + +All three operations create a new instance, leave it **stopped**, and preserve the source: + +| Operation | Source | +| --- | --- | +| Restore backup | A locally created or uploaded full backup. | +| Full clone | An independent copy of the current instance's disks. | +| Instantiate template | A reusable full template saved from an installed instance. | + +The new instance receives a new ID, UUID, MAC and host storage paths. Public IPv4/IPv6 assignments, port mappings, sub-user grants, firewall policies and snapshot schedules are not copied directly. New NAT management ports can be allocated. Linux guests also receive a new hostname, machine identity, SSH host keys and DHCP network configuration. Windows networking is adjusted to DHCP on first boot. **Guest accounts and login passwords are preserved**. + +The instance-template page can create 1–10 copies per submission. Multiple copies use a name prefix and numbered suffixes, with one independent task per copy. Partial failures keep accepted tasks visible and identify each rejected name. + +KVM restore, clone and template instantiation require the guestfs tools `virt-customize`, `virt-inspector`, `virt-cat`, `virt-edit` and `virt-filesystems` to update guest network identity offline. The tools must recognize a single installed operating system; encrypted disks, multiple operating systems and uninstalled blank disks return an explicit error. Windows first-boot networking additionally needs a guestfs-compatible `rhsrvany` or `pvvxsvc` helper. Missing dependencies prevent publication of the new instance. See [installation dependencies](../guide/installation#kvm-guestfs). + +## Existing Snapshots + +The existing snapshot workflow supports the system disk. If an instance has any data disks, creating/restoring old snapshots and enabling scheduled snapshots are rejected to prevent incomplete rollback. Detached disks count too. Disable an existing snapshot schedule before adding data disks. + +Use full backups for rollback or migration with data disks. Snapshot quotas do not limit full backup files; remove old artifacts separately in backup management. + +## API + +```http +GET /api/v1/containers/{id}/disks +POST /api/v1/containers/{id}/disks +PUT /api/v1/containers/{id}/disks/system +PUT /api/v1/containers/{id}/disks/{disk_id} +PUT /api/v1/containers/{id}/disks/{disk_id}/attachment +DELETE /api/v1/containers/{id}/disks/{disk_id} +POST /api/v1/containers/{id}/backup +POST /api/v1/containers/{id}/clone +POST /api/v1/containers/{id}/template +GET /api/v1/backups +POST /api/v1/backups +GET /api/v1/backups/{artifact_id} +DELETE /api/v1/backups/{artifact_id} +POST /api/v1/backups/{artifact_id}/restore +GET /api/v1/instance-templates +DELETE /api/v1/instance-templates/{artifact_id} +POST /api/v1/instance-templates/{artifact_id}/instantiate +``` + +Grow with `{"size_gb": 20}`, change attachment with `{"attached": false}`, and delete with `{"delete_data": true}`. Disk/restore requests use IDs and do not accept arbitrary host paths. + +Upload backups with the `file` field in `multipart/form-data`, optionally adding `name` and `storage_pool_id`. Restore/clone/instantiate requests use `{"name":"new-instance","storage_pool_id":"pool-id","assign_nat":true,"port_mapping_count":2}`. Asynchronous operations return `202` with `data.task_id`. A successful backup upload returns `201` and does not automatically restore an instance. diff --git a/docs/en/features/tasks.md b/docs/en/features/tasks.md new file mode 100644 index 0000000..4139248 --- /dev/null +++ b/docs/en/features/tasks.md @@ -0,0 +1,23 @@ +# Tasks and Metric History + +The Tasks page shows lifecycle operations, disk growth, data-disk changes, full backups, restore, clone and template operations with status, duration, errors and stage logs. Long changes for the same instance run sequentially. + +```http +GET /api/v1/tasks +DELETE /api/v1/tasks/{task_id} +``` + +After a `202` response, find `data.task_id` in the task list. `done` indicates success; inspect `error` and stage logs for `failed` tasks. A running task cannot be removed. Deleting completed history does not undo disk, backup or instance changes. + +## Service Restarts + +- Task records and stage logs are stored in SQLite. Terminal history is retained for up to 30 days and 1,000 records, with up to 200 stage events per task. +- Pending generic operations return to the queue. +- Disk, backup, restore, clone and other generic operations that were running at restart become `failed/interrupted` and are not blindly replayed. Inspect actual resources before retrying. +- Sub-users only see tasks for assigned instances. Internal execution payloads and credentials are not exposed as task results. + +## Resource History + +Host and instance CPU, memory, network and disk I/O history is sampled approximately every 30 seconds and persisted for up to 7 days across service restarts. Downtime and periods when the service was not running are not backfilled. + +Back up the panel database to preserve task and metric history. Full instance backups contain guest disks and instance settings and do not replace panel database backups. diff --git a/docs/en/guide/configuration.md b/docs/en/guide/configuration.md index 9bba804..9898576 100644 --- a/docs/en/guide/configuration.md +++ b/docs/en/guide/configuration.md @@ -8,12 +8,14 @@ After installation, CLICD runs as a systemd service. Runtime configuration and t | --- | --- | | Web port | Defaults to `8999`, listening on `0.0.0.0:8999`. | | Administrator account | Used to log in to the web panel and manage API keys. | -| Database | SQLite storage for container metadata, sub-users, audit logs, API keys, and more. | +| Database | SQLite storage for instance/data-disk metadata, sub-users, audit logs, API keys, task stage logs and metric history. | | NAT port range | Used for random ports and port mapping allocation. | | IPv6 prefixes | Used when the host has routable IPv6 prefixes. | ## Service Commands +Terminal task history is retained for up to 30 days/1,000 records and metric history for up to 7 days. Full instance backups contain guest disks and instance settings; back up the database separately for panel accounts, API keys, grants and history. + ```bash systemctl status clicd systemctl restart clicd diff --git a/docs/en/guide/installation.md b/docs/en/guide/installation.md index 4b91f4e..d3dab4a 100644 --- a/docs/en/guide/installation.md +++ b/docs/en/guide/installation.md @@ -39,6 +39,25 @@ http://YOUR_SERVER_IP:8999 Use the administrator credentials printed by the installer for the first login. In production, restrict access at the firewall or reverse proxy layer and change the default username and password as soon as possible. +## Optional KVM Restore and Clone Dependencies {#kvm-guestfs} + +KVM full restore, full clone and instance-template instantiation use `virt-customize` to update guest network identity offline. On supported KVM architectures, the installer tries these packages in order and checks whether the command is actually available: + +| Distribution | Candidate packages | +| --- | --- | +| Debian / Ubuntu | `guestfs-tools`, falling back to `libguestfs-tools`. | +| RHEL / Rocky / AlmaLinux / Fedora | `libguestfs-tools`, then `guestfs-tools` and `libguestfs-tools-c`. | +| Alpine | Try `guestfs-tools` and `libguestfs-tools`; show a clear notice if unavailable for the repository/architecture. | + +A missing dependency does not block basic LXC/KVM installation. The affected KVM restore/clone tasks fail explicitly instead of skipping identity updates. See the Ubuntu [guestfs-tools file list](https://packages.ubuntu.com/en/jammy/arm64/guestfs-tools/filelist) and the [Red Hat package documentation](https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/virtualization_deployment_and_administration_guide/sect-guest_virtual_machine_disk_access_with_offline_tools-using_virt_customize). + +```bash +command -v virt-customize +virt-customize --version +``` + +Growing managed LXC ext4 loop images also requires `e2fsck`, `resize2fs`, `losetup` and mount utilities. The installer retains `e2fsprogs` and related dependencies. Keep `conntrack`, which is still used for NAT connection cleanup. + ## Uninstall ```bash diff --git a/docs/en/guide/introduction.md b/docs/en/guide/introduction.md index 2e16f9d..b77ca6b 100644 --- a/docs/en/guide/introduction.md +++ b/docs/en/guide/introduction.md @@ -11,6 +11,8 @@ CLICD is a lightweight virtualization management panel for LXC and KVM. It bring - Open WebSSH or WebVNC from the browser. - Manage image downloads, enablement, and local cache. - Create, restore, and delete snapshots, plus scheduled snapshots and quotas. +- Grow managed disks offline, add data disks, and use full backup/import, independent clones and reusable installed-instance templates. +- Inspect persisted task stages and resource history across panel restarts. - Keep operation audit logs and login logs. - Create sub-user access links for specific containers. - Integrate automation through API keys and `/api/v1`. diff --git a/docs/en/operations/deployment.md b/docs/en/operations/deployment.md index 5e03218..78a4cde 100644 --- a/docs/en/operations/deployment.md +++ b/docs/en/operations/deployment.md @@ -44,3 +44,5 @@ Back up regularly: - SQLite database. - Container configuration. - Snapshots or external data backups for important containers. + +[Full instance backups](../features/storage-backups) include the system disk and all managed data disks and support download/import. They do not replace configuration/database backups; task and metric history remains in the panel SQLite database. Use full backups for instances with data disks instead of existing system-disk snapshots. diff --git a/docs/features/api.md b/docs/features/api.md index ed7ddd7..5a0f813 100644 --- a/docs/features/api.md +++ b/docs/features/api.md @@ -289,6 +289,9 @@ print(resp.json()) | POST | `/api/v1/containers/{id}/reinstall` | 重装 | | DELETE | `/api/v1/containers/{id}/delete` | 删除 | | GET | `/api/v1/containers/{id}/usage` | 资源用量 | +| GET | `/api/v1/containers/{id}/history` | 持久化资源历史,最多 7 天 | +| GET | `/api/v1/containers/{id}/installation-media` | KVM 安装介质、启动方式及可选 ISO | +| PUT | `/api/v1/containers/{id}/installation-media` | 停止状态下挂载/更换/弹出 ISO 与设置启动方式 | | GET | `/api/v1/containers/{id}/traffic` | 流量统计 | | POST | `/api/v1/containers/{id}/traffic-reset` | 重置流量 | | PUT | `/api/v1/containers/{id}/traffic-limit` | 调整流量限制 | @@ -315,6 +318,32 @@ print(resp.json()) | POST | `/api/v1/containers/{id}/snapshots/schedule` | 计划快照 | | PUT | `/api/v1/containers/{id}/snapshots/quota` | 快照配额 | +### 磁盘、完整备份与实例模板 + +磁盘修改需管理员和 `container:resize` 权限,子用户仅可读取自己实例的磁盘清单。完整备份、恢复、克隆和模板接口需管理员权限(外部 API Key 需 `admin:access`)。支持边界与请求示例见[磁盘、备份与克隆](./storage-backups)。 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| GET | `/api/v1/containers/{id}/disks` | 真实容量、已分配空间与编辑能力 | +| POST | `/api/v1/containers/{id}/disks` | 添加受管数据盘 | +| PUT | `/api/v1/containers/{id}/disks/system` | 离线扩容系统盘,只增不减 | +| PUT | `/api/v1/containers/{id}/disks/{disk_id}` | 离线扩容数据盘 | +| PUT | `/api/v1/containers/{id}/disks/{disk_id}/attachment` | 连接/断开数据盘 | +| DELETE | `/api/v1/containers/{id}/disks/{disk_id}` | 永久删除数据盘,需 `delete_data: true` | +| POST | `/api/v1/containers/{id}/backup` | 创建完整备份 | +| POST | `/api/v1/containers/{id}/clone` | 完整克隆为新停止实例 | +| POST | `/api/v1/containers/{id}/template` | 保存已安装实例模板 | +| GET | `/api/v1/backups` | 完整备份列表 | +| POST | `/api/v1/backups` | 上传 `.clicd.tar.gz` 完整备份 | +| GET | `/api/v1/backups/{artifact_id}` | 下载完整备份 | +| DELETE | `/api/v1/backups/{artifact_id}` | 删除备份文件 | +| POST | `/api/v1/backups/{artifact_id}/restore` | 恢复为新停止实例 | +| GET | `/api/v1/instance-templates` | 已安装实例模板列表 | +| DELETE | `/api/v1/instance-templates/{artifact_id}` | 删除实例模板 | +| POST | `/api/v1/instance-templates/{artifact_id}/instantiate` | 从模板创建新停止实例 | + +磁盘修改及备份/恢复/克隆/模板操作返回 `202` 和 `data.task_id`;持续查询 `GET /api/v1/tasks`,查看最终状态、阶段日志和结果。上传备份本身返回 `201`,不会自动恢复。计划快照与带数据盘工作流互斥。 + ### 平台管理 | 方法 | 路径 | 说明 | @@ -328,6 +357,8 @@ print(resp.json()) | POST | `/api/v1/images/cancel` | 取消镜像下载 | | DELETE | `/api/v1/images/delete` | 删除镜像缓存 | | PUT | `/api/v1/images/toggle` | 启用/禁用镜像 | +| POST | `/api/v1/images/upload` | 本地 ISO/QCOW2 上传,`multipart/form-data`,文件最多 32 GiB | +| GET | `/api/v1/host-history` | 持久化主机历史指标,最多 7 天 | | GET | `/api/v1/swap` | Swap 信息 | | POST | `/api/v1/swap` | 调整 Swap | | GET | `/api/v1/language` | 当前面板语言 | diff --git a/docs/features/containers.md b/docs/features/containers.md index 82b69e4..bffd6f3 100644 --- a/docs/features/containers.md +++ b/docs/features/containers.md @@ -51,6 +51,8 @@ DELETE /api/v1/containers/{id}/delete 容器详情页支持查看资源用量,调整流量限制、资源限制和到期时间。 +系统盘扩容和数据盘管理从详情页的磁盘管理入口操作,要求实例停止。完整备份、恢复、克隆及保存实例模板见[磁盘、备份与克隆](./storage-backups)。运行进度与错误可在[任务页面](./tasks)查看。 + ```http GET /api/v1/containers/{id}/usage GET /api/v1/containers/{id}/traffic diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 2198ea8..2a78d10 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -2,6 +2,8 @@ 控制面板用于查看宿主机和虚拟化资源的整体状态。 +宿主机和实例历史指标约每 30 秒采样并持久化到 SQLite,最多保留 7 天,面板重启后继续展示。任务记录和阶段日志同样持久化,见[任务与历史指标](./tasks)。 + ## 统计项 - 容器总数、运行中数量和停止数量。 diff --git a/docs/features/images.md b/docs/features/images.md index 405c6e3..7c84837 100644 --- a/docs/features/images.md +++ b/docs/features/images.md @@ -2,6 +2,8 @@ 镜像管理用于维护可创建容器或虚拟机的模板。 +主页面显示本地已下载和正在下载的镜像;预设目录从下载按钮打开。可将本地 ISO/QCOW2 文件上传为 KVM 镜像,也可维护第三方下载源。 + ## 支持的模板类型 项目内置了常见 Linux 发行版模板,例如 Debian、Ubuntu、Alpine、CentOS、Fedora、Arch Linux、Rocky Linux 等。KVM 模板会使用对应发行版的云镜像资源。 @@ -15,6 +17,7 @@ POST /api/v1/images/download POST /api/v1/images/cancel DELETE /api/v1/images/delete PUT /api/v1/images/toggle +POST /api/v1/images/upload ``` - `templates` 返回可用模板定义。 @@ -23,9 +26,18 @@ PUT /api/v1/images/toggle - `cancel` 取消下载任务。 - `delete` 删除本地镜像缓存。 - `toggle` 控制模板是否对创建流程可用。 +- `upload` 使用 `multipart/form-data` 上传 `file`,可附 `name`、`description`、`arch`、`sha256`、`provisioner`、`distro`、`release`;单文件最多 **32 GiB**,存储池通过查询参数 `storage_pool_id` 指定。 镜像源创建、下载、取消、删除和启用管理需要管理员权限。使用外部 API Key 时,需同时授予 `admin:access` 和对应的 `image:*` 操作权限。 +## 本地镜像与通用 ISO + +上传会检查文件内容、可选 SHA-256 及磁盘格式,扩展名本身不能证明文件有效。QCOW2 必须是独立磁盘,不能依赖外部 backing/data file,也不能带加密或内嵌快照。只会在上传和验证全部成功后注册镜像。 + +`provisioner=manual-iso` 用于 Linux、Windows 或其他系统的手动安装:创建空白系统盘并挂载 ISO,通过 WebVNC 安装,不强制生成 Windows 无人值守盘或等待 SSH。详情页顶部的“KVM 安装介质”按钮打开介质弹窗,支持停止状态下选择已下载 ISO、设置从光盘/磁盘启动或弹出 ISO;界面不接受任意宿主机路径。介质选择及弹出状态持久化,开关机和修改资源不会重新挂回已弹出的 ISO;主动重装则按新选模板重新准备安装介质。 + +预装 QCOW2 默认使用 `manual-disk`,保留镜像内已有账户和网络设置;具备 cloud-init 的 Linux 镜像可明确选择 `linux-cloud-init`。上传的架构必须与宿主机匹配。完整实例模板(含数据盘)使用[完整备份与克隆](./storage-backups)的模板工作流。 + ## 私网镜像源 下载器默认只连接公网镜像。要使用内网镜像站,请在服务器上设置 `CLICD_IMAGE_MIRROR_ORIGINS`,列出允许访问的来源,多个来源用逗号分隔: diff --git a/docs/features/snapshots.md b/docs/features/snapshots.md index ad7b033..bc96e4e 100644 --- a/docs/features/snapshots.md +++ b/docs/features/snapshots.md @@ -2,6 +2,8 @@ 快照用于保存容器当前状态,方便在升级、变更配置或交付前回滚。 +配置数据盘的实例不能创建或恢复旧快照,也不能启用计划快照;已断开的数据盘同样计入。添加数据盘前请先关闭现有计划快照。需要包含系统盘和全部数据盘的回滚、迁移或克隆时,请使用[完整备份](./storage-backups)。 + ## 全局总览 ```http diff --git a/docs/features/storage-backups.md b/docs/features/storage-backups.md new file mode 100644 index 0000000..13233ab --- /dev/null +++ b/docs/features/storage-backups.md @@ -0,0 +1,85 @@ +# 磁盘、完整备份与克隆 + +实例详情页的磁盘管理和备份操作由管理员执行;子用户可查看自己授权实例的磁盘信息。耗时操作进入[任务队列](./tasks),返回 `task_id`,应等待任务完成后再进行下一项磁盘或生命周期操作。 + +## 系统盘扩容 + +必须先正常关闭实例。后端检查 LXC/libvirt 的实际状态,运行、暂停或冻结状态都不能修改磁盘。 + +| 类型 | 支持范围 | 扩容后的操作 | +| --- | --- | --- | +| KVM | 受管 QCOW2 系统盘和数据盘离线扩容,只增不减。 | 面板只增加虚拟磁盘容量;客户机内的分区、LVM、文件系统需自行扩展。 | +| LXC | 受管 ext4 loop 镜像离线扩容,执行文件系统检查和 `resize2fs`。 | 成功后启动即可使用;目录型 rootfs、其他文件系统和 quota 后端暂不提供通用扩容。 | + +磁盘管理显示实际镜像容量和已分配的宿主机空间,两者可能因稀疏文件而不同。资源限制接口不能替代实际磁盘扩容。 + +## 数据盘 + +每台实例最多管理 8 块数据盘。添加时指定名称、容量和可选存储池;LXC 还需指定客户机挂载路径。 + +- KVM 数据盘使用独立 QCOW2 文件。连接后由客户机自行分区、格式化并配置持久挂载。 +- LXC 数据盘使用独立 ext4 镜像,挂载在宿主机受管目录后绑定进容器。客户机路径仅允许 `/data`、`/mnt`、`/srv` 及其子目录;路径不能交叠、经过符号链接或隐藏已有的非空目录。 +- 添加、扩容、连接、断开和删除均要求实例停止。断开保留文件;删除需要显式确认 `delete_data: true`,会永久删除受管数据文件。 +- 开关机和重装系统盘会保留数据盘配置和数据。完整备份包含连接和已断开的所有受管数据盘。 + +## 完整备份 + +完整备份保存系统盘、全部数据盘及必要的实例配置,可以下载为 `.clicd.tar.gz`,再上传到兼容架构的 CLICD 节点恢复。KVM 磁盘会转换为不依赖原镜像 backing file 的独立 QCOW2;LXC 保存独立 ext4 镜像。 + +创建备份、完整克隆和保存实例模板采用冷复制。运行中的源实例会被暂时关闭,复制后尝试恢复原运行状态;请预留业务中断窗口和足够的存储空间。 + +当前可移植格式的边界: + +- 归档文件和解包后的磁盘文件负载分别最多 **64 GiB**。LXC 使用 raw 镜像,系统盘与数据盘的逻辑容量也会计入这一负载;KVM 的稀疏 QCOW2 虚拟容量可大于 64 GiB,单盘虚拟容量最多 16 TiB。 +- 导入/恢复会校验格式版本、CPU 架构、磁盘清单和每个文件的 SHA-256;不接受缺少数据盘的归档。 +- 压缩率不会绕过解包负载限制;KVM 在停机后估算独立 QCOW2 的实际文件大小,并检查临时复制空间。创建、解包和恢复仍需额外空间。 + +备份保留客户机账户、密码和磁盘内数据,也可能包含面板保存的 SSH 登录信息。请按敏感数据管理下载的归档。 + +## 恢复、完整克隆和实例模板 + +三种操作都会创建新实例,并默认保持 **停止**,不会覆盖原实例: + +| 操作 | 来源 | +| --- | --- | +| 恢复备份 | 本机创建或上传的完整备份。 | +| 完整克隆 | 当前实例的独立全盘副本。 | +| 实例模板实例化 | 从已安装实例保存的完整模板,可重复创建。 | + +实例模板页面支持一次创建 1–10 个副本。多个副本使用名称前缀和数字后缀,每个副本有独立任务;部分失败时会保留已提交的任务并显示对应名称的错误。 + +新实例生成新的 ID、UUID、MAC 和宿主机存储路径。原公网 IPv4/IPv6、端口映射、子用户授权、防火墙策略及计划快照不会直接复制;可按请求分配新的 NAT 管理端口。Linux 客户机还会更新主机名、机器标识、SSH 主机密钥和 DHCP 网络配置;Windows 网络在首次启动时调整为 DHCP。**客户机账户和登录密码保留**,不会伪造新的安装密码。 + +KVM 恢复、克隆和模板实例化需要宿主机提供 guestfs 的 `virt-customize`、`virt-inspector`、`virt-cat`、`virt-edit` 和 `virt-filesystems`,用于离线更新客户机网络身份。仅支持工具能够识别的单系统安装;加密、多系统和未安装系统的空盘会明确失败。Windows 首次启动网络配置还需要 guestfs 可用的 `rhsrvany` 或 `pvvxsvc` 辅助程序;缺少依赖时不会发布新实例。安装包和排查方式见[安装说明](../guide/installation#kvm-guestfs)。 + +## 与快照的关系 + +现有快照仅支持系统盘工作流。实例只要配置了数据盘,创建或恢复旧快照、启用计划快照都会被拒绝,避免漏盘回滚;已断开的数据盘也计入这一判断。添加数据盘前需先关闭现有计划快照。 + +需要带数据盘回滚或迁移时使用完整备份。快照配额不控制完整备份文件数量,应在备份管理页单独清理不再需要的文件。 + +## API + +```http +GET /api/v1/containers/{id}/disks +POST /api/v1/containers/{id}/disks +PUT /api/v1/containers/{id}/disks/system +PUT /api/v1/containers/{id}/disks/{disk_id} +PUT /api/v1/containers/{id}/disks/{disk_id}/attachment +DELETE /api/v1/containers/{id}/disks/{disk_id} +POST /api/v1/containers/{id}/backup +POST /api/v1/containers/{id}/clone +POST /api/v1/containers/{id}/template +GET /api/v1/backups +POST /api/v1/backups +GET /api/v1/backups/{artifact_id} +DELETE /api/v1/backups/{artifact_id} +POST /api/v1/backups/{artifact_id}/restore +GET /api/v1/instance-templates +DELETE /api/v1/instance-templates/{artifact_id} +POST /api/v1/instance-templates/{artifact_id}/instantiate +``` + +扩容请求为 `{"size_gb": 20}`,连接状态为 `{"attached": false}`,删除为 `{"delete_data": true}`。数据盘和恢复操作只接受磁盘/归档 ID,不接受任意宿主机路径。 + +备份上传使用 `multipart/form-data` 的 `file` 字段;可附 `name` 和 `storage_pool_id`。恢复、克隆和模板实例化使用 `{"name":"new-instance","storage_pool_id":"pool-id","assign_nat":true,"port_mapping_count":2}`。异步请求返回 `202` 和 `data.task_id`;上传备份完成返回 `201`,并不自动恢复实例。 diff --git a/docs/features/tasks.md b/docs/features/tasks.md new file mode 100644 index 0000000..3a13eed --- /dev/null +++ b/docs/features/tasks.md @@ -0,0 +1,23 @@ +# 任务与历史指标 + +任务页面集中显示生命周期操作、磁盘扩容、数据盘管理、完整备份、恢复、克隆和模板保存的状态、耗时、错误与阶段日志。同一个实例的耗时变更按顺序执行,不会并发删除正在修改的磁盘。 + +```http +GET /api/v1/tasks +DELETE /api/v1/tasks/{task_id} +``` + +异步接口返回 `202` 后,使用 `data.task_id` 在任务列表中查询;`done` 表示成功,`failed` 时应查看 `error` 和阶段日志。运行中的任务不能从列表删除;删除已完成任务记录不会撤销其磁盘、备份或实例变更。 + +## 面板重启 + +- 任务记录与阶段日志持久化到 SQLite,终态记录保留最多 30 天、1000 条;每个任务最多保留 200 条阶段事件。 +- 已排队、尚未开始的通用操作会恢复排队。 +- 服务重启时正在执行的磁盘、备份、恢复、克隆等通用操作会标记为 `failed/interrupted`,不会盲目重跑。检查实际资源状态后再决定是否重试。 +- 子用户只能看到授权实例对应的任务;内部执行参数和凭据不会作为任务结果返回。 + +## 资源历史 + +宿主机与实例 CPU、内存、网络和磁盘 I/O 历史按约 30 秒采样、持久化保存最多 7 天,服务重启后继续显示。指标不是连续监控期间的回填:停机和服务未运行的时段不会自动补样。 + +配置数据库的备份同时保护任务和指标历史;完整实例备份关注客户机磁盘与实例配置,不替代面板数据库备份。 diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index f66931d..2ed83bb 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -8,12 +8,14 @@ CLICD 安装后会以 systemd 服务运行,运行时配置和数据库保存 | --- | --- | | Web 端口 | 默认 `8999`,服务启动时监听 `0.0.0.0:8999`。 | | 管理员账号 | 用于登录 Web 面板和管理 API Key。 | -| 数据库 | SQLite,用于保存容器元数据、子用户、审计日志、API Key 等。 | +| 数据库 | SQLite,用于保存容器/数据盘元数据、子用户、审计日志、API Key、任务阶段日志与历史指标。 | | NAT 端口范围 | 用于随机端口和端口映射分配。 | | IPv6 地址段 | 宿主机有可路由 IPv6 时可配置分配策略。 | ## 服务命令 +任务终态记录最多保留 30 天/1000 条,指标最多保留 7 天。完整实例备份包含客户机磁盘和实例配置;面板账户、API Key、授权和历史记录仍应通过数据库备份保护。 + ```bash systemctl status clicd systemctl restart clicd diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 7c56ed8..b608261 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -39,6 +39,25 @@ http://YOUR_SERVER_IP:8999 首次登录请使用安装脚本输出的管理员账号信息。生产环境建议在防火墙或反向代理层限制访问来源,并尽快修改默认账号和密码。 +## 可选的 KVM 恢复/克隆依赖 {#kvm-guestfs} + +KVM 完整恢复、完整克隆和实例模板实例化会使用 `virt-customize` 离线更新客户机网络身份。安装器在支持 KVM 的架构上按下列顺序尝试安装,并检查该命令是否实际可用: + +| 系统 | 候选包 | +| --- | --- | +| Debian / Ubuntu | `guestfs-tools`,未提供命令时回退 `libguestfs-tools`。 | +| RHEL / Rocky / AlmaLinux / Fedora | `libguestfs-tools`,再尝试 `guestfs-tools`、`libguestfs-tools-c`。 | +| Alpine | 尝试 `guestfs-tools`、`libguestfs-tools`;仓库/架构不提供时输出明确提示。 | + +该依赖缺失不会阻断基本 LXC/KVM 安装,但相应 KVM 恢复/克隆任务会失败,不会跳过身份更新而报告成功。Debian/Ubuntu 的命令由 [guestfs-tools](https://packages.ubuntu.com/en/jammy/arm64/guestfs-tools/filelist) 提供;旧版 RHEL 的包名可参照 [Red Hat 文档](https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/virtualization_deployment_and_administration_guide/sect-guest_virtual_machine_disk_access_with_offline_tools-using_virt_customize)。 + +```bash +command -v virt-customize +virt-customize --version +``` + +受管 LXC ext4 loop 磁盘扩容还需要 `e2fsck`、`resize2fs`、`losetup` 和 mount 工具;安装器保留 `e2fsprogs` 等相关依赖。`conntrack` 仍用于 NAT 连接跟踪清理,应保留。 + ## 卸载 ```bash diff --git a/docs/guide/introduction.md b/docs/guide/introduction.md index efeb9ab..958a95a 100644 --- a/docs/guide/introduction.md +++ b/docs/guide/introduction.md @@ -11,6 +11,8 @@ CLICD 是一个面向 LXC/KVM 的轻量虚拟化管理面板。它把常见宿 - 在浏览器中打开 WebSSH 或 WebVNC。 - 管理镜像下载、启用状态和本地缓存。 - 创建、恢复、删除快照,配置计划快照和快照配额。 +- 离线扩容受管磁盘,添加数据盘,创建/导入完整备份、完整克隆和可重复实例化的已安装模板。 +- 在任务页面查看持久化阶段日志,并在面板重启后继续查看历史资源指标。 - 保留操作审计日志和登录日志。 - 为指定容器创建子用户访问链接。 - 通过 API Key 接入 `/api/v1` 自动化接口。 diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md index 640a1c4..4c079c1 100644 --- a/docs/operations/deployment.md +++ b/docs/operations/deployment.md @@ -44,3 +44,5 @@ journalctl -u clicd -f - SQLite 数据库。 - 容器配置。 - 关键容器的快照或外部数据备份。 + +面板支持[完整实例备份](../features/storage-backups)下载和导入,包含系统盘及全部受管数据盘。它不替代配置/数据库备份;任务与历史指标仍保存在面板 SQLite 数据库中。带数据盘实例应使用完整备份,不能依赖旧系统盘快照。 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 3e79db3..86450ac 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -28,7 +28,9 @@ "lucide-react": "^0.454.0", "react": "19.2.8", "react-dom": "19.2.8", + "react-is": "19.2.8", "react-router": "8.3.0", + "recharts": "3.8.0", "sonner": "^2.0.8", "tailwind-merge": "^2.6.0", "tailwindcss-animate": "^1.0.7" @@ -1217,6 +1219,42 @@ "integrity": "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw==", "license": "MIT" }, + "node_modules/@reduxjs/toolkit": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.12.0.tgz", + "integrity": "sha512-KiT+RzZbp6mQET+Mg+h2c97+9j1sNflUxQkIHI7Yuzf6Peu+OYpmkn6nbHWmLLWj+1ZODUJFwGZ7gx3L9R9EOw==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@standard-schema/utils": "^0.3.0", + "immer": "^11.0.0", + "redux": "^5.0.1", + "redux-thunk": "^3.1.0", + "reselect": "^5.1.0" + }, + "peerDependencies": { + "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", + "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-redux": { + "optional": true + } + } + }, + "node_modules/@reduxjs/toolkit/node_modules/immer": { + "version": "11.1.18", + "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.18.tgz", + "integrity": "sha512-EQyQtLiYW029lyoczMl/Hh4Xu7cDecSc58JRYpHyL4tIAu3eqd1yJzQX04d2BZHDkzFFvm6qJEJWOtfDSWAXbQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.15", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", @@ -1497,6 +1535,18 @@ "dev": true, "license": "MIT" }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@standard-schema/utils": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz", + "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", + "license": "MIT" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1542,6 +1592,69 @@ "@babel/types": "^7.28.2" } }, + "node_modules/@types/d3-array": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, "node_modules/@types/node": { "version": "22.20.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", @@ -1572,6 +1685,12 @@ "@types/react": "^19.2.0" } }, + "node_modules/@types/use-sync-external-store": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", + "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==", + "license": "MIT" + }, "node_modules/@vitejs/plugin-react": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz", @@ -1936,6 +2055,127 @@ "devOptional": true, "license": "MIT" }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1953,6 +2193,12 @@ } } }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", + "license": "MIT" + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -2056,6 +2302,18 @@ "node": ">= 0.4" } }, + "node_modules/es-toolkit": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -2066,6 +2324,12 @@ "node": ">=6" } }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, "node_modules/fast-glob": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", @@ -2320,6 +2584,25 @@ "node": ">= 6" } }, + "node_modules/immer": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz", + "integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/is-binary-path": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", @@ -3101,6 +3384,35 @@ "react": "^19.2.8" } }, + "node_modules/react-is": { + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.8.tgz", + "integrity": "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ==", + "license": "MIT" + }, + "node_modules/react-redux": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.3.0.tgz", + "integrity": "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==", + "license": "MIT", + "dependencies": { + "@types/use-sync-external-store": "^0.0.6", + "use-sync-external-store": "^1.4.0" + }, + "peerDependencies": { + "@types/react": "^18.2.25 || ^19", + "react": "^18.0 || ^19", + "redux": "^5.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "redux": { + "optional": true + } + } + }, "node_modules/react-refresh": { "version": "0.18.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", @@ -3222,6 +3534,57 @@ "node": ">=8.10.0" } }, + "node_modules/recharts": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/recharts/-/recharts-3.8.0.tgz", + "integrity": "sha512-Z/m38DX3L73ExO4Tpc9/iZWHmHnlzWG4njQbxsF5aSjwqmHNDDIm0rdEBArkwsBvR8U6EirlEHiQNYWCVh9sGQ==", + "license": "MIT", + "workspaces": [ + "www" + ], + "dependencies": { + "@reduxjs/toolkit": "^1.9.0 || 2.x.x", + "clsx": "^2.1.1", + "decimal.js-light": "^2.5.1", + "es-toolkit": "^1.39.3", + "eventemitter3": "^5.0.1", + "immer": "^10.1.1", + "react-redux": "8.x.x || 9.x.x", + "reselect": "5.1.1", + "tiny-invariant": "^1.3.3", + "use-sync-external-store": "^1.2.2", + "victory-vendor": "^37.0.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/redux": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", + "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", + "license": "MIT" + }, + "node_modules/redux-thunk": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz", + "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==", + "license": "MIT", + "peerDependencies": { + "redux": "^5.0.0" + } + }, + "node_modules/reselect": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz", + "integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==", + "license": "MIT" + }, "node_modules/resolve": { "version": "1.22.12", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", @@ -3469,6 +3832,12 @@ "node": ">=0.8" } }, + "node_modules/tiny-invariant": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -3633,12 +4002,43 @@ } } }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", + "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, + "node_modules/victory-vendor": { + "version": "37.3.6", + "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz", + "integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==", + "license": "MIT AND ISC", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, "node_modules/vite": { "version": "8.3.5", "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", diff --git a/frontend/package.json b/frontend/package.json index 5f40ce6..9c1069e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -29,7 +29,9 @@ "lucide-react": "^0.454.0", "react": "19.2.8", "react-dom": "19.2.8", + "react-is": "19.2.8", "react-router": "8.3.0", + "recharts": "3.8.0", "sonner": "^2.0.8", "tailwind-merge": "^2.6.0", "tailwindcss-animate": "^1.0.7" diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 59ba4e6..42a18fc 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -15,6 +15,8 @@ import Routing from './pages/Routing' import Storage from './pages/Storage' import SubUserManagement from './pages/SubUserManagement' import Layout from './components/Layout' +import PortableLibrary from './pages/PortableLibrary' +import Tasks from './pages/Tasks' function ProtectedRoute({ children }: { children: React.ReactNode }) { const { isAuthenticated, isLoading } = useAuth() @@ -61,6 +63,9 @@ function App() { } /> } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/CreateContainerModal.tsx b/frontend/src/components/CreateContainerModal.tsx index a031b41..f46e32e 100644 --- a/frontend/src/components/CreateContainerModal.tsx +++ b/frontend/src/components/CreateContainerModal.tsx @@ -202,6 +202,8 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist const manualIPv4s = form.public_ipv4s || [] const selectedTemplate = templates.find((template) => template.id === form.template_id) const manualISO = form.virtualization === 'kvm' && isManualISOTemplate(selectedTemplate) + const manualDisk = selectedTemplate?.provisioner === 'manual-disk' + const manualMessage = manualDisk ? '预装磁盘保留原系统账号和配置,请通过 VNC 检查网络,不会注入新密码。' : '此 ISO 将通过 VNC 手动安装系统,磁盘分区、账号和网络需要自行设置,不会注入 SSH 密码或云初始化。' const maxVCPU = hostInfo?.cpu.cores || 64 const maxRAMMB = hostInfo?.ram.total_mb ? Number(hostInfo.ram.total_mb) : undefined const kvmAvailable = !!hostInfo?.runtime?.kvm_available @@ -217,7 +219,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist } }, [hostInfo, kvmAvailable, form.virtualization]) const maxDiskGB = hostInfo?.disk.total_gb ? Math.max(1, Math.floor(hostInfo.disk.total_gb)) : undefined - const resourceErrors = validateResourceInputs(form, maxVCPU, maxRAMMB, maxDiskGB, manualISO) + const resourceErrors = validateResourceInputs(form, maxVCPU, maxRAMMB, maxDiskGB, manualISO, selectedTemplate?.min_disk_gb) const lanIPv4Enabled = form.lan_ipv4_mode === 'dhcp' || form.lan_ipv4_mode === 'static' const lanStaticEnabled = form.lan_ipv4_mode === 'static' const natEnabled = form.assign_nat !== false && !lanIPv4Enabled @@ -529,7 +531,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist )} - {manualISO && {t('此 ISO 将通过 VNC 手动安装系统,磁盘分区、账号和网络需要自行设置,不会注入 SSH 密码或云初始化。')}} + {manualISO && {t(manualMessage)}} {linuxTemplate && (
@@ -624,7 +626,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist )} - {manualISO && {t('此 ISO 将通过 VNC 手动安装系统,磁盘分区、账号和网络需要自行设置,不会注入 SSH 密码或云初始化。')}} + {manualISO && {t(manualMessage)}} {templates.length > 0 &&
默认勾选当前系统;取消后,子用户也不能重装该系统。
@@ -1190,7 +1192,7 @@ export default function CreateContainerModal({ isOpen, onClose, onSuccess, exist

{t('镜像与登录')}

- {manualISO && } + {manualISO && } > = {} const windows = !manualISO && isWindowsTemplate(form.template_id) const windows11 = windows && form.template_id.toLowerCase().includes('windows-11') const minVCPU = windows ? 2 : (form.virtualization === 'kvm' ? 1 : 0.25) const minRAMMB = manualISO ? 512 : windows11 ? 4096 : windows ? 2048 : 128 - const minDiskGB = getTemplateMinDiskGB(form.template_id, form.virtualization, manualISO) + const minDiskGB = Math.max(getTemplateMinDiskGB(form.template_id, form.virtualization, manualISO), templateMin) if (!Number.isFinite(form.vcpu)) { errors.vcpu = '请输入 vCPU' @@ -1500,10 +1502,11 @@ function getLANDHCPInterfaces(report: HostProbeReport | null) { } function isManualISOTemplate(template?: Template) { - return template?.manual_install === true || template?.provisioner === 'manual-iso' + return template?.manual_install === true || template?.provisioner === 'manual-iso' || template?.provisioner === 'manual-disk' } function applyTemplateDefaults(form: CreateContainerRequest, template?: Template): CreateContainerRequest { + if (template?.min_disk_gb && form.disk_gb < template.min_disk_gb) form = { ...form, disk_gb: template.min_disk_gb } if (isManualISOTemplate(template) || !isWindowsTemplate(form.template_id)) return form return { ...form, diff --git a/frontend/src/components/DiskManagerModal.tsx b/frontend/src/components/DiskManagerModal.tsx new file mode 100644 index 0000000..eaf8413 --- /dev/null +++ b/frontend/src/components/DiskManagerModal.tsx @@ -0,0 +1,94 @@ +import { useCallback, useEffect, useState } from 'react' +import { HardDrive, Plus, RefreshCw, Unplug, Plug, Trash2, Expand } from 'lucide-react' +import { type ContainerIdentifier, getStorageInfo, type StoragePool } from '../services/api' +import { addDataDisk, attachDataDisk, deleteDataDisk, formatBytes, getDisks, operationError, resizeDisk, type DiskInventory } from '../services/operations' +import { useLanguage } from '../contexts/LanguageContext' +import { useDialog } from './Dialog' +import OperationTask from './OperationTask' +import { Modal } from './ui/modal' +import { Button } from './ui/button' +import { Card } from './ui/card' +import { Alert } from './ui/alert' +import { Badge } from './ui/badge' +import { Input } from './ui/input' +import { Label } from './ui/label' +import { NativeSelect } from './ui/native-select' + +export default function DiskManagerModal({ containerId, runtime, readOnly = false, onClose, onUpdated }: { containerId: ContainerIdentifier; runtime: string; readOnly?: boolean; onClose: () => void; onUpdated: () => void | Promise }) { + const { t } = useLanguage() + const dialog = useDialog() + const [inventory, setInventory] = useState(null) + const [pools, setPools] = useState([]) + const [error, setError] = useState('') + const [loading, setLoading] = useState(true) + const [busy, setBusy] = useState(false) + const [taskId, setTaskId] = useState('') + const [editor, setEditor] = useState<{ kind: 'add' | 'resize'; id: string; current: number } | null>(null) + const [name, setName] = useState('') + const [size, setSize] = useState('10') + const [pool, setPool] = useState('') + const [mount, setMount] = useState('/mnt/data1') + const refresh = useCallback(async () => { + try { const data = (await getDisks(containerId)).data.data; if (!data) throw new Error('磁盘数据不可用'); setInventory(data); setError('') } + catch (e) { setError(operationError(e)) } + finally { setLoading(false) } + }, [containerId]) + useEffect(() => { void refresh(); if (!readOnly) void getStorageInfo().then(r => setPools((r.data.data?.pools || []).filter(p => p.enabled && p.available && p.content_types.includes(runtime)))).catch(() => {}) }, [refresh, readOnly, runtime]) + const editable = !!inventory?.can_edit && !busy && !readOnly + const run = async (operation: () => Promise<{ data: { data?: { task_id: string } } }>) => { + if (!editable) return + setBusy(true); setError('') + try { const response = await operation(); const id = response.data.data?.task_id; if (!id) throw new Error('服务器未返回任务标识'); setTaskId(id); setEditor(null) } + catch (e) { setError(operationError(e)); setBusy(false); void refresh() } + } + const openResize = (id: string, current: number) => { setEditor({ kind: 'resize', id, current }); setSize(String(Math.ceil(current + 1))); setError('') } + const save = () => { + const amount = Number(size) + if (!Number.isFinite(amount) || amount < 0.125 || amount > 16384 || (editor?.kind === 'resize' && amount <= editor.current)) { setError(t('请输入更大的有效容量,磁盘仅支持扩容。')); return } + if (editor?.kind === 'add') { + if (!name.trim()) { setError(t('请输入数据盘名称')); return } + void run(() => addDataDisk(containerId, { name: name.trim(), size_gb: amount, storage_pool_id: pool || undefined, mount_path: runtime === 'lxc' ? mount : undefined })) + } else if (editor) void run(() => resizeDisk(containerId, editor.id, amount)) + } + return {t(busy ? '后台继续' : '关闭')}}> +
+
+

{t(runtime === 'kvm' ? '修改磁盘前请先关机。虚拟磁盘扩容后,仍需在客户机内扩展分区和文件系统。' : '修改磁盘前请先停止容器。受管 ext4 磁盘扩容会同步扩展文件系统。')}

+ +
+ {error && {error}} + {taskId && { setBusy(false); void refresh(); void onUpdated() }} />} + {loading ?

{t('正在读取磁盘…')}

: inventory && <> + {!inventory.can_edit && {inventory.reason || t('实例运行或有任务执行时,只能查看磁盘。')}} + +

{t('系统盘')} {inventory.system.format}

{inventory.system.size_gb} GiB · {t('已占用')} {formatBytes(inventory.system.allocated_bytes)}

{inventory.system.error &&

{inventory.system.error}

}
+ {!readOnly && } +
+

{t('数据盘')} {inventory.data_disks.length}/{inventory.limits.max_data_disks}

{!readOnly && }
+ {!inventory.data_disks.length && {t('尚未添加数据盘')}} + {inventory.data_disks.map(disk => +

{disk.name}

{t(disk.attached ? '已挂载' : '已卸载')}
+

{disk.size_gb} GiB · {t('已占用')} {formatBytes(disk.allocated_bytes)} · {disk.mount_path || `${disk.target} (${disk.bus})`}

+ {disk.error &&

{disk.error}

} + {!readOnly &&
+ + + +
} +
)} + {!!inventory.data_disks.length &&

{t('完整备份会包含数据盘。包含数据盘的实例请使用完整备份进行回滚。')}

} + } + {editor && +

{t(editor.kind === 'add' ? '添加数据盘' : '扩容磁盘')}

+
+ {editor.kind === 'add' && } + + {editor.kind === 'add' && } + {editor.kind === 'add' && runtime === 'lxc' && } +
+ {runtime === 'kvm' && editor.kind === 'add' &&

{t('新数据盘为空白盘,需要在客户机内分区、格式化并挂载。')}

} +
+
} +
+
+} diff --git a/frontend/src/components/ImageUploadModal.tsx b/frontend/src/components/ImageUploadModal.tsx new file mode 100644 index 0000000..aa44f39 --- /dev/null +++ b/frontend/src/components/ImageUploadModal.tsx @@ -0,0 +1,63 @@ +import { useRef, useState } from 'react' +import { Upload, X, Loader2, FileImage } from 'lucide-react' +import { type StoragePool } from '../services/api' +import { formatBytes, operationError, uploadLocalImage } from '../services/operations' +import { useLanguage } from '../contexts/LanguageContext' +import { Modal } from './ui/modal' +import { Alert } from './ui/alert' +import { Button } from './ui/button' +import { Input } from './ui/input' +import { Label } from './ui/label' +import { NativeSelect } from './ui/native-select' +import { Progress } from './ui/progress' + +export default function ImageUploadModal({ arch, pools, onClose, onUploaded }: { arch: string; pools: StoragePool[]; onClose: () => void; onUploaded: () => void | Promise }) { + const { t } = useLanguage() + const [file, setFile] = useState(null) + const [name, setName] = useState('') + const [provisioner, setProvisioner] = useState('manual-iso') + const [distro, setDistro] = useState('') + const [release, setRelease] = useState('') + const [pool, setPool] = useState('') + const [sha, setSHA] = useState('') + const [busy, setBusy] = useState(false) + const [percent, setPercent] = useState(0) + const [error, setError] = useState('') + const controller = useRef(null) + const isISO = provisioner === 'manual-iso' || provisioner.startsWith('windows-') + const submit = async () => { + if (!file || !name.trim()) { setError(t('请选择镜像文件并填写名称')); return } + if (file.size <= 0 || file.size > 32 * 1024 ** 3) { setError(t('请选择不超过 32 GiB 的有效文件')); return } + if (sha.trim() && !/^[a-f0-9]{64}$/i.test(sha.trim())) { setError(t('SHA-256 必须是 64 位十六进制字符串')); return } + setBusy(true); setError(''); setPercent(0) + const abort = new AbortController(); controller.current = abort + try { + await uploadLocalImage(file, { name: name.trim(), provisioner, arch, distro: distro.trim(), release: release.trim(), sha256: sha.trim() }, pool, setPercent, abort.signal) + setPercent(100); await onUploaded(); onClose() + } catch (e) { + setError(abort.signal.aborted ? t('上传已取消') : operationError(e)) + if (abort.signal.aborted) await onUploaded() + } finally { setBusy(false); controller.current = null } + } + return + + + }> + + {file &&

{file.name} · {formatBytes(file.size)}

} +
+ + + + +
+ + + {t(isISO ? 'ISO 用于虚拟光驱。通用 ISO 在 VNC 中安装;Windows 自动安装使用对应模板。' : provisioner === 'manual-disk' ? '预装磁盘保留原系统账号与配置,请通过 VNC 检查网络。QCOW2 必须是无外部依赖的完整磁盘。' : '请选择已安装 cloud-init 的 Linux 磁盘,创建时将注入新的账号和网络配置。')} + {busy &&

{percent >= 99 ? t('传输完成,正在验证镜像完整性…') : `${t('上传进度')} ${percent}%`}

} + {error && {error}} +
+} diff --git a/frontend/src/components/InstanceTransferModal.tsx b/frontend/src/components/InstanceTransferModal.tsx new file mode 100644 index 0000000..c058ad4 --- /dev/null +++ b/frontend/src/components/InstanceTransferModal.tsx @@ -0,0 +1,55 @@ +import { useEffect, useState } from 'react' +import { getStorageInfo, type ContainerIdentifier, type StoragePool } from '../services/api' +import { cloneInstance, createBackup, operationError, saveInstanceTemplate } from '../services/operations' +import { useLanguage } from '../contexts/LanguageContext' +import OperationTask from './OperationTask' +import { Modal } from './ui/modal' +import { Alert } from './ui/alert' +import { Button } from './ui/button' +import { Input } from './ui/input' +import { Label } from './ui/label' +import { NativeSelect } from './ui/native-select' + +export default function InstanceTransferModal({ containerId, containerName, runtime, initialKind = 'backup', onClose, onUpdated }: { containerId: ContainerIdentifier; containerName: string; runtime: string; initialKind?: 'backup' | 'clone' | 'template'; onClose: () => void; onUpdated: () => void | Promise }) { + const { t } = useLanguage() + const [kind, setKind] = useState(initialKind) + const [name, setName] = useState(initialKind === 'clone' ? `${containerName}-copy` : `${containerName}-${initialKind}`) + const [pool, setPool] = useState('') + const [pools, setPools] = useState([]) + const [ports, setPorts] = useState('2') + const [submitting, setSubmitting] = useState(false) + const [taskId, setTaskId] = useState('') + const [error, setError] = useState('') + useEffect(() => { void getStorageInfo().then(r => setPools((r.data.data?.pools || []).filter(p => p.enabled && p.available))).catch(e => setError(operationError(e))) }, []) + const submit = async () => { + if (!name.trim()) { setError(t('请输入名称')); return } + if (kind === 'clone' && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$/.test(name.trim())) { setError(t('实例名称只能包含字母、数字、点、下划线和短横线,最长 63 字符。')); return } + if (kind === 'clone' && (!Number.isInteger(Number(ports)) || Number(ports) < 1 || Number(ports) > 64)) { setError(t('NAT 端口配额请输入 1–64 的整数')); return } + setSubmitting(true); setError('') + try { + const response = kind === 'backup' ? await createBackup(containerId, { name: name.trim(), storage_pool_id: pool || undefined }) : kind === 'template' ? await saveInstanceTemplate(containerId, { name: name.trim(), storage_pool_id: pool || undefined }) : await cloneInstance(containerId, { name: name.trim(), storage_pool_id: pool || undefined, assign_nat: true, port_mapping_count: Number(ports) }) + const id = response.data.data?.task_id + if (!id) throw new Error('服务器未返回任务标识') + setTaskId(id) + } catch (e) { setError(operationError(e)) } + finally { setSubmitting(false) } + } + const content = kind === 'clone' ? runtime : 'backups' + return + + {!taskId && } + }> +
+ {!taskId && <> +
{(['backup', 'clone', 'template'] as const).map(value => )}
+ {t('任务会先关闭源实例,复制系统盘和全部数据盘,再恢复源实例原来的运行状态。请为业务安排可中断的时间。')} + + + {kind === 'clone' && } + {kind !== 'backup' &&

{t('完整副本独立于原实例。新实例使用新的 UUID、MAC 和端口,默认保持关机;系统账号保留,请通过 VNC 检查网络与应用身份。')}

} + } + {error && {error}} + {taskId && void onUpdated()} />} +
+
+} diff --git a/frontend/src/components/KVMInstallMedia.tsx b/frontend/src/components/KVMInstallMedia.tsx index 92d41f1..e305f85 100644 --- a/frontend/src/components/KVMInstallMedia.tsx +++ b/frontend/src/components/KVMInstallMedia.tsx @@ -156,7 +156,7 @@ export default function KVMInstallMedia({ open, onClose, containerId, status, ta {t('当前介质')}:{state.image_name || t('未挂载 ISO')} {t('启动顺序')}:{state.boot === 'cdrom' ? t('光驱优先') : t('磁盘优先')}
- {state.manual_install && {t('此 ISO 将通过 VNC 手动安装系统,磁盘分区、账号和网络需要自行设置,不会注入 SSH 密码或云初始化。')}} + {state.manual_install && {t(state.image_id ? '此 ISO 将通过 VNC 手动安装系统,磁盘分区、账号和网络需要自行设置,不会注入 SSH 密码或云初始化。' : '此系统保留原有账号和网络配置,请通过 VNC 检查,不会注入新密码。')}} {(!canEdit && !saving) &&

{t('更改安装介质前请先关闭虚拟机并等待当前任务结束;面板不会自动关机或重启。')}

}
diff --git a/frontend/src/components/OperationTask.tsx b/frontend/src/components/OperationTask.tsx new file mode 100644 index 0000000..516514e --- /dev/null +++ b/frontend/src/components/OperationTask.tsx @@ -0,0 +1,55 @@ +import { useEffect, useRef, useState } from 'react' +import { Link } from 'react-router' +import { CheckCircle2, Loader2, XCircle } from 'lucide-react' +import { getTasks, type Task } from '../services/api' +import { Alert } from './ui/alert' +import { Button } from './ui/button' +import { useLanguage } from '../contexts/LanguageContext' + +export default function OperationTask({ id, onFinish }: { id: string; onFinish?: (task: Task) => void }) { + const [task, setTask] = useState(null) + const [error, setError] = useState('') + const finished = useRef('') + const callback = useRef(onFinish) + callback.current = onFinish + const { t } = useLanguage() + useEffect(() => { + let active = true + const refresh = async () => { + try { + const response = await getTasks() + if (!active) return + const next = response.data.data?.find(item => item.id === id) + if (next) { + setTask(next) + setError('') + if (['done', 'failed', 'cancelled'].includes(next.status) && finished.current !== id) { + finished.current = id + window.clearInterval(timer) + callback.current?.(next) + } + } + } catch { if (active) setError(t('暂时无法读取任务,可在任务中心查看进度。')) } + } + void refresh() + const timer = window.setInterval(() => void refresh(), 1500) + return () => { active = false; window.clearInterval(timer) } + }, [id, t]) + const done = task?.status === 'done' + const failed = task?.status === 'failed' || task?.status === 'cancelled' + const result = task?.result as { container_uuid?: string } | undefined + return +
+ {done ? : failed ? : } +
+

{t(done ? '操作已完成' : failed ? '操作未完成' : '任务处理中')} {id}

+

{task?.error || task?.stage_detail || error || t('任务已提交,正在等待执行。')}

+
+
+ {task?.logs?.length ?
{task.logs.slice(-4).map((log, i) =>

{log.detail || log.stage}

)}
: null} +
+ + {done && result?.container_uuid && } +
+
+} diff --git a/frontend/src/components/ResourceStatsPanel.tsx b/frontend/src/components/ResourceStatsPanel.tsx index af4de51..804a80a 100644 --- a/frontend/src/components/ResourceStatsPanel.tsx +++ b/frontend/src/components/ResourceStatsPanel.tsx @@ -1,23 +1,14 @@ -import { Card } from './ui/card' -import { Button } from './ui/button' -import { ReactNode, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { type ReactNode, useId, useMemo } from 'react' import { RefreshCw } from 'lucide-react' -import { calculateChartLayout, type ChartLayout } from '../lib/chart-layout' +import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from 'recharts' +import { useLanguage } from '../contexts/LanguageContext' +import { Button } from './ui/button' +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card' +import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from './ui/chart' export type StatsRangeKey = '30m' | '1h' | '1d' | '1w' - -export type ChartPoint = { - ts: number - value: number -} - -export type ResourceChartSeries = { - label: string - points: ChartPoint[] - current?: number - color?: string -} - +export type ChartPoint = { ts: number; value: number } +export type ResourceChartSeries = { label: string; points: ChartPoint[]; current?: number; color?: string } export type ResourceChartConfig = { title: string icon: ReactNode @@ -29,370 +20,207 @@ export type ResourceChartConfig = { unitLabel?: string formatValue: (value: number) => string } - -const chartPalette = ['#2563eb', '#16a34a', '#d97706', '#dc2626'] - -const rangeLabels: Record = { - '30m': '30分钟', - '1h': '1小时', - '1d': '1天', - '1w': '1周', -} - +const rangeLabels: Record = { '30m': '30分钟', '1h': '1小时', '1d': '1天', '1w': '1周' } export const statsRanges: Record = { - '30m': 30 * 60 * 1000, - '1h': 60 * 60 * 1000, - '1d': 24 * 60 * 60 * 1000, - '1w': 7 * 24 * 60 * 60 * 1000, + '30m': 30 * 60 * 1000, '1h': 60 * 60 * 1000, '1d': 24 * 60 * 60 * 1000, '1w': 7 * 24 * 60 * 60 * 1000, } +const palette = [1, 2, 3, 4, 5].map(n => `hsl(var(--chart-${n}))`) -export default function ResourceStatsPanel({ - range, - onRangeChange, - onRefresh, - charts, -}: { - range: StatsRangeKey - onRangeChange: (range: StatsRangeKey) => void - onRefresh: () => void - charts: ResourceChartConfig[] +export default function ResourceStatsPanel({ range, onRangeChange, onRefresh, charts }: { + range: StatsRangeKey; onRangeChange: (range: StatsRangeKey) => void; onRefresh: () => void; charts: ResourceChartConfig[] }) { + const { t } = useLanguage() return ( - -
-

统计信息

-
-
- {(Object.keys(rangeLabels) as StatsRangeKey[]).map((item) => ( - +
+
+

{t('统计信息')}

+
+
+ {(Object.keys(rangeLabels) as StatsRangeKey[]).map(item => ( + ))}
-
- -
- {charts.map((chart, index) => ( - - ))} +
+ {charts.map(chart => )}
+
+ ) +} + +function ResourceChart({ chart, range }: { chart: ResourceChartConfig; range: StatsRangeKey }) { + const { t, language } = useLanguage() + const id = useId().replace(/[^a-zA-Z0-9_-]/g, '') + const now = useMemo(() => Date.now(), [chart, range]) + const start = now - statsRanges[range] + const locale = language === 'en' ? 'en-US' : 'zh-CN' + const series = useMemo(() => { + const source = chart.series?.length ? chart.series : [{ label: chart.title, points: chart.points, current: chart.current }] + return source.map((item, index) => { + const samples = new Map() + for (const point of item.points) { + if (Number.isFinite(point.ts) && Number.isFinite(point.value) && point.ts >= start && point.ts <= now) samples.set(point.ts, point.value) + } + const points = Array.from(samples, ([ts, value]) => ({ ts, value })).sort((a, b) => a.ts - b.ts) + const current = Number.isFinite(item.current) ? Number(item.current) : source.length === 1 ? finite(chart.current) : 0 + return { ...item, points, current, key: `metric${index}`, color: item.color || palette[index % palette.length] } + }) + }, [chart, start, now]) + const config = Object.fromEntries(series.map(item => [item.key, { label: t(item.label), color: item.color }])) satisfies ChartConfig + const statistics = series.map(item => getSeriesStats(item)) + const { data, ceiling, sampleCount } = useMemo(() => { + const rows = new Map() + let ceiling = Math.max(finite(chart.max), 1) + let sampleCount = 0 + for (const item of series) { + for (const point of item.points) { + const row = rows.get(point.ts) || { ts: point.ts } + row[item.key] = point.value + rows.set(point.ts, row) + ceiling = Math.max(ceiling, point.value) + sampleCount++ + } + } + // Timestamp anchors keep the selected window without inventing samples. + if (!rows.has(start)) rows.set(start, { ts: start }) + if (!rows.has(now)) rows.set(now, { ts: now }) + const data = sampleChartRows(Array.from(rows.values()).sort((a, b) => a.ts - b.ts), series.map(item => item.key)) + return { data, ceiling, sampleCount } + }, [chart.max, series, start, now]) + const timeFormat = useMemo(() => new Intl.DateTimeFormat(locale, range === '1w' + ? { month: 'numeric', day: 'numeric' } : { hour: '2-digit', minute: '2-digit', hour12: false }), [locale, range]) + const tooltipFormat = useMemo(() => new Intl.DateTimeFormat(locale, { + month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, + }), [locale]) + // Integer byte-rate formatting can give 0.5 B/s and 1 B/s the same label. + const yTicks = [0, ceiling / 2, ceiling].filter((tick, index, ticks) => + !ticks.slice(index + 1).some(next => chart.formatValue(next) === chart.formatValue(tick))) + + return ( + + + + {chart.icon} + {t(chart.title)} + + {chart.detail && {t(chart.detail)}} + + + {series.length === 1 ? ( +
+ + + +
+ ) : ( +
+ {series.map((item, index) => ( +
+
+ + {t(item.label)} +
+
+ {chart.formatValue(statistics[index].current)} +
+
+ + +
+
+ ))} +
+ )} +
+ + + + {series.map(item => ( + + + + + ))} + + + timeFormat.format(Number(ts))} /> + + tooltipFormat.format(Number(payload[0]?.payload.ts))} + formatter={(value, name, item) => <> + + {config[String(name)]?.label || String(name)} + {chart.formatValue(Number(value))} + } /> + } /> + {series.map(item => ( + + ))} + + + {sampleCount === 0 &&
{t('暂无数据')}
} +
+
) } -function DetailedChart({ chart, range, className }: { chart: ResourceChartConfig; range: StatsRangeKey; className: string }) { - const series = chart.series?.length - ? chart.series - : [{ label: chart.title, points: chart.points, current: chart.current }] - const primaryStats = getSeriesStats(series[0], chart.current) - - return ( -
-
-
-
- {chart.icon} - {chart.title} -
- {chart.detail &&

{chart.detail}

} -
- {series.length > 1 ? ( -
- {series.map((item, index) => ( - - ))} -
- ) : ( -
- - - -
- )} -
- -
- ) +function Stat({ label, value, prominent }: { label: string; value: string; prominent?: boolean }) { + return
+
{label}
+
{value}
+
+} +function SummaryRow({ label, value, kind }: { label: string; value: string; kind: string }) { + return
+
{label}
{value}
+
+} +function finite(value?: number) { return Number.isFinite(value) ? Number(value) : 0 } +function getSeriesStats(series: ResourceChartSeries) { + const current = finite(series.current) + let total = 0; let peak = Math.max(0, current) + for (const point of series.points) { total += point.value; peak = Math.max(peak, point.value) } + return { current, avg: series.points.length ? total / series.points.length : current, peak } } -function SeriesStat({ - color, - label, - stats, - formatValue, -}: { - color: string - label: string - stats: { current: number; avg: number; peak: number } - formatValue: (value: number) => string -}) { - return ( -
-
- - {label} -
-
- {formatValue(stats.current)} -
-
- 均 {formatValue(stats.avg)} / 峰 {formatValue(stats.peak)} -
-
- ) -} - -function Stat({ label, value }: { label: string; value: string }) { - return ( -
-
{label}
-
{value}
-
- ) -} - -function getSeriesStats(series: ResourceChartSeries, fallbackCurrent = 0) { - const values = series.points - .map((point) => point.value) - .filter((value) => Number.isFinite(value)) - const current = Number.isFinite(series.current) ? Number(series.current) : fallbackCurrent - const samples = values.length > 0 ? values : [current] - const avg = samples.reduce((sum, value) => sum + value, 0) / samples.length - const peak = Math.max(current, ...samples, 0) - return { current, avg, peak } -} - -function LineAreaChart({ - label, - series, - range, - max, - formatValue, - unitLabel, -}: { - label: string - series: ResourceChartSeries[] - range: StatsRangeKey - max?: number - formatValue: (value: number) => string - unitLabel?: string -}) { - const chartId = `resource-chart-${useId().replace(/:/g, '')}` - const containerRef = useRef(null) - const measureRef = useRef(null) - const [layout, setLayout] = useState(null) - const now = useMemo(() => Date.now(), [series, range]) - const chartSeries = series.map((item) => { - const validPoints = item.points.filter((point) => Number.isFinite(point.ts) && Number.isFinite(point.value)) - return { - ...item, - points: validPoints.length > 0 - ? validPoints - : [{ ts: now, value: Number.isFinite(item.current) ? Number(item.current) : 0 }], - } - }) - const allPoints = chartSeries.flatMap((item) => item.points) - const maxValue = Math.max(max || 0, ...allPoints.map((point) => point.value), 1) - const minTs = now - statsRanges[range] - const span = Math.max(statsRanges[range], 1) - const yLabelKey = JSON.stringify([1, 0.5, 0].map((tick) => formatValue(maxValue * tick))) - const xLabelKey = JSON.stringify([0, 0.5, 1].map((tick) => formatTime(minTs + tick * span))) - - useLayoutEffect(() => { - const container = containerRef.current - const textNode = measureRef.current - if (!container || !textNode) return - let disposed = false - let frame = 0 - const measure = (text: string) => { - textNode.textContent = text - return textNode.getComputedTextLength() - } - const update = () => { - if (disposed) return - const width = container.getBoundingClientRect().width - if (width <= 0) return - const yLabels: string[] = JSON.parse(yLabelKey) - const xLabels: string[] = JSON.parse(xLabelKey) - let fontTop = 0 - let fontBottom = 0 - // Real SVG metrics include tabular figures and any translated fallback font. - for (const text of [...yLabels, ...xLabels, unitLabel || '', '0123456789Mg']) { - measure(text) - const box = textNode.getBBox() - fontTop = Math.min(fontTop, box.y) - fontBottom = Math.max(fontBottom, box.y + box.height) +type ChartDatum = { ts: number; [key: string]: number | null } +// Only drawing is sampled: retain real extrema/endpoints from each bucket. +// Current/average/peak above continue to use every original history sample. +function sampleChartRows(rows: ChartDatum[], keys: string[], limit = 1200): ChartDatum[] { + if (rows.length <= limit) return rows + const bucketCount = Math.max(1, Math.floor((limit - 2) / (keys.length * 2 + 2))) + const selected = new Set([0, rows.length - 1]) + for (let bucket = 0; bucket < bucketCount; bucket++) { + const first = Math.floor(bucket * rows.length / bucketCount) + const end = Math.floor((bucket + 1) * rows.length / bucketCount) + selected.add(first); selected.add(end - 1) + for (const key of keys) { + let minIndex = -1; let maxIndex = -1 + for (let index = first; index < end; index++) { + const value = rows[index][key] + if (typeof value !== 'number') continue + if (minIndex < 0 || value < Number(rows[minIndex][key])) minIndex = index + if (maxIndex < 0 || value > Number(rows[maxIndex][key])) maxIndex = index } - const next = calculateChartLayout({ - width, yLabels, xLabels, unitLabel, measure, fontTop, - fontHeight: Math.max(1, fontBottom - fontTop), - }) - setLayout((previous) => JSON.stringify(previous) === JSON.stringify(next) ? previous : next) + if (minIndex >= 0) selected.add(minIndex) + if (maxIndex >= 0) selected.add(maxIndex) } - const schedule = () => { - if (disposed) return - cancelAnimationFrame(frame) - frame = requestAnimationFrame(update) - } - const observer = new ResizeObserver(schedule) - observer.observe(container) - document.fonts.ready.then(schedule) - document.fonts.addEventListener('loadingdone', schedule) - update() - return () => { - disposed = true - cancelAnimationFrame(frame) - observer.disconnect() - document.fonts.removeEventListener('loadingdone', schedule) - } - }, [yLabelKey, xLabelKey, unitLabel]) - - const gridStroke = 'hsl(var(--border))' - const axisStroke = 'hsl(var(--muted-foreground))' - const lineStroke = 'hsl(var(--foreground))' - const plot = layout?.plot - const primaryLine = plot - ? buildLine(chartSeries[0]?.points || [], minTs, span, plot.left, plot.top, plot.width, plot.height, maxValue) - : '' - const area = plot ? `${plot.left},${plot.top + plot.height} ${primaryLine} ${plot.left + plot.width},${plot.top + plot.height}` : '' - const textBaseline = (center: number, lines: string[]) => layout - ? center - (layout.fontHeight + (lines.length - 1) * layout.lineHeight) / 2 - layout.fontTop - : center - - return ( -
- - - {layout && plot && <> - - - - - - - - - - - {layout.yLabels.map(({ tick, lines }) => { - const y = plot.top + (1 - tick) * plot.height - return ( - - - - {lines.map((line, index) => {line})} - - - ) - })} - - {layout.xLabels.map(({ tick, lines }) => { - const x = plot.left + tick * plot.width - return ( - - - - {lines.map((line, index) => {line})} - - - ) - })} - - {layout.unitLines.length > 0 && ( - - {layout.unitLines.map((line, index) => {line})} - - )} - - - {chartSeries.length === 1 && } - {chartSeries.map((item, index) => ( - - ))} - - } - -
- ) -} - -function buildLine( - points: ChartPoint[], - minTs: number, - span: number, - left: number, - top: number, - innerWidth: number, - innerHeight: number, - maxValue: number, -) { - const coords = points.map((point) => { - const x = left + ((point.ts - minTs) / span) * innerWidth - const y = top + innerHeight - (point.value / maxValue) * innerHeight - return `${Number.isFinite(x) ? x : left},${Number.isFinite(y) ? y : top + innerHeight}` - }) - if (coords.length > 1) return coords.join(' ') - - const [, yText] = (coords[0] || `${left},${top + innerHeight}`).split(',') - const y = Number(yText) - const safeY = Number.isFinite(y) ? y : top + innerHeight - return `${left},${safeY} ${left + innerWidth},${safeY}` -} - -function chartBorderClass(index: number) { - const right = index % 2 === 0 ? 'xl:border-r' : '' - const top = index > 1 ? 'border-t' : '' - return `${right} ${top} border-border` -} - -function formatTime(ts: number) { - return new Date(ts).toLocaleString('zh-CN', { - month: 'numeric', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - hour12: false, - }) + } + return Array.from(selected).sort((a, b) => a - b).map(index => rows[index]) } diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 0eae249..2c16c8c 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -19,6 +19,9 @@ import { Server, Sun, UserCog, + Archive, + Boxes, + ListChecks, } from 'lucide-react' import { useAuth } from '../contexts/AuthContext' import { useLanguage } from '../contexts/LanguageContext' @@ -90,6 +93,9 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) { { path: '/containers', label: '容器管理', icon: Server, active: location.pathname.startsWith('/container'), admin: false }, { path: '/images', label: '镜像管理', icon: Package, active: location.pathname.startsWith('/images'), admin: true }, { path: '/snapshots', label: '快照管理', icon: Camera, active: location.pathname.startsWith('/snapshots'), admin: true }, + { path: '/backups', label: '备份与恢复', icon: Archive, active: location.pathname.startsWith('/backups'), admin: true }, + { path: '/instance-templates', label: '实例模板', icon: Boxes, active: location.pathname.startsWith('/instance-templates'), admin: true }, + { path: '/tasks', label: '任务中心', icon: ListChecks, active: location.pathname.startsWith('/tasks'), admin: false }, { path: '/routing', label: '路由管理', icon: Route, active: location.pathname.startsWith('/routing'), admin: true }, { path: '/storage', label: '存储管理', icon: HardDrive, active: location.pathname.startsWith('/storage'), admin: true }, { path: '/audit-logs', label: '操作日志', icon: ScrollText, active: location.pathname.startsWith('/audit-logs'), admin: true }, diff --git a/frontend/src/components/ui/chart.tsx b/frontend/src/components/ui/chart.tsx new file mode 100644 index 0000000..8d265ac --- /dev/null +++ b/frontend/src/components/ui/chart.tsx @@ -0,0 +1,377 @@ +// shadcn/ui New York / Radix Chart. Copyright (c) 2023 shadcn. +// MIT License: ./SHADCN-LICENSE.md +// Source: https://ui.shadcn.com/r/styles/new-york-v4/chart.json +// Tailwind 4 utilities adapted to the existing Tailwind 3 application. +"use client" + +import * as React from "react" +import { cn } from "@/lib/utils" +import * as RechartsPrimitive from "recharts" +import type { TooltipValueType } from "recharts" + +// Format: { THEME_NAME: CSS_SELECTOR } +const THEMES = { light: "", dark: ".dark" } as const + +const INITIAL_DIMENSION = { width: 320, height: 200 } as const +type TooltipNameType = number | string + +export type ChartConfig = Record< + string, + { + label?: React.ReactNode + icon?: React.ComponentType + } & ( + | { color?: string; theme?: never } + | { color?: never; theme: Record } + ) +> + +type ChartContextProps = { + config: ChartConfig +} + +const ChartContext = React.createContext(null) + +function useChart() { + const context = React.useContext(ChartContext) + + if (!context) { + throw new Error("useChart must be used within a ") + } + + return context +} + +function ChartContainer({ + id, + className, + children, + config, + initialDimension = INITIAL_DIMENSION, + ...props +}: React.ComponentProps<"div"> & { + config: ChartConfig + children: React.ComponentProps< + typeof RechartsPrimitive.ResponsiveContainer + >["children"] + initialDimension?: { + width: number + height: number + } +}) { + const uniqueId = React.useId() + const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}` + + return ( + +
+ + + {children} + +
+
+ ) +} + +const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { + const colorConfig = Object.entries(config).filter( + ([, config]) => config.theme ?? config.color + ) + + if (!colorConfig.length) { + return null + } + + return ( +