| 1 | package vm |
| 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 | "runtime" |
| 14 | "slices" |
| 15 | "sort" |
| 16 | "strconv" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "time" |
| 20 | |
| 21 | "al.essio.dev/pkg/shellescape" |
| 22 | "github.com/coreos/go-semver/semver" |
| 23 | "github.com/mattn/go-isatty" |
| 24 | "github.com/sirupsen/logrus" |
| 25 | |
| 26 | "github.com/lima-vm/lima/v2/pkg/driver/external/server" |
| 27 | "github.com/lima-vm/lima/v2/pkg/driverutil" |
| 28 | "github.com/lima-vm/lima/v2/pkg/instance" |
| 29 | "github.com/lima-vm/lima/v2/pkg/limatmpl" |
| 30 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 31 | "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 32 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 33 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 34 | "github.com/lima-vm/lima/v2/pkg/networks/reconcile" |
| 35 | "github.com/lima-vm/lima/v2/pkg/osutil" |
| 36 | "github.com/lima-vm/lima/v2/pkg/sshutil" |
| 37 | "github.com/lima-vm/lima/v2/pkg/store" |
| 38 | "github.com/lima-vm/lima/v2/pkg/yqutil" |
| 39 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 40 | |
| 41 | "github.com/sylvinus/agent-vm/internal/cage" |
| 42 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 43 | "github.com/sylvinus/agent-vm/internal/paths" |
| 44 | ) |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | type Lima struct { |
| 50 | stateDir string |
| 51 | |
| 52 | once sync.Once |
| 53 | share *limaembed.Share |
| 54 | err error |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | func MaxName(home string) int { |
| 61 | stable := os.Getenv("CAGE_LOGICAL_LIMA_HOME") |
| 62 | return int(vmname.HomeLimit(home, stable != "" && filepath.Clean(home) == filepath.Clean(stable))) |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | func NewLima(home, stateDir string) (*Lima, error) { |
| 68 | limaHomeMu.Lock() |
| 69 | defer limaHomeMu.Unlock() |
| 70 | |
| 71 | if cur := os.Getenv("LIMA_HOME"); cur != limaHomeSet { |
| 72 | userLimaHome = cur |
| 73 | } |
| 74 | if err := os.Setenv("LIMA_HOME", home); err != nil { |
| 75 | return nil, err |
| 76 | } |
| 77 | limaHomeSet = home |
| 78 | return &Lima{stateDir: stateDir}, nil |
| 79 | } |
| 80 | |
| 81 | var ( |
| 82 | limaHomeMu sync.Mutex |
| 83 | |
| 84 | limaHomeSet string |
| 85 | |
| 86 | userLimaHome string |
| 87 | ) |
| 88 | |
| 89 | |
| 90 | |
| 91 | func UserLimaHome() string { |
| 92 | limaHomeMu.Lock() |
| 93 | defer limaHomeMu.Unlock() |
| 94 | if limaHomeSet == "" { |
| 95 | return os.Getenv("LIMA_HOME") |
| 96 | } |
| 97 | return userLimaHome |
| 98 | } |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | func (l *Lima) prepare() (*limaembed.Share, error) { |
| 105 | l.once.Do(func() { |
| 106 | l.share, l.err = limaembed.WriteShare(l.stateDir) |
| 107 | if l.err == nil { |
| 108 | l.err = os.Setenv("LIMA_TEMPLATES_PATH", l.share.Templates()) |
| 109 | } |
| 110 | }) |
| 111 | if l.err != nil { |
| 112 | return nil, l.err |
| 113 | } |
| 114 | home, err := dirnames.LimaDir() |
| 115 | if err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | if found := LimaOverrides(home); len(found) > 0 { |
| 119 | return nil, fmt.Errorf("%w: %s", ErrLimaOverrides, strings.Join(found, ", ")) |
| 120 | } |
| 121 | return l.share, nil |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | func Confined(inst *Instance) error { |
| 128 | for _, m := range inst.Mounts { |
| 129 | if m.SSHFS == nil || m.SSHFS.SFTPDriver != "builtin" { |
| 130 | return fmt.Errorf("%w: the share of %s is not served by the builtin SFTP server", ErrUnconfined, m.Location) |
| 131 | } |
| 132 | } |
| 133 | if len(inst.Mounts) > 0 && inst.MountType != ReverseSSHFS { |
| 134 | return fmt.Errorf("%w: the mount type is %q, not %s", ErrUnconfined, inst.MountType, ReverseSSHFS) |
| 135 | } |
| 136 | return nil |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | func LimaOverrides(home string) []string { |
| 142 | var out []string |
| 143 | for _, f := range []string{filenames.Default, filenames.Override} { |
| 144 | p := filepath.Join(home, filenames.ConfigDir, f) |
| 145 | if _, err := os.Lstat(p); err == nil { |
| 146 | out = append(out, paths.Host(p)) |
| 147 | } |
| 148 | } |
| 149 | return out |
| 150 | } |
| 151 | |
| 152 | func (l *Lima) List(ctx context.Context) ([]*Instance, error) { |
| 153 | names, err := store.Instances() |
| 154 | if err != nil { |
| 155 | return nil, err |
| 156 | } |
| 157 | sort.Strings(names) |
| 158 | var out []*Instance |
| 159 | for _, name := range names { |
| 160 | inst, err := l.Get(ctx, name) |
| 161 | if errors.Is(err, ErrNotFound) { |
| 162 | continue |
| 163 | } |
| 164 | if err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | out = append(out, inst) |
| 168 | } |
| 169 | return out, nil |
| 170 | } |
| 171 | |
| 172 | func (l *Lima) Get(ctx context.Context, name string) (*Instance, error) { |
| 173 | inst, err := l.inspect(ctx, name) |
| 174 | if err != nil { |
| 175 | return nil, err |
| 176 | } |
| 177 | return fromLima(inst), nil |
| 178 | } |
| 179 | |
| 180 | func (l *Lima) inspect(ctx context.Context, name string) (*limatype.Instance, error) { |
| 181 | inst, err := store.Inspect(ctx, name) |
| 182 | if errors.Is(err, os.ErrNotExist) { |
| 183 | return nil, fmt.Errorf("%w: %s", ErrNotFound, name) |
| 184 | } |
| 185 | return inst, err |
| 186 | } |
| 187 | |
| 188 | func fromLima(inst *limatype.Instance) *Instance { |
| 189 | out := &Instance{ |
| 190 | Name: inst.Name, |
| 191 | Dir: inst.Dir, |
| 192 | CPUs: inst.CPUs, |
| 193 | Memory: inst.Memory, |
| 194 | Disk: inst.Disk, |
| 195 | SSHLocalPort: inst.SSHLocalPort, |
| 196 | SSHAddress: inst.SSHAddress, |
| 197 | SSHConfig: inst.SSHConfigFile, |
| 198 | VMType: inst.VMType, |
| 199 | Arch: inst.Arch, |
| 200 | } |
| 201 | switch inst.Status { |
| 202 | case limatype.StatusRunning: |
| 203 | out.Status = Running |
| 204 | case limatype.StatusStopped: |
| 205 | out.Status = Stopped |
| 206 | default: |
| 207 | out.Status = Broken |
| 208 | } |
| 209 | if inst.Config == nil { |
| 210 | out.Status = Broken |
| 211 | out.ConfigErr = errors.Join(inst.Errors...) |
| 212 | } |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | out.Orphaned = out.Status == Broken && inst.Config != nil && inst.HostAgentPID == 0 && inst.DriverPID > 0 && |
| 219 | inst.VMType == limatype.QEMU && isQEMU(inst.DriverPID, inst.Dir, inst.Name) |
| 220 | if c := inst.Config; c != nil { |
| 221 | if c.SSH.LocalPort != nil { |
| 222 | out.SSHPortConfig = *c.SSH.LocalPort |
| 223 | } |
| 224 | if c.MountType != nil { |
| 225 | out.MountType = *c.MountType |
| 226 | } |
| 227 | for _, m := range c.Mounts { |
| 228 | mm := Mount{Location: paths.Host(m.Location), Writable: m.Writable != nil && *m.Writable} |
| 229 | if m.MountPoint != nil { |
| 230 | mm.MountPoint = *m.MountPoint |
| 231 | } |
| 232 | if s := m.SSHFS; s.SFTPDriver != nil || s.Cache != nil || len(s.ReadonlyNames) > 0 { |
| 233 | mm.SSHFS = &SSHFS{Cache: s.Cache, ReadonlyNames: s.ReadonlyNames} |
| 234 | if s.SFTPDriver != nil { |
| 235 | mm.SSHFS.SFTPDriver = string(*s.SFTPDriver) |
| 236 | } |
| 237 | } |
| 238 | out.Mounts = append(out.Mounts, mm) |
| 239 | } |
| 240 | } |
| 241 | return out |
| 242 | } |
| 243 | |
| 244 | |
| 245 | func exprs(s Settings) ([]string, error) { |
| 246 | var e []string |
| 247 | if s.macOSTimezone != "" { |
| 248 | e = append(e, ".timezone = "+strconv.Quote(s.macOSTimezone)) |
| 249 | } |
| 250 | if s.CPUs > 0 { |
| 251 | e = append(e, fmt.Sprintf(".cpus = %d", s.CPUs)) |
| 252 | } |
| 253 | if s.MemoryGiB > 0 { |
| 254 | e = append(e, fmt.Sprintf(".memory = %q", strconv.Itoa(s.MemoryGiB)+"GiB")) |
| 255 | } |
| 256 | if s.DiskGiB > 0 { |
| 257 | e = append(e, fmt.Sprintf(".disk = %q", strconv.Itoa(s.DiskGiB)+"GiB")) |
| 258 | } |
| 259 | if s.NoContainerd { |
| 260 | e = append(e, ".containerd.user = false | .containerd.system = false") |
| 261 | } |
| 262 | if s.SSHLocalPort != nil { |
| 263 | e = append(e, fmt.Sprintf(".ssh.localPort = %d", *s.SSHLocalPort)) |
| 264 | } |
| 265 | if s.noEphemeralPorts { |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | e = append(e, fmt.Sprintf(`.portForwards = ((.portForwards // []) | map(select(((.guestPortRange // []) | join("-")) != "%d-%d"))) + [{"guestIP": "0.0.0.0", "guestIPMustBeZero": false, "guestPortRange": [%d, %d], "proto": "any", "ignore": true}]`, ephemeralPorts[0], ephemeralPorts[1], ephemeralPorts[0], ephemeralPorts[1])) |
| 271 | } |
| 272 | if s.MountType != nil { |
| 273 | if *s.MountType == "" { |
| 274 | e = append(e, "del(.mountType)") |
| 275 | } else { |
| 276 | e = append(e, fmt.Sprintf(".mountType = %q", *s.MountType)) |
| 277 | } |
| 278 | } |
| 279 | if s.Mounts != nil { |
| 280 | mounts := *s.Mounts |
| 281 | if mounts == nil { |
| 282 | mounts = []Mount{} |
| 283 | } |
| 284 | |
| 285 | |
| 286 | var j bytes.Buffer |
| 287 | enc := json.NewEncoder(&j) |
| 288 | enc.SetEscapeHTML(false) |
| 289 | if err := enc.Encode(mounts); err != nil { |
| 290 | return nil, err |
| 291 | } |
| 292 | e = append(e, ".mounts = "+strings.TrimSuffix(j.String(), "\n")) |
| 293 | } |
| 294 | return e, nil |
| 295 | } |
| 296 | |
| 297 | func (l *Lima) Create(ctx context.Context, name, template string, s Settings, log io.Writer) error { |
| 298 | if _, err := l.prepare(); err != nil { |
| 299 | return err |
| 300 | } |
| 301 | if _, err := store.Inspect(ctx, name); err == nil { |
| 302 | return fmt.Errorf("VM %s already exists", name) |
| 303 | } |
| 304 | return withLog(log, func() error { |
| 305 | tmpl, err := limatmpl.Read(ctx, name, template) |
| 306 | if err != nil { |
| 307 | return err |
| 308 | } |
| 309 | |
| 310 | if err := tmpl.Embed(ctx, true, false); err != nil { |
| 311 | return err |
| 312 | } |
| 313 | if err := tmpl.Unmarshal(); err != nil { |
| 314 | return err |
| 315 | } |
| 316 | e, err := exprs(s) |
| 317 | if err != nil { |
| 318 | return err |
| 319 | } |
| 320 | if path := os.Getenv(cage.ConfigEnv); path != "" { |
| 321 | cfg, err := cage.Load(path) |
| 322 | if err != nil { |
| 323 | return err |
| 324 | } |
| 325 | if template == "template:debian-13" { |
| 326 | images, err := cageDebianImages(tmpl.Config.Images) |
| 327 | if err != nil { |
| 328 | return err |
| 329 | } |
| 330 | e = append(e, ".images = "+string(images)) |
| 331 | |
| 332 | |
| 333 | e = append(e, `.provision += [{"mode": "dependency", "script": `+strconv.Quote(cage.DebianPrepareScript)+`}]`) |
| 334 | } |
| 335 | tz, _ := json.Marshal(cfg.Timezone) |
| 336 | e = append(e, ".propagateProxyEnv = false", `.env = {"http_proxy":"","https_proxy":"","ftp_proxy":"","no_proxy":"","HTTP_PROXY":"","HTTPS_PROXY":"","FTP_PROXY":"","NO_PROXY":"","ALL_PROXY":"","all_proxy":""}`, ".timezone = "+string(tz)) |
| 337 | if tmpl.Config.OS != nil && *tmpl.Config.OS == limatype.DARWIN { |
| 338 | e = append(e, `.user.name = "cageprovision"`, `.user.home = "/Users/cageprovision"`, `.user.comment = "Cage Provisioning"`, ".user.uid = 501", `.video.display = "offscreen"`) |
| 339 | } else { |
| 340 | e = append(e, `.user.name = "cage"`, `.user.home = "/home/cage"`, ".user.uid = 1000") |
| 341 | } |
| 342 | } |
| 343 | if len(e) > 0 { |
| 344 | if tmpl.Bytes, err = yqutil.EvaluateExpression(ctx, yqutil.Join(e), tmpl.Bytes); err != nil { |
| 345 | return err |
| 346 | } |
| 347 | } |
| 348 | _, err = instance.Create(ctx, name, tmpl.Bytes, false) |
| 349 | return err |
| 350 | }) |
| 351 | } |
| 352 | |
| 353 | |
| 354 | |
| 355 | func cageDebianImages(images []limatype.Image) ([]byte, error) { |
| 356 | const upstream = "https://cloud.debian.org/images/cloud/" |
| 357 | var candidates []limatype.Image |
| 358 | for _, img := range images { |
| 359 | suffix, ok := strings.CutPrefix(img.Location, upstream) |
| 360 | if !ok || img.Variant != "genericcloud" || img.Digest.Validate() != nil || img.Digest.Algorithm() != "sha512" { |
| 361 | continue |
| 362 | } |
| 363 | for _, base := range []string{upstream, "https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/"} { |
| 364 | candidate := img |
| 365 | candidate.Location = base + suffix |
| 366 | candidates = append(candidates, candidate) |
| 367 | } |
| 368 | } |
| 369 | if len(candidates) == 0 { |
| 370 | return nil, errors.New("embedded Debian template contains no pinned cloud image") |
| 371 | } |
| 372 | return json.Marshal(candidates) |
| 373 | } |
| 374 | |
| 375 | func (l *Lima) Clone(ctx context.Context, from, to string) error { |
| 376 | inst, err := l.inspect(ctx, from) |
| 377 | if err != nil { |
| 378 | return err |
| 379 | } |
| 380 | dir, err := dirnames.InstanceDir(to) |
| 381 | switch { |
| 382 | case err != nil && strings.Contains(err.Error(), "maximum length"): |
| 383 | return fmt.Errorf("%w: %v", ErrNameTooLong, err) |
| 384 | case err != nil: |
| 385 | return err |
| 386 | } |
| 387 | if sock := filepath.Join(dir, filenames.LongestSock); len(sock) >= osutil.UnixPathMax { |
| 388 | return fmt.Errorf("%w: its sockets in %s would need %d characters, at most %d", ErrNameTooLong, filepath.Dir(dir), len(sock), osutil.UnixPathMax-1) |
| 389 | } |
| 390 | _, err = instance.CloneOrRename(ctx, inst, to, false) |
| 391 | return err |
| 392 | } |
| 393 | |
| 394 | |
| 395 | |
| 396 | func (l *Lima) Edit(ctx context.Context, name string, s Settings) error { |
| 397 | inst, err := l.inspect(ctx, name) |
| 398 | if err != nil { |
| 399 | return err |
| 400 | } |
| 401 | if inst.Status == limatype.StatusRunning { |
| 402 | return fmt.Errorf("cannot edit the running VM %s", name) |
| 403 | } |
| 404 | e, err := exprs(s) |
| 405 | if err != nil || len(e) == 0 { |
| 406 | return err |
| 407 | } |
| 408 | path := filepath.Join(inst.Dir, filenames.LimaYAML) |
| 409 | old, err := os.ReadFile(path) |
| 410 | if err != nil { |
| 411 | return err |
| 412 | } |
| 413 | y, err := yqutil.EvaluateExpression(ctx, yqutil.Join(e), old) |
| 414 | if err != nil { |
| 415 | return err |
| 416 | } |
| 417 | if bytes.Equal(y, old) { |
| 418 | return nil |
| 419 | } |
| 420 | cfg, err := limayaml.LoadWithWarnings(ctx, y, path) |
| 421 | if err != nil { |
| 422 | return err |
| 423 | } |
| 424 | if s.Mounts != nil { |
| 425 | if err := sharesKept(*s.Mounts, cfg.Mounts); err != nil { |
| 426 | return err |
| 427 | } |
| 428 | } |
| 429 | if err := driverutil.ResolveVMType(cfg); err != nil { |
| 430 | return err |
| 431 | } |
| 432 | if err := limayaml.Validate(cfg, false); err != nil { |
| 433 | return err |
| 434 | } |
| 435 | inst.Config = cfg |
| 436 | drv, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) |
| 437 | if err != nil { |
| 438 | return err |
| 439 | } |
| 440 | defer server.Stop(inst.Dir, true) |
| 441 | if err := drv.Validate(ctx); err != nil { |
| 442 | return err |
| 443 | } |
| 444 | if err := limayaml.Validate(inst.Config, true); err != nil { |
| 445 | return err |
| 446 | } |
| 447 | if err := limayaml.ValidateAgainstLatestConfig(ctx, y, old); err != nil { |
| 448 | return err |
| 449 | } |
| 450 | |
| 451 | |
| 452 | f, err := os.CreateTemp(inst.Dir, filenames.LimaYAML+".*.tmp") |
| 453 | if err != nil { |
| 454 | return err |
| 455 | } |
| 456 | tmp := f.Name() |
| 457 | _, err = f.Write(y) |
| 458 | if cerr := f.Close(); err == nil { |
| 459 | err = cerr |
| 460 | } |
| 461 | if err == nil { |
| 462 | err = os.Chmod(tmp, 0o644) |
| 463 | } |
| 464 | if err == nil { |
| 465 | err = os.Rename(tmp, path) |
| 466 | } |
| 467 | if err != nil { |
| 468 | os.Remove(tmp) |
| 469 | } |
| 470 | return err |
| 471 | } |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | func sharesKept(want []Mount, got []limatype.Mount) error { |
| 477 | if len(got) != len(want) { |
| 478 | return fmt.Errorf("%w: Lima reads %d shares, not %d", ErrUnmountable, len(got), len(want)) |
| 479 | } |
| 480 | for i, m := range want { |
| 481 | mp := m.MountPoint |
| 482 | if mp == "" { |
| 483 | mp = m.Location |
| 484 | } |
| 485 | |
| 486 | if paths.Host(got[i].Location) != m.Location || got[i].MountPoint == nil || *got[i].MountPoint != mp { |
| 487 | return fmt.Errorf("%w: Lima reads %q as another path", ErrUnmountable, m.Location) |
| 488 | } |
| 489 | if m.SSHFS != nil && !slices.Equal(got[i].SSHFS.ReadonlyNames, m.SSHFS.ReadonlyNames) { |
| 490 | return fmt.Errorf("%w: Lima reads the read-only names of %q otherwise", ErrUnmountable, m.Location) |
| 491 | } |
| 492 | } |
| 493 | return nil |
| 494 | } |
| 495 | |
| 496 | |
| 497 | var logMu sync.Mutex |
| 498 | |
| 499 | |
| 500 | func withLog(log io.Writer, fn func() error) error { |
| 501 | logMu.Lock() |
| 502 | defer logMu.Unlock() |
| 503 | saved := logrus.StandardLogger().Out |
| 504 | logrus.SetOutput(log) |
| 505 | defer logrus.SetOutput(saved) |
| 506 | return fn() |
| 507 | } |
| 508 | |
| 509 | func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error { |
| 510 | share, err := l.prepare() |
| 511 | if err != nil { |
| 512 | return err |
| 513 | } |
| 514 | inst, err := l.inspect(ctx, name) |
| 515 | if err != nil { |
| 516 | return err |
| 517 | } |
| 518 | if inst.Status == limatype.StatusRunning { |
| 519 | return nil |
| 520 | } |
| 521 | if inst.Config == nil { |
| 522 | return errors.Join(inst.Errors...) |
| 523 | } |
| 524 | |
| 525 | |
| 526 | settings := Settings{noEphemeralPorts: true} |
| 527 | if configPath := os.Getenv(cage.ConfigEnv); configPath != "" { |
| 528 | allocation, loadErr := cage.LoadResourceAllocation(configPath) |
| 529 | if loadErr != nil { |
| 530 | return loadErr |
| 531 | } |
| 532 | settings.MemoryGiB, settings.CPUs, err = allocation.Limits() |
| 533 | if *inst.Config.OS == limatype.DARWIN && err == nil { |
| 534 | cfg, loadErr := cage.Load(configPath) |
| 535 | if loadErr != nil { |
| 536 | return loadErr |
| 537 | } |
| 538 | settings.macOSTimezone = cfg.Timezone |
| 539 | requirements, requirementErr := ReadMacOSResourceRequirements(inst.Dir) |
| 540 | if requirementErr != nil { |
| 541 | return requirementErr |
| 542 | } |
| 543 | settings.MemoryGiB, settings.CPUs, err = requirements.Limits(allocation) |
| 544 | if err == nil { |
| 545 | err = saveMacOSResourceRequirements(inst.Dir, requirements) |
| 546 | } |
| 547 | } |
| 548 | if err != nil { |
| 549 | return err |
| 550 | } |
| 551 | } |
| 552 | if err := l.Edit(ctx, name, settings); err != nil { |
| 553 | return err |
| 554 | } |
| 555 | if inst, err = l.inspect(ctx, name); err != nil { |
| 556 | return err |
| 557 | } |
| 558 | if err := Confined(fromLima(inst)); err != nil { |
| 559 | return err |
| 560 | } |
| 561 | if err := NetworkConfined(inst.Config); err != nil { |
| 562 | return err |
| 563 | } |
| 564 | var guestAgent string |
| 565 | |
| 566 | |
| 567 | if *inst.Config.OS == limatype.DARWIN || (*inst.Config.OS == limatype.LINUX && !*inst.Config.Plain) { |
| 568 | guestAgent, err = share.GuestAgent(*inst.Config.OS, *inst.Config.Arch) |
| 569 | if err != nil { |
| 570 | return err |
| 571 | } |
| 572 | } |
| 573 | return withLog(log, func() error { |
| 574 | if err := reconcile.Reconcile(ctx, name); err != nil { |
| 575 | return err |
| 576 | } |
| 577 | started := time.Now() |
| 578 | return vmStartError(instance.StartWithPaths(ctx, inst, false, false, "", guestAgent), inst.Dir, started) |
| 579 | }) |
| 580 | } |
| 581 | |
| 582 | func (l *Lima) Stop(ctx context.Context, name string) error { |
| 583 | inst, err := l.inspect(ctx, name) |
| 584 | if err != nil { |
| 585 | return err |
| 586 | } |
| 587 | switch { |
| 588 | case inst.Status == limatype.StatusRunning: |
| 589 | return withLog(io.Discard, func() error { |
| 590 | return errors.Join(stopInstance(ctx, inst), reconcile.Reconcile(ctx, "")) |
| 591 | }) |
| 592 | case fromLima(inst).Orphaned: |
| 593 | return withLog(io.Discard, func() error { |
| 594 | if err := stopOrphanedInstance(ctx, inst); err != nil { |
| 595 | return err |
| 596 | } |
| 597 | return reconcile.Reconcile(ctx, "") |
| 598 | }) |
| 599 | } |
| 600 | return nil |
| 601 | } |
| 602 | |
| 603 | func (l *Lima) Delete(ctx context.Context, name string) error { |
| 604 | inst, err := l.inspect(ctx, name) |
| 605 | if err != nil { |
| 606 | return err |
| 607 | } |
| 608 | return withLog(io.Discard, func() error { |
| 609 | if inst.Status == limatype.StatusRunning { |
| 610 | if err := stopInstance(ctx, inst); err != nil { |
| 611 | return err |
| 612 | } |
| 613 | } else if fromLima(inst).Orphaned { |
| 614 | if err := stopOrphanedInstance(ctx, inst); err != nil { |
| 615 | return err |
| 616 | } |
| 617 | } |
| 618 | return errors.Join(instance.Delete(ctx, inst, true), reconcile.Reconcile(ctx, "")) |
| 619 | }) |
| 620 | } |
| 621 | |
| 622 | func isTerminal(v any) bool { |
| 623 | f, ok := v.(*os.File) |
| 624 | return ok && (isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd())) |
| 625 | } |
| 626 | |
| 627 | |
| 628 | |
| 629 | func (l *Lima) Shell(ctx context.Context, name string, o ShellOpts) (int, error) { |
| 630 | inst, err := l.inspect(ctx, name) |
| 631 | if err != nil { |
| 632 | return 0, err |
| 633 | } |
| 634 | if inst.Status != limatype.StatusRunning || inst.Config == nil { |
| 635 | return 0, fmt.Errorf("VM %s is not running", name) |
| 636 | } |
| 637 | |
| 638 | cd := "false" |
| 639 | if o.Workdir != "" { |
| 640 | cd = "cd " + shellescape.Quote(o.Workdir) + " || exit 1" |
| 641 | } |
| 642 | shell := `"$SHELL"` |
| 643 | if inst.Config.User.Shell != nil { |
| 644 | shell = shellescape.Quote(*inst.Config.User.Shell) |
| 645 | } |
| 646 | script := cd + " ; exec " + shell + " -l" |
| 647 | if len(o.Args) > 0 { |
| 648 | q := make([]string, len(o.Args)) |
| 649 | for i, a := range o.Args { |
| 650 | q[i] = shellescape.Quote(a) |
| 651 | } |
| 652 | script += " -c " + shellescape.Quote(strings.Join(q, " ")) |
| 653 | } |
| 654 | sshExe, err := sshutil.NewSSHExe() |
| 655 | if err != nil { |
| 656 | return 0, err |
| 657 | } |
| 658 | c := inst.Config |
| 659 | opts, err := sshutil.SSHOpts(ctx, sshExe, inst.Dir, *c.User.Name, *c.SSH.LoadDotSSHPubKeys, |
| 660 | *c.SSH.ForwardAgent, *c.SSH.ForwardX11, *c.SSH.ForwardX11Trusted) |
| 661 | if err != nil { |
| 662 | return 0, err |
| 663 | } |
| 664 | if runtime.GOOS == "windows" { |
| 665 | |
| 666 | opts = sshutil.SSHOptsRemovingControlPath(opts) |
| 667 | } |
| 668 | args := append(append([]string{}, sshExe.Args...), sshutil.SSHArgsFromOpts(opts)...) |
| 669 | |
| 670 | |
| 671 | if isTerminal(o.Stdout) || o.Interactive && isTerminal(o.Stdin) { |
| 672 | args = append(args, "-t") |
| 673 | } |
| 674 | if _, ok := os.LookupEnv("COLORTERM"); ok { |
| 675 | args = append(args, "-o", "SendEnv=COLORTERM") |
| 676 | } |
| 677 | logLevel := "ERROR" |
| 678 | if sshutil.DetectOpenSSHVersion(ctx, sshExe).LessThan(*semver.New("8.9.0")) { |
| 679 | logLevel = "QUIET" |
| 680 | } |
| 681 | args = append(args, "-o", "LogLevel="+logLevel, "-p", strconv.Itoa(inst.SSHLocalPort), inst.SSHAddress, "--", script) |
| 682 | cmd := exec.CommandContext(ctx, sshExe.Exe, args...) |
| 683 | cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr |
| 684 | err = cmd.Run() |
| 685 | var ee *exec.ExitError |
| 686 | if errors.As(err, &ee) { |
| 687 | return ee.ExitCode(), nil |
| 688 | } |
| 689 | if err != nil { |
| 690 | return 0, err |
| 691 | } |
| 692 | return 0, nil |
| 693 | } |