From d26ca8244ff65e9739bb60192c4b7fc5d83ea96a Mon Sep 17 00:00:00 2001 From: Yoko <13830214+yokowu@users.noreply.github.com> Date: Thu, 28 May 2026 14:49:13 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20MonkeyCode=20?= =?UTF-8?q?=E7=A6=BB=E7=BA=BF=E9=83=A8=E7=BD=B2=E5=8D=87=E7=BA=A7=E5=9B=9E?= =?UTF-8?q?=E6=BB=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增加离线包 manifest 生成、解析与静态校验 - 增加安装目录版本元数据、环境变量合并和整站快照恢复 - 支持中心端升级、失败自动恢复和手动回滚 - 支持宿主机通过安装器菜单手动升级 - 接入 center/host 安装器升级菜单 --- backend/cmd/installer/main.go | 12 ++ backend/cmd/installer/main_test.go | 29 ++++ backend/pkg/installer/deploy/envmerge.go | 54 ++++++++ backend/pkg/installer/deploy/envmerge_test.go | 27 ++++ backend/pkg/installer/deploy/manifest.go | 110 +++++++++++++++ backend/pkg/installer/deploy/manifest_test.go | 41 ++++++ backend/pkg/installer/deploy/metadata.go | 95 +++++++++++++ backend/pkg/installer/deploy/metadata_test.go | 41 ++++++ backend/pkg/installer/deploy/snapshot.go | 105 +++++++++++++++ backend/pkg/installer/deploy/snapshot_test.go | 42 ++++++ .../pkg/installer/deploy/upgrade_center.go | 126 ++++++++++++++++++ .../installer/deploy/upgrade_center_test.go | 86 ++++++++++++ backend/pkg/installer/deploy/upgrade_host.go | 70 ++++++++++ .../pkg/installer/deploy/upgrade_host_test.go | 54 ++++++++ backend/pkg/installer/logging/logger.go | 30 ++++- .../pkg/installer/steps/fake_reporter_test.go | 6 +- backend/pkg/installer/steps/upgrade_center.go | 75 +++++++++++ .../installer/steps/upgrade_center_test.go | 109 +++++++++++++++ backend/pkg/installer/steps/upgrade_host.go | 58 ++++++++ .../pkg/installer/steps/upgrade_host_test.go | 17 +++ backend/scripts/build-offline-package.sh | 37 +++++ backend/scripts/check-offline-package.sh | 10 ++ .../tests/offline_package_static_test.go | 18 +++ 23 files changed, 1245 insertions(+), 7 deletions(-) create mode 100644 backend/cmd/installer/main_test.go create mode 100644 backend/pkg/installer/deploy/envmerge.go create mode 100644 backend/pkg/installer/deploy/envmerge_test.go create mode 100644 backend/pkg/installer/deploy/manifest.go create mode 100644 backend/pkg/installer/deploy/manifest_test.go create mode 100644 backend/pkg/installer/deploy/metadata.go create mode 100644 backend/pkg/installer/deploy/metadata_test.go create mode 100644 backend/pkg/installer/deploy/snapshot.go create mode 100644 backend/pkg/installer/deploy/snapshot_test.go create mode 100644 backend/pkg/installer/deploy/upgrade_center.go create mode 100644 backend/pkg/installer/deploy/upgrade_center_test.go create mode 100644 backend/pkg/installer/deploy/upgrade_host.go create mode 100644 backend/pkg/installer/deploy/upgrade_host_test.go create mode 100644 backend/pkg/installer/steps/upgrade_center.go create mode 100644 backend/pkg/installer/steps/upgrade_center_test.go create mode 100644 backend/pkg/installer/steps/upgrade_host.go create mode 100644 backend/pkg/installer/steps/upgrade_host_test.go diff --git a/backend/cmd/installer/main.go b/backend/cmd/installer/main.go index 6d118588..cd2ebc1d 100644 --- a/backend/cmd/installer/main.go +++ b/backend/cmd/installer/main.go @@ -94,6 +94,14 @@ func buildApp(m mode, logger *logging.Logger) *app.App { &steps.ServiceForm{}, &steps.InstallService{}, }}, + {Label: "升级", Value: "upgrade", Steps: []steps.Step{ + &steps.CheckDocker{}, + &steps.CenterUpgrade{}, + }}, + {Label: "回滚", Value: "rollback", Steps: []steps.Step{ + &steps.CheckDocker{}, + &steps.CenterRollback{}, + }}, }, } default: @@ -106,6 +114,10 @@ func buildApp(m mode, logger *logging.Logger) *app.App { &steps.CheckDocker{}, &steps.HostInstall{}, }}, + {Label: "升级", Value: "upgrade", Steps: []steps.Step{ + &steps.CheckDocker{}, + &steps.HostUpgrade{}, + }}, {Label: "卸载", Value: "uninstall", Steps: []steps.Step{ &steps.HostUninstall{}, }}, diff --git a/backend/cmd/installer/main_test.go b/backend/cmd/installer/main_test.go new file mode 100644 index 00000000..68bafc41 --- /dev/null +++ b/backend/cmd/installer/main_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "testing" + + "github.com/chaitin/MonkeyCode/backend/pkg/installer/app" + "github.com/chaitin/MonkeyCode/backend/pkg/installer/logging" +) + +func TestBuildAppIncludesUpgradeActions(t *testing.T) { + logger := logging.NewDiscard() + center := buildApp(modeCenter, logger) + if !hasAction(center.Actions, "upgrade") || !hasAction(center.Actions, "rollback") { + t.Fatalf("center actions = %#v", center.Actions) + } + host := buildApp(modeHost, logger) + if !hasAction(host.Actions, "upgrade") { + t.Fatalf("host actions = %#v", host.Actions) + } +} + +func hasAction(actions []app.Action, value string) bool { + for _, action := range actions { + if action.Value == value { + return true + } + } + return false +} diff --git a/backend/pkg/installer/deploy/envmerge.go b/backend/pkg/installer/deploy/envmerge.go new file mode 100644 index 00000000..94645675 --- /dev/null +++ b/backend/pkg/installer/deploy/envmerge.go @@ -0,0 +1,54 @@ +package deploy + +import "strings" + +func MergeEnv(oldEnv, newTemplate string, forceNew map[string]bool) string { + oldValues := parseEnvLines(oldEnv) + var out []string + seen := map[string]bool{} + + for _, line := range strings.Split(newTemplate, "\n") { + if strings.TrimSpace(line) == "" { + continue + } + + key, value, ok := strings.Cut(line, "=") + if !ok { + out = append(out, line) + continue + } + + key = strings.TrimSpace(key) + seen[key] = true + if !forceNew[key] { + if old, exists := oldValues[key]; exists { + value = old + } + } + out = append(out, key+"="+value) + } + + for key, value := range oldValues { + if !seen[key] { + out = append(out, key+"="+value) + } + } + return strings.Join(out, "\n") + "\n" +} + +func parseEnvLines(content string) map[string]string { + values := map[string]string{} + for _, line := range strings.Split(content, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + values[strings.TrimSpace(key)] = value + } + return values +} diff --git a/backend/pkg/installer/deploy/envmerge_test.go b/backend/pkg/installer/deploy/envmerge_test.go new file mode 100644 index 00000000..1daca4da --- /dev/null +++ b/backend/pkg/installer/deploy/envmerge_test.go @@ -0,0 +1,27 @@ +package deploy + +import ( + "strings" + "testing" +) + +func TestMergeEnvKeepsSecretsAndUpdatesImages(t *testing.T) { + oldEnv := "POSTGRES_PASSWORD=old-secret\nBACKEND_IMAGE=backend:old\nREMOTE_IP=10.0.0.1\n" + newTemplate := "POSTGRES_PASSWORD=\nBACKEND_IMAGE=backend:new\nFRONTEND_IMAGE=frontend:new\nREMOTE_IP=\nNEW_FLAG=true\n" + got := MergeEnv(oldEnv, newTemplate, map[string]bool{ + "BACKEND_IMAGE": true, + "FRONTEND_IMAGE": true, + }) + + for _, want := range []string{ + "POSTGRES_PASSWORD=old-secret", + "BACKEND_IMAGE=backend:new", + "FRONTEND_IMAGE=frontend:new", + "REMOTE_IP=10.0.0.1", + "NEW_FLAG=true", + } { + if !strings.Contains(got, want) { + t.Fatalf("merged env missing %q:\n%s", want, got) + } + } +} diff --git a/backend/pkg/installer/deploy/manifest.go b/backend/pkg/installer/deploy/manifest.go new file mode 100644 index 00000000..baafcb56 --- /dev/null +++ b/backend/pkg/installer/deploy/manifest.go @@ -0,0 +1,110 @@ +package deploy + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" +) + +type PackageManifest struct { + Version string `json:"version"` + Commit string `json:"commit"` + BuiltAt string `json:"built_at"` + Arch string `json:"arch"` + MinUpgradeFrom string `json:"min_upgrade_from"` + ComposeSHA256 string `json:"compose_sha256"` + StaticSHA256 string `json:"static_sha256"` + Images []ManifestImage `json:"images"` + HostBundles []HostBundle `json:"host_bundles"` +} + +type ManifestImage struct { + Name string `json:"name"` + Archive string `json:"archive"` + Image string `json:"image"` + SHA256 string `json:"sha256"` +} + +type HostBundle struct { + Arch string `json:"arch"` + Path string `json:"path"` + SHA256 string `json:"sha256"` +} + +func ReadPackageManifest(packageDir string) (PackageManifest, error) { + data, err := os.ReadFile(filepath.Join(packageDir, "manifest.json")) + if err != nil { + return PackageManifest{}, fmt.Errorf("read manifest: %w", err) + } + + var manifest PackageManifest + if err := json.Unmarshal(data, &manifest); err != nil { + return PackageManifest{}, fmt.Errorf("parse manifest: %w", err) + } + return manifest, nil +} + +func ValidatePackageManifest(packageDir string, manifest PackageManifest) error { + if manifest.Version == "" || manifest.Arch == "" { + return fmt.Errorf("manifest missing version or arch") + } + if len(manifest.Images) == 0 { + return fmt.Errorf("manifest missing images") + } + if len(manifest.HostBundles) == 0 { + return fmt.Errorf("manifest missing host bundles") + } + + for _, image := range manifest.Images { + if err := validateManifestFile(packageDir, image.Archive, image.SHA256); err != nil { + return fmt.Errorf("validate image %s: %w", image.Name, err) + } + } + for _, bundle := range manifest.HostBundles { + if err := validateManifestFile(packageDir, bundle.Path, bundle.SHA256); err != nil { + return fmt.Errorf("validate host bundle %s: %w", bundle.Arch, err) + } + } + return nil +} + +func validateManifestFile(root, rel, want string) error { + if rel == "" { + return fmt.Errorf("empty path") + } + + path := filepath.Join(root, rel) + if _, err := os.Stat(path); err != nil { + return err + } + if want == "" { + return nil + } + + got, err := fileSHA256(path) + if err != nil { + return err + } + if got != want { + return fmt.Errorf("sha256 mismatch for %s", rel) + } + return nil +} + +func fileSHA256(path string) (string, error) { + file, err := os.Open(path) + if err != nil { + return "", err + } + defer file.Close() + + hash := sha256.New() + if _, err := io.Copy(hash, file); err != nil { + return "", err + } + return hex.EncodeToString(hash.Sum(nil)), nil +} diff --git a/backend/pkg/installer/deploy/manifest_test.go b/backend/pkg/installer/deploy/manifest_test.go new file mode 100644 index 00000000..cdd76184 --- /dev/null +++ b/backend/pkg/installer/deploy/manifest_test.go @@ -0,0 +1,41 @@ +package deploy + +import ( + "os" + "path/filepath" + "testing" +) + +func TestReadPackageManifest(t *testing.T) { + dir := t.TempDir() + content := `{ + "version": "2026.05.27", + "commit": "32df5254", + "built_at": "2026-05-27T10:00:00+08:00", + "arch": "amd64", + "min_upgrade_from": "2026.05.01", + "compose_sha256": "abc", + "static_sha256": "def", + "images": [{"name":"backend","archive":"images/backend.tar.gz","image":"repo/backend:32df5254","sha256":"123"}], + "host_bundles": [{"arch":"x86_64","path":"static/installer/x86_64/host.tgz","sha256":"456"}] + }` + if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + + m, err := ReadPackageManifest(dir) + if err != nil { + t.Fatal(err) + } + if m.Version != "2026.05.27" || m.Commit != "32df5254" || len(m.Images) != 1 || len(m.HostBundles) != 1 { + t.Fatalf("manifest = %#v", m) + } +} + +func TestValidatePackageManifestRequiresHostBundles(t *testing.T) { + m := PackageManifest{Version: "2026.05.27", Arch: "amd64"} + err := ValidatePackageManifest(t.TempDir(), m) + if err == nil { + t.Fatal("expected error") + } +} diff --git a/backend/pkg/installer/deploy/metadata.go b/backend/pkg/installer/deploy/metadata.go new file mode 100644 index 00000000..1a8c0aa4 --- /dev/null +++ b/backend/pkg/installer/deploy/metadata.go @@ -0,0 +1,95 @@ +package deploy + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "time" +) + +type InstallMetadata struct { + Version string `json:"version"` + Commit string `json:"commit"` + InstallDir string `json:"install_dir"` + ComposeSHA string `json:"compose_sha256"` + StaticSHA string `json:"static_sha256"` + Images []string `json:"images"` + LastUpgraded string `json:"last_upgraded"` +} + +type UpgradeRecord struct { + Type string `json:"type"` + From string `json:"from"` + To string `json:"to"` + BackupDir string `json:"backup_dir"` + StartedAt string `json:"started_at"` + FinishedAt string `json:"finished_at"` + Status string `json:"status"` + Error string `json:"error,omitempty"` +} + +func metadataDir(installDir string) string { + return filepath.Join(installDir, ".monkeycode") +} + +func currentMetadataPath(installDir string) string { + return filepath.Join(metadataDir(installDir), "current.json") +} + +func ReadInstallMetadata(installDir string) (InstallMetadata, error) { + data, err := os.ReadFile(currentMetadataPath(installDir)) + if err != nil { + return InstallMetadata{}, err + } + + var meta InstallMetadata + if err := json.Unmarshal(data, &meta); err != nil { + return InstallMetadata{}, err + } + return meta, nil +} + +func WriteInstallMetadata(installDir string, meta InstallMetadata) error { + if err := os.MkdirAll(metadataDir(installDir), 0o755); err != nil { + return err + } + + data, err := json.MarshalIndent(meta, "", " ") + if err != nil { + return err + } + return os.WriteFile(currentMetadataPath(installDir), append(data, '\n'), 0o644) +} + +func BuildLegacyMetadata(installDir string) (InstallMetadata, error) { + for _, name := range []string{".env", "docker-compose.yml"} { + if _, err := os.Stat(filepath.Join(installDir, name)); err != nil { + return InstallMetadata{}, fmt.Errorf("legacy install missing %s: %w", name, err) + } + } + + composeSHA, _ := fileSHA256(filepath.Join(installDir, "docker-compose.yml")) + return InstallMetadata{ + Version: "legacy", + Commit: "legacy", + InstallDir: installDir, + ComposeSHA: composeSHA, + }, nil +} + +func WriteUpgradeRecord(installDir string, record UpgradeRecord) error { + if record.StartedAt == "" { + record.StartedAt = time.Now().Format(time.RFC3339) + } + if err := os.MkdirAll(filepath.Join(metadataDir(installDir), "upgrades"), 0o755); err != nil { + return err + } + + name := time.Now().Format("20060102-150405") + ".json" + data, err := json.MarshalIndent(record, "", " ") + if err != nil { + return err + } + return os.WriteFile(filepath.Join(metadataDir(installDir), "upgrades", name), append(data, '\n'), 0o644) +} diff --git a/backend/pkg/installer/deploy/metadata_test.go b/backend/pkg/installer/deploy/metadata_test.go new file mode 100644 index 00000000..4aff85b9 --- /dev/null +++ b/backend/pkg/installer/deploy/metadata_test.go @@ -0,0 +1,41 @@ +package deploy + +import ( + "os" + "path/filepath" + "testing" +) + +func TestWriteAndReadInstallMetadata(t *testing.T) { + dir := t.TempDir() + meta := InstallMetadata{Version: "2026.05.27", Commit: "32df5254", InstallDir: dir} + if err := WriteInstallMetadata(dir, meta); err != nil { + t.Fatal(err) + } + + got, err := ReadInstallMetadata(dir) + if err != nil { + t.Fatal(err) + } + if got.Version != meta.Version || got.Commit != meta.Commit || got.InstallDir != dir { + t.Fatalf("metadata = %#v", got) + } +} + +func TestBuildLegacyMetadata(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("BACKEND_IMAGE=backend:old\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "docker-compose.yml"), []byte("services: {}\n"), 0o644); err != nil { + t.Fatal(err) + } + + meta, err := BuildLegacyMetadata(dir) + if err != nil { + t.Fatal(err) + } + if meta.Version != "legacy" || meta.InstallDir != dir { + t.Fatalf("legacy metadata = %#v", meta) + } +} diff --git a/backend/pkg/installer/deploy/snapshot.go b/backend/pkg/installer/deploy/snapshot.go new file mode 100644 index 00000000..3d45940c --- /dev/null +++ b/backend/pkg/installer/deploy/snapshot.go @@ -0,0 +1,105 @@ +package deploy + +import ( + "fmt" + "io" + "io/fs" + "os" + "path/filepath" +) + +type CenterSnapshot struct { + Path string +} + +func CreateCenterSnapshot(installDir, backupDir string) (CenterSnapshot, error) { + if err := os.MkdirAll(backupDir, 0o755); err != nil { + return CenterSnapshot{}, err + } + + for _, name := range centerSnapshotPaths() { + src := filepath.Join(installDir, name) + dst := filepath.Join(backupDir, name) + if err := copyPathIfExists(src, dst); err != nil { + return CenterSnapshot{}, fmt.Errorf("backup %s: %w", name, err) + } + } + return CenterSnapshot{Path: backupDir}, nil +} + +func RestoreCenterSnapshot(installDir string, snap CenterSnapshot) error { + for _, name := range centerSnapshotPaths() { + src := filepath.Join(snap.Path, name) + dst := filepath.Join(installDir, name) + if _, err := os.Stat(src); os.IsNotExist(err) { + continue + } + if err := os.RemoveAll(dst); err != nil { + return err + } + if err := copyPathIfExists(src, dst); err != nil { + return fmt.Errorf("restore %s: %w", name, err) + } + } + return nil +} + +func centerSnapshotPaths() []string { + return []string{".env", "docker-compose.yml", "tls", "static", "images", "data", "logs", ".monkeycode/current.json"} +} + +func copyPathIfExists(src, dst string) error { + info, err := os.Stat(src) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + if info.IsDir() { + return copyDir(src, dst) + } + return copyFileMode(src, dst, info.Mode()) +} + +func copyDir(src, dst string) error { + return filepath.WalkDir(src, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + + rel, err := filepath.Rel(src, path) + if err != nil { + return err + } + target := filepath.Join(dst, rel) + info, err := entry.Info() + if err != nil { + return err + } + if entry.IsDir() { + return os.MkdirAll(target, info.Mode()) + } + return copyFileMode(path, target, info.Mode()) + }) +} + +func copyFileMode(src, dst string, mode os.FileMode) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return err + } + out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, in) + return err +} diff --git a/backend/pkg/installer/deploy/snapshot_test.go b/backend/pkg/installer/deploy/snapshot_test.go new file mode 100644 index 00000000..bd2cd393 --- /dev/null +++ b/backend/pkg/installer/deploy/snapshot_test.go @@ -0,0 +1,42 @@ +package deploy + +import ( + "os" + "path/filepath" + "testing" +) + +func TestCreateAndRestoreCenterSnapshot(t *testing.T) { + installDir := t.TempDir() + if err := os.WriteFile(filepath.Join(installDir, ".env"), []byte("A=old\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(installDir, "docker-compose.yml"), []byte("old-compose\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(installDir, "data", "postgres"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(installDir, "data", "postgres", "PG_VERSION"), []byte("17"), 0o644); err != nil { + t.Fatal(err) + } + + snap, err := CreateCenterSnapshot(installDir, filepath.Join(installDir, ".monkeycode", "backups", "snap")) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(installDir, ".env"), []byte("A=new\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := RestoreCenterSnapshot(installDir, snap); err != nil { + t.Fatal(err) + } + + got, err := os.ReadFile(filepath.Join(installDir, ".env")) + if err != nil { + t.Fatal(err) + } + if string(got) != "A=old\n" { + t.Fatalf(".env = %q", got) + } +} diff --git a/backend/pkg/installer/deploy/upgrade_center.go b/backend/pkg/installer/deploy/upgrade_center.go new file mode 100644 index 00000000..9747bfa3 --- /dev/null +++ b/backend/pkg/installer/deploy/upgrade_center.go @@ -0,0 +1,126 @@ +package deploy + +import ( + "context" + "fmt" + "os" + "path/filepath" +) + +type CenterUpgradePlan struct { + InstallDir string + PackageDir string + BackupDir string +} + +func UpgradeCenter(ctx context.Context, r Runner, plan CenterUpgradePlan) error { + manifest, err := ReadPackageManifest(plan.PackageDir) + if err != nil { + return err + } + if err := ValidatePackageManifest(plan.PackageDir, manifest); err != nil { + return err + } + if plan.BackupDir == "" { + plan.BackupDir = filepath.Join(plan.InstallDir, ".monkeycode", "backups", manifest.Commit) + } + + if err := stopCenterBusiness(ctx, r, plan.InstallDir); err != nil { + return err + } + snap, err := CreateCenterSnapshot(plan.InstallDir, plan.BackupDir) + if err != nil { + return err + } + if err := stopCenterAll(ctx, r, plan.InstallDir); err != nil { + _ = RestoreCenterSnapshot(plan.InstallDir, snap) + return err + } + if err := applyCenterPackage(ctx, r, plan); err != nil { + _ = RestoreCenterSnapshot(plan.InstallDir, snap) + _ = InstallCenter(ctx, r, CenterInstallPlan{ + WorkDir: plan.InstallDir, + ComposeFile: filepath.Join(plan.InstallDir, "docker-compose.yml"), + EnvFile: filepath.Join(plan.InstallDir, ".env"), + }) + return err + } + + return WriteInstallMetadata(plan.InstallDir, InstallMetadata{ + Version: manifest.Version, + Commit: manifest.Commit, + InstallDir: plan.InstallDir, + }) +} + +func RollbackCenter(ctx context.Context, r Runner, installDir string, snap CenterSnapshot) error { + _ = stopCenterAll(ctx, r, installDir) + if err := RestoreCenterSnapshot(installDir, snap); err != nil { + return err + } + return InstallCenter(ctx, r, CenterInstallPlan{ + WorkDir: installDir, + ComposeFile: filepath.Join(installDir, "docker-compose.yml"), + EnvFile: filepath.Join(installDir, ".env"), + }) +} + +func stopCenterBusiness(ctx context.Context, r Runner, installDir string) error { + return run(ctx, r, "docker", "compose", "-f", filepath.Join(installDir, "docker-compose.yml"), "--env-file", filepath.Join(installDir, ".env"), "stop", "backend", "frontend", "taskflow", "preview", "ingress") +} + +func stopCenterAll(ctx context.Context, r Runner, installDir string) error { + return run(ctx, r, "docker", "compose", "-f", filepath.Join(installDir, "docker-compose.yml"), "--env-file", filepath.Join(installDir, ".env"), "down") +} + +func applyCenterPackage(ctx context.Context, r Runner, plan CenterUpgradePlan) error { + oldEnv, err := os.ReadFile(filepath.Join(plan.InstallDir, ".env")) + if err != nil { + return err + } + newEnv, err := os.ReadFile(filepath.Join(plan.PackageDir, ".env.example")) + if err != nil { + return err + } + merged := MergeEnv(string(oldEnv), string(newEnv), imageEnvKeys()) + if err := os.WriteFile(filepath.Join(plan.InstallDir, ".env"), []byte(merged), 0o600); err != nil { + return err + } + + for _, name := range []string{"docker-compose.yml", "static", "images"} { + if err := os.RemoveAll(filepath.Join(plan.InstallDir, name)); err != nil { + return err + } + if err := copyPathIfExists(filepath.Join(plan.PackageDir, name), filepath.Join(plan.InstallDir, name)); err != nil { + return fmt.Errorf("copy %s: %w", name, err) + } + } + + images, err := ScanImages(filepath.Join(plan.InstallDir, "images")) + if err != nil { + return err + } + if err := LoadImages(ctx, r, images); err != nil { + return err + } + return InstallCenter(ctx, r, CenterInstallPlan{ + WorkDir: plan.InstallDir, + ComposeFile: filepath.Join(plan.InstallDir, "docker-compose.yml"), + EnvFile: filepath.Join(plan.InstallDir, ".env"), + }) +} + +func imageEnvKeys() map[string]bool { + return map[string]bool{ + "POSTGRES_IMAGE": true, + "REDIS_IMAGE": true, + "CLICKHOUSE_IMAGE": true, + "RUSTFS_IMAGE": true, + "INGRESS_IMAGE": true, + "TASKFLOW_IMAGE": true, + "PREVIEW_IMAGE": true, + "FRONTEND_IMAGE": true, + "BACKEND_IMAGE": true, + "INIT_TEAM_IMAGE": true, + } +} diff --git a/backend/pkg/installer/deploy/upgrade_center_test.go b/backend/pkg/installer/deploy/upgrade_center_test.go new file mode 100644 index 00000000..eb959daa --- /dev/null +++ b/backend/pkg/installer/deploy/upgrade_center_test.go @@ -0,0 +1,86 @@ +package deploy + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestUpgradeCenterStopsBackupsLoadsAndStarts(t *testing.T) { + dir := t.TempDir() + pkg := t.TempDir() + writeMinimalCenterInstall(t, dir) + writeMinimalPackage(t, pkg) + r := &FakeRunner{} + plan := CenterUpgradePlan{ + InstallDir: dir, + PackageDir: pkg, + BackupDir: filepath.Join(dir, ".monkeycode", "backups", "snap"), + } + + if err := UpgradeCenter(context.Background(), r, plan); err != nil { + t.Fatal(err) + } + + calls := strings.Join(r.Calls, "\n") + for _, want := range []string{ + "docker compose -f " + filepath.Join(dir, "docker-compose.yml") + " --env-file " + filepath.Join(dir, ".env") + " stop backend frontend taskflow preview ingress", + "docker compose -f " + filepath.Join(dir, "docker-compose.yml") + " --env-file " + filepath.Join(dir, ".env") + " down", + "docker compose -f " + filepath.Join(dir, "docker-compose.yml") + " --env-file " + filepath.Join(dir, ".env") + " up -d", + } { + if !strings.Contains(calls, want) { + t.Fatalf("calls missing %q:\n%s", want, calls) + } + } +} + +func writeMinimalCenterInstall(t *testing.T, dir string) { + t.Helper() + for _, sub := range []string{"data/postgres", "data/redis", "data/clickhouse", "data/rustfs", "static", "images"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("BACKEND_IMAGE=backend:old\nPOSTGRES_PASSWORD=old\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "docker-compose.yml"), []byte("services: {}\n"), 0o644); err != nil { + t.Fatal(err) + } +} + +func writeMinimalPackage(t *testing.T, dir string) { + t.Helper() + for _, sub := range []string{"images", "static/installer/x86_64", "static/installer/aarch64"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + files := map[string]string{ + ".env.example": "BACKEND_IMAGE=backend:new\nPOSTGRES_PASSWORD=\n", + "docker-compose.yml": "services: {}\n", + "images/backend.tar.gz": "image", + "static/installer/x86_64/host.tgz": "host-x86", + "static/installer/aarch64/host.tgz": "host-arm", + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + manifest := `{ + "version":"2026.05.27", + "commit":"new", + "arch":"amd64", + "images":[{"name":"backend","archive":"images/backend.tar.gz","image":"backend:new"}], + "host_bundles":[ + {"arch":"x86_64","path":"static/installer/x86_64/host.tgz"}, + {"arch":"aarch64","path":"static/installer/aarch64/host.tgz"} + ] + }` + if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte(manifest), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/backend/pkg/installer/deploy/upgrade_host.go b/backend/pkg/installer/deploy/upgrade_host.go new file mode 100644 index 00000000..1c2627f1 --- /dev/null +++ b/backend/pkg/installer/deploy/upgrade_host.go @@ -0,0 +1,70 @@ +package deploy + +import ( + "context" + "path/filepath" + "time" +) + +type HostUpgradePlan struct { + WorkDir string + BundleFile string + Token string + GrpcURL string +} + +func UpgradeHost(ctx context.Context, r Runner, plan HostUpgradePlan) error { + backupDir := filepath.Join(plan.WorkDir, ".backup", time.Now().Format("20060102-150405")) + for _, name := range hostUpgradeFiles() { + if err := copyPathIfExists(filepath.Join(plan.WorkDir, name), filepath.Join(backupDir, name)); err != nil { + return err + } + } + + oldPlan := HostInstallPlan{ + WorkDir: plan.WorkDir, + ComposeFile: filepath.Join(plan.WorkDir, "docker-compose.yml"), + EnvFile: filepath.Join(plan.WorkDir, ".env"), + } + if err := run(ctx, r, "docker", "compose", "-f", oldPlan.ComposeFile, "--env-file", oldPlan.EnvFile, "down"); err != nil { + return err + } + if err := run(ctx, r, "tar", "-zxf", plan.BundleFile, "-C", plan.WorkDir); err != nil { + _ = restoreHostBackup(plan.WorkDir, backupDir) + _ = InstallHost(ctx, r, oldPlan) + return err + } + + images, err := ScanImages(filepath.Join(plan.WorkDir, "images")) + if err != nil { + _ = restoreHostBackup(plan.WorkDir, backupDir) + return err + } + newPlan := HostInstallPlan{ + WorkDir: plan.WorkDir, + ComposeFile: filepath.Join(plan.WorkDir, "docker-compose.yml"), + EnvFile: filepath.Join(plan.WorkDir, ".env"), + Token: plan.Token, + GrpcURL: plan.GrpcURL, + Images: images, + } + if err := InstallHost(ctx, r, newPlan); err != nil { + _ = restoreHostBackup(plan.WorkDir, backupDir) + _ = InstallHost(ctx, r, oldPlan) + return err + } + return nil +} + +func restoreHostBackup(workDir, backupDir string) error { + for _, name := range hostUpgradeFiles() { + if err := copyPathIfExists(filepath.Join(backupDir, name), filepath.Join(workDir, name)); err != nil { + return err + } + } + return nil +} + +func hostUpgradeFiles() []string { + return []string{"docker-compose.yml", ".env", "images"} +} diff --git a/backend/pkg/installer/deploy/upgrade_host_test.go b/backend/pkg/installer/deploy/upgrade_host_test.go new file mode 100644 index 00000000..5e159cc2 --- /dev/null +++ b/backend/pkg/installer/deploy/upgrade_host_test.go @@ -0,0 +1,54 @@ +package deploy + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestUpgradeHostBacksUpAndRestartsRunner(t *testing.T) { + dir := t.TempDir() + writeMinimalHostInstall(t, dir) + r := &FakeRunner{} + bundleFile := filepath.Join(t.TempDir(), "host.tgz") + if err := os.WriteFile(bundleFile, []byte("fake"), 0o644); err != nil { + t.Fatal(err) + } + plan := HostUpgradePlan{ + WorkDir: dir, + BundleFile: bundleFile, + Token: "token-new", + GrpcURL: "127.0.0.1:50443", + } + + if err := UpgradeHost(context.Background(), r, plan); err != nil { + t.Fatal(err) + } + + calls := strings.Join(r.Calls, "\n") + if !strings.Contains(calls, "docker compose -f "+filepath.Join(dir, "docker-compose.yml")+" --env-file "+filepath.Join(dir, ".env")+" down") { + t.Fatalf("missing compose down:\n%s", calls) + } + if !strings.Contains(calls, "docker compose -f "+filepath.Join(dir, "docker-compose.yml")+" --env-file "+filepath.Join(dir, ".env")+" up -d") { + t.Fatalf("missing compose up:\n%s", calls) + } +} + +func writeMinimalHostInstall(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(filepath.Join(dir, "images"), 0o755); err != nil { + t.Fatal(err) + } + files := map[string]string{ + ".env": "TOKEN=old\nGRPC_URL=old:50443\n", + "docker-compose.yml": "services: {}\n", + "images/runner.tar": "image", + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } +} diff --git a/backend/pkg/installer/logging/logger.go b/backend/pkg/installer/logging/logger.go index ca1f28e8..522d00fd 100644 --- a/backend/pkg/installer/logging/logger.go +++ b/backend/pkg/installer/logging/logger.go @@ -23,7 +23,29 @@ func New() (*Logger, error) { return &Logger{file: f, path: path}, nil } -func (l *Logger) Path() string { return l.path } -func (l *Logger) Plain() io.Writer { return l.file } -func (l *Logger) Sync() error { return l.file.Sync() } -func (l *Logger) Close() error { return l.file.Close() } +func NewDiscard() *Logger { + return &Logger{path: "/dev/null"} +} + +func (l *Logger) Path() string { return l.path } + +func (l *Logger) Plain() io.Writer { + if l.file == nil { + return io.Discard + } + return l.file +} + +func (l *Logger) Sync() error { + if l.file == nil { + return nil + } + return l.file.Sync() +} + +func (l *Logger) Close() error { + if l.file == nil { + return nil + } + return l.file.Close() +} diff --git a/backend/pkg/installer/steps/fake_reporter_test.go b/backend/pkg/installer/steps/fake_reporter_test.go index 2654ee3f..b463751d 100644 --- a/backend/pkg/installer/steps/fake_reporter_test.go +++ b/backend/pkg/installer/steps/fake_reporter_test.go @@ -28,9 +28,9 @@ func (r *fakeReporter) SetStep(title, hint string) { r.StepCalls = append(r.StepCalls, title) } -func (r *fakeReporter) StartProgress(label string) {} -func (r *fakeReporter) UpdateProgress(downloaded, total int64) {} -func (r *fakeReporter) EndProgress() {} +func (r *fakeReporter) StartProgress(label string) {} +func (r *fakeReporter) UpdateProgress(downloaded, total int64) {} +func (r *fakeReporter) EndProgress() {} func (r *fakeReporter) AskInput(label, def string, password bool, v Validator) (string, error) { if r.inputIdx >= len(r.InputAns) { diff --git a/backend/pkg/installer/steps/upgrade_center.go b/backend/pkg/installer/steps/upgrade_center.go new file mode 100644 index 00000000..eb00cc8b --- /dev/null +++ b/backend/pkg/installer/steps/upgrade_center.go @@ -0,0 +1,75 @@ +package steps + +import ( + "context" + "fmt" + "path/filepath" + + "github.com/chaitin/MonkeyCode/backend/pkg/installer/deploy" +) + +type CenterUpgrade struct{} + +func (s *CenterUpgrade) Name() string { return "中心端升级" } + +func (s *CenterUpgrade) Run(c *Context) error { + pkgDir, err := packageDir() + if err != nil { + return err + } + values, err := c.Reporter.AskForm([]FormField{ + {Label: "安装目录", Default: "/data/monkeycode-ai", Validate: validateAbsPath}, + }) + if err != nil { + return err + } + installDir := values[0] + ok, err := c.Reporter.AskConfirm(fmt.Sprintf("确认升级 %s ?", installDir)) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("已取消升级") + } + + c.Reporter.SetStep("升级中心端...", "下一步: 完成") + backupDir := filepath.Join(installDir, ".monkeycode", "backups") + plan := deploy.CenterUpgradePlan{ + InstallDir: installDir, + PackageDir: pkgDir, + BackupDir: backupDir, + } + if err := deploy.UpgradeCenter(context.Background(), wrapRunner(c.Runner, c.Reporter, " "), plan); err != nil { + return fmt.Errorf("升级中心端失败: %w", err) + } + c.Log("✓ 中心端升级完成,快照保留在 %s", backupDir) + return nil +} + +type CenterRollback struct{} + +func (s *CenterRollback) Name() string { return "中心端回滚" } + +func (s *CenterRollback) Run(c *Context) error { + values, err := c.Reporter.AskForm([]FormField{ + {Label: "安装目录", Default: "/data/monkeycode-ai", Validate: validateAbsPath}, + {Label: "快照目录", Default: "", Validate: validateAbsPath}, + }) + if err != nil { + return err + } + ok, err := c.Reporter.AskConfirm(fmt.Sprintf("确认回滚 %s ?", values[0])) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("已取消回滚") + } + + c.Reporter.SetStep("回滚中心端...", "下一步: 完成") + if err := deploy.RollbackCenter(context.Background(), wrapRunner(c.Runner, c.Reporter, " "), values[0], deploy.CenterSnapshot{Path: values[1]}); err != nil { + return fmt.Errorf("回滚中心端失败: %w", err) + } + c.Log("✓ 中心端回滚完成") + return nil +} diff --git a/backend/pkg/installer/steps/upgrade_center_test.go b/backend/pkg/installer/steps/upgrade_center_test.go new file mode 100644 index 00000000..aff13059 --- /dev/null +++ b/backend/pkg/installer/steps/upgrade_center_test.go @@ -0,0 +1,109 @@ +package steps + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCenterUpgradeUsesInstallDirAndPackageDir(t *testing.T) { + ctx, r, _ := ctxWithFakeReporter() + installDir := t.TempDir() + pkgDir := t.TempDir() + writeStepCenterInstall(t, installDir) + writeStepCenterPackage(t, pkgDir) + oldPackageDir := packageDir + packageDir = func() (string, error) { return pkgDir, nil } + defer func() { packageDir = oldPackageDir }() + r.FormAns = [][]string{{installDir}} + r.ConfirmAns = []bool{true} + + if err := (&CenterUpgrade{}).Run(ctx); err != nil { + t.Fatal(err) + } + + got, err := os.ReadFile(filepath.Join(installDir, ".env")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(got), "BACKEND_IMAGE=backend:new") { + t.Fatalf(".env was not upgraded:\n%s", got) + } +} + +func TestCenterRollbackPassesSnapshotDir(t *testing.T) { + ctx, r, _ := ctxWithFakeReporter() + installDir := t.TempDir() + snapDir := filepath.Join(t.TempDir(), "snap") + writeStepCenterInstall(t, installDir) + if err := os.MkdirAll(snapDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(snapDir, ".env"), []byte("BACKEND_IMAGE=backend:old\n"), 0o600); err != nil { + t.Fatal(err) + } + r.FormAns = [][]string{{installDir, snapDir}} + r.ConfirmAns = []bool{true} + + if err := (&CenterRollback{}).Run(ctx); err != nil { + t.Fatal(err) + } + + got, err := os.ReadFile(filepath.Join(installDir, ".env")) + if err != nil { + t.Fatal(err) + } + if string(got) != "BACKEND_IMAGE=backend:old\n" { + t.Fatalf(".env = %q", got) + } +} + +func writeStepCenterInstall(t *testing.T, dir string) { + t.Helper() + for _, sub := range []string{"data/postgres", "static", "images"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("BACKEND_IMAGE=backend:old\nPOSTGRES_PASSWORD=old\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "docker-compose.yml"), []byte("services: {}\n"), 0o644); err != nil { + t.Fatal(err) + } +} + +func writeStepCenterPackage(t *testing.T, dir string) { + t.Helper() + for _, sub := range []string{"images", "static/installer/x86_64", "static/installer/aarch64"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + files := map[string]string{ + ".env.example": "BACKEND_IMAGE=backend:new\nPOSTGRES_PASSWORD=\n", + "docker-compose.yml": "services: {}\n", + "images/backend.tar.gz": "image", + "static/installer/x86_64/host.tgz": "host-x86", + "static/installer/aarch64/host.tgz": "host-arm", + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + manifest := `{ + "version":"2026.05.27", + "commit":"new", + "arch":"amd64", + "images":[{"name":"backend","archive":"images/backend.tar.gz","image":"backend:new"}], + "host_bundles":[ + {"arch":"x86_64","path":"static/installer/x86_64/host.tgz"}, + {"arch":"aarch64","path":"static/installer/aarch64/host.tgz"} + ] + }` + if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte(manifest), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/backend/pkg/installer/steps/upgrade_host.go b/backend/pkg/installer/steps/upgrade_host.go new file mode 100644 index 00000000..102da805 --- /dev/null +++ b/backend/pkg/installer/steps/upgrade_host.go @@ -0,0 +1,58 @@ +package steps + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/chaitin/MonkeyCode/backend/pkg/installer/deploy" +) + +type HostUpgrade struct{} + +func (h *HostUpgrade) Name() string { return "宿主机升级" } + +func (h *HostUpgrade) Run(c *Context) error { + cfg := loadHostConfig() + values, err := c.Reporter.AskForm([]FormField{ + {Label: "安装目录", Default: HostDefaultInstallDir, Validate: validateAbsPath}, + }) + if err != nil { + return err + } + workDir := values[0] + ok, err := c.Reporter.AskConfirm(fmt.Sprintf("确认升级 %s ?", workDir)) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("已取消升级") + } + + hostURL, err := cfg.hostBundleURL() + if err != nil { + return err + } + bundleFile := filepath.Join(os.TempDir(), "monkeycode-host-upgrade.tgz") + c.Reporter.SetStep("下载宿主机升级包...", "下一步: 升级宿主机") + c.Reporter.StartProgress(filepath.Base(bundleFile)) + err = deploy.DownloadFile(context.Background(), hostURL, bundleFile, hostProgress(c.Reporter)) + c.Reporter.EndProgress() + if err != nil { + return fmt.Errorf("下载宿主机升级包失败: %w", err) + } + + c.Reporter.SetStep("升级宿主机服务...", "下一步: 完成") + plan := deploy.HostUpgradePlan{ + WorkDir: workDir, + BundleFile: bundleFile, + Token: os.Getenv(envHostToken), + GrpcURL: os.Getenv(envTaskflowGRPC), + } + if err := deploy.UpgradeHost(context.Background(), wrapRunner(c.Runner, c.Reporter, " "), plan); err != nil { + return fmt.Errorf("升级宿主机失败: %w", err) + } + c.Log("✓ 宿主机升级完成") + return nil +} diff --git a/backend/pkg/installer/steps/upgrade_host_test.go b/backend/pkg/installer/steps/upgrade_host_test.go new file mode 100644 index 00000000..3fa10781 --- /dev/null +++ b/backend/pkg/installer/steps/upgrade_host_test.go @@ -0,0 +1,17 @@ +package steps + +import ( + "strings" + "testing" +) + +func TestHostUpgradeCancel(t *testing.T) { + ctx, r, _ := ctxWithFakeReporter() + r.FormAns = [][]string{{HostDefaultInstallDir}} + r.ConfirmAns = []bool{false} + + err := (&HostUpgrade{}).Run(ctx) + if err == nil || !strings.Contains(err.Error(), "已取消升级") { + t.Fatalf("expected cancel error, got %v", err) + } +} diff --git a/backend/scripts/build-offline-package.sh b/backend/scripts/build-offline-package.sh index e3a010ef..d5b213b3 100755 --- a/backend/scripts/build-offline-package.sh +++ b/backend/scripts/build-offline-package.sh @@ -192,6 +192,43 @@ build_host_bundle() { build_host_bundle x86_64 build_host_bundle aarch64 +file_sha256() { + sha256sum "$1" | awk '{print $1}' +} + +write_manifest() { + manifest="$PACKAGE_DIR/manifest.json" + compose_sha="$(file_sha256 "$PACKAGE_DIR/docker-compose.yml")" + static_sha="$(tar -C "$PACKAGE_DIR" -cf - static | sha256sum | awk '{print $1}')" + cat > "$manifest" </dev/null + +for file in static/installer/x86_64/host.tgz static/installer/aarch64/host.tgz; do + if ! grep -q "\"path\":\"$file\"" "$ROOT/manifest.json" && ! grep -q "\"path\": \"$file\"" "$ROOT/manifest.json"; then + echo "manifest missing $file" + exit 1 + fi +done diff --git a/backend/scripts/tests/offline_package_static_test.go b/backend/scripts/tests/offline_package_static_test.go index 29c21557..5c9d98f2 100644 --- a/backend/scripts/tests/offline_package_static_test.go +++ b/backend/scripts/tests/offline_package_static_test.go @@ -130,6 +130,24 @@ func TestOfflinePackageCheckRequiresPreviewImage(t *testing.T) { } } +func TestOfflinePackageBuildWritesManifest(t *testing.T) { + content := readFile(t, "../build-offline-package.sh") + for _, want := range []string{"manifest.json", "host_bundles", "sha256sum"} { + if !strings.Contains(content, want) { + t.Fatalf("build-offline-package.sh missing %q", want) + } + } +} + +func TestOfflinePackageCheckRequiresManifest(t *testing.T) { + content := readFile(t, "../check-offline-package.sh") + for _, want := range []string{"manifest.json", "static/installer/x86_64/host.tgz", "static/installer/aarch64/host.tgz"} { + if !strings.Contains(content, want) { + t.Fatalf("check-offline-package.sh missing %q", want) + } + } +} + func TestCenterEnvExampleIncludesPreviewRelaySettings(t *testing.T) { content := readFile(t, "../../installation/center/.env.example") for _, want := range []string{