| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | "github.com/sylvinus/agent-vm/internal/env" |
| 18 | "github.com/sylvinus/agent-vm/internal/guard" |
| 19 | "github.com/sylvinus/agent-vm/internal/host" |
| 20 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 21 | "github.com/sylvinus/agent-vm/internal/netguard" |
| 22 | "github.com/sylvinus/agent-vm/internal/paths" |
| 23 | "github.com/sylvinus/agent-vm/internal/runscript" |
| 24 | "github.com/sylvinus/agent-vm/internal/state" |
| 25 | "github.com/sylvinus/agent-vm/internal/vm" |
| 26 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 27 | ) |
| 28 | |
| 29 | var errStop = errors.New("stop") |
| 30 | |
| 31 | |
| 32 | func (s *start) get(name string) (*vm.Instance, error) { |
| 33 | b, err := s.backend() |
| 34 | if err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | inst, err := b.Get(s.ctx, name) |
| 38 | if errors.Is(err, vm.ErrNotFound) { |
| 39 | return nil, nil |
| 40 | } |
| 41 | return inst, err |
| 42 | } |
| 43 | |
| 44 | func (s *start) running() bool { |
| 45 | inst, err := s.get(s.name) |
| 46 | return err == nil && inst != nil && inst.Status == vm.Running |
| 47 | } |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | func (s *start) shares(writable bool) ([]vm.Mount, []mounts.FileMount) { |
| 57 | if s.opts.Scratch { |
| 58 | return []vm.Mount{}, nil |
| 59 | } |
| 60 | n := s.names |
| 61 | if !s.protect { |
| 62 | n = []string{} |
| 63 | } |
| 64 | key := fmt.Sprint(writable, n) |
| 65 | if s.built != nil && s.builtKey == key { |
| 66 | return s.built, s.builtFiles |
| 67 | } |
| 68 | s.built, s.builtFiles = mounts.Build(mounts.Shares{ |
| 69 | VM: s.name, Dir: s.dir, Writable: writable, Names: n, |
| 70 | Entries: s.entries(s.dir, s.io.Stderr), StateDir: string(s.state), Warn: s.io.Stderr, |
| 71 | }) |
| 72 | s.builtKey = key |
| 73 | return s.built, s.builtFiles |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | func (s *start) applyShares(writable bool) error { |
| 79 | b, err := s.backend() |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | ms, files := s.shares(writable) |
| 84 | mt := vm.ReverseSSHFS |
| 85 | if err := b.Edit(s.ctx, s.name, vm.Settings{Mounts: &ms, MountType: &mt}); err != nil { |
| 86 | s.warnf("Error: could not set the shares of VM '%s':\n%v", s.name, err) |
| 87 | return errStop |
| 88 | } |
| 89 | cache := s.state.Marker(state.FileMountsOf, s.name) |
| 90 | if err := os.Remove(cache); err != nil && !os.IsNotExist(err) { |
| 91 | s.warnf("Error: could not remove %s:\n%v", cache, err) |
| 92 | return errStop |
| 93 | } |
| 94 | if len(files) > 0 { |
| 95 | var lines []string |
| 96 | for _, f := range files { |
| 97 | lines = append(lines, f.Line()) |
| 98 | } |
| 99 | if err := s.state.Write(state.FileMountsOf+s.name, []byte(strings.Join(lines, "\n")+"\n")); err != nil { |
| 100 | s.warnf("Error: could not record the single files of ~/.agent-vm/volumes for VM '%s':\n%v", s.name, err) |
| 101 | return errStop |
| 102 | } |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | |
| 108 | |
| 109 | func (s *start) applyResources() error { |
| 110 | b, err := s.backend() |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | set := vm.Settings{CPUs: s.opts.CPUs, MemoryGiB: s.opts.Memory} |
| 115 | if s.opts.SSHPort >= 0 { |
| 116 | p := s.opts.SSHPort |
| 117 | set.SSHLocalPort = &p |
| 118 | } |
| 119 | if err := b.Edit(s.ctx, s.name, set); err != nil { |
| 120 | s.warnf("Error: could not set the memory, CPUs or SSH port of VM '%s':\n%v", s.name, err) |
| 121 | return errStop |
| 122 | } |
| 123 | if s.opts.Disk > 0 { |
| 124 | if err := b.Edit(s.ctx, s.name, vm.Settings{DiskGiB: s.opts.Disk}); err != nil { |
| 125 | s.warnf("Warning: cannot set the disk of VM '%s' to %d GiB: it can grow, not shrink ('agent-vm setup --disk %d' for a smaller base).\n%v", s.name, s.opts.Disk, s.opts.Disk, err) |
| 126 | } |
| 127 | } |
| 128 | return nil |
| 129 | } |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | func (s *start) resourcesDiffer(inst *vm.Instance) bool { |
| 135 | o := s.opts |
| 136 | switch { |
| 137 | case inst == nil: |
| 138 | return true |
| 139 | case o.CPUs > 0 && o.CPUs != inst.CPUs: |
| 140 | return true |
| 141 | case o.Memory > 0 && int64(o.Memory)<<30 != inst.Memory: |
| 142 | return true |
| 143 | case o.Disk > 0 && int64(o.Disk)<<30 > inst.Disk: |
| 144 | return true |
| 145 | } |
| 146 | return false |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | func (s *start) stopToChange() error { |
| 152 | if !s.stopVM(s.ctx, s.name) { |
| 153 | s.warnf("Error: could not stop VM '%s': nothing was changed.", s.name) |
| 154 | return errStop |
| 155 | } |
| 156 | if s.vmUp { |
| 157 | s.vmUp = false |
| 158 | if !s.checks() { |
| 159 | s.warnf("VM '%s' is stopped.", s.name) |
| 160 | return errStop |
| 161 | } |
| 162 | } |
| 163 | return nil |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | func (s *start) beforeBoot() error { |
| 170 | inst, err := s.get(s.name) |
| 171 | if err != nil || inst == nil { |
| 172 | s.warnf("Error: could not read Lima's config for VM '%s', so what it would boot with is not known.", s.name) |
| 173 | return errStop |
| 174 | } |
| 175 | |
| 176 | |
| 177 | var whys []string |
| 178 | if s.opts.Scratch && len(inst.Mounts) > 0 { |
| 179 | whys = append(whys, "a share, though a scratch VM gets none") |
| 180 | } |
| 181 | if err := vm.Confined(inst); err != nil { |
| 182 | whys = append(whys, err.Error()) |
| 183 | } |
| 184 | if s.protect && !s.opts.Scratch { |
| 185 | whys = append(whys, unprotected(inst, s.names)) |
| 186 | } |
| 187 | if s.opts.ReadOnly { |
| 188 | whys = append(whys, notReadOnly(inst)) |
| 189 | } |
| 190 | for _, why := range whys { |
| 191 | if why != "" { |
| 192 | s.warnf("Error: VM '%s' would not boot as asked: %s.", s.name, why) |
| 193 | return errStop |
| 194 | } |
| 195 | } |
| 196 | if err := policiesErr(s.state); err != nil { |
| 197 | s.warnf("Error: %v", err) |
| 198 | return errStop |
| 199 | } |
| 200 | return nil |
| 201 | } |
| 202 | |
| 203 | |
| 204 | |
| 205 | func policiesErr(st state.Dir) error { |
| 206 | if _, err := netguard.Load(string(st)); err != nil { |
| 207 | return err |
| 208 | } |
| 209 | _, err := guard.Load(string(st), "") |
| 210 | return err |
| 211 | } |
| 212 | |
| 213 | |
| 214 | func (s *start) configErr(inst *vm.Instance) bool { |
| 215 | if inst == nil || inst.ConfigErr == nil { |
| 216 | return false |
| 217 | } |
| 218 | s.warnf("Error: Lima cannot read the config of VM '%s':\n %v\n'agent-vm --reset <command>' re-clones it.", inst.Name, inst.ConfigErr) |
| 219 | return true |
| 220 | } |
| 221 | |
| 222 | |
| 223 | |
| 224 | func (s *start) limaOverridesOK() bool { |
| 225 | found := vm.LimaOverrides(LimaHome(s.state)) |
| 226 | for _, f := range found { |
| 227 | s.warnf("Error: %s adds to every VM's config (shares, mount type...): agent-vm makes and starts no VM while it is there. Move it out of the way.", f) |
| 228 | } |
| 229 | return len(found) == 0 |
| 230 | } |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | func unprotected(inst *vm.Instance, names []string) string { |
| 240 | if err := vm.Confined(inst); err != nil { |
| 241 | return err.Error() |
| 242 | } |
| 243 | if names == nil { |
| 244 | names = mounts.BaseNames |
| 245 | } |
| 246 | for _, m := range inst.Mounts { |
| 247 | if slices.ContainsFunc(names, func(n string) bool { return !slices.Contains(m.SSHFS.ReadonlyNames, n) }) { |
| 248 | return "the share of " + m.Location + " lacks the read-only names" |
| 249 | } |
| 250 | } |
| 251 | return "" |
| 252 | } |
| 253 | |
| 254 | |
| 255 | func notReadOnly(inst *vm.Instance) string { |
| 256 | if err := vm.Confined(inst); err != nil { |
| 257 | return err.Error() |
| 258 | } |
| 259 | for _, m := range inst.Mounts { |
| 260 | if m.Writable { |
| 261 | return "a writable share of " + m.Location |
| 262 | } |
| 263 | } |
| 264 | return "" |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | func sharesDiffer(inst *vm.Instance, want []vm.Mount) bool { |
| 270 | if len(inst.Mounts) == 0 && len(want) == 0 { |
| 271 | return false |
| 272 | } |
| 273 | norm := func(ms []vm.Mount) []vm.Mount { |
| 274 | out := make([]vm.Mount, len(ms)) |
| 275 | for i, m := range ms { |
| 276 | o := vm.SSHFS{} |
| 277 | if m.SSHFS != nil { |
| 278 | o = *m.SSHFS |
| 279 | } |
| 280 | if o.Cache == nil { |
| 281 | on := true |
| 282 | o.Cache = &on |
| 283 | } |
| 284 | if len(o.ReadonlyNames) == 0 { |
| 285 | o.ReadonlyNames = nil |
| 286 | } |
| 287 | m.SSHFS = &o |
| 288 | out[i] = m |
| 289 | } |
| 290 | return out |
| 291 | } |
| 292 | return !reflect.DeepEqual(norm(inst.Mounts), norm(want)) || inst.MountType != vm.ReverseSSHFS |
| 293 | } |
| 294 | |
| 295 | |
| 296 | func allReadOnly(inst *vm.Instance) bool { |
| 297 | for _, m := range inst.Mounts { |
| 298 | if m.Writable { |
| 299 | return false |
| 300 | } |
| 301 | } |
| 302 | return len(inst.Mounts) > 0 |
| 303 | } |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | func (s *start) ensureRunning() error { |
| 310 | |
| 311 | if !s.opts.Scratch { |
| 312 | unlock, err := s.lockVM(s.ctx, s.name) |
| 313 | if err != nil { |
| 314 | s.warnf("Error: could not lock VM '%s': %v", s.name, err) |
| 315 | return errStop |
| 316 | } |
| 317 | defer unlock() |
| 318 | } |
| 319 | return s.ensureRunningLocked() |
| 320 | } |
| 321 | |
| 322 | func (s *start) ensureRunningLocked() error { |
| 323 | o := &s.opts |
| 324 | if o.Scratch && (o.Reset || o.ReadOnly) { |
| 325 | s.warnf("Error: --scratch makes a new VM that shares nothing: --reset and --readonly do not go with it.") |
| 326 | return errStop |
| 327 | } |
| 328 | wantWritable := !o.ReadOnly |
| 329 | o.CPUs = host.Cap("cpus", o.CPUs, s.io.Stderr) |
| 330 | o.Memory = host.Cap("memory", o.Memory, s.io.Stderr) |
| 331 | host.WarnDiskSpace(LimaHome(s.state), o.Disk, s.io.Stderr) |
| 332 | b, err := s.backend() |
| 333 | if err != nil { |
| 334 | s.warnf("Error: %v", err) |
| 335 | return errStop |
| 336 | } |
| 337 | if !s.limaOverridesOK() { |
| 338 | return errStop |
| 339 | } |
| 340 | warnDomains(s.state, s.io.Stderr) |
| 341 | |
| 342 | if o.SSHPort > 0 { |
| 343 | if all, err := b.List(s.ctx); err == nil { |
| 344 | for _, v := range all { |
| 345 | if v.Name != s.name && v.SSHPortConfig == o.SSHPort { |
| 346 | s.warnf("Error: SSH port %d is already set for VM '%s'.", o.SSHPort, v.Name) |
| 347 | return errStop |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | if !o.Scratch { |
| 357 | refs := s.refs() |
| 358 | if _, off := s.promptsDisabledBy(); off { |
| 359 | var others []mounts.Ref |
| 360 | for _, r := range refs { |
| 361 | if r.What != mounts.SelfRef { |
| 362 | others = append(others, r) |
| 363 | } |
| 364 | } |
| 365 | if _, bad := mounts.UnsafeProject(s.dir, others); !bad { |
| 366 | if why, self := mounts.UnsafeLocation(s.dir, refs); self { |
| 367 | s.warnf("Warning: sharing %s with the VM: it %s. The VM can change the agent-vm this machine runs next.", s.dir, why) |
| 368 | s.confirmUnsafe() |
| 369 | } |
| 370 | refs = others |
| 371 | } |
| 372 | } |
| 373 | if why, bad := mounts.UnsafeProject(s.dir, refs); bad { |
| 374 | s.warnf("Error: refusing to share %s with a VM: it %s.\nRun agent-vm from a project directory.", s.dir, why) |
| 375 | return errStop |
| 376 | } |
| 377 | if why, bad := mounts.Unmountable(s.dir); bad { |
| 378 | s.warnf("Error: project path %s:\n %s\nRename the directory, then retry.", why, s.dir) |
| 379 | return errStop |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | |
| 384 | if d := filepath.Join(LimaHome(s.state), s.name); isDirNoYAML(d) { |
| 385 | s.warnf("Detected partial VM state at %s (no lima.yaml): cleaning up.", d) |
| 386 | if err := os.RemoveAll(d); err != nil { |
| 387 | s.warnf("Error: could not remove %s:\n%v", d, err) |
| 388 | return errStop |
| 389 | } |
| 390 | } |
| 391 | base, err := s.get(vmname.Template) |
| 392 | if err != nil { |
| 393 | s.warnf("Error: could not query Lima: %v", err) |
| 394 | return errStop |
| 395 | } |
| 396 | if s.configErr(base) { |
| 397 | return errStop |
| 398 | } |
| 399 | if _, merr := os.Stat(s.state.Path(state.BaseVersion)); base == nil || merr != nil { |
| 400 | if base != nil { |
| 401 | s.warnf("Error: Base VM setup did not complete. Run 'agent-vm setup' again.") |
| 402 | } else { |
| 403 | s.warnf("Error: Base VM not found. Run 'agent-vm setup' first.") |
| 404 | } |
| 405 | return errStop |
| 406 | } |
| 407 | |
| 408 | s.vmUp = !o.Reset && s.running() |
| 409 | if !s.checks() { |
| 410 | return errStop |
| 411 | } |
| 412 | inst, err := s.get(s.name) |
| 413 | if err != nil { |
| 414 | s.warnf("Error: could not query Lima: %v", err) |
| 415 | return errStop |
| 416 | } |
| 417 | if !o.Reset && s.configErr(inst) { |
| 418 | return errStop |
| 419 | } |
| 420 | |
| 421 | |
| 422 | if inst != nil && inst.Orphaned { |
| 423 | s.warnf("Warning: VM '%s' was left running without Lima's host agent, cut off: stopping it.", s.name) |
| 424 | if !s.stopVM(s.ctx, s.name) { |
| 425 | s.warnf("Error: could not stop VM '%s'. See 'agent-vm list'.", s.name) |
| 426 | return errStop |
| 427 | } |
| 428 | if inst, err = s.get(s.name); err != nil { |
| 429 | s.warnf("Error: could not query Lima: %v", err) |
| 430 | return errStop |
| 431 | } |
| 432 | } |
| 433 | if o.Reset && inst != nil { |
| 434 | fmt.Fprintf(s.io.Stdout, "Resetting VM '%s'...\n", s.name) |
| 435 | if !s.deleteVM(s.ctx, s.name) { |
| 436 | return errStop |
| 437 | } |
| 438 | inst = nil |
| 439 | } |
| 440 | |
| 441 | |
| 442 | |
| 443 | if inst != nil && !o.Scratch && !exists(s.state.Marker(state.BuiltByOf, s.name)) && !exists(s.state.Marker(state.SSHFSOf, s.name)) { |
| 444 | s.warnf("Error: VM '%s' comes from a base built by agent-vm 0.1.0, without the sshfs its shares need. Run 'agent-vm setup', then 'agent-vm --reset <command>' here.", s.name) |
| 445 | return errStop |
| 446 | } |
| 447 | |
| 448 | isNew := inst == nil |
| 449 | applyResize := false |
| 450 | if isNew { |
| 451 | fmt.Fprintf(s.io.Stdout, "Creating VM '%s'...\n", s.name) |
| 452 | marks, err := s.cloneBase() |
| 453 | if err != nil { |
| 454 | s.warnf("Error: could not clone the base template into '%s':\n%v", s.name, err) |
| 455 | if errors.Is(err, vm.ErrNameTooLong) { |
| 456 | s.warnf(" The VM's name comes from the project folder's: give the folder a shorter name.") |
| 457 | } |
| 458 | return errStop |
| 459 | } |
| 460 | s.created = true |
| 461 | for _, k := range []string{state.BuiltByOf, state.SSHFSOf} { |
| 462 | os.Remove(s.state.Marker(k, s.name)) |
| 463 | } |
| 464 | if marks.builtBy != nil { |
| 465 | if err := s.state.Write(state.BuiltByOf+s.name, marks.builtBy); err != nil { |
| 466 | s.warnf("Error: could not record which agent-vm built the base of VM '%s': %v", s.name, err) |
| 467 | s.dropNew() |
| 468 | return errStop |
| 469 | } |
| 470 | } else if s.protect { |
| 471 | |
| 472 | s.warnf("Error: the base VM was built by agent-vm 0.1.0, without what the shares that keep .git read-only need. Run 'agent-vm setup' to build a new one.") |
| 473 | s.dropNew() |
| 474 | return errStop |
| 475 | } |
| 476 | |
| 477 | |
| 478 | if s.applyShares(wantWritable) != nil || s.applyResources() != nil { |
| 479 | s.dropNew() |
| 480 | return errStop |
| 481 | } |
| 482 | fmt.Fprint(s.io.Stdout, s.notes) |
| 483 | if marks.version != nil { |
| 484 | if err := s.state.Write(state.VersionOf+s.name, marks.version); err != nil { |
| 485 | s.warnf("Warning: could not record the base VM '%s' was cloned from: %v. Every start will say that the base has been updated.", s.name, err) |
| 486 | } |
| 487 | } |
| 488 | } else if ((o.Disk > 0 || o.Memory > 0 || o.CPUs > 0) && s.resourcesDiffer(inst)) || (o.SSHPort >= 0 && o.SSHPort != inst.SSHPortConfig) { |
| 489 | |
| 490 | |
| 491 | |
| 492 | applyResize = true |
| 493 | if s.running() { |
| 494 | fmt.Fprintf(s.io.Stdout, "VM '%s' is currently running. It must be stopped to apply new settings.\n", s.name) |
| 495 | if s.ui.CanAsk() && s.ui.AskYN("Stop the VM and apply changes?", false) { |
| 496 | fmt.Fprintln(s.io.Stdout, "Stopping VM...") |
| 497 | if err := s.stopToChange(); err != nil { |
| 498 | return err |
| 499 | } |
| 500 | } else { |
| 501 | fmt.Fprintln(s.io.Stdout, "Not applied: the VM keeps its current settings.") |
| 502 | applyResize = false |
| 503 | } |
| 504 | } |
| 505 | } |
| 506 | if applyResize { |
| 507 | fmt.Fprintln(s.io.Stdout, "Updating VM settings...") |
| 508 | if err := s.applyResources(); err != nil { |
| 509 | return err |
| 510 | } |
| 511 | } |
| 512 | if s.staleState(s.name) == "1" { |
| 513 | s.warnf("Warning: Base VM has been updated since this VM was cloned. Use --reset to re-clone from the new base.") |
| 514 | } |
| 515 | |
| 516 | |
| 517 | |
| 518 | |
| 519 | wasRunning := s.running() |
| 520 | if inst, err = s.get(s.name); err != nil || inst == nil { |
| 521 | s.warnf("Error: could not query Lima: %v", err) |
| 522 | return errStop |
| 523 | } |
| 524 | want, _ := s.shares(wantWritable) |
| 525 | wasProtected := len(inst.Mounts) > 0 && unprotected(inst, nil) == "" |
| 526 | gitStale := !o.Scratch && wasProtected != s.protect |
| 527 | namesStale := s.protect && wasProtected && unprotected(inst, s.names) != "" |
| 528 | stale := sharesDiffer(inst, want) |
| 529 | if !o.ReadOnly && wasRunning && s.protect && (gitStale || namesStale) { |
| 530 | if gitStale { |
| 531 | s.warnf("Warning: VM '%s' is running with .git writable, so the agent can still write .git.", s.name) |
| 532 | } else { |
| 533 | s.warnf("Warning: VM '%s' runs with an older list of read-only names (it needs %s), so the agent can still write the new ones.", s.name, strings.Join(s.names, ", ")) |
| 534 | } |
| 535 | if _, off := s.promptsDisabledBy(); !off && s.ui.CanAsk() && s.ui.AskYN("Restart it now to apply them? Sessions using it are cut.", true) { |
| 536 | if err := s.stopToChange(); err != nil { |
| 537 | return err |
| 538 | } |
| 539 | wasRunning = false |
| 540 | } else if !s.confirmUnsafe() { |
| 541 | s.warnf("Aborted. 'agent-vm stop', then run again.") |
| 542 | return errStop |
| 543 | } |
| 544 | } |
| 545 | switch { |
| 546 | case gitStale && wasRunning && !s.protect: |
| 547 | s.warnf("Note: VM '%s' keeps .git read-only until it stops.", s.name) |
| 548 | case !wasRunning && stale: |
| 549 | switch { |
| 550 | case gitStale && s.protect: |
| 551 | fmt.Fprintf(s.io.Stdout, "Making every .git read-only for VM '%s'...\n", s.name) |
| 552 | case gitStale: |
| 553 | if cageWritableGit() { |
| 554 | fmt.Fprintf(s.io.Stdout, "Enabling Git writes in Cage projects for VM '%s'...\n", s.name) |
| 555 | } else { |
| 556 | s.warnf("Making .git writable for VM '%s' (%s)...", s.name, map[bool]string{true: "--unsafe-writable-git", false: "AGENT_VM_UNSAFE_WRITABLE_GIT=1"}[o.UnsafeWritableGit]) |
| 557 | } |
| 558 | case namesStale: |
| 559 | fmt.Fprintf(s.io.Stdout, "Making %s read-only for VM '%s'...\n", strings.Join(s.names, ", "), s.name) |
| 560 | } |
| 561 | if gitStale || namesStale { |
| 562 | fmt.Fprint(s.io.Stdout, s.notes) |
| 563 | } |
| 564 | if !isNew { |
| 565 | switch { |
| 566 | case !wantWritable && !allReadOnly(inst): |
| 567 | fmt.Fprintf(s.io.Stdout, "Making every share of VM '%s' read-only...\n", s.name) |
| 568 | case wantWritable && allReadOnly(inst): |
| 569 | fmt.Fprintf(s.io.Stdout, "VM '%s' was left read-only by --readonly; making it writable again...\n", s.name) |
| 570 | } |
| 571 | } |
| 572 | if err := s.applyShares(wantWritable); err != nil { |
| 573 | return err |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | if wasRunning { |
| 578 | s.notePolicyChange() |
| 579 | } else if err := s.boot(); err != nil { |
| 580 | return err |
| 581 | } |
| 582 | return s.afterBoot(isNew, wasRunning, wantWritable) |
| 583 | } |
| 584 | |
| 585 | |
| 586 | |
| 587 | type baseMarkers struct{ builtBy, version []byte } |
| 588 | |
| 589 | |
| 590 | |
| 591 | |
| 592 | func (s *start) cloneBase() (baseMarkers, error) { |
| 593 | var m baseMarkers |
| 594 | b, err := s.backend() |
| 595 | if err != nil { |
| 596 | return m, err |
| 597 | } |
| 598 | unlock, err := s.lockVM(s.ctx, vmname.Template) |
| 599 | if err != nil { |
| 600 | return m, err |
| 601 | } |
| 602 | defer unlock() |
| 603 | if err := b.Clone(s.ctx, vmname.Template, s.name); err != nil { |
| 604 | return m, err |
| 605 | } |
| 606 | m.builtBy, _ = os.ReadFile(s.state.Path(state.BaseBuiltBy)) |
| 607 | m.version, _ = os.ReadFile(s.state.Path(state.BaseVersion)) |
| 608 | return m, nil |
| 609 | } |
| 610 | |
| 611 | |
| 612 | func (s *start) dropNew() { |
| 613 | if s.deleteVM(context.WithoutCancel(s.ctx), s.name) { |
| 614 | s.created = false |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | func isDirNoYAML(d string) bool { |
| 619 | if fi, err := os.Stat(d); err != nil || !fi.IsDir() { |
| 620 | return false |
| 621 | } |
| 622 | _, err := os.Stat(filepath.Join(d, "lima.yaml")) |
| 623 | return err != nil |
| 624 | } |
| 625 | |
| 626 | |
| 627 | func (s *start) boot() error { |
| 628 | if err := s.beforeBoot(); err != nil { |
| 629 | return err |
| 630 | } |
| 631 | |
| 632 | |
| 633 | if !skipPrereqs && !host.LinuxPrereqs(s.io.Stderr) { |
| 634 | return errStop |
| 635 | } |
| 636 | |
| 637 | |
| 638 | if !host.WindowsPrereqs(s.io.Stdout, s.io.Stderr) { |
| 639 | return errStop |
| 640 | } |
| 641 | fmt.Fprintf(s.io.Stdout, "Starting VM '%s'...\n", s.name) |
| 642 | b, _ := s.backend() |
| 643 | var log bytes.Buffer |
| 644 | if err := s.startVM(s.ctx, b, s.name, &log); err != nil { |
| 645 | ha := paths.Host(filepath.Join(LimaHome(s.state), s.name, "ha.stderr.log")) |
| 646 | s.warnf("Error: Failed to start VM '%s'.\n--- Lima's output ---\n%s%v\nFull log: %s", s.name, log.String(), err, ha) |
| 647 | host.WindowsStartHint(s.io.Stderr, ha) |
| 648 | return errStop |
| 649 | } |
| 650 | s.recordPolicy() |
| 651 | return nil |
| 652 | } |
| 653 | |
| 654 | |
| 655 | |
| 656 | |
| 657 | func (s *start) afterBoot(isNew, wasRunning, wantWritable bool) error { |
| 658 | o := s.opts |
| 659 | guest := paths.Guest(s.dir) |
| 660 | var guestEnv, guestRuntime, projectRuntime, payload string |
| 661 | if o.Scratch { |
| 662 | if code, err := s.shellRun(nil, "", "sh", "-c", `sudo install -d -o "$(id -u)" -g "$(id -g)" "$1"`, "sh", guest); err != nil || code != 0 { |
| 663 | s.warnf("Error: could not make %s in VM '%s'.", s.dir, s.name) |
| 664 | return errStop |
| 665 | } |
| 666 | |
| 667 | |
| 668 | if b, ok := readRegular(s.state.Path("env")); ok { |
| 669 | payload = strings.TrimRight(env.StripCR(b), "\n") |
| 670 | } |
| 671 | } else { |
| 672 | pe := env.ProjectEnvFile(s.dir) |
| 673 | projectRuntime = runscript.ProjectPath(s.dir) |
| 674 | |
| 675 | if rel, ok := env.ProjectRel(s.dir, pe); ok { |
| 676 | guestEnv = guest + "/" + rel |
| 677 | } |
| 678 | if rel, ok := env.ProjectRel(s.dir, projectRuntime); ok { |
| 679 | guestRuntime = guest + "/" + rel |
| 680 | } |
| 681 | payload = strings.TrimRight(env.Payload(s.state.Path("env"), s.dir), "\n") |
| 682 | } |
| 683 | probe := s.probe(payload, guestEnv, guestRuntime) |
| 684 | if o.Scratch && probe.writable != "true" { |
| 685 | s.warnf("Error: %s is not writable in VM '%s'.", s.dir, s.name) |
| 686 | return errStop |
| 687 | } |
| 688 | inst, _ := s.get(s.name) |
| 689 | want := fmt.Sprint(wantWritable) |
| 690 | if !o.Scratch && (probe.writable != want || !wantWritable && inst != nil && !allReadOnly(inst)) { |
| 691 | switch { |
| 692 | case probe.writable == "lost": |
| 693 | s.warnf("Warning: the project share is not mounted in VM '%s': what was written in %s in the VM since then is on the VM's own disk, and hidden once the share is back.", s.name, s.dir) |
| 694 | s.warnf("Project share is not mounted; repairing...") |
| 695 | case wantWritable && wasRunning && inst != nil && allReadOnly(inst): |
| 696 | fmt.Fprintf(s.io.Stdout, "VM '%s' runs read-only (--readonly). It must be restarted to make its shares writable.\n", s.name) |
| 697 | if !s.ui.CanAsk() || !s.ui.AskYN("Stop the VM and make it writable? Sessions using it are cut.", false) { |
| 698 | s.warnf("Error: not restarted. Pass --readonly to use it as it is, or 'agent-vm stop' it first.") |
| 699 | return errStop |
| 700 | } |
| 701 | case !wantWritable && wasRunning: |
| 702 | fmt.Fprintf(s.io.Stdout, "VM '%s' was already running. It must be restarted to make its shares read-only.\n", s.name) |
| 703 | if !s.ui.CanAsk() || !s.ui.AskYN("Stop the VM and apply --readonly?", false) { |
| 704 | |
| 705 | |
| 706 | s.warnf("Error: --readonly was requested but not applied. Aborting.") |
| 707 | return errStop |
| 708 | } |
| 709 | case wantWritable: |
| 710 | s.warnf("Project mount is not writable; repairing...") |
| 711 | } |
| 712 | |
| 713 | |
| 714 | if err := s.stopToChange(); err != nil { |
| 715 | return err |
| 716 | } |
| 717 | if err := s.applyShares(wantWritable); err != nil { |
| 718 | return err |
| 719 | } |
| 720 | if err := s.beforeBoot(); err != nil { |
| 721 | return err |
| 722 | } |
| 723 | b, _ := s.backend() |
| 724 | if err := s.startVM(s.ctx, b, s.name, io.Discard); err != nil { |
| 725 | s.warnf("Error: VM '%s' did not come back up after changing the project mount.", s.name) |
| 726 | return errStop |
| 727 | } |
| 728 | s.recordPolicy() |
| 729 | if probe = s.probe(payload, guestEnv, guestRuntime); probe.writable != want { |
| 730 | switch { |
| 731 | case probe.writable == "lost": |
| 732 | s.warnf("Error: the project share did not mount in VM '%s':\n %s\nLima's log: %s", s.name, s.dir, filepath.Join(LimaHome(s.state), s.name, "ha.stderr.log")) |
| 733 | case wantWritable: |
| 734 | s.warnf("Error: project directory is still not writable inside the VM:\n %s\nThe host mount failed to attach. Try 'agent-vm --reset <command>'\nto re-clone the VM from the base template.", s.dir) |
| 735 | default: |
| 736 | s.warnf("Error: failed to mount the project directory read-only:\n %s", s.dir) |
| 737 | } |
| 738 | return errStop |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | |
| 743 | if o.ReadOnly { |
| 744 | inst, _ := s.get(s.name) |
| 745 | if inst == nil { |
| 746 | s.warnf("Error: --readonly cannot hold: could not read Lima's config for VM '%s'.", s.name) |
| 747 | return errStop |
| 748 | } |
| 749 | why := notReadOnly(inst) |
| 750 | if why == "" && !allReadOnly(inst) { |
| 751 | why = "no share" |
| 752 | } |
| 753 | if why != "" { |
| 754 | s.warnf("Error: --readonly cannot hold: VM '%s' runs with %s.", s.name, why) |
| 755 | return errStop |
| 756 | } |
| 757 | fmt.Fprintln(s.io.Stdout, "Read-only: the project and every other share (enforced on the host).") |
| 758 | } |
| 759 | |
| 760 | s.terminfo() |
| 761 | if _, err := os.Stat(s.state.Path("runtime.sh")); err == nil { |
| 762 | fmt.Fprintln(s.io.Stdout, "Running user runtime setup...") |
| 763 | s.runHostScript(s.state.Path("runtime.sh")) |
| 764 | } |
| 765 | switch { |
| 766 | case guestRuntime != "": |
| 767 | if probe.runtimeFound { |
| 768 | fmt.Fprintln(s.io.Stdout, "Running project runtime setup...") |
| 769 | s.shellRun(nil, guest, "zsh", "-lc", `[ -f "$3" ] || exit 0; i="$(awk "$1" "$3")" && awk "$2" "$3" | "$i" -s`, |
| 770 | "agent-vm", runscript.ShebangAWK, runscript.StripCRAWK, guestRuntime) |
| 771 | } |
| 772 | case projectRuntime != "" && isFile(projectRuntime): |
| 773 | fmt.Fprintln(s.io.Stdout, "Running project runtime setup...") |
| 774 | s.runHostScript(projectRuntime) |
| 775 | } |
| 776 | s.bindFiles(isNew) |
| 777 | if path := os.Getenv(cage.ConfigEnv); path != "" { |
| 778 | cfg, err := cage.Load(path) |
| 779 | if err != nil { |
| 780 | return err |
| 781 | } |
| 782 | code, err := s.shellRun(strings.NewReader(cfg.EnvironmentScript()), paths.Guest(s.dir), "bash", "-s") |
| 783 | if err != nil || code != 0 { |
| 784 | return fmt.Errorf("cage environment could not be applied (exit %d): %w", code, err) |
| 785 | } |
| 786 | } |
| 787 | return nil |
| 788 | } |
| 789 | |
| 790 | func isFile(p string) bool { fi, err := os.Stat(p); return err == nil && fi.Mode().IsRegular() } |
| 791 | |
| 792 | |
| 793 | |
| 794 | func readRegular(p string) (string, bool) { |
| 795 | if !isFile(p) { |
| 796 | return "", false |
| 797 | } |
| 798 | b, err := os.ReadFile(p) |
| 799 | return string(b), err == nil |
| 800 | } |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | func (s *start) runHostScript(path string) { |
| 806 | b, ok := readRegular(path) |
| 807 | if !ok { |
| 808 | s.warnf("Warning: could not read %s (not a regular file, or unreadable): not run.", path) |
| 809 | return |
| 810 | } |
| 811 | interp := runscript.Interpreter(b) |
| 812 | s.shellRun(strings.NewReader(env.StripCR(b)), paths.Guest(s.dir), "zsh", "-lc", "exec "+interp+" -s") |
| 813 | } |
| 814 | |
| 815 | |
| 816 | |
| 817 | func (s *start) shellRun(stdin io.Reader, workdir string, args ...string) (int, error) { |
| 818 | b, err := s.backend() |
| 819 | if err != nil { |
| 820 | return 0, err |
| 821 | } |
| 822 | if stdin == nil { |
| 823 | stdin = strings.NewReader("") |
| 824 | } |
| 825 | return b.Shell(s.ctx, s.name, vm.ShellOpts{Workdir: workdir, Args: args, Stdin: stdin, Stdout: s.io.Stdout, Stderr: s.io.Stderr}) |
| 826 | } |
| 827 | |
| 828 | |
| 829 | |
| 830 | func (s *start) terminfo() { |
| 831 | t := os.Getenv("TERM") |
| 832 | if t == "" || s.state.ReadMarker(state.TermOf, s.name) == t { |
| 833 | return |
| 834 | } |
| 835 | entry, err := exec.CommandContext(s.ctx, "infocmp", "-x", t).Output() |
| 836 | if err != nil { |
| 837 | return |
| 838 | } |
| 839 | b, _ := s.backend() |
| 840 | code, err := b.Shell(s.ctx, s.name, vm.ShellOpts{Args: []string{"sudo", "tic", "-x", "-"}, Stdin: bytes.NewReader(entry), Stdout: io.Discard, Stderr: io.Discard}) |
| 841 | if err != nil || code != 0 { |
| 842 | s.warnf("Warning: failed to install '%s' terminfo inside VM.", t) |
| 843 | return |
| 844 | } |
| 845 | if err := s.state.Write(state.TermOf+s.name, []byte(t+"\n")); err != nil { |
| 846 | s.warnf("Warning: could not record that VM '%s' has the terminfo of '%s': %v", s.name, t, err) |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | |
| 851 | |
| 852 | |
| 853 | |
| 854 | func (s *start) bindFiles(isNew bool) { |
| 855 | b, err := os.ReadFile(s.state.Marker(state.FileMountsOf, s.name)) |
| 856 | if err != nil { |
| 857 | return |
| 858 | } |
| 859 | var entries []string |
| 860 | for _, line := range strings.Split(strings.TrimSuffix(string(b), "\n"), "\n") { |
| 861 | f := strings.SplitN(line, "|", 4) |
| 862 | if len(f) != 4 || f[1] == "" { |
| 863 | continue |
| 864 | } |
| 865 | switch { |
| 866 | case isNew: |
| 867 | case !exists(f[0]): |
| 868 | s.warnf("Warning: Mount source '%s' no longer exists; VM will see the last-staged copy.", f[0]) |
| 869 | case !mounts.Stage(f[0], f[1], s.io.Stderr): |
| 870 | s.warnf("Warning: Failed to refresh staged '%s'; VM may see stale content.", f[0]) |
| 871 | } |
| 872 | if f[2] != "" && f[3] != "" { |
| 873 | entries = append(entries, f[2]+"|"+f[3]) |
| 874 | } |
| 875 | } |
| 876 | if len(entries) == 0 { |
| 877 | return |
| 878 | } |
| 879 | fmt.Fprintln(s.io.Stdout, "Mounting individual files...") |
| 880 | |
| 881 | code, err := s.shellRun(nil, "", append([]string{"sudo", "bash", "-c", ` |
| 882 | set -e |
| 883 | for entry in "$@"; do |
| 884 | bind_src="${entry%%|*}" |
| 885 | bind_dst="${entry#*|}" |
| 886 | if ! findmnt -no TARGET "$bind_dst" >/dev/null 2>&1; then |
| 887 | mkdir -p "$(dirname "$bind_dst")" && touch "$bind_dst" |
| 888 | mount --bind "$bind_src" "$bind_dst" |
| 889 | mount -o remount,ro,bind "$bind_dst" |
| 890 | fi |
| 891 | done |
| 892 | `, "--"}, entries...)...) |
| 893 | if err != nil { |
| 894 | s.warnf("Warning: could not bind the single files of ~/.agent-vm/volumes in VM '%s': %v", s.name, err) |
| 895 | } else if code != 0 { |
| 896 | s.warnf("Warning: binding the single files of ~/.agent-vm/volumes in VM '%s' failed (status %d).", s.name, code) |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | func exists(p string) bool { _, err := os.Stat(p); return err == nil } |