| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "errors" |
| 7 | "flag" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | "path/filepath" |
| 14 | "slices" |
| 15 | "sort" |
| 16 | "strconv" |
| 17 | "strings" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/equipo" |
| 21 | "amadan.net/oficina/equipo/internal/release" |
| 22 | "amadan.net/oficina/equipo/internal/runner" |
| 23 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 24 | runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| 25 | "amadan.net/rastrillo/rastrillo" |
| 26 | ) |
| 27 | |
| 28 | // macInstallHost is what installing on a Mac touches; tests stand in. |
| 29 | type macInstallHost struct { |
| 30 | goos, goarch, users, self string |
| 31 | exec mac.Exec |
| 32 | exposed func(string) bool |
| 33 | // tools are what srt needs on macOS (mac.SRTTools: Node first, then |
| 34 | // ripgrep), fetched with fetch and checked against their pins; npmCI |
| 35 | // installs the pinned srt into prefix with the npm beside Node. |
| 36 | tools []mac.Tool |
| 37 | fetch func(ctx context.Context, url string, limit int64) ([]byte, error) |
| 38 | npmCI func(ctx context.Context, npm, prefix, home string) error |
| 39 | // verify checks what was installed under lib against the pins |
| 40 | // compiled into this binary (mac.VerifyTools). |
| 41 | scannerPin string |
| 42 | verify func(lib string) error |
| 43 | enrol func(ctx context.Context, cfg runner.Config, out io.Writer) error |
| 44 | // launchctl runs launchctl; firstLaunch runs xcodebuild -runFirstLaunch |
| 45 | // as the user whose home is home. |
| 46 | launchctl func(ctx context.Context, args ...string) error |
| 47 | // stopWait bounds the wait for a runner to stop (a minute). |
| 48 | stopWait time.Duration |
| 49 | firstLaunch func(ctx context.Context, home string) |
| 50 | // chdir moves the installer into the user's home before it runs |
| 51 | // anything there (os.Chdir). |
| 52 | chdir func(dir string) error |
| 53 | } |
| 54 | |
| 55 | // userEnv is environ for a program run as the user whose home is home and |
| 56 | // name is name: under su or sudo, HOME, USER and LOGNAME can be the |
| 57 | // caller's, and npm or xcodebuild would write into the caller's home. |
| 58 | func userEnv(environ []string, home, name string, extra ...string) []string { |
| 59 | var env []string |
| 60 | for _, kv := range environ { |
| 61 | k, _, _ := strings.Cut(kv, "=") |
| 62 | switch k { |
| 63 | case "HOME", "USER", "LOGNAME": |
| 64 | continue |
| 65 | } |
| 66 | if !slices.ContainsFunc(extra, func(e string) bool { return strings.HasPrefix(e, k+"=") }) { |
| 67 | env = append(env, kv) |
| 68 | } |
| 69 | } |
| 70 | return append(append(env, "HOME="+home, "USER="+name, "LOGNAME="+name), extra...) |
| 71 | } |
| 72 | |
| 73 | // Every program the installer runs is given its own working directory: |
| 74 | // started from a folder this user cannot read (su without a dash), npm |
| 75 | // and xcodebuild fail on the inherited one (2026-11-28). |
| 76 | |
| 77 | // systemCommand runs a system tool (id, dscl, scutil, launchctl) from /. |
| 78 | func systemCommand(ctx context.Context, name string, args ...string) *exec.Cmd { |
| 79 | cmd := exec.CommandContext(ctx, name, args...) |
| 80 | cmd.Dir = "/" |
| 81 | return cmd |
| 82 | } |
| 83 | |
| 84 | // npmCICommand installs the pinned srt into prefix, run there, as the |
| 85 | // user whose home is home. |
| 86 | func npmCICommand(ctx context.Context, npm, prefix, home string) *exec.Cmd { |
| 87 | cmd := exec.CommandContext(ctx, npm, "ci", "--prefix", prefix, "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund") |
| 88 | cmd.Dir = prefix |
| 89 | cmd.Env = userEnv(os.Environ(), home, filepath.Base(home), "PATH="+filepath.Dir(npm)+":/usr/bin:/bin") |
| 90 | return cmd |
| 91 | } |
| 92 | |
| 93 | // firstLaunchCommand is xcodebuild -runFirstLaunch, run in home as the |
| 94 | // user whose home it is. |
| 95 | func firstLaunchCommand(ctx context.Context, home string) *exec.Cmd { |
| 96 | cmd := exec.CommandContext(ctx, "/usr/bin/xcodebuild", "-runFirstLaunch") |
| 97 | cmd.Dir = home |
| 98 | cmd.Env = userEnv(os.Environ(), home, filepath.Base(home)) |
| 99 | return cmd |
| 100 | } |
| 101 | |
| 102 | func realMacInstallHost() macInstallHost { |
| 103 | self, _ := os.Executable() |
| 104 | return macInstallHost{goos: goos(), goarch: goarch(), users: "/Users", self: self, scannerPin: release.GitleaksSHA256(), exec: func(ctx context.Context, name string, args ...string) (string, error) { |
| 105 | out, err := systemCommand(ctx, name, args...).Output() |
| 106 | return string(out), err |
| 107 | }, exposed: mac.Exposed, tools: mac.SRTTools, fetch: fetchTool, |
| 108 | verify: func(lib string) error { return mac.VerifyTools(lib, mac.PinnedTools(lib)) }, |
| 109 | npmCI: func(ctx context.Context, npm, prefix, home string) error { |
| 110 | return npmCICommand(ctx, npm, prefix, home).Run() |
| 111 | }, |
| 112 | enrol: runner.Enrol, |
| 113 | launchctl: func(ctx context.Context, args ...string) error { |
| 114 | return systemCommand(ctx, "/bin/launchctl", args...).Run() |
| 115 | }, |
| 116 | firstLaunch: func(ctx context.Context, home string) { |
| 117 | c, cancel := context.WithTimeout(ctx, 10*time.Minute) |
| 118 | defer cancel() |
| 119 | _ = firstLaunchCommand(c, home).Run() |
| 120 | }, |
| 121 | chdir: os.Chdir, |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // installMac installs a Mac worker for the user running it (Mac runners |
| 126 | // spec §3.2): refuses root, administrators, users without equipo in their name |
| 127 | // and a readable foreign home; refuses, changing nothing, a user whose |
| 128 | // runner is enrolled with another Equipo; copies the verified runner into |
| 129 | // ~/.local/lib/equipo-runner; installs the pinned srt; writes the |
| 130 | // environment file; enrols (the link Paul taps); then loads the launchd |
| 131 | // agent, whose runner probes the Mac by itself. What a runner installed |
| 132 | // before ran on is kept aside until the enrolment is done, and put back |
| 133 | // and started again if anything stops the install before then. |
| 134 | func installMac(ctx context.Context, args []string, h macInstallHost, out, errout io.Writer) int { |
| 135 | say := func(key string, a ...any) { fmt.Fprintf(errout, equipo.RunnerSetupCopy(key)+"\n", a...) } |
| 136 | fail := func(key string, a ...any) int { say(key, a...); return 1 } |
| 137 | flags := flag.NewFlagSet("install", flag.ContinueOnError) |
| 138 | flags.SetOutput(io.Discard) |
| 139 | instance := flags.String("instance", "", "") |
| 140 | version := flags.String("release", "", "") |
| 141 | origin := flags.String("origin", "", "") |
| 142 | if flags.Parse(args) != nil || flags.NArg() != 0 || *instance == "" || *version != rastrillo.BuildVersion || !release.InstallOrigin(*origin) || !release.ValidInstallVersion(*version) { |
| 143 | return fail("runner.install.release") |
| 144 | } |
| 145 | if h.goos != "darwin" || h.goarch != "arm64" { |
| 146 | return fail("runner.mac.platform") |
| 147 | } |
| 148 | account, err := mac.ReadAccount(ctx, h.exec) |
| 149 | if err != nil { |
| 150 | return fail("runner.install.unavailable") |
| 151 | } |
| 152 | if key := mac.RefuseAccount(account); key != "" { |
| 153 | return fail(key) |
| 154 | } |
| 155 | // The user's own home, from the user directory: under su or sudo the |
| 156 | // environment's HOME can be the caller's. |
| 157 | home, err := mac.ReadHome(ctx, h.exec, account.Name) |
| 158 | if err != nil || filepath.Base(home) != account.Name { |
| 159 | return fail("runner.install.destination") |
| 160 | } |
| 161 | // The installer and everything it runs work from this home, never |
| 162 | // the folder it was started from (which this user may not read). |
| 163 | if h.chdir(home) != nil { |
| 164 | return fail("runner.install.destination") |
| 165 | } |
| 166 | others, err := mac.OtherHomes(h.users, home) |
| 167 | if err != nil { |
| 168 | return fail("runner.mac.homes_unknown") |
| 169 | } |
| 170 | if exposed := mac.ExposedHomes(others, h.exposed); len(exposed) > 0 { |
| 171 | return fail("runner.mac.home", strings.Join(exposed, " "), account.Name) |
| 172 | } |
| 173 | // The agent runs in the user's login session: without one (su or |
| 174 | // sudo -iu from another user's session, with this user logged out) |
| 175 | // there is nowhere to load it. |
| 176 | domain := "gui/" + strconv.Itoa(account.UID) |
| 177 | if h.launchctl(ctx, "print", domain) != nil { |
| 178 | return fail("runner.mac.not_logged_in", account.Name) |
| 179 | } |
| 180 | lib := filepath.Join(home, ".local", "lib", "equipo-runner") |
| 181 | share := filepath.Join(home, ".local", "share", "equipo-runner") |
| 182 | conf := filepath.Join(home, ".config", "equipo-runner") |
| 183 | logs := filepath.Join(home, "Library", "Logs", "equipo-runner") |
| 184 | agents := filepath.Join(home, "Library", "LaunchAgents") |
| 185 | // Paths are this user's, whichever Equipo it works for: a runner |
| 186 | // enrolled with another one is said so before anything is stopped or |
| 187 | // rewritten (the Studio's staging runner, 2026-11-28, was left down). |
| 188 | // One install at a time, from this check until it is enrolled or put |
| 189 | // back: a second one is refused, not let put back over the first. |
| 190 | lock, err := installLock(filepath.Join(share, "state")) |
| 191 | if err != nil { |
| 192 | return fail(lockKey(err)) |
| 193 | } |
| 194 | defer lock.Close() |
| 195 | if key, a := enrolledElsewhere(filepath.Join(share, "state"), *origin, *instance, "runner.mac.other_instance"); key != "" { |
| 196 | return fail(key, a...) |
| 197 | } |
| 198 | // A runner installed before is stopped first: nothing it uses is |
| 199 | // replaced under it, and its state lock is free for the enrolment |
| 200 | // check below (an existing, valid enrolment is kept as it is). If it |
| 201 | // does not stop, nothing at all is changed. |
| 202 | plist := filepath.Join(agents, mac.AgentLabel+".plist") |
| 203 | stopped, tookDown := stopRunner(ctx, h, domain+"/"+mac.AgentLabel, filepath.Join(share, "state")) |
| 204 | if !stopped { |
| 205 | if tookDown { |
| 206 | // Taken out of launchd but still holding its lock: launchd |
| 207 | // gets it back as it was, or the person is told it is not. |
| 208 | back, cancel := detached(ctx) |
| 209 | defer cancel() |
| 210 | if h.launchctl(back, "bootstrap", domain, plist) != nil { |
| 211 | say("runner.mac.still_running") |
| 212 | return fail("runner.mac.not_restored") |
| 213 | } |
| 214 | } |
| 215 | return fail("runner.mac.still_running") |
| 216 | } |
| 217 | binary := filepath.Join(lib, "equipo-runner") |
| 218 | scannerPath := filepath.Join(lib, "gitleaks") |
| 219 | envFile := filepath.Join(conf, "runner.env") |
| 220 | // From here until the enrolment is done, a failure puts back what the |
| 221 | // runner installed before ran on and starts it again if it was |
| 222 | // running. Its launchd agent is not touched before then. The context |
| 223 | // may be the one the person ended (Ctrl-C while waiting for the |
| 224 | // link): putting back still happens. |
| 225 | var backup *installBackup |
| 226 | abort := func(key string, a ...any) int { |
| 227 | if key != "" { |
| 228 | say(key, a...) |
| 229 | } |
| 230 | kept := backup != nil && backup.kept() |
| 231 | restored := backup == nil || backup.restore() |
| 232 | if restored && tookDown { |
| 233 | back, cancel := detached(ctx) |
| 234 | defer cancel() |
| 235 | restored = h.launchctl(back, "bootstrap", domain, plist) == nil |
| 236 | } |
| 237 | switch { |
| 238 | case !restored: |
| 239 | say("runner.mac.not_restored") |
| 240 | case tookDown || kept: |
| 241 | say("runner.mac.restored") |
| 242 | } |
| 243 | return 1 |
| 244 | } |
| 245 | for _, d := range []string{lib, filepath.Join(share, "state"), filepath.Join(share, "work"), filepath.Join(share, "scratch"), conf, logs} { |
| 246 | if err := os.MkdirAll(d, 0700); err != nil { |
| 247 | return abort("runner.install.destination") |
| 248 | } |
| 249 | } |
| 250 | if err := os.MkdirAll(agents, 0755); err != nil { |
| 251 | return abort("runner.install.destination") |
| 252 | } |
| 253 | backup, err = newInstallBackup(share) |
| 254 | if err != nil { |
| 255 | return abort("runner.install.destination") |
| 256 | } |
| 257 | // Run from the runner installed here (its own install command), the |
| 258 | // new copy comes from where that binary was moved aside. |
| 259 | source := h.self |
| 260 | fromInstalled := sameFile(h.self, binary) |
| 261 | if err := backup.keep(binary, scannerPath, filepath.Join(lib, "srt"), envFile); err != nil { |
| 262 | return abort("runner.install.destination") |
| 263 | } |
| 264 | if fromInstalled { |
| 265 | source = backup.asideOf(binary) |
| 266 | } |
| 267 | if err := copyPrivate(source, binary, 0700); err != nil { |
| 268 | return abort("runner.install.destination") |
| 269 | } |
| 270 | scanner, err := h.fetch(ctx, *origin+"/releases/"+*version+"/darwin-arm64/gitleaks", 128<<20) |
| 271 | if err != nil { |
| 272 | return abort("runner.install.release") |
| 273 | } |
| 274 | if h.scannerPin == "" || fmt.Sprintf("%x", sha256.Sum256(scanner)) != h.scannerPin { |
| 275 | return abort("runner.install.checksum") |
| 276 | } |
| 277 | if err := os.WriteFile(scannerPath, scanner, 0700); err != nil { |
| 278 | return abort("runner.install.destination") |
| 279 | } |
| 280 | if !release.VerifyGitleaks(scannerPath, h.scannerPin) { |
| 281 | return abort("runner.install.checksum") |
| 282 | } |
| 283 | values := map[string]string{"EQUIPO_ORIGIN": *origin, "EQUIPO_INSTANCE_ID": *instance, "EQUIPO_RUNNER_STATE_DIR": filepath.Join(share, "state"), "EQUIPO_WORKSPACE_ROOT": filepath.Join(share, "work"), "EQUIPO_SCRATCH_ROOT": filepath.Join(share, "scratch"), "EQUIPO_GIT_PATH": "/usr/bin/git"} |
| 284 | // srt and what it needs on macOS, all in the runner's own directory: |
| 285 | // a Standard user cannot install them with Homebrew. Each archive is |
| 286 | // checked against its pinned digest before it is unpacked. |
| 287 | fetched := map[string]string{} |
| 288 | for _, t := range h.tools { |
| 289 | path, err := mac.Fetch(ctx, t, filepath.Join(lib, "tools"), h.fetch) |
| 290 | if err != nil { |
| 291 | break |
| 292 | } |
| 293 | fetched[t.Name] = path |
| 294 | } |
| 295 | if fetched[mac.Node.Name] == "" || fetched[mac.Ripgrep.Name] == "" { |
| 296 | say("runner.mac.no_srt") |
| 297 | } else { |
| 298 | values["EQUIPO_NODE_PATH"], values["EQUIPO_RG_PATH"] = fetched[mac.Node.Name], fetched[mac.Ripgrep.Name] |
| 299 | prefix := filepath.Join(lib, "srt") |
| 300 | pkg, lock := mac.SRTPackage() |
| 301 | if os.MkdirAll(prefix, 0700) != nil || os.WriteFile(filepath.Join(prefix, "package.json"), pkg, 0600) != nil || os.WriteFile(filepath.Join(prefix, "package-lock.json"), lock, 0600) != nil { |
| 302 | return abort("runner.install.destination") |
| 303 | } |
| 304 | if err := h.npmCI(ctx, filepath.Join(filepath.Dir(fetched[mac.Node.Name]), "npm"), prefix, home); err != nil || h.verify(lib) != nil { |
| 305 | // Not installed, or not exactly the pinned srt, Node and |
| 306 | // ripgrep: the runner would never trust them anyway. |
| 307 | say("runner.mac.no_srt") |
| 308 | } else { |
| 309 | values["EQUIPO_SRT_PATH"] = filepath.Join(prefix, "node_modules", ".bin", "srt") |
| 310 | } |
| 311 | } |
| 312 | h.firstLaunch(ctx, home) |
| 313 | label := mac.ComputerName(ctx, h.exec) |
| 314 | if label == "" || len(label) > 80 || strings.ContainsAny(label, "\r\n\x00") { |
| 315 | label = "Mac" |
| 316 | } |
| 317 | values["EQUIPO_MACHINE_LABEL"] = label |
| 318 | if err := writeEnvFile(envFile, values); err != nil { |
| 319 | return abort("runner.install.config") |
| 320 | } |
| 321 | cfg := runner.Config{Origin: *origin, InstanceID: *instance, StateDir: values["EQUIPO_RUNNER_STATE_DIR"], WorkspaceRoot: values["EQUIPO_WORKSPACE_ROOT"], ScratchRoot: values["EQUIPO_SCRATCH_ROOT"], GitPath: values["EQUIPO_GIT_PATH"], MachineLabel: label, Executable: binary, WorkerOnly: true} |
| 322 | // The line to open the link comes right before the link, and only |
| 323 | // when there is one: a valid enrolment is kept and said so instead. |
| 324 | report := macEnrolReport(errout, filepath.Join(logs, "install.log")) |
| 325 | cfg.EnrolNotify = report.notify |
| 326 | // An error after the credential was published (its directory sync) |
| 327 | // is still an enrolment: what was kept aside is not put back beside it. |
| 328 | before := credentialBefore(cfg.StateDir) |
| 329 | if err := h.enrol(ctx, cfg, out); err != nil { |
| 330 | enrolled, unknown := enrolOutcome(cfg.StateDir, *origin, *instance, before) |
| 331 | switch { |
| 332 | case unknown: |
| 333 | // Whether it was published cannot be read: nothing is put back |
| 334 | // beside what may be a new credential, and what was kept aside |
| 335 | // stays where it is. |
| 336 | report.failed(err) |
| 337 | return fail("runner.mac.not_restored") |
| 338 | case enrolled: |
| 339 | case errors.Is(err, runner.ErrEnrolledAsPrimary): |
| 340 | return abort("runner.needs_primary") |
| 341 | default: |
| 342 | report.failed(err) |
| 343 | return abort("") |
| 344 | } |
| 345 | } |
| 346 | // Enrolled: the state now holds the credential this configuration |
| 347 | // goes with, so the earlier one is not put back any more. |
| 348 | backup.drop() |
| 349 | if err := os.WriteFile(plist, mac.LaunchAgent(binary, envFile, logs), 0644); err != nil { |
| 350 | return fail("runner.install.service") |
| 351 | } |
| 352 | if err := h.launchctl(ctx, "bootstrap", domain, plist); err != nil { |
| 353 | return fail("runner.install.service") |
| 354 | } |
| 355 | say("runner.mac.installed") |
| 356 | return 0 |
| 357 | } |
| 358 | |
| 359 | // fetchTool downloads a pinned tool archive over HTTPS, following |
| 360 | // redirects (GitHub's release downloads redirect to its object store) only |
| 361 | // to HTTPS. The pinned digest, checked by mac.Fetch, is what is trusted. |
| 362 | func fetchTool(ctx context.Context, url string, limit int64) ([]byte, error) { |
| 363 | c := http.Client{Timeout: 10 * time.Minute, CheckRedirect: func(r *http.Request, via []*http.Request) error { |
| 364 | if r.URL.Scheme != "https" || len(via) > 5 { |
| 365 | return errors.New("refused redirect") |
| 366 | } |
| 367 | return nil |
| 368 | }} |
| 369 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 370 | if err != nil || req.URL.Scheme != "https" { |
| 371 | return nil, errors.New("refused tool URL") |
| 372 | } |
| 373 | resp, err := c.Do(req) |
| 374 | if err != nil { |
| 375 | return nil, err |
| 376 | } |
| 377 | defer resp.Body.Close() |
| 378 | if resp.StatusCode != http.StatusOK { |
| 379 | return nil, errors.New("tool download: " + resp.Status) |
| 380 | } |
| 381 | b, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) |
| 382 | if err != nil || int64(len(b)) > limit { |
| 383 | return nil, errors.New("tool download too large") |
| 384 | } |
| 385 | return b, nil |
| 386 | } |
| 387 | |
| 388 | func writeEnvFile(path string, values map[string]string) error { |
| 389 | keys := make([]string, 0, len(values)) |
| 390 | for k := range values { |
| 391 | keys = append(keys, k) |
| 392 | } |
| 393 | sort.Strings(keys) |
| 394 | var b strings.Builder |
| 395 | for _, k := range keys { |
| 396 | fmt.Fprintf(&b, "%s=%s\n", k, strconv.Quote(values[k])) |
| 397 | } |
| 398 | tmp := path + ".new" |
| 399 | if err := os.WriteFile(tmp, []byte(b.String()), 0600); err != nil { |
| 400 | return err |
| 401 | } |
| 402 | if err := os.Chmod(tmp, 0600); err != nil { |
| 403 | return err |
| 404 | } |
| 405 | if err := os.Rename(tmp, path); err != nil { |
| 406 | return err |
| 407 | } |
| 408 | // Read it back the way the agent will. |
| 409 | _, err := runnersetup.ReadEnvFile(path) |
| 410 | return err |
| 411 | } |
| 412 | |
| 413 | func copyPrivate(src, dst string, mode os.FileMode) error { |
| 414 | if src == "" { |
| 415 | return errors.New("no source") |
| 416 | } |
| 417 | raw, err := os.ReadFile(src) |
| 418 | if err != nil { |
| 419 | return err |
| 420 | } |
| 421 | tmp, err := os.CreateTemp(filepath.Dir(dst), ".equipo-runner-") |
| 422 | if err != nil { |
| 423 | return err |
| 424 | } |
| 425 | defer os.Remove(tmp.Name()) |
| 426 | if _, err = tmp.Write(raw); err == nil { |
| 427 | err = tmp.Chmod(mode) |
| 428 | } |
| 429 | if cerr := tmp.Close(); err == nil { |
| 430 | err = cerr |
| 431 | } |
| 432 | if err != nil { |
| 433 | return err |
| 434 | } |
| 435 | return os.Rename(tmp.Name(), dst) |
| 436 | } |
| 437 | |
| 438 | // stopRunner stops a runner installed before and confirms it stopped: |
| 439 | // launchd no longer has the agent, and the runner's state lock is free. |
| 440 | // It changes nothing itself; not stopped means do not change anything. |
| 441 | // tookDown is whether it took the agent out of launchd (which loads it |
| 442 | // again if the install does not go ahead); a refused bootout did not. |
| 443 | func stopRunner(ctx context.Context, h macInstallHost, service, state string) (stopped, tookDown bool) { |
| 444 | if h.launchctl(ctx, "print", service) != nil { |
| 445 | // Not loaded. Its lock must still be free: a runner started by |
| 446 | // hand holds it too. |
| 447 | return lockFree(state), false |
| 448 | } |
| 449 | // The bootout is not cut short by Ctrl-C: launchd may have taken the |
| 450 | // agent out before it answers, and whether it did is checked below. |
| 451 | stop, cancel := detached(ctx) |
| 452 | defer cancel() |
| 453 | refused := h.launchctl(stop, "bootout", service) != nil |
| 454 | check, cancelCheck := detached(ctx) |
| 455 | defer cancelCheck() |
| 456 | if refused && h.launchctl(check, "print", service) == nil { |
| 457 | // Refused, and the agent is still there: nothing was taken down. |
| 458 | return false, false |
| 459 | } |
| 460 | return waitStopped(ctx, h, service, state), true |
| 461 | } |
| 462 | |
| 463 | // sameFile reports whether a and b are the same existing file. |
| 464 | func sameFile(a, b string) bool { |
| 465 | ai, err := os.Stat(a) |
| 466 | if err != nil { |
| 467 | return false |
| 468 | } |
| 469 | bi, err := os.Stat(b) |
| 470 | return err == nil && os.SameFile(ai, bi) |
| 471 | } |
| 472 | |
| 473 | // waitStopped waits for a booted-out runner to be gone and its lock free. |
| 474 | func waitStopped(ctx context.Context, h macInstallHost, service, state string) bool { |
| 475 | wait := h.stopWait |
| 476 | if wait <= 0 { |
| 477 | wait = time.Minute |
| 478 | } |
| 479 | deadline := time.Now().Add(wait) |
| 480 | for { |
| 481 | if h.launchctl(ctx, "print", service) != nil && lockFree(state) { |
| 482 | return true |
| 483 | } |
| 484 | if time.Now().After(deadline) { |
| 485 | return false |
| 486 | } |
| 487 | select { |
| 488 | case <-ctx.Done(): |
| 489 | return false |
| 490 | case <-time.After(250 * time.Millisecond): |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | // lockFree reports whether no runner holds the state lock (a state dir |
| 496 | // not made yet is free). |
| 497 | func lockFree(state string) bool { |
| 498 | if _, err := os.Stat(state); os.IsNotExist(err) { |
| 499 | return true |
| 500 | } |
| 501 | lock, err := runner.LockState(state) |
| 502 | if err != nil { |
| 503 | return false |
| 504 | } |
| 505 | return lock.Close() == nil |
| 506 | } |
| 507 | |