| 1 | package guestos |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "reflect" |
| 14 | "regexp" |
| 15 | "runtime" |
| 16 | "strings" |
| 17 | "time" |
| 18 | |
| 19 | "al.essio.dev/pkg/shellescape" |
| 20 | "github.com/sylvinus/agent-vm/internal/hostproxy" |
| 21 | ) |
| 22 | |
| 23 | |
| 24 | |
| 25 | func MaintainMacOSComponents(ctx context.Context, profile, kit, manifestPath string, tools bool, stdout, stderr io.Writer) error { |
| 26 | if runtime.GOOS != "darwin" { |
| 27 | return errors.New("macOS 客机维护需要其 Mac 主机") |
| 28 | } |
| 29 | binding, err := LoadMacOSProfile(profile) |
| 30 | if err != nil { |
| 31 | return err |
| 32 | } |
| 33 | if binding == nil { |
| 34 | return errors.New("此配置尚未绑定 macOS 客机") |
| 35 | } |
| 36 | required, err := RequiredNativeComponents(kit, MacOS) |
| 37 | if err != nil { |
| 38 | return err |
| 39 | } |
| 40 | data, err := os.ReadFile(manifestPath) |
| 41 | if err != nil { |
| 42 | return err |
| 43 | } |
| 44 | var selected NativeComponentManifest |
| 45 | if json.Unmarshal(data, &selected) != nil || selected.Validate() != nil || !reflect.DeepEqual(required, selected) { |
| 46 | return errors.New("当前应用组件包已变化,请重新发起更新") |
| 47 | } |
| 48 | provision, err := MacOSProvisionUser(profile) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | args, err := MacOSSSHArgs(profile, provision) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | guest := func(callctx context.Context, script string) *exec.Cmd { |
| 57 | argv := append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/bash -ec "+shellescape.Quote(script)) |
| 58 | command := exec.CommandContext(callctx, "/usr/bin/ssh", argv...) |
| 59 | command.Stderr = stderr |
| 60 | return command |
| 61 | } |
| 62 | mode := "components" |
| 63 | cache := filepath.Join(profile, "state", "guest-media", MacOS) |
| 64 | if tools { |
| 65 | mode = "tools" |
| 66 | exe, err := os.Executable() |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | command := exec.CommandContext(ctx, "/bin/bash", filepath.Join(kit, "prepare-macos-media.sh"), cache) |
| 71 | command.Env = append(append(os.Environ(), hostproxy.DownloadEnvironment()...), "CAGE_REFRESH_TOOLS=1", "CAGE_HOST_DOWNLOADER="+exe) |
| 72 | command.Stdout, command.Stderr = stdout, stderr |
| 73 | if err = command.Run(); err != nil { |
| 74 | return fmt.Errorf("准备原生工具包失败:%w", err) |
| 75 | } |
| 76 | } |
| 77 | local, err := os.MkdirTemp("", "cage-native-components-") |
| 78 | if err != nil { |
| 79 | return err |
| 80 | } |
| 81 | defer os.RemoveAll(local) |
| 82 | if err = os.WriteFile(filepath.Join(local, "native-components.json"), data, 0600); err != nil { |
| 83 | return err |
| 84 | } |
| 85 | output, err := guest(ctx, `umask 077; test "$(id -un)" = `+shellescape.Quote(provision)+`; mktemp -d /private/var/tmp/cage-components.XXXXXXXX`).Output() |
| 86 | remote := strings.TrimSpace(string(output)) |
| 87 | if err != nil || !regexp.MustCompile(`^/private/var/tmp/cage-components\.[A-Za-z0-9]{8}$`).MatchString(remote) { |
| 88 | return errors.New("无法在已绑定客机中准备组件维护目录") |
| 89 | } |
| 90 | passwordInput := ` < /Users/` + provision + `/password` |
| 91 | defer func() { |
| 92 | cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 93 | defer cancel() |
| 94 | _ = guest(cleanup, `sudo -S -p '' /bin/rm -rf `+remote+passwordInput).Run() |
| 95 | }() |
| 96 | archiveArgs := []string{"--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", local, "native-components.json"} |
| 97 | if tools { |
| 98 | archiveArgs = append(archiveArgs, "-C", cache, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "cli") |
| 99 | } |
| 100 | archive := exec.CommandContext(ctx, "/usr/bin/tar", archiveArgs...) |
| 101 | archive.Env = append(os.Environ(), "COPYFILE_DISABLE=1") |
| 102 | var archiveErrors bytes.Buffer |
| 103 | archive.Stderr = &archiveErrors |
| 104 | pipe, err := archive.StdoutPipe() |
| 105 | if err != nil { |
| 106 | return err |
| 107 | } |
| 108 | receiver := guest(ctx, `umask 077; cd `+remote+`; /usr/bin/tar -xf -`) |
| 109 | receiver.Stdin = pipe |
| 110 | if err = archive.Start(); err != nil { |
| 111 | return err |
| 112 | } |
| 113 | receiveErr := receiver.Run() |
| 114 | pipe.Close() |
| 115 | archiveErr := archive.Wait() |
| 116 | if archiveErrors.Len() > 0 { |
| 117 | _, _ = stderr.Write(archiveErrors.Bytes()) |
| 118 | } |
| 119 | if err = errors.Join(receiveErr, archiveErr); err != nil { |
| 120 | return fmt.Errorf("传递原生组件失败:%w", err) |
| 121 | } |
| 122 | takeOwnership := guest(ctx, `sudo -S -p '' /usr/sbin/chown -R root:wheel `+remote+passwordInput) |
| 123 | if err = takeOwnership.Run(); err != nil { |
| 124 | return errors.New("无法取得已绑定客机的组件维护权限") |
| 125 | } |
| 126 | script := shellescape.QuoteCommand([]string{"/bin/bash", remote + "/maintain-macos-workbench.sh", remote, binding.User, mode}) |
| 127 | command := guest(ctx, `sudo -S -p '' `+script+passwordInput) |
| 128 | command.Stdout = stdout |
| 129 | if err = command.Run(); err != nil { |
| 130 | return fmt.Errorf("原生组件维护未完成,原系统和账户已保留,可重试更新:%w", err) |
| 131 | } |
| 132 | return nil |
| 133 | } |
| 134 | |
| 135 | func WriteNativeComponentManifest(filename string, manifest NativeComponentManifest) error { |
| 136 | if err := manifest.Validate(); err != nil { |
| 137 | return err |
| 138 | } |
| 139 | data, err := json.Marshal(manifest) |
| 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| 143 | file, err := os.CreateTemp(filepath.Dir(filename), ".native-components-*.json") |
| 144 | if err != nil { |
| 145 | return err |
| 146 | } |
| 147 | defer os.Remove(file.Name()) |
| 148 | _, writeErr := file.Write(append(bytes.TrimSpace(data), '\n')) |
| 149 | err = errors.Join(writeErr, file.Sync(), file.Close()) |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | return os.Rename(file.Name(), filename) |
| 154 | } |