| 1 | |
| 2 | |
| 3 | |
| 4 | package krunkit |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "embed" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "net" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "path/filepath" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "syscall" |
| 18 | "time" |
| 19 | |
| 20 | "github.com/coreos/go-semver/semver" |
| 21 | "github.com/lima-vm/go-qcow2reader/image/raw" |
| 22 | "github.com/sirupsen/logrus" |
| 23 | |
| 24 | "github.com/lima-vm/lima/v2/pkg/driver" |
| 25 | "github.com/lima-vm/lima/v2/pkg/driverutil" |
| 26 | "github.com/lima-vm/lima/v2/pkg/executil" |
| 27 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 28 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 29 | "github.com/lima-vm/lima/v2/pkg/networks/usernet" |
| 30 | "github.com/lima-vm/lima/v2/pkg/osutil" |
| 31 | "github.com/lima-vm/lima/v2/pkg/reflectutil" |
| 32 | "github.com/lima-vm/lima/v2/pkg/store" |
| 33 | ) |
| 34 | |
| 35 | const ( |
| 36 | vSockPort = 2222 |
| 37 | sshVsockSock = "ssh-vsock.sock" |
| 38 | ) |
| 39 | |
| 40 | type LimaKrunkitDriver struct { |
| 41 | Instance *limatype.Instance |
| 42 | SSHLocalPort int |
| 43 | |
| 44 | usernetClient *usernet.Client |
| 45 | stopUsernet context.CancelFunc |
| 46 | krunkitCmd *exec.Cmd |
| 47 | krunkitWaitCh chan error |
| 48 | } |
| 49 | |
| 50 | var ( |
| 51 | _ driver.Driver = (*LimaKrunkitDriver)(nil) |
| 52 | vmType limatype.VMType = "krunkit" |
| 53 | ) |
| 54 | |
| 55 | func New() *LimaKrunkitDriver { |
| 56 | return &LimaKrunkitDriver{} |
| 57 | } |
| 58 | |
| 59 | func (l *LimaKrunkitDriver) Configure(_ context.Context, inst *limatype.Instance) (*driver.ConfiguredDriver, error) { |
| 60 | if err := fillConfig(inst.Config); err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | |
| 64 | l.Instance = inst |
| 65 | l.SSHLocalPort = inst.SSHLocalPort |
| 66 | |
| 67 | return &driver.ConfiguredDriver{ |
| 68 | Driver: l, |
| 69 | }, nil |
| 70 | } |
| 71 | |
| 72 | func (l *LimaKrunkitDriver) CreateDisk(ctx context.Context) error { |
| 73 | |
| 74 | return driverutil.EnsureDisk(ctx, l.Instance.Dir, *l.Instance.Config.Disk, raw.Type) |
| 75 | } |
| 76 | |
| 77 | func (l *LimaKrunkitDriver) Start(ctx context.Context) (chan error, error) { |
| 78 | if err := l.cleanupStaleSockets(); err != nil { |
| 79 | logrus.WithError(err).Warn("Failed to clean up stale krunkit sockets before start") |
| 80 | } |
| 81 | |
| 82 | var err error |
| 83 | l.usernetClient, l.stopUsernet, err = startUsernet(ctx, l.Instance) |
| 84 | if err != nil { |
| 85 | return nil, fmt.Errorf("failed to start usernet: %w", err) |
| 86 | } |
| 87 | |
| 88 | krunkitCmd, err := Cmdline(l.Instance) |
| 89 | if err != nil { |
| 90 | return nil, fmt.Errorf("failed to construct krunkit command line: %w", err) |
| 91 | } |
| 92 | |
| 93 | krunkitCmd.SysProcAttr = executil.BackgroundSysProcAttr |
| 94 | |
| 95 | logPath := filepath.Join(l.Instance.Dir, "krunkit.log") |
| 96 | logfile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) |
| 97 | if err != nil { |
| 98 | return nil, fmt.Errorf("failed to open krunkit logfile: %w", err) |
| 99 | } |
| 100 | krunkitCmd.Stderr = logfile |
| 101 | |
| 102 | logrus.Infof("Starting krun VM (hint: to watch the progress, see %#q)", logPath) |
| 103 | logrus.Infof("krunkitCmd.Args: %v", krunkitCmd.Args) |
| 104 | |
| 105 | if err := krunkitCmd.Start(); err != nil { |
| 106 | logfile.Close() |
| 107 | return nil, errors.New("failed to start krunkitCmd") |
| 108 | } |
| 109 | |
| 110 | pidPath := filepath.Join(l.Instance.Dir, filenames.PIDFile(*l.Instance.Config.VMType)) |
| 111 | if err := store.WritePIDFile(pidPath, krunkitCmd.Process.Pid); err != nil { |
| 112 | logrus.WithError(err).Warn("Failed to write PID file") |
| 113 | } |
| 114 | |
| 115 | l.krunkitCmd = krunkitCmd |
| 116 | l.krunkitWaitCh = make(chan error, 1) |
| 117 | go func() { |
| 118 | defer func() { |
| 119 | logfile.Close() |
| 120 | os.RemoveAll(pidPath) |
| 121 | close(l.krunkitWaitCh) |
| 122 | }() |
| 123 | l.krunkitWaitCh <- krunkitCmd.Wait() |
| 124 | }() |
| 125 | |
| 126 | usernetSSHLocalPort := l.SSHLocalPort |
| 127 | useSSHOverVsock := l.Instance.Config.SSH.OverVsock != nil && *l.Instance.Config.SSH.OverVsock |
| 128 | |
| 129 | if !useSSHOverVsock { |
| 130 | logrus.Info("ssh.overVsock is false, using usernet forwarder for SSH") |
| 131 | } else if err := l.usernetClient.WaitOpeningSSHPort(ctx, l.Instance); err == nil { |
| 132 | hostAddress := net.JoinHostPort(l.Instance.SSHAddress, strconv.Itoa(usernetSSHLocalPort)) |
| 133 | sshVsockPath := filepath.Join(l.Instance.Dir, sshVsockSock) |
| 134 | if err := startVsockForwarder(ctx, sshVsockPath, hostAddress); err == nil { |
| 135 | logrus.Infof("Detected SSH server is listening on the vsock port; changed %s to proxy for the vsock port", hostAddress) |
| 136 | usernetSSHLocalPort = 0 |
| 137 | } else { |
| 138 | logrus.WithError(err).WithField("hostAddress", hostAddress). |
| 139 | Debugf("Failed to start vsock forwarder (systemd is older than v256?)") |
| 140 | logrus.Info("SSH server does not seem to be running on vsock port, using usernet forwarder") |
| 141 | } |
| 142 | } else { |
| 143 | logrus.WithError(err).Warn("Failed to wait for the guest SSH server to become available, falling back to usernet forwarder") |
| 144 | } |
| 145 | |
| 146 | err = l.usernetClient.ConfigureDriver(ctx, l.Instance, usernetSSHLocalPort) |
| 147 | if err != nil { |
| 148 | l.krunkitWaitCh <- fmt.Errorf("failed to configure usernet: %w", err) |
| 149 | } |
| 150 | |
| 151 | return l.krunkitWaitCh, nil |
| 152 | } |
| 153 | |
| 154 | func (l *LimaKrunkitDriver) Stop(_ context.Context) error { |
| 155 | if l.krunkitCmd == nil { |
| 156 | return nil |
| 157 | } |
| 158 | |
| 159 | if err := l.krunkitCmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 160 | logrus.WithError(err).Warn("Failed to send interrupt signal") |
| 161 | } |
| 162 | |
| 163 | go func() { |
| 164 | if l.usernetClient != nil { |
| 165 | _ = l.usernetClient.UnExposeSSH(l.Instance.SSHLocalPort) |
| 166 | } |
| 167 | if l.stopUsernet != nil { |
| 168 | l.stopUsernet() |
| 169 | } |
| 170 | }() |
| 171 | |
| 172 | timeout := time.After(30 * time.Second) |
| 173 | select { |
| 174 | case <-l.krunkitWaitCh: |
| 175 | return nil |
| 176 | case <-timeout: |
| 177 | if err := l.krunkitCmd.Process.Kill(); err != nil { |
| 178 | return err |
| 179 | } |
| 180 | |
| 181 | <-l.krunkitWaitCh |
| 182 | return nil |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | func (l *LimaKrunkitDriver) Validate(_ context.Context) error { |
| 187 | return validateConfig(l.Instance.Config) |
| 188 | } |
| 189 | |
| 190 | func checkKrunkitVersion() error { |
| 191 | cmd := exec.CommandContext(context.Background(), vmType, "--version") |
| 192 | output, err := cmd.Output() |
| 193 | if err != nil { |
| 194 | return fmt.Errorf("failed to check krunkit version: %w", err) |
| 195 | } |
| 196 | versionStr := strings.TrimSpace(string(output)) |
| 197 | versionStr = strings.TrimPrefix(versionStr, "krunkit ") |
| 198 | |
| 199 | minVersion := semver.New("1.2.1") |
| 200 | currentVersion, err := semver.NewVersion(versionStr) |
| 201 | if err != nil { |
| 202 | logrus.WithError(err).Warnf("Failed to parse krunkit version %#q, skipping version check", versionStr) |
| 203 | return nil |
| 204 | } |
| 205 | |
| 206 | if currentVersion.LessThan(*minVersion) { |
| 207 | return fmt.Errorf("krunkit version %#q is older than required minimum 1.2.1 (needed for vsock forwarder feature)", currentVersion) |
| 208 | } |
| 209 | |
| 210 | return nil |
| 211 | } |
| 212 | |
| 213 | func validateConfig(cfg *limatype.LimaYAML) error { |
| 214 | if cfg == nil { |
| 215 | return errors.New("configuration is nil") |
| 216 | } |
| 217 | macOSProductVersion, err := osutil.ProductVersion() |
| 218 | if err != nil { |
| 219 | return err |
| 220 | } |
| 221 | if macOSProductVersion.LessThan(*semver.New("13.0.0")) { |
| 222 | return errors.New("krunkit driver requires macOS 13 or higher to run") |
| 223 | } |
| 224 | if cfg.Arch != nil && !limatype.IsNativeArch(*cfg.Arch) { |
| 225 | return fmt.Errorf("unsupported arch: %#q (krunkit requires native arch)", *cfg.Arch) |
| 226 | } |
| 227 | if _, err := exec.LookPath(vmType); err != nil { |
| 228 | return errors.New("krunkit CLI not found in PATH. Install it via:\nbrew tap slp/krun\nbrew install krunkit") |
| 229 | } |
| 230 | |
| 231 | if err := checkKrunkitVersion(); err != nil { |
| 232 | return err |
| 233 | } |
| 234 | |
| 235 | if cfg.MountType != nil && (*cfg.MountType != limatype.VIRTIOFS && *cfg.MountType != limatype.REVSSHFS) { |
| 236 | return fmt.Errorf("field `mountType` must be %#q or %#q for krunkit driver, got %#q", limatype.VIRTIOFS, limatype.REVSSHFS, *cfg.MountType) |
| 237 | } |
| 238 | |
| 239 | if cfg.TPM != nil && *cfg.TPM { |
| 240 | return errors.New("field `tpm` is not supported in krunkit driver") |
| 241 | } |
| 242 | |
| 243 | if cfg.NestedVirtualization != nil && *cfg.NestedVirtualization { |
| 244 | if macOSProductVersion.LessThan(*semver.New("15.0.0")) { |
| 245 | return errors.New("nested virtualization requires macOS 15 or newer") |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | if cfg.OS != nil && *cfg.OS == limatype.WINDOWS { |
| 250 | return errors.New("currently Windows guest OS is only supported on QEMU") |
| 251 | } |
| 252 | |
| 253 | audio := cfg.Audio |
| 254 | if audio.Device != nil && *audio.Device == "" { |
| 255 | audio.Device = nil |
| 256 | } |
| 257 | if audio.Interface != nil && *audio.Interface == "" { |
| 258 | audio.Interface = nil |
| 259 | } |
| 260 | if audio.Microphone != nil && !*audio.Microphone { |
| 261 | audio.Microphone = nil |
| 262 | } |
| 263 | if unknown := reflectutil.UnknownNonEmptyFields(audio); len(unknown) > 0 { |
| 264 | logrus.Warnf("vmType %s: ignoring audio: %+v", *cfg.VMType, unknown) |
| 265 | } |
| 266 | |
| 267 | return nil |
| 268 | } |
| 269 | |
| 270 | func isFedoraConfigured(cfg *limatype.LimaYAML) bool { |
| 271 | for _, b := range cfg.Base { |
| 272 | if strings.Contains(strings.ToLower(b.URL), "fedora") { |
| 273 | return true |
| 274 | } |
| 275 | } |
| 276 | for _, img := range cfg.Images { |
| 277 | if strings.Contains(strings.ToLower(img.Location), "fedora") { |
| 278 | return true |
| 279 | } |
| 280 | } |
| 281 | return false |
| 282 | } |
| 283 | |
| 284 | func fillConfig(cfg *limatype.LimaYAML) error { |
| 285 | if cfg.MountType == nil { |
| 286 | cfg.MountType = new(limatype.VIRTIOFS) |
| 287 | } |
| 288 | if cfg.Arch == nil { |
| 289 | cfg.Arch = new(limatype.AARCH64) |
| 290 | } |
| 291 | cfg.VMType = new(vmType) |
| 292 | if cfg.SSH.OverVsock == nil { |
| 293 | |
| 294 | |
| 295 | cfg.SSH.OverVsock = new(false) |
| 296 | } else if *cfg.SSH.OverVsock { |
| 297 | logrus.Warn("ssh.overVsock is known not to work since Fedora 44: https://github.com/lima-vm/lima/issues/5085") |
| 298 | } |
| 299 | |
| 300 | return validateConfig(cfg) |
| 301 | } |
| 302 | |
| 303 | |
| 304 | var bootLinuxFS embed.FS |
| 305 | |
| 306 | func (l *LimaKrunkitDriver) BootScripts(_ context.Context) (map[string][]byte, error) { |
| 307 | scripts := make(map[string][]byte) |
| 308 | |
| 309 | entries, err := bootLinuxFS.ReadDir("boot.Linux") |
| 310 | if err == nil && !isFedoraConfigured(l.Instance.Config) { |
| 311 | for _, entry := range entries { |
| 312 | if entry.IsDir() { |
| 313 | continue |
| 314 | } |
| 315 | entryPath := "boot.Linux/" + entry.Name() |
| 316 | |
| 317 | content, err := bootLinuxFS.ReadFile(entryPath) |
| 318 | if err != nil { |
| 319 | return nil, err |
| 320 | } |
| 321 | |
| 322 | scripts[entryPath] = content |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | |
| 327 | if isFedoraConfigured(l.Instance.Config) { |
| 328 | scripts["boot.Linux/00-reboot-if-required.sh"] = []byte(`#!/bin/sh |
| 329 | set -eu |
| 330 | exit 0 |
| 331 | `) |
| 332 | } |
| 333 | |
| 334 | return scripts, nil |
| 335 | } |
| 336 | |
| 337 | func (l *LimaKrunkitDriver) Create(_ context.Context) error { |
| 338 | return nil |
| 339 | } |
| 340 | |
| 341 | func (l *LimaKrunkitDriver) Info(_ context.Context) driver.Info { |
| 342 | var info driver.Info |
| 343 | info.Name = vmType |
| 344 | info.VsockPort = vSockPort |
| 345 | if l.Instance != nil && l.Instance.Dir != "" { |
| 346 | info.InstanceDir = l.Instance.Dir |
| 347 | } |
| 348 | |
| 349 | info.Features = driver.DriverFeatures{ |
| 350 | DynamicSSHAddress: false, |
| 351 | SkipSocketForwarding: false, |
| 352 | CanRunGUI: false, |
| 353 | SupportedImageFormats: []string{string(raw.Type)}, |
| 354 | } |
| 355 | return info |
| 356 | } |
| 357 | |
| 358 | func (l *LimaKrunkitDriver) SSHAddress(_ context.Context) (string, error) { |
| 359 | return "127.0.0.1", nil |
| 360 | } |
| 361 | |
| 362 | func (l *LimaKrunkitDriver) ForwardGuestAgent(_ context.Context) bool { |
| 363 | return false |
| 364 | } |
| 365 | |
| 366 | func (l *LimaKrunkitDriver) Delete(_ context.Context) error { |
| 367 | return nil |
| 368 | } |
| 369 | |
| 370 | func (l *LimaKrunkitDriver) InspectStatus(_ context.Context, _ *limatype.Instance) string { |
| 371 | return "" |
| 372 | } |
| 373 | |
| 374 | func (l *LimaKrunkitDriver) RunGUI(_ context.Context) error { |
| 375 | return nil |
| 376 | } |
| 377 | |
| 378 | func (l *LimaKrunkitDriver) ChangeDisplayPassword(_ context.Context, _ string) error { |
| 379 | return errUnimplemented |
| 380 | } |
| 381 | |
| 382 | func (l *LimaKrunkitDriver) DisplayConnection(_ context.Context) (string, error) { |
| 383 | return "", errUnimplemented |
| 384 | } |
| 385 | |
| 386 | func (l *LimaKrunkitDriver) CreateSnapshot(_ context.Context, _ string) error { |
| 387 | return errUnimplemented |
| 388 | } |
| 389 | |
| 390 | func (l *LimaKrunkitDriver) ApplySnapshot(_ context.Context, _ string) error { |
| 391 | return errUnimplemented |
| 392 | } |
| 393 | |
| 394 | func (l *LimaKrunkitDriver) DeleteSnapshot(_ context.Context, _ string) error { |
| 395 | return errUnimplemented |
| 396 | } |
| 397 | |
| 398 | func (l *LimaKrunkitDriver) ListSnapshots(_ context.Context) (string, error) { |
| 399 | return "", errUnimplemented |
| 400 | } |
| 401 | |
| 402 | func (l *LimaKrunkitDriver) Register(_ context.Context) error { |
| 403 | return nil |
| 404 | } |
| 405 | |
| 406 | func (l *LimaKrunkitDriver) Unregister(_ context.Context) error { |
| 407 | return nil |
| 408 | } |
| 409 | |
| 410 | func (l *LimaKrunkitDriver) GuestAgentConn(ctx context.Context) (net.Conn, string, error) { |
| 411 | var d net.Dialer |
| 412 | conn, err := d.DialContext(ctx, "unix", filepath.Join(l.Instance.Dir, filenames.GuestAgentSock)) |
| 413 | return conn, "unix", err |
| 414 | } |
| 415 | |
| 416 | func (l *LimaKrunkitDriver) AdditionalSetupForSSH(_ context.Context) error { |
| 417 | return nil |
| 418 | } |
| 419 | |
| 420 | |
| 421 | |
| 422 | func (l *LimaKrunkitDriver) cleanupStaleSockets() error { |
| 423 | if l.Instance == nil || l.Instance.Dir == "" { |
| 424 | return nil |
| 425 | } |
| 426 | |
| 427 | var errs []error |
| 428 | for _, sock := range []string{ |
| 429 | filepath.Join(l.Instance.Dir, filenames.GuestAgentSock), |
| 430 | filepath.Join(l.Instance.Dir, sshVsockSock), |
| 431 | } { |
| 432 | if err := os.RemoveAll(sock); err != nil { |
| 433 | errs = append(errs, fmt.Errorf("failed to remove socket %#q: %w", sock, err)) |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | return errors.Join(errs...) |
| 438 | } |