Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ missing) seeds a new device from its `device.plist` in its own goroutine
(`seedNew`), since a `simctl list` on a loaded host takes longer than a script
waits between `simctl create` and boot. A boot that starts first is logged and
caught by the no-reboot slim at boot, which stays as the read-back and fallback.
Each boot's after-boot pass has its own cancel (`slimPass`), called when the
device shuts down or is deleted, so a pass never retries into the next boot; a
superseded pass reports `stopped`, never `slimmed`. `WatchWithEvents` emits
`WatchEvent`s, which `watch --json` prints one per line as a stable contract.

**Live enable/disable.** `live.go` holds `EnableServices`/`DisableServices`
(`simslim enable`/`disable`), which act on a booted simulator only and keep no
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,22 @@ It takes the same `--profile`/`--except`/`--keep` selection as `on`, and scans
the default and `testing` sets plus any passed with `--set`. Point `--set` at a
custom parallel-testing device set if your Xcode uses one. It runs until Ctrl-C.

A wrapper that turns services on per run with `simslim enable` should wait for
watch to finish with the boot first, or watch may switch them off again.
`simslim watch --json` prints one JSON object per line on stdout, a stable
interface unlike the log lines:

```json
{"event":"slimmed","udid":"…","set":"default"}
```

`event` is `slimming` (a boot's pass started), `slimmed` (it finished; watch
leaves the device alone until it shuts down), `failed` (with `error`; the next
scan retries), `stopped` (the device shut down mid-pass, so the pass was
cancelled), or `slimmed_before_boot` (with `services`, the disables written into
a shut-down device's store). Boot the device, wait for its `slimmed` (or
`failed`), then call `enable`.

## Disk cleanup

Disk cleanup is permanent and separate from service slimming. `disk-plan` is
Expand Down
1 change: 1 addition & 0 deletions cmd/simslim/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ func newApp() *cli.Command {
&cli.StringFlag{Name: "save", Usage: "also remove the services from this profile file, creating it if needed"},
}, Action: cmdDisable},
{Name: "watch", Flags: []cli.Flag{
&cli.BoolFlag{Name: "json", Usage: "print one JSON object per event on stdout (slimming, slimmed, failed, stopped, slimmed_before_boot) instead of log lines"},
&cli.StringFlag{Name: "profile", Usage: "apply a JSON profile file (mutually exclusive with --except/--keep)"},
&cli.StringFlag{Name: "except", Usage: "comma-separated category IDs to leave fully enabled (see `simslim profiles`)"},
&cli.StringFlag{Name: "keep", Usage: "comma-separated launchd labels to keep running"},
Expand Down
14 changes: 14 additions & 0 deletions cmd/simslim/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"runtime"
"sort"
"strings"
"sync"

"github.com/mattn/go-isatty"
"github.com/mobai-app/simslim"
Expand Down Expand Up @@ -843,6 +844,16 @@ func cmdWatch(ctx context.Context, cmd *cli.Command) error {
if err != nil {
return err
}
if cmd.Bool("json") {
var mu sync.Mutex
encoder := json.NewEncoder(os.Stdout)
events := func(e simslim.WatchEvent) {
mu.Lock()
defer mu.Unlock()
_ = encoder.Encode(e)
}
return simslim.WatchWithEvents(ctx, p, cmd.Duration("interval"), nil, events)
}
report := simslim.Reporter(func(msg string) { fmt.Fprintln(os.Stderr, msg) })
sets := append([]string{"default", "testing"}, simslim.ExtraDeviceSetTokens()...)
fmt.Fprintf(os.Stderr, "Watching device sets [%s]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n", strings.Join(sets, ", "))
Expand Down Expand Up @@ -1111,6 +1122,9 @@ COMMANDS
--except ids Leave these categories enabled (comma-separated)
--keep labels Keep these individual daemons running (comma-separated)
--interval dur How often to rescan for booting simulators (default 3s)
--json One JSON object per event on stdout, a stable interface
for wrappers: wait for "slimmed" after a boot before
enabling services on it
status <udid> Report how slim a booted simulator is
--dropped Also list the disabled daemons grouped by category
verify <udid> Check that a booted simulator's disable overrides still
Expand Down
127 changes: 99 additions & 28 deletions watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,40 @@ type preslimStrategy func(d Device, p Profile) (int, error)
// each booted device in its own goroutine so one slow reconfigure does not delay
// catching the next clone, and returns once those goroutines are done.
func Watch(ctx context.Context, p Profile, interval time.Duration, report Reporter) error {
return watch(ctx, p, interval, report, EnableSlimNoReboot)
return WatchWithEvents(ctx, p, interval, report, nil)
}

func watch(ctx context.Context, p Profile, interval time.Duration, report Reporter, slim slimStrategy) error {
// The WatchEvent kinds. A wrapper that boots a device and then changes its
// services waits for WatchSlimmed (or WatchFailed): after it, the watcher does
// not touch that device again until the device shuts down.
const (
WatchSlimming = "slimming" // an after-boot pass started
WatchSlimmed = "slimmed" // the pass for the current boot finished
WatchFailed = "failed" // the pass failed; the next scan retries it
WatchStopped = "stopped" // the device shut down, so its pass was cancelled
WatchSlimmedBeforeBoot = "slimmed_before_boot" // disables were written into a shut-down device's store
)

// WatchEvent is the stable, machine-readable form of a watcher log line.
type WatchEvent struct {
Event string `json:"event"`
UDID string `json:"udid"`
Set string `json:"set"`
Services int `json:"services,omitempty"` // disables written, for slimmed_before_boot
Error string `json:"error,omitempty"` // for failed
}

// WatchWithEvents is Watch that also hands every WatchEvent to events, which
// may be called from several goroutines at once. A nil events behaves as Watch.
func WatchWithEvents(ctx context.Context, p Profile, interval time.Duration, report Reporter, events func(WatchEvent)) error {
return watch(ctx, p, interval, report, events, EnableSlimNoReboot)
}

func watch(ctx context.Context, p Profile, interval time.Duration, report Reporter, events func(WatchEvent), slim slimStrategy) error {
if interval <= 0 {
interval = DefaultWatchInterval
}
w := &watcher{p: p, report: report, slim: slim, preslim: preslimDevice, seen: map[string]bool{}, seeded: map[string]bool{}}
w := &watcher{p: p, report: report, events: events, slim: slim, preslim: preslimDevice, passes: map[string]*slimPass{}, seeded: map[string]bool{}}
// The CLI exits right after this returns, but an importer keeps running, so
// no slim may outlive the call. A cancelled ctx aborts an in-flight slim
// inside its next simctl call, which keeps the wait short.
Expand Down Expand Up @@ -204,20 +230,34 @@ func (w *watcher) seedNew(ctx context.Context, dir deviceDir) {
w.seed(d)
}

// watcher holds the UDIDs already slimmed or in flight, and in seeded the
// shut-down UDIDs whose store already holds the profile. The scan loop, the
// slim goroutines and the seed goroutines all touch them, so mu guards both.
// watcher holds in passes the booted UDIDs already slimmed or in flight, and in
// seeded the shut-down UDIDs whose store already holds the profile. The scan
// loop, the slim goroutines and the seed goroutines all touch them, so mu
// guards both.
type watcher struct {
p Profile
report Reporter
events func(WatchEvent)
slim slimStrategy
preslim preslimStrategy
wg sync.WaitGroup
mu sync.Mutex
seen map[string]bool
passes map[string]*slimPass
seeded map[string]bool
}

// slimPass is one boot's after-boot slim. Its cancel stops it once that boot
// ends, so it cannot keep retrying into the device's next boot.
type slimPass struct {
cancel context.CancelFunc
}

func (w *watcher) emit(e WatchEvent) {
if w.events != nil {
w.events(e)
}
}

func (w *watcher) scan(ctx context.Context) {
devices, err := ListDevices(ctx)
if err != nil {
Expand All @@ -240,22 +280,18 @@ func (w *watcher) scan(ctx context.Context) {
w.mu.Lock()
delete(w.seeded, d.UDID)
w.mu.Unlock()
if !w.claim(d.UDID) {
pctx, pass := w.claim(ctx, d.UDID)
if pass == nil {
continue
}
w.wg.Add(1)
go func(d Device) {
defer w.wg.Done()
defer pass.cancel()
w.report.report(fmt.Sprintf("watch: slimming %s (set %s)", d.UDID, d.Set))
if _, err := w.slim(ctx, d.Set, d.UDID, w.p, prefixed(w.report, d.UDID)); err != nil {
w.report.report(fmt.Sprintf("watch: %s: %v", d.UDID, err))
// A transient launchctl failure would otherwise leave this clone
// stock for the whole test run. The next scan retries it, and a
// torn-down clone drops out of simctl list, so this does not loop.
w.forget(d.UDID)
return
}
w.report.report(fmt.Sprintf("watch: slimmed %s", d.UDID))
w.emit(WatchEvent{Event: WatchSlimming, UDID: d.UDID, Set: d.Set})
_, err := w.slim(pctx, d.Set, d.UDID, w.p, prefixed(w.report, d.UDID))
w.finish(d, pass, err)
}(d)
}
}
Expand All @@ -267,6 +303,10 @@ func (w *watcher) seed(d Device) {
if w.preslim == nil {
return
}
// A device caught Shutting Down or Booting is seeded once it reads Shutdown.
if d.State != "Shutdown" {
return
}
w.mu.Lock()
defer w.mu.Unlock() // serializes the store writes of seedNew and scan
if w.seeded[d.UDID] {
Expand All @@ -288,22 +328,47 @@ func (w *watcher) seed(d Device) {
return
}
w.report.report(fmt.Sprintf("watch: slimmed %s before boot (%d services disabled, set %s)", d.UDID, n, d.Set))
w.emit(WatchEvent{Event: WatchSlimmedBeforeBoot, UDID: d.UDID, Set: d.Set, Services: n})
}

// finish reports a pass's outcome. It holds mu so a superseded pass, whose boot
// ended, can never announce slimmed after a newer boot's pass has started.
func (w *watcher) finish(d Device, pass *slimPass, err error) {
w.mu.Lock()
defer w.mu.Unlock()
switch {
case w.passes[d.UDID] != pass:
w.report.report(fmt.Sprintf("watch: %s shut down; stopped its slim", d.UDID))
w.emit(WatchEvent{Event: WatchStopped, UDID: d.UDID, Set: d.Set})
case err != nil:
// A transient launchctl failure would otherwise leave this clone stock
// for the whole test run. The next scan retries it, and a torn-down
// clone drops out of simctl list, so this does not loop.
delete(w.passes, d.UDID)
w.report.report(fmt.Sprintf("watch: %s: %v", d.UDID, err))
w.emit(WatchEvent{Event: WatchFailed, UDID: d.UDID, Set: d.Set, Error: err.Error()})
default:
w.report.report(fmt.Sprintf("watch: slimmed %s", d.UDID))
w.emit(WatchEvent{Event: WatchSlimmed, UDID: d.UDID, Set: d.Set})
}
}

// claim reserves a UDID for this scan, reporting false when it is already
// slimmed or in flight.
func (w *watcher) claim(udid string) bool {
// claim starts a pass for a booted UDID, returning a nil pass when one is
// already done or in flight for this boot.
func (w *watcher) claim(ctx context.Context, udid string) (context.Context, *slimPass) {
w.mu.Lock()
defer w.mu.Unlock()
if w.seen[udid] {
return false
if w.passes[udid] != nil {
return nil, nil
}
w.seen[udid] = true
return true
pctx, cancel := context.WithCancel(ctx)
pass := &slimPass{cancel: cancel}
w.passes[udid] = pass
return pctx, pass
}

// prune drops the UDIDs of deleted devices, such as finished parallel-testing
// clones, so seen and seeded do not grow by one entry per clone. A device
// clones, so passes and seeded do not grow by one entry per clone. A device
// created after the listing started is only seeded again, which is a no-op.
func (w *watcher) prune(devices []Device) {
listed := make(map[string]bool, len(devices))
Expand All @@ -312,9 +377,10 @@ func (w *watcher) prune(devices []Device) {
}
w.mu.Lock()
defer w.mu.Unlock()
for udid := range w.seen {
for udid, pass := range w.passes {
if !listed[udid] {
delete(w.seen, udid)
pass.cancel()
delete(w.passes, udid)
}
}
for udid := range w.seeded {
Expand All @@ -324,9 +390,14 @@ func (w *watcher) prune(devices []Device) {
}
}

// forget ends a device's boot: its pass, if still running, is cancelled, and
// its next boot gets a pass of its own.
func (w *watcher) forget(udid string) {
w.mu.Lock()
delete(w.seen, udid)
if pass := w.passes[udid]; pass != nil {
pass.cancel()
delete(w.passes, udid)
}
w.mu.Unlock()
}

Expand Down
Loading
Loading