| 1 | |
| 2 | |
| 3 | |
| 4 | package wsl2 |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | _ "embed" |
| 9 | "fmt" |
| 10 | "net" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | |
| 18 | "github.com/sirupsen/logrus" |
| 19 | |
| 20 | "github.com/lima-vm/lima/v2/pkg/executil" |
| 21 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 22 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 23 | "github.com/lima-vm/lima/v2/pkg/textutil" |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | func startVM(ctx context.Context, distroName string) error { |
| 28 | out, err := executil.RunUTF16leCommand([]string{ |
| 29 | "wsl.exe", |
| 30 | "--distribution", |
| 31 | distroName, |
| 32 | }, executil.WithContext(ctx)) |
| 33 | if err != nil { |
| 34 | return fmt.Errorf("failed to run `wsl.exe --distribution %s`: %w (out=%#q)", |
| 35 | distroName, err, out) |
| 36 | } |
| 37 | return nil |
| 38 | } |
| 39 | |
| 40 | |
| 41 | func initVM(ctx context.Context, instanceDir, distroName string) error { |
| 42 | baseDisk := filepath.Join(instanceDir, filenames.BaseDiskLegacy) |
| 43 | logrus.Infof("Importing distro from %#q to %#q", baseDisk, instanceDir) |
| 44 | out, err := executil.RunUTF16leCommand([]string{ |
| 45 | "wsl.exe", |
| 46 | "--import", |
| 47 | distroName, |
| 48 | instanceDir, |
| 49 | baseDisk, |
| 50 | }, executil.WithContext(ctx)) |
| 51 | if err != nil { |
| 52 | return fmt.Errorf("failed to run `wsl.exe --import %s %s %s`: %w (out=%#q)", |
| 53 | distroName, instanceDir, baseDisk, err, out) |
| 54 | } |
| 55 | return nil |
| 56 | } |
| 57 | |
| 58 | |
| 59 | func stopVM(ctx context.Context, distroName string) error { |
| 60 | out, err := executil.RunUTF16leCommand([]string{ |
| 61 | "wsl.exe", |
| 62 | "--terminate", |
| 63 | distroName, |
| 64 | }, executil.WithContext(ctx)) |
| 65 | if err != nil { |
| 66 | return fmt.Errorf("failed to run `wsl.exe --terminate %s`: %w (out=%#q)", |
| 67 | distroName, err, out) |
| 68 | } |
| 69 | return nil |
| 70 | } |
| 71 | |
| 72 | |
| 73 | var limaBoot string |
| 74 | |
| 75 | |
| 76 | func provisionVM(ctx context.Context, instanceDir, instanceName, distroName string, errCh chan<- error) error { |
| 77 | ciDataPath := filepath.Join(instanceDir, filenames.CIDataISODir) |
| 78 | m := map[string]string{ |
| 79 | "CIDataPath": ciDataPath, |
| 80 | } |
| 81 | limaBootB, err := textutil.ExecuteTemplate(limaBoot, m) |
| 82 | if err != nil { |
| 83 | return fmt.Errorf("failed to construct wsl boot.sh script: %w", err) |
| 84 | } |
| 85 | limaBootFile, err := os.CreateTemp("", "lima-wsl2-boot-*.sh") |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | if _, err = limaBootFile.Write(limaBootB); err != nil { |
| 90 | limaBootFile.Close() |
| 91 | return err |
| 92 | } |
| 93 | limaBootFileWinPath := limaBootFile.Name() |
| 94 | if err = limaBootFile.Close(); err != nil { |
| 95 | return err |
| 96 | } |
| 97 | |
| 98 | bootFileWSLPath := strconv.Quote(limaBootFileWinPath) |
| 99 | limaBootFilePathOnLinuxB, err := exec.CommandContext( |
| 100 | ctx, |
| 101 | "wsl.exe", |
| 102 | "-d", |
| 103 | distroName, |
| 104 | "bash", |
| 105 | "-c", |
| 106 | fmt.Sprintf("wslpath -u %s", bootFileWSLPath), |
| 107 | bootFileWSLPath, |
| 108 | ).Output() |
| 109 | if err != nil { |
| 110 | os.RemoveAll(limaBootFileWinPath) |
| 111 | |
| 112 | |
| 113 | return fmt.Errorf("failed to run wslpath command: %w", err) |
| 114 | } |
| 115 | limaBootFileLinuxPath := strings.TrimSpace(string(limaBootFilePathOnLinuxB)) |
| 116 | go func() { |
| 117 | cmd := exec.CommandContext( |
| 118 | ctx, |
| 119 | "wsl.exe", |
| 120 | "-d", |
| 121 | distroName, |
| 122 | "bash", |
| 123 | "-c", |
| 124 | limaBootFileLinuxPath, |
| 125 | ) |
| 126 | out, err := cmd.CombinedOutput() |
| 127 | os.RemoveAll(limaBootFileWinPath) |
| 128 | logrus.Debugf("%v: %#q", cmd.Args, string(out)) |
| 129 | if err != nil { |
| 130 | errCh <- fmt.Errorf( |
| 131 | "error running wslCommand that executes boot.sh (%v): %w, "+ |
| 132 | "check /var/log/lima-init.log for more details (out=%#q)", cmd.Args, err, string(out)) |
| 133 | } |
| 134 | |
| 135 | <-ctx.Done() |
| 136 | logrus.Info("Context closed, stopping vm") |
| 137 | if status, err := getWslStatus(ctx, instanceName); err == nil && |
| 138 | status == limatype.StatusRunning { |
| 139 | _ = stopVM(ctx, distroName) |
| 140 | } |
| 141 | }() |
| 142 | |
| 143 | return err |
| 144 | } |
| 145 | |
| 146 | |
| 147 | func keepAlive(ctx context.Context, distroName string, errCh chan<- error) { |
| 148 | keepAliveCmd := exec.CommandContext( |
| 149 | ctx, |
| 150 | "wsl.exe", |
| 151 | "-d", |
| 152 | distroName, |
| 153 | "bash", |
| 154 | "-c", |
| 155 | "nohup sleep 2147483647d >/dev/null 2>&1", |
| 156 | ) |
| 157 | |
| 158 | go func() { |
| 159 | if err := keepAliveCmd.Run(); err != nil { |
| 160 | errCh <- fmt.Errorf( |
| 161 | "error running wsl keepAlive command: %w", err) |
| 162 | } |
| 163 | }() |
| 164 | } |
| 165 | |
| 166 | |
| 167 | func unregisterVM(ctx context.Context, distroName string) error { |
| 168 | logrus.Info("Unregistering WSL2 VM") |
| 169 | out, err := executil.RunUTF16leCommand([]string{ |
| 170 | "wsl.exe", |
| 171 | "--unregister", |
| 172 | distroName, |
| 173 | }, executil.WithContext(ctx)) |
| 174 | if err != nil { |
| 175 | return fmt.Errorf("failed to run `wsl.exe --unregister %s`: %w (out=%#q)", |
| 176 | distroName, err, out) |
| 177 | } |
| 178 | return nil |
| 179 | } |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | func getWslStatus(ctx context.Context, instName string) (string, error) { |
| 209 | distroName := "lima-" + instName |
| 210 | out, err := executil.RunUTF16leCommand([]string{ |
| 211 | "wsl.exe", |
| 212 | "--list", |
| 213 | "--verbose", |
| 214 | }, executil.WithContext(ctx)) |
| 215 | if err != nil { |
| 216 | return "", fmt.Errorf("failed to run `wsl --list --verbose`, err: %w (out=%#q)", err, out) |
| 217 | } |
| 218 | |
| 219 | if out == "" { |
| 220 | return limatype.StatusBroken, fmt.Errorf("failed to read instance state for instance %#q, try running `wsl --list --verbose` to debug, err: %w", instName, err) |
| 221 | } |
| 222 | |
| 223 | |
| 224 | if strings.Contains(out, "Windows Subsystem for Linux has no installed distributions.") { |
| 225 | if strings.Contains(out, "Wsl/WSL_E_DEFAULT_DISTRO_NOT_FOUND") { |
| 226 | return limatype.StatusBroken, fmt.Errorf( |
| 227 | "failed to read instance state for instance %#q because no distro is installed,"+ |
| 228 | "try running `wsl --install -d Ubuntu` and then re-running Lima", instName) |
| 229 | } |
| 230 | return limatype.StatusBroken, fmt.Errorf( |
| 231 | "failed to read instance state for instance %#q because there is no WSL kernel installed,"+ |
| 232 | "this usually happens when WSL was installed for another user, but never for your user."+ |
| 233 | "Try running `wsl --install -d Ubuntu` and `wsl --update`, and then re-running Lima", instName) |
| 234 | } |
| 235 | |
| 236 | var instState string |
| 237 | wslListColsRegex := regexp.MustCompile(`\s+`) |
| 238 | |
| 239 | for rows := range strings.SplitSeq(strings.ReplaceAll(out, "\r\n", "\n"), "\n") { |
| 240 | cols := wslListColsRegex.Split(strings.TrimSpace(rows), -1) |
| 241 | nameIdx := 0 |
| 242 | |
| 243 | if cols[0] == "*" { |
| 244 | nameIdx = 1 |
| 245 | } |
| 246 | if cols[nameIdx] == distroName { |
| 247 | instState = cols[nameIdx+1] |
| 248 | break |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | if instState == "" { |
| 253 | return limatype.StatusUninitialized, nil |
| 254 | } |
| 255 | |
| 256 | return instState, nil |
| 257 | } |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | func getSSHAddress(ctx context.Context, instName string) (string, error) { |
| 267 | distroName := "lima-" + instName |
| 268 | |
| 269 | cmd := exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "bash", "-c", `hostname -I | cut -d ' ' -f1`) |
| 270 | out, err := cmd.CombinedOutput() |
| 271 | if err == nil { |
| 272 | return strings.TrimSpace(string(out)), nil |
| 273 | } |
| 274 | |
| 275 | cmd = exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "sh", "-c", `ip route get 1 | awk '{gsub("^.*src ",""); print $1; exit}'`) |
| 276 | out, err = cmd.CombinedOutput() |
| 277 | if err == nil { |
| 278 | return strings.TrimSpace(string(out)), nil |
| 279 | } |
| 280 | |
| 281 | cmd = exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "hostname", "-i") |
| 282 | out, err = cmd.CombinedOutput() |
| 283 | if err == nil { |
| 284 | ip := net.ParseIP(strings.TrimSpace(string(out))) |
| 285 | |
| 286 | if ip != nil && !ip.IsLoopback() { |
| 287 | return strings.TrimSpace(string(out)), nil |
| 288 | } |
| 289 | } |
| 290 | return "", fmt.Errorf("failed to get hostname for instance %#q, err: %w (out=%#q)", instName, err, string(out)) |
| 291 | } |