| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | "runtime" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | |
| 18 | "al.essio.dev/pkg/shellescape" |
| 19 | "github.com/coreos/go-semver/semver" |
| 20 | "github.com/lima-vm/sshocker/pkg/ssh" |
| 21 | "github.com/mattn/go-isatty" |
| 22 | "github.com/sirupsen/logrus" |
| 23 | "github.com/spf13/cobra" |
| 24 | |
| 25 | "github.com/lima-vm/lima/v2/pkg/autostart" |
| 26 | "github.com/lima-vm/lima/v2/pkg/copytool" |
| 27 | "github.com/lima-vm/lima/v2/pkg/envutil" |
| 28 | "github.com/lima-vm/lima/v2/pkg/fsutil" |
| 29 | "github.com/lima-vm/lima/v2/pkg/instance" |
| 30 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 31 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 32 | "github.com/lima-vm/lima/v2/pkg/localpathutil" |
| 33 | "github.com/lima-vm/lima/v2/pkg/networks/reconcile" |
| 34 | "github.com/lima-vm/lima/v2/pkg/sshutil" |
| 35 | "github.com/lima-vm/lima/v2/pkg/store" |
| 36 | "github.com/lima-vm/lima/v2/pkg/uiutil" |
| 37 | ) |
| 38 | |
| 39 | const shellHelp = `Execute shell in Lima |
| 40 | |
| 41 | lima command is provided as an alias for limactl shell $LIMA_INSTANCE. $LIMA_INSTANCE defaults to "` + DefaultInstanceName + `". |
| 42 | |
| 43 | By default, the first 'ssh' executable found in the host's PATH is used to connect to the Lima instance. |
| 44 | A custom ssh alias can be used instead by setting the $` + sshutil.EnvShellSSH + ` environment variable. |
| 45 | |
| 46 | Environment Variables: |
| 47 | --preserve-env: Propagates host environment variables to the guest instance. |
| 48 | Use LIMA_SHELLENV_BLOCK to specify variables to block (prefix with + to extend the default blocklist). |
| 49 | Use LIMA_SHELLENV_ALLOW to exempt specific variables from the blocklist. |
| 50 | |
| 51 | Hint: try --debug to show the detailed logs, if it seems hanging (mostly due to some SSH issue). |
| 52 | ` |
| 53 | |
| 54 | func newShellCommand() *cobra.Command { |
| 55 | shellCmd := &cobra.Command{ |
| 56 | Use: "shell [flags] INSTANCE [COMMAND...]", |
| 57 | SuggestFor: []string{"ssh"}, |
| 58 | Short: "Execute shell in Lima", |
| 59 | Long: shellHelp, |
| 60 | Args: WrapArgsError(cobra.ArbitraryArgs), |
| 61 | RunE: shellAction, |
| 62 | ValidArgsFunction: shellBashComplete, |
| 63 | SilenceErrors: true, |
| 64 | GroupID: basicCommand, |
| 65 | } |
| 66 | |
| 67 | shellCmd.Flags().SetInterspersed(false) |
| 68 | |
| 69 | shellCmd.Flags().String("instance", "", "Instance name (used by the lima wrapper script)") |
| 70 | _ = shellCmd.Flags().MarkHidden("instance") |
| 71 | shellCmd.Flags().String("shell", "", "Shell interpreter, e.g. /bin/bash") |
| 72 | shellCmd.Flags().String("workdir", "", "Working directory") |
| 73 | shellCmd.Flags().Bool("reconnect", false, "Reconnect to the SSH session") |
| 74 | shellCmd.Flags().Bool("preserve-env", false, "Propagate environment variables to the shell") |
| 75 | shellCmd.Flags().Bool("start", false, "Start the instance if it is not already running") |
| 76 | shellCmd.Flags().String("sync", "", "Copy a host directory to the guest and vice-versa upon exit") |
| 77 | |
| 78 | return shellCmd |
| 79 | } |
| 80 | |
| 81 | const ( |
| 82 | rsyncMinimumSrcDirDepth = 4 |
| 83 | colorGray = "\033[0;90m" |
| 84 | colorNone = "\033[0m" |
| 85 | ) |
| 86 | |
| 87 | func shellAction(cmd *cobra.Command, args []string) error { |
| 88 | ctx := cmd.Context() |
| 89 | flags := cmd.Flags() |
| 90 | tty, err := flags.GetBool("tty") |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | |
| 95 | |
| 96 | |
| 97 | instName, err := flags.GetString("instance") |
| 98 | if err != nil { |
| 99 | return err |
| 100 | } |
| 101 | if instName != "" { |
| 102 | |
| 103 | args = append([]string{instName}, args...) |
| 104 | } else { |
| 105 | if len(args) == 0 { |
| 106 | return errors.New("requires instance name as first argument") |
| 107 | } |
| 108 | |
| 109 | newArg := []string{} |
| 110 | if len(args) >= 2 && args[1] == "--" { |
| 111 | newArg = append(newArg, args[:1]...) |
| 112 | newArg = append(newArg, args[2:]...) |
| 113 | args = newArg |
| 114 | } |
| 115 | instName = args[0] |
| 116 | } |
| 117 | |
| 118 | if len(args) >= 2 { |
| 119 | switch args[1] { |
| 120 | case "create", "start", "delete", "shell": |
| 121 | |
| 122 | logrus.Warnf("Perhaps you meant `limactl %s`?", strings.Join(args[1:], " ")) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | inst, err := store.Inspect(ctx, instName) |
| 127 | if err != nil { |
| 128 | if errors.Is(err, os.ErrNotExist) { |
| 129 | return fmt.Errorf("instance %#q does not exist, run `limactl create %s` to create a new instance", instName, instName) |
| 130 | } |
| 131 | return err |
| 132 | } |
| 133 | if len(inst.Errors) > 0 { |
| 134 | logrus.WithError(errors.Join(inst.Errors...)).Errorf("Instance %#q has configuration errors", instName) |
| 135 | } |
| 136 | if inst.Config == nil { |
| 137 | return fmt.Errorf("instance %#q has no configuration", instName) |
| 138 | } |
| 139 | if inst.Status == limatype.StatusStopped { |
| 140 | startNow, err := flags.GetBool("start") |
| 141 | if err != nil { |
| 142 | return err |
| 143 | } |
| 144 | |
| 145 | if tty && !flags.Changed("start") { |
| 146 | startNow, err = askWhetherToStart(cmd) |
| 147 | if err != nil { |
| 148 | return err |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | if !startNow { |
| 153 | return fmt.Errorf("instance %#q is stopped, run `limactl start %s` to start the instance", instName, instName) |
| 154 | } |
| 155 | |
| 156 | |
| 157 | if registered, err := autostart.IsRegistered(ctx, inst); err != nil && !errors.Is(err, autostart.ErrNotSupported) { |
| 158 | return fmt.Errorf("failed to check if the autostart entry for instance %#q is registered: %w", inst.Name, err) |
| 159 | } else if !registered { |
| 160 | err = reconcile.Reconcile(ctx, inst.Name) |
| 161 | if err != nil { |
| 162 | return err |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | err = instance.Start(instance.WithLaunchingShell(ctx), inst, false, false) |
| 167 | if err != nil { |
| 168 | return err |
| 169 | } |
| 170 | |
| 171 | inst, err = store.Inspect(ctx, instName) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | restart, err := cmd.Flags().GetBool("reconnect") |
| 178 | if err != nil { |
| 179 | return err |
| 180 | } |
| 181 | if restart && sshutil.IsControlMasterExisting(inst.Dir) { |
| 182 | logrus.Infof("Exiting ssh session for the instance %#q", instName) |
| 183 | |
| 184 | sshConfig := &ssh.SSHConfig{ |
| 185 | ConfigFile: inst.SSHConfigFile, |
| 186 | Persist: false, |
| 187 | AdditionalArgs: []string{}, |
| 188 | } |
| 189 | |
| 190 | if err := ssh.ExitMaster(inst.Hostname, inst.SSHLocalPort, sshConfig); err != nil { |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | removed, rmErr := sshutil.RemoveStaleControlMaster(ctx, inst.Dir) |
| 198 | if rmErr != nil { |
| 199 | return rmErr |
| 200 | } |
| 201 | if !removed { |
| 202 | return err |
| 203 | } |
| 204 | logrus.WithError(err).Warnf("Removed stale ssh control socket for the instance %#q after the master had already exited", instName) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | syncDirVal, err := flags.GetString("sync") |
| 209 | if err != nil { |
| 210 | return fmt.Errorf("failed to get sync flag: %w", err) |
| 211 | } |
| 212 | syncHostWorkdir := syncDirVal != "" |
| 213 | if syncHostWorkdir && len(inst.Config.Mounts) > 0 { |
| 214 | return errors.New("cannot use `--sync` when the instance has host mounts configured, start the instance with `--mount-none` to disable mounts") |
| 215 | } |
| 216 | |
| 217 | |
| 218 | if syncHostWorkdir && inst.VMType == limatype.WSL2 { |
| 219 | return errors.New("cannot use `--sync` with a wsl2 instance, the host directory is already visible in the guest") |
| 220 | } |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | var changeDirCmd string |
| 227 | |
| 228 | |
| 229 | var hostCurrentDir, hostCurrentDirNative string |
| 230 | if syncDirVal != "" { |
| 231 | hostCurrentDirNative, err = filepath.Abs(syncDirVal) |
| 232 | } else { |
| 233 | hostCurrentDirNative, err = os.Getwd() |
| 234 | } |
| 235 | if err == nil { |
| 236 | hostCurrentDir = hostCurrentDirNative |
| 237 | if runtime.GOOS == "windows" { |
| 238 | hostCurrentDir, err = mountDirFromWindowsDir(ctx, inst, hostCurrentDirNative) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | if err != nil { |
| 243 | |
| 244 | if syncHostWorkdir { |
| 245 | return fmt.Errorf("failed to determine the host directory to sync: %w", err) |
| 246 | } |
| 247 | changeDirCmd = "false" |
| 248 | logrus.WithError(err).Warn("failed to get the current directory") |
| 249 | } |
| 250 | if syncHostWorkdir { |
| 251 | if _, err := exec.LookPath(string(copytool.BackendRsync)); err != nil { |
| 252 | return fmt.Errorf("rsync is required for `--sync` but not found: %w", err) |
| 253 | } |
| 254 | |
| 255 | |
| 256 | |
| 257 | srcWdDepth := pathDepth(hostCurrentDirNative, runtime.GOOS == "windows") |
| 258 | if srcWdDepth < rsyncMinimumSrcDirDepth { |
| 259 | return fmt.Errorf("expected the depth of the host working directory (%#q) to be at least %d, only got %d (Hint: %s)", |
| 260 | hostCurrentDirNative, rsyncMinimumSrcDirDepth, srcWdDepth, "cd to a deeper directory") |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | if dstWdDepth := pathDepth(hostCurrentDir, false); dstWdDepth < rsyncMinimumSrcDirDepth { |
| 266 | return fmt.Errorf("expected the depth of the converted host working directory (%#q) to be at least %d, only got %d", |
| 267 | hostCurrentDir, rsyncMinimumSrcDirDepth, dstWdDepth) |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | var destRsyncDir string |
| 272 | workDir, err := cmd.Flags().GetString("workdir") |
| 273 | if err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if workDir != "" && syncHostWorkdir { |
| 277 | return errors.New("cannot use `--workdir` and `--sync` at the same time") |
| 278 | } |
| 279 | if syncHostWorkdir { |
| 280 | destRsyncDir = *inst.Config.User.Home + hostCurrentDir |
| 281 | } |
| 282 | hostHomeDir, err := os.UserHomeDir() |
| 283 | if err == nil && runtime.GOOS == "windows" { |
| 284 | hostHomeDir, err = mountDirFromWindowsDir(ctx, inst, hostHomeDir) |
| 285 | } |
| 286 | if err != nil { |
| 287 | logrus.WithError(err).Warn("failed to get the home directory") |
| 288 | hostHomeDir = "" |
| 289 | } |
| 290 | |
| 291 | switch { |
| 292 | case workDir != "": |
| 293 | changeDirCmd = fmt.Sprintf("cd %s || exit 1", shellescape.Quote(workDir)) |
| 294 | case mountsContainPath(inst.Config.Mounts, hostCurrentDir) || inst.VMType == limatype.WSL2: |
| 295 | changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(hostCurrentDir)) |
| 296 | if hostHomeDir != "" { |
| 297 | changeDirCmd = fmt.Sprintf("%s || cd %s", changeDirCmd, shellescape.Quote(hostHomeDir)) |
| 298 | } |
| 299 | case syncHostWorkdir: |
| 300 | changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(destRsyncDir)) |
| 301 | case hostHomeDir != "" && mountsContainPath(inst.Config.Mounts, hostHomeDir): |
| 302 | changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(hostHomeDir)) |
| 303 | default: |
| 304 | logrus.Debug("the host home does not seem mounted, so the guest shell will have a different cwd") |
| 305 | } |
| 306 | |
| 307 | if changeDirCmd == "" { |
| 308 | changeDirCmd = "false" |
| 309 | } |
| 310 | logrus.Debugf("changeDirCmd=%#q", changeDirCmd) |
| 311 | |
| 312 | shell, err := cmd.Flags().GetString("shell") |
| 313 | if err != nil { |
| 314 | return err |
| 315 | } |
| 316 | if *inst.Config.OS == limatype.WINDOWS { |
| 317 | if shell == "" { |
| 318 | if inst.Config.User.Shell != nil { |
| 319 | shell = *inst.Config.User.Shell |
| 320 | } else { |
| 321 | shell = "cmd.exe" |
| 322 | } |
| 323 | } |
| 324 | if !limayaml.IsSupportedWindowsShell(shell) { |
| 325 | return fmt.Errorf("unsupported shell %#q for Windows guest, must be one of %v", shell, limayaml.SupportedWindowsShells) |
| 326 | } |
| 327 | } else if shell == "" { |
| 328 | if inst.Config.User.Shell != nil { |
| 329 | shell = shellescape.Quote(*inst.Config.User.Shell) |
| 330 | } else { |
| 331 | shell = `"$SHELL"` |
| 332 | } |
| 333 | } else { |
| 334 | shell = shellescape.Quote(shell) |
| 335 | } |
| 336 | |
| 337 | var envPrefix string |
| 338 | preserveEnv, err := cmd.Flags().GetBool("preserve-env") |
| 339 | if err != nil { |
| 340 | return err |
| 341 | } |
| 342 | if preserveEnv { |
| 343 | filteredEnv := envutil.FilterEnvironment() |
| 344 | if len(filteredEnv) > 0 { |
| 345 | envPrefix = "env " |
| 346 | for _, envVar := range filteredEnv { |
| 347 | envPrefix += shellescape.Quote(envVar) + " " |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | |
| 353 | |
| 354 | script := fmt.Sprintf("%s ; exec %s%s -l", changeDirCmd, envPrefix, shell) |
| 355 | if *inst.Config.OS == limatype.WINDOWS { |
| 356 | TODO: |
| 357 | script = windowsQuoteShell(shell) |
| 358 | } |
| 359 | if len(args) > 1 { |
| 360 | quotedArgs := make([]string, len(args[1:])) |
| 361 | parsingEnv := true |
| 362 | for i, arg := range args[1:] { |
| 363 | if parsingEnv && isEnv(arg) { |
| 364 | quotedArgs[i] = quoteEnv(arg) |
| 365 | } else { |
| 366 | parsingEnv = false |
| 367 | quotedArgs[i] = shellescape.Quote(arg) |
| 368 | } |
| 369 | } |
| 370 | switch *inst.Config.OS { |
| 371 | case limatype.WINDOWS: |
| 372 | |
| 373 | flag := windowsShellCommandFlag(shell) |
| 374 | |
| 375 | script += fmt.Sprintf(` %s "%s"`, flag, strings.Join(quotedArgs, " ")) |
| 376 | default: |
| 377 | script += fmt.Sprintf( |
| 378 | " -c %s", |
| 379 | shellescape.Quote(strings.Join(quotedArgs, " ")), |
| 380 | ) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | sshExe, err := sshutil.NewSSHExe() |
| 385 | if err != nil { |
| 386 | return err |
| 387 | } |
| 388 | |
| 389 | sshOpts, err := sshutil.SSHOpts( |
| 390 | ctx, |
| 391 | sshExe, |
| 392 | inst.Dir, |
| 393 | *inst.Config.User.Name, |
| 394 | *inst.Config.SSH.LoadDotSSHPubKeys, |
| 395 | *inst.Config.SSH.ForwardAgent, |
| 396 | *inst.Config.SSH.ForwardX11, |
| 397 | *inst.Config.SSH.ForwardX11Trusted) |
| 398 | if err != nil { |
| 399 | return err |
| 400 | } |
| 401 | if runtime.GOOS == "windows" { |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | sshOpts = sshutil.SSHOptsRemovingControlPath(sshOpts) |
| 414 | } |
| 415 | sshArgs := append([]string{}, sshExe.Args...) |
| 416 | sshArgs = append(sshArgs, sshutil.SSHArgsFromOpts(sshOpts)...) |
| 417 | |
| 418 | var ( |
| 419 | sshExecForRsync *exec.Cmd |
| 420 | rsync copytool.CopyTool |
| 421 | ) |
| 422 | if syncHostWorkdir { |
| 423 | logrus.Infof("Syncing host current directory(%s) to guest instance...", hostCurrentDir) |
| 424 | sshExecForRsync = exec.CommandContext(ctx, sshExe.Exe, sshArgs...) |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | if err := executeSSHForRsync(ctx, *sshExecForRsync, inst.SSHLocalPort, inst.SSHAddress, fmt.Sprintf("mkdir -p %s", shellescape.Quote(destRsyncDir))); err != nil { |
| 430 | return fmt.Errorf("failed to create the synced workdir in guest instance: %w", err) |
| 431 | } |
| 432 | |
| 433 | |
| 434 | |
| 435 | rsyncVer, err := rsyncVersion(ctx) |
| 436 | if err != nil { |
| 437 | return fmt.Errorf("failed to get rsync version: %w", err) |
| 438 | } |
| 439 | if rsyncVer.LessThan(*semver.New("3.2.4")) { |
| 440 | destRsyncDir = shellescape.Quote(destRsyncDir) |
| 441 | } |
| 442 | |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | paths := []string{ |
| 448 | hostCurrentDir + "/", |
| 449 | fmt.Sprintf("%s:%s/", inst.Name, destRsyncDir), |
| 450 | } |
| 451 | rsync, err = copytool.New(ctx, string(copytool.BackendRsync), paths, ©tool.Options{ |
| 452 | Verbose: false, |
| 453 | AdditionalArgs: []string{ |
| 454 | "--delete", |
| 455 | }, |
| 456 | }) |
| 457 | if err != nil { |
| 458 | return err |
| 459 | } |
| 460 | logrus.Debugf("using copy tool %#q", rsync.Name()) |
| 461 | |
| 462 | if err := rsyncDirectory(ctx, cmd, rsync, paths); err != nil { |
| 463 | return fmt.Errorf("failed to rsync to the guest %w", err) |
| 464 | } |
| 465 | logrus.Infof("Successfully synced host current directory to guest(%s) instance.", destRsyncDir) |
| 466 | } |
| 467 | |
| 468 | if isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) { |
| 469 | |
| 470 | sshArgs = append(sshArgs, "-t") |
| 471 | } |
| 472 | if _, present := os.LookupEnv("COLORTERM"); present { |
| 473 | |
| 474 | sshArgs = append(sshArgs, "-o", "SendEnv=COLORTERM") |
| 475 | } |
| 476 | logLevel := "ERROR" |
| 477 | |
| 478 | |
| 479 | olderSSH := sshutil.DetectOpenSSHVersion(ctx, sshExe).LessThan(*semver.New("8.9.0")) |
| 480 | if olderSSH { |
| 481 | logLevel = "QUIET" |
| 482 | } |
| 483 | sshArgs = append(sshArgs, []string{ |
| 484 | "-o", fmt.Sprintf("LogLevel=%s", logLevel), |
| 485 | "-p", strconv.Itoa(inst.SSHLocalPort), |
| 486 | inst.SSHAddress, |
| 487 | "--", |
| 488 | script, |
| 489 | }...) |
| 490 | sshCmd := exec.CommandContext(ctx, sshExe.Exe, sshArgs...) |
| 491 | sshCmd.Stdin = os.Stdin |
| 492 | sshCmd.Stdout = os.Stdout |
| 493 | sshCmd.Stderr = os.Stderr |
| 494 | logrus.Debugf("executing ssh (may take a long)): %+v", sshCmd.Args) |
| 495 | |
| 496 | TODO: |
| 497 | if err := sshCmd.Run(); err != nil { |
| 498 | return err |
| 499 | } |
| 500 | |
| 501 | |
| 502 | |
| 503 | |
| 504 | if syncHostWorkdir { |
| 505 | tty, err := flags.GetBool("tty") |
| 506 | if err != nil { |
| 507 | return err |
| 508 | } |
| 509 | return askUserForRsyncBack(ctx, cmd, inst, sshExecForRsync, hostCurrentDir, destRsyncDir, rsync, tty) |
| 510 | } |
| 511 | return nil |
| 512 | } |
| 513 | |
| 514 | |
| 515 | |
| 516 | |
| 517 | |
| 518 | func windowsShellCommandFlag(shell string) string { |
| 519 | if i := strings.LastIndexAny(shell, `/\`); i >= 0 { |
| 520 | shell = shell[i+1:] |
| 521 | } |
| 522 | if strings.EqualFold(shell, "cmd.exe") { |
| 523 | return "/c" |
| 524 | } |
| 525 | return "-Command" |
| 526 | } |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | func windowsQuoteShell(shell string) string { |
| 532 | if strings.HasPrefix(shell, `"`) && strings.HasSuffix(shell, `"`) && len(shell) >= 2 { |
| 533 | return shell |
| 534 | } |
| 535 | if !strings.ContainsAny(shell, " \t") { |
| 536 | return shell |
| 537 | } |
| 538 | return `"` + shell + `"` |
| 539 | } |
| 540 | |
| 541 | func askUserForRsyncBack(ctx context.Context, cmd *cobra.Command, inst *limatype.Instance, sshCmd *exec.Cmd, hostCurrentDir, destRsyncDir string, rsync copytool.CopyTool, tty bool) error { |
| 542 | remoteSource := fmt.Sprintf("%s:%s", inst.Name, destRsyncDir) |
| 543 | |
| 544 | remoteContents := remoteSource + "/" |
| 545 | clean := filepath.Clean(hostCurrentDir) |
| 546 | dirForCleanup := shellescape.Quote(filepath.Join(*inst.Config.User.Home, clean)) |
| 547 | cleanupGuestWorkdir := false |
| 548 | |
| 549 | rsyncBack := func() error { |
| 550 | paths := []string{ |
| 551 | remoteContents, |
| 552 | hostCurrentDir, |
| 553 | } |
| 554 | |
| 555 | if err := rsyncDirectory(ctx, cmd, rsync, paths); err != nil { |
| 556 | return fmt.Errorf("failed to sync back the changes from guest instance to host: %w", err) |
| 557 | } |
| 558 | logrus.Info("Successfully synced back the changes to host.") |
| 559 | cleanupGuestWorkdir = true |
| 560 | return nil |
| 561 | } |
| 562 | |
| 563 | defer func() { |
| 564 | if !cleanupGuestWorkdir { |
| 565 | return |
| 566 | } |
| 567 | |
| 568 | if err := executeSSHForRsync(ctx, *sshCmd, inst.SSHLocalPort, inst.SSHAddress, fmt.Sprintf("rm -rf %s", dirForCleanup)); err != nil { |
| 569 | logrus.WithError(err).Warn("Failed to clean up guest synced workdir") |
| 570 | } |
| 571 | }() |
| 572 | |
| 573 | if !tty { |
| 574 | return rsyncBack() |
| 575 | } |
| 576 | |
| 577 | rawOutput, stats, err := getRsyncStats(ctx, remoteSource, filepath.Dir(hostCurrentDir)) |
| 578 | if err != nil { |
| 579 | logrus.WithError(err).Warn("failed to get rsync stats") |
| 580 | } |
| 581 | if stats != nil && stats.String() == "" { |
| 582 | logrus.Info("No changes detected") |
| 583 | cleanupGuestWorkdir = true |
| 584 | return nil |
| 585 | } |
| 586 | statsMsg := "" |
| 587 | if stats != nil { |
| 588 | if s := stats.String(); s != "" { |
| 589 | statsMsg = fmt.Sprintf(" (%s)", s) |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | message := fmt.Sprintf("⚠️ Accept the changes?%s", statsMsg) |
| 594 | options := []string{ |
| 595 | "Yes", |
| 596 | "No", |
| 597 | "View the changed contents", |
| 598 | } |
| 599 | |
| 600 | baseDir, err := os.MkdirTemp("", "lima-guest-synced-*") |
| 601 | if err != nil { |
| 602 | return fmt.Errorf("failed to create temporary directory: %w; preserving guest synced workdir at %s", err, destRsyncDir) |
| 603 | } |
| 604 | defer func() { |
| 605 | if err := os.RemoveAll(baseDir); err != nil { |
| 606 | logrus.WithError(err).Warnf("Failed to clean up temporary directory %s", baseDir) |
| 607 | } |
| 608 | }() |
| 609 | hostTmpDest := filepath.Join(baseDir, filepath.Base(hostCurrentDir)) |
| 610 | err = os.MkdirAll(hostTmpDest, 0o755) |
| 611 | if err != nil { |
| 612 | return fmt.Errorf("failed to create temporary directory: %w; preserving guest synced workdir at %s", err, destRsyncDir) |
| 613 | } |
| 614 | |
| 615 | rsyncToTempDir := false |
| 616 | |
| 617 | for { |
| 618 | ans, err := uiutil.Select(message, options) |
| 619 | if err != nil { |
| 620 | return fmt.Errorf("failed to open TUI: %w; preserving guest synced workdir at %s", err, destRsyncDir) |
| 621 | } |
| 622 | |
| 623 | switch ans { |
| 624 | case 0: |
| 625 | return rsyncBack() |
| 626 | case 1: |
| 627 | cleanupGuestWorkdir = true |
| 628 | logrus.Info("Skipping syncing back the changes to host.") |
| 629 | return nil |
| 630 | case 2: |
| 631 | var diffCmd *exec.Cmd |
| 632 | if _, err := exec.LookPath("diff"); err != nil { |
| 633 | logrus.WithError(err).Warn("`diff` not found; showing rsync dry-run output only") |
| 634 | } else { |
| 635 | diffCmd = exec.CommandContext(ctx, "diff", "-ruN", "--color=always", hostCurrentDir, hostTmpDest) |
| 636 | if !rsyncToTempDir { |
| 637 | paths := []string{ |
| 638 | remoteContents, |
| 639 | hostTmpDest, |
| 640 | } |
| 641 | |
| 642 | if err := rsyncDirectory(ctx, cmd, rsync, paths); err != nil { |
| 643 | return fmt.Errorf("failed to sync back the changes from guest instance to host temporary directory: %w", err) |
| 644 | } |
| 645 | rsyncToTempDir = true |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | pagerArgs := pagerCommand() |
| 650 | lessCmd := exec.CommandContext(ctx, pagerArgs[0], pagerArgs[1:]...) |
| 651 | |
| 652 | pipeIn, err := lessCmd.StdinPipe() |
| 653 | if err != nil { |
| 654 | return fmt.Errorf("failed to create pipe for less: %w", err) |
| 655 | } |
| 656 | if diffCmd != nil { |
| 657 | diffCmd.Stdout = pipeIn |
| 658 | } |
| 659 | lessCmd.Stdout = cmd.OutOrStdout() |
| 660 | lessCmd.Stderr = cmd.OutOrStderr() |
| 661 | |
| 662 | if err := lessCmd.Start(); err != nil { |
| 663 | return fmt.Errorf("failed to start less: %w", err) |
| 664 | } |
| 665 | |
| 666 | |
| 667 | if stats != nil { |
| 668 | rsyncHead := fmt.Sprintf("%s--- rsync dry-run statistics ---%s", colorGray, colorNone) |
| 669 | diffHead := fmt.Sprintf("%s--- detailed diff --- %s", colorGray, colorNone) |
| 670 | if diffCmd == nil { |
| 671 | diffHead = fmt.Sprintf("%s--- detailed diff unavailable (`diff` not found) --- %s", colorGray, colorNone) |
| 672 | } |
| 673 | combinedOutput := fmt.Sprintf( |
| 674 | "%s\n%s\n\n%s\n\n\n%s\n", |
| 675 | rsyncHead, |
| 676 | stats.String(), |
| 677 | rawOutput, |
| 678 | diffHead, |
| 679 | ) |
| 680 | |
| 681 | if _, err := fmt.Fprint(pipeIn, combinedOutput); err != nil { |
| 682 | _ = pipeIn.Close() |
| 683 | return fmt.Errorf("failed to write rsync stats to pager: %w", err) |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | if diffCmd != nil { |
| 688 | if err := diffCmd.Run(); err != nil { |
| 689 | |
| 690 | var exitErr *exec.ExitError |
| 691 | if errors.As(err, &exitErr) && exitErr.ExitCode() >= 2 { |
| 692 | _ = pipeIn.Close() |
| 693 | return fmt.Errorf("failed to run diff command: %w", err) |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | _ = pipeIn.Close() |
| 699 | |
| 700 | if err := lessCmd.Wait(); err != nil { |
| 701 | return fmt.Errorf("failed to wait for less command: %w", err) |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | |
| 708 | func pagerCommand() []string { |
| 709 | pager := strings.TrimSpace(os.Getenv("PAGER")) |
| 710 | if pager == "" { |
| 711 | return []string{"less", "-R"} |
| 712 | } |
| 713 | args := strings.Fields(pager) |
| 714 | if filepath.Base(args[0]) != "less" { |
| 715 | return args |
| 716 | } |
| 717 | if lessHasRawColorFlag(args[1:]) { |
| 718 | return args |
| 719 | } |
| 720 | if lessHasRawColorFlag(strings.Fields(os.Getenv("LESS"))) { |
| 721 | return args |
| 722 | } |
| 723 | return append(args, "-R") |
| 724 | } |
| 725 | |
| 726 | func lessHasRawColorFlag(flags []string) bool { |
| 727 | for _, f := range flags { |
| 728 | switch f { |
| 729 | case "-R", "-r", "--RAW-CONTROL-CHARS", "--raw-control-chars": |
| 730 | return true |
| 731 | } |
| 732 | if strings.HasPrefix(f, "-") && !strings.HasPrefix(f, "--") { |
| 733 | if strings.ContainsAny(f, "Rr") { |
| 734 | return true |
| 735 | } |
| 736 | } |
| 737 | } |
| 738 | return false |
| 739 | } |
| 740 | |
| 741 | func mountsContainPath(mounts []limatype.Mount, path string) bool { |
| 742 | resolvedPath, err := filepath.EvalSymlinks(path) |
| 743 | if err != nil { |
| 744 | resolvedPath = path |
| 745 | } |
| 746 | for _, m := range mounts { |
| 747 | loc, err := localpathutil.Expand(m.Location) |
| 748 | if err != nil { |
| 749 | continue |
| 750 | } |
| 751 | resolvedLoc, err := filepath.EvalSymlinks(loc) |
| 752 | if err != nil { |
| 753 | resolvedLoc = loc |
| 754 | } |
| 755 | if resolvedPath == resolvedLoc || |
| 756 | resolvedLoc == string(os.PathSeparator) || strings.HasPrefix(resolvedPath, resolvedLoc+string(os.PathSeparator)) { |
| 757 | return true |
| 758 | } |
| 759 | } |
| 760 | return false |
| 761 | } |
| 762 | |
| 763 | func executeSSHForRsync(ctx context.Context, sshCmd exec.Cmd, sshLocalPort int, sshAddress, command string) error { |
| 764 | args := make([]string, len(sshCmd.Args), len(sshCmd.Args)+3) |
| 765 | copy(args, sshCmd.Args) |
| 766 | args = append(args, "-p", strconv.Itoa(sshLocalPort), sshAddress) |
| 767 | |
| 768 | |
| 769 | sshRmCmd := exec.CommandContext(ctx, sshCmd.Path, append(args[1:], command)...) |
| 770 | if err := sshRmCmd.Run(); err != nil { |
| 771 | return err |
| 772 | } |
| 773 | return nil |
| 774 | } |
| 775 | |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | func pathDepth(path string, windows bool) int { |
| 782 | slashed := path |
| 783 | if windows { |
| 784 | slashed = strings.ReplaceAll(path, `\`, "/") |
| 785 | |
| 786 | |
| 787 | |
| 788 | if strings.HasPrefix(slashed, "//?/") || strings.HasPrefix(slashed, "//./") { |
| 789 | slashed = slashed[len("//?/"):] |
| 790 | } |
| 791 | } |
| 792 | |
| 793 | |
| 794 | |
| 795 | for strings.Contains(slashed, "//") { |
| 796 | slashed = strings.ReplaceAll(slashed, "//", "/") |
| 797 | } |
| 798 | |
| 799 | |
| 800 | |
| 801 | if trimmed := strings.TrimSuffix(slashed, "/"); strings.Contains(trimmed, "/") { |
| 802 | slashed = trimmed |
| 803 | } |
| 804 | return strings.Count(slashed, "/") + 1 |
| 805 | } |
| 806 | |
| 807 | func rsyncVersion(ctx context.Context) (*semver.Version, error) { |
| 808 | out, err := exec.CommandContext(ctx, string(copytool.BackendRsync), "--version").Output() |
| 809 | if err != nil { |
| 810 | return nil, err |
| 811 | } |
| 812 | |
| 813 | |
| 814 | re := regexp.MustCompile(`version (\d+\.\d+\.\d+)`) |
| 815 | matches := re.FindSubmatch(out) |
| 816 | if len(matches) < 2 { |
| 817 | return nil, errors.New("failed to parse rsync version") |
| 818 | } |
| 819 | return semver.NewVersion(string(matches[1])) |
| 820 | } |
| 821 | |
| 822 | |
| 823 | |
| 824 | func rsyncDirectory(ctx context.Context, cmd *cobra.Command, rsync copytool.CopyTool, paths []string) error { |
| 825 | rsyncCmd, err := rsync.Command(ctx, paths, nil) |
| 826 | if err != nil { |
| 827 | return err |
| 828 | } |
| 829 | rsyncCmd.Stdout = cmd.OutOrStdout() |
| 830 | rsyncCmd.Stderr = cmd.OutOrStderr() |
| 831 | logrus.Debugf("executing rsync: %+v", rsyncCmd.Args) |
| 832 | return rsyncCmd.Run() |
| 833 | } |
| 834 | |
| 835 | func mountDirFromWindowsDir(ctx context.Context, inst *limatype.Instance, dir string) (string, error) { |
| 836 | if inst.VMType == limatype.WSL2 { |
| 837 | distroName := "lima-" + inst.Name |
| 838 | return fsutil.WindowsSubsystemPathForLinux(ctx, dir, distroName) |
| 839 | } |
| 840 | return fsutil.WindowsSubsystemPath(ctx, dir) |
| 841 | } |
| 842 | |
| 843 | func shellBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { |
| 844 | return bashCompleteInstanceNames(cmd) |
| 845 | } |
| 846 | |
| 847 | func isEnv(arg string) bool { |
| 848 | return len(strings.Split(arg, "=")) > 1 |
| 849 | } |
| 850 | |
| 851 | func quoteEnv(arg string) string { |
| 852 | env := strings.SplitN(arg, "=", 2) |
| 853 | env[1] = shellescape.Quote(env[1]) |
| 854 | return strings.Join(env, "=") |
| 855 | } |
| 856 | |
| 857 | type rsyncStats struct { |
| 858 | Added int |
| 859 | Deleted int |
| 860 | Modified int |
| 861 | Metadata int |
| 862 | } |
| 863 | |
| 864 | func (s *rsyncStats) String() string { |
| 865 | if s.Added == 0 && s.Deleted == 0 && s.Modified == 0 && s.Metadata == 0 { |
| 866 | return "" |
| 867 | } |
| 868 | return fmt.Sprintf("added: %d, deleted: %d, modified: %d, metadata: %d", s.Added, s.Deleted, s.Modified, s.Metadata) |
| 869 | } |
| 870 | |
| 871 | func getRsyncStats(ctx context.Context, source, destination string) (string, *rsyncStats, error) { |
| 872 | paths := []string{source, destination} |
| 873 | rsync, err := copytool.New(ctx, string(copytool.BackendRsync), paths, ©tool.Options{ |
| 874 | Verbose: true, |
| 875 | AdditionalArgs: []string{ |
| 876 | "--dry-run", |
| 877 | "--itemize-changes", |
| 878 | "-ah", |
| 879 | "--delete", |
| 880 | }, |
| 881 | }) |
| 882 | if err != nil { |
| 883 | return "", nil, err |
| 884 | } |
| 885 | |
| 886 | rsyncCmd, err := rsync.Command(ctx, paths, nil) |
| 887 | if err != nil { |
| 888 | return "", nil, err |
| 889 | } |
| 890 | logrus.Debugf("executing rsync for stats: %+v", rsyncCmd.Args) |
| 891 | |
| 892 | out, err := rsyncCmd.Output() |
| 893 | if err != nil { |
| 894 | return "", nil, err |
| 895 | } |
| 896 | output := string(out) |
| 897 | return output, parseRsyncStats(output), nil |
| 898 | } |
| 899 | |
| 900 | |
| 901 | |
| 902 | |
| 903 | |
| 904 | |
| 905 | |
| 906 | |
| 907 | |
| 908 | |
| 909 | |
| 910 | |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | func parseRsyncStats(output string) *rsyncStats { |
| 921 | var s rsyncStats |
| 922 | for line := range strings.SplitSeq(output, "\n") { |
| 923 | if len(line) < 12 { |
| 924 | continue |
| 925 | } |
| 926 | |
| 927 | if strings.HasPrefix(line, "*deleting") { |
| 928 | s.Deleted++ |
| 929 | continue |
| 930 | } |
| 931 | |
| 932 | updateType := line[0] |
| 933 | checksum := line[2] |
| 934 | |
| 935 | if updateType == '<' || updateType == '>' || updateType == 'c' { |
| 936 | if checksum == '+' { |
| 937 | s.Added++ |
| 938 | } else { |
| 939 | s.Modified++ |
| 940 | } |
| 941 | continue |
| 942 | } |
| 943 | |
| 944 | if updateType == '.' && hasMetadataDelta(line[2:11]) { |
| 945 | s.Metadata++ |
| 946 | } |
| 947 | } |
| 948 | return &s |
| 949 | } |
| 950 | |
| 951 | func hasMetadataDelta(attrs string) bool { |
| 952 | for _, ch := range attrs { |
| 953 | if ch != '.' { |
| 954 | return true |
| 955 | } |
| 956 | } |
| 957 | return false |
| 958 | } |