Files
Reims-Go/internal/installer/installer.go
T

432 lines
13 KiB
Go

// Package installer downloads and manages macOS installers through reims-util,
// the way reims-ctl does, so a download started here and one started by
// reims-ctl share files, resume each other and never write at the same time.
//
// Upstream facts (steelbrain/reims-vgpu 3731afd, crates/reims-ctl/src/):
// - reims-util runs with --json; stdout is one JSON event per line, ending in
// done or error (reims_util.rs:7-8, 423-509).
// - Installers live in the data directory's "installers", shared by every VM
// (reims_util.rs:29-32, paths.rs:79-81).
// - A stopped download is continued by the next run of the same command
// (reims_util.rs:30-31; `reims-util --help`: "Downloads resume").
// - Only one reims-util writes there at a time: reims-ctl holds an exclusive
// lock on "installers/.lock" while it runs (reims_util.rs:571-593).
// - On Windows reims-ctl points reims-util's XDG_CACHE_HOME at its own cache
// root (reims_util.rs:558-569); BuildChildEnv already sets it.
// - `reims-ctl downloads delete NAME --yes` refuses a file a VM boots from or
// one being downloaded (downloads.rs:108-123, cli.rs:391-454).
package installer
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// Client runs reims-util (and reims-ctl, for deletes) from one runtime.
type Client struct {
Util string // reims-util binary
Ctl string // reims-ctl binary
Env []string // child environment (XDG_* on the data root)
InstallersDir string
// LockPoll is how often a waiting download retries the lock.
LockPoll time.Duration
}
// NewClient builds a client for the active runtime and data root.
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
return &Client{
Util: installed.ReimsUtilPath(),
Ctl: installed.ReimsCtlPath(),
Env: rt.BuildChildEnv(cfg, installed),
InstallersDir: Dir(cfg),
LockPoll: time.Second,
}
}
// Dir is reims-ctl's installers directory under reims-go's data root:
// XDG_DATA_HOME/reims-ctl/installers (paths.rs:68-81).
func Dir(cfg *config.Config) string {
return filepath.Join(cfg.XDGDataDir(), "reims-ctl", "installers")
}
// Release is one offline installer Apple offers, as
// `reims-util --json offline-installer list` reports it (measured 2026-11-28
// with reims-util 0.1.0 from runtime 3731afd).
type Release struct {
Product string `json:"product"`
Title string `json:"title"` // "macOS Tahoe"
Version string `json:"version"` // "26.7.3"
Build string `json:"build"` // "25G342"
Posted string `json:"posted"` // "2026-11-16"
Size int64 `json:"size"` // bytes of Apple's InstallAssistant.pkg
}
// Result is what a finished offline download made.
type Result struct {
Image string `json:"image"`
Version string `json:"version"`
Build string `json:"build,omitempty"`
}
// offlineResult is the done event's result for offline-installer
// (reims_util.rs:233-242, 266-271).
type offlineResult struct {
Image string `json:"image"`
Installer struct {
Version string `json:"version"`
Build string `json:"build"`
} `json:"installer"`
}
// onlineResult is the done event's result for online-installer
// (reims_util.rs:228-231, 273-277).
type onlineResult struct {
Title string `json:"title"`
Image string `json:"image"`
}
// ErrUtilFailed wraps a reims-util run that ended without a done event.
var ErrUtilFailed = errors.New("reims-util failed")
// run starts reims-util with --json and args, reports steps, progress and notes
// to onUpdate, and returns the done event's result. Cancelling ctx kills it; a
// download left part way resumes on the next run.
func (c *Client) run(ctx context.Context, onUpdate func(Update), args ...string) (json.RawMessage, error) {
if onUpdate == nil {
onUpdate = func(Update) {}
}
cmd := exec.CommandContext(ctx, c.Util, append([]string{"--json"}, args...)...)
configureCmd(cmd)
cmd.Env = c.Env
cmd.Stdin = nil
var stderr bytes.Buffer
cmd.Stderr = &stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("run %s: %w", c.Util, err)
}
var (
step string
result json.RawMessage
failed string
)
sc := bufio.NewScanner(stdout)
sc.Buffer(make([]byte, 64*1024), 16*1024*1024) // a list result is one long line
for sc.Scan() {
var ev event
if json.Unmarshal(sc.Bytes(), &ev) != nil {
continue // reims-ctl skips non-JSON lines too (reims_util.rs:469-471)
}
switch ev.Event {
case "step":
step = lowerFirst(ev.Message)
onUpdate(Update{Kind: KindStep, Message: step, Step: step, Percent: -1})
case "note":
onUpdate(Update{Kind: KindNote, Message: ev.Message, Step: step, Percent: -1})
case "progress":
var total int64
if ev.Total != nil {
total = *ev.Total
}
onUpdate(Update{Kind: KindProgress, Step: step, Done: ev.Done, Total: total, Percent: percentOf(ev.Done, total)})
case "done":
result = ev.Result
case "error":
failed = ev.Message
}
}
waitErr := cmd.Wait()
if ctx.Err() != nil {
return nil, ctx.Err()
}
switch {
case failed != "":
return nil, errors.New(failed)
case result != nil && waitErr == nil:
return result, nil
case waitErr != nil:
return nil, fmt.Errorf("%w (%v): %s", ErrUtilFailed, waitErr, strings.TrimSpace(stderr.String()))
default:
return nil, fmt.Errorf("%w: no result", ErrUtilFailed)
}
}
// ListOffline lists the offline installers Apple offers, newest first. It
// reads Apple's catalog, so it needs the network.
func (c *Client) ListOffline(ctx context.Context, onUpdate func(Update)) ([]Release, error) {
raw, err := c.run(ctx, onUpdate, "offline-installer", "list")
if err != nil {
return nil, err
}
var list []Release
if err := json.Unmarshal(raw, &list); err != nil {
return nil, fmt.Errorf("read reims-util's list: %w", err)
}
return list, nil
}
// DownloadOffline makes the offline installer for version (a release such as
// "26.7.1", a build, a name such as "tahoe", or "latest") in the installers
// directory: it downloads it, continues a stopped download, or checks one
// already there. It waits for any other download holding the directory's lock.
func (c *Client) DownloadOffline(ctx context.Context, version string, onUpdate func(Update)) (*Result, error) {
v := strings.TrimSpace(version)
if v == "" || strings.EqualFold(v, "list") {
return nil, errors.New("give the macOS release to download, such as 26.7.1, tahoe or latest")
}
if onUpdate == nil {
onUpdate = func(Update) {}
}
if err := os.MkdirAll(c.InstallersDir, 0o755); err != nil {
return nil, err
}
unlock, err := c.lock(ctx, onUpdate)
if err != nil {
return nil, err
}
defer unlock()
raw, err := c.run(ctx, onUpdate, "offline-installer", v, "-o", c.InstallersDir)
if err != nil {
return nil, err
}
var r offlineResult
if err := json.Unmarshal(raw, &r); err != nil {
return nil, fmt.Errorf("read reims-util's result: %w", err)
}
return &Result{Image: r.Image, Version: r.Installer.Version, Build: r.Installer.Build}, nil
}
// DownloadOnline downloads Apple's ~1 GB online recovery image (BaseSystem.dmg)
// via `reims-util online-installer <version> -o <InstallersDir>` (upstream
// 3731afd reims_util.rs:246-278), resuming or reusing an existing download.
func (c *Client) DownloadOnline(ctx context.Context, version string, onUpdate func(Update)) (*Result, error) {
v := strings.TrimSpace(version)
if v == "" {
v = "latest"
}
if strings.EqualFold(v, "list") {
return nil, errors.New("give the macOS release to download, such as tahoe, 26 or latest")
}
if onUpdate == nil {
onUpdate = func(Update) {}
}
if err := os.MkdirAll(c.InstallersDir, 0o755); err != nil {
return nil, err
}
unlock, err := c.lock(ctx, onUpdate)
if err != nil {
return nil, err
}
defer unlock()
raw, err := c.run(ctx, onUpdate, "online-installer", v, "-o", c.InstallersDir)
if err != nil {
return nil, err
}
var r onlineResult
if err := json.Unmarshal(raw, &r); err != nil {
return nil, fmt.Errorf("read reims-util's result: %w", err)
}
parts := strings.Fields(r.Title)
ver := ""
if len(parts) > 0 {
ver = parts[len(parts)-1]
}
return &Result{Image: r.Image, Version: ver}, nil
}
// WaitingNote is reported once while another download holds the installers
// directory lock.
const WaitingNote = "waiting for another download of a macOS installer to end"
const waitingNote = WaitingNote
func (c *Client) lock(ctx context.Context, onUpdate func(Update)) (func(), error) {
path := filepath.Join(c.InstallersDir, ".lock")
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, err
}
poll := c.LockPoll
if poll <= 0 {
poll = time.Second
}
said := false
for {
ok, err := tryLock(f)
if err != nil {
f.Close()
return nil, fmt.Errorf("lock %s: %w", path, err)
}
if ok {
return func() { unlock(f); f.Close() }, nil
}
if !said {
// Same wording as reims-ctl (reims_util.rs:587).
onUpdate(Update{Kind: KindNote, Message: waitingNote, Percent: -1})
said = true
}
select {
case <-ctx.Done():
f.Close()
return nil, ctx.Err()
case <-time.After(poll):
}
}
}
// Busy reports whether a download (here or in reims-ctl) holds the installers
// directory right now.
func (c *Client) Busy() bool {
f, err := os.OpenFile(filepath.Join(c.InstallersDir, ".lock"), os.O_RDWR, 0)
if err != nil {
return false
}
defer f.Close()
ok, err := tryLock(f)
if err != nil || !ok {
return err == nil
}
unlock(f)
return false
}
// Cached is a file kept in the installers directory.
type Cached struct {
Name string `json:"name"`
Path string `json:"path"`
Bytes int64 `json:"bytes"`
Kind string `json:"kind"` // offline | online | ipsw | other
Partial bool `json:"partial"`
Title string `json:"title,omitempty"` // "macOS Tahoe"
Version string `json:"version,omitempty"` // "26.6.2"
Build string `json:"build,omitempty"` // "25G83"
}
// ListCached lists the files kept for new VMs, by name, skipping hidden files
// such as the lock (downloads.rs:43-70).
func (c *Client) ListCached() ([]Cached, error) {
entries, err := os.ReadDir(c.InstallersDir)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []Cached
for _, e := range entries {
name := e.Name()
if strings.HasPrefix(name, ".") || !e.Type().IsRegular() {
continue
}
info, err := e.Info()
if err != nil {
continue
}
item := Describe(name)
item.Path = filepath.Join(c.InstallersDir, name)
item.Bytes = info.Size()
out = append(out, item)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out, nil
}
// Describe says what a kept file is from its name, as reims-ctl does
// (downloads.rs:72-97):
//
// macOS-Tahoe-26.6.2-25G83-offline-installer.img
// macOS-Tahoe-online-installer.dmg
// UniversalMac_27.2.1_26B131_Restore.ipsw
//
// with ".part" for a download that stopped part way.
func Describe(name string) Cached {
c := Cached{Name: name, Kind: "other"}
base := name
if b, ok := strings.CutSuffix(name, ".part"); ok {
c.Partial = true
base = b
}
if n, ok := strings.CutPrefix(base, "macOS-"); ok {
if n, ok := strings.CutSuffix(n, "-offline-installer.img"); ok {
parts := strings.Split(n, "-")
if len(parts) >= 3 {
c.Kind = "offline"
c.Build = parts[len(parts)-1]
c.Version = parts[len(parts)-2]
c.Title = "macOS " + strings.Join(parts[:len(parts)-2], " ")
}
return c
}
if n, ok := strings.CutSuffix(n, "-online-installer.dmg"); ok {
c.Kind = "online"
c.Title = "macOS " + strings.ReplaceAll(n, "-", " ")
return c
}
}
if strings.HasPrefix(base, "UniversalMac_") && strings.HasSuffix(base, "_Restore.ipsw") {
parts := strings.Split(base, "_")
if len(parts) == 4 {
c.Kind = "ipsw"
c.Version = parts[1]
c.Build = parts[2]
c.Title = "macOS"
}
}
return c
}
// DeleteCached deletes a kept file through reims-ctl, which refuses one a VM
// boots from or one being downloaded (downloads.rs:108-123).
func (c *Client) DeleteCached(ctx context.Context, name string, stdout io.Writer) error {
if name == "" || strings.ContainsAny(name, `/\`) || name == "." || name == ".." {
return fmt.Errorf("not a download name: %q", name)
}
cmd := exec.CommandContext(ctx, c.Ctl, "downloads", "delete", name, "--yes")
configureCmd(cmd)
cmd.Env = c.Env
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
if err := cmd.Run(); err != nil {
msg := strings.TrimSpace(errBuf.String())
if msg == "" {
msg = strings.TrimSpace(out.String())
}
msg = strings.TrimPrefix(msg, "Error: ")
return fmt.Errorf("%s", firstNonEmpty(msg, err.Error()))
}
if stdout != nil {
io.Copy(stdout, &out)
}
return nil
}
func firstNonEmpty(s ...string) string {
for _, v := range s {
if v != "" {
return v
}
}
return ""
}