| 1 | |
| 2 | |
| 3 | |
| 4 | package store |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "runtime" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "syscall" |
| 17 | "text/tabwriter" |
| 18 | "text/template" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/docker/go-units" |
| 22 | "github.com/sirupsen/logrus" |
| 23 | |
| 24 | "github.com/lima-vm/lima/v2/pkg/driverutil" |
| 25 | hostagentclient "github.com/lima-vm/lima/v2/pkg/hostagent/api/client" |
| 26 | "github.com/lima-vm/lima/v2/pkg/instance/hostname" |
| 27 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 28 | "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 29 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 30 | "github.com/lima-vm/lima/v2/pkg/textutil" |
| 31 | "github.com/lima-vm/lima/v2/pkg/version/versionutil" |
| 32 | ) |
| 33 | |
| 34 | |
| 35 | |
| 36 | func Inspect(ctx context.Context, instName string) (*limatype.Instance, error) { |
| 37 | inst := &limatype.Instance{ |
| 38 | Name: instName, |
| 39 | TODO: |
| 40 | Hostname: hostname.FromInstName(instName), |
| 41 | Status: limatype.StatusUnknown, |
| 42 | } |
| 43 | |
| 44 | instDir, err := dirnames.InstanceDir(instName) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | |
| 49 | inst.Dir = instDir |
| 50 | yamlPath := filepath.Join(instDir, filenames.LimaYAML) |
| 51 | y, err := LoadYAMLByFilePath(ctx, yamlPath) |
| 52 | if err != nil { |
| 53 | if errors.Is(err, os.ErrNotExist) { |
| 54 | return nil, err |
| 55 | } |
| 56 | inst.Errors = append(inst.Errors, err) |
| 57 | return inst, nil |
| 58 | } |
| 59 | inst.Config = y |
| 60 | inst.Arch = *y.Arch |
| 61 | inst.VMType = *y.VMType |
| 62 | inst.SSHAddress = "127.0.0.1" |
| 63 | inst.SSHLocalPort = *y.SSH.LocalPort |
| 64 | inst.SSHConfigFile = filepath.Join(instDir, filenames.SSHConfig) |
| 65 | inst.HostAgentPID, err = ReadPIDFile(filepath.Join(instDir, filenames.HostAgentPID)) |
| 66 | if err != nil { |
| 67 | inst.Status = limatype.StatusBroken |
| 68 | inst.Errors = append(inst.Errors, err) |
| 69 | } |
| 70 | |
| 71 | if inst.HostAgentPID != 0 { |
| 72 | haSock := filepath.Join(instDir, filenames.HostAgentSock) |
| 73 | haClient, err := hostagentclient.NewHostAgentClient(haSock) |
| 74 | if err != nil { |
| 75 | inst.Status = limatype.StatusBroken |
| 76 | inst.Errors = append(inst.Errors, fmt.Errorf("failed to connect to %#q: %w", haSock, err)) |
| 77 | } else { |
| 78 | ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| 79 | defer cancel() |
| 80 | info, err := haClient.Info(ctx) |
| 81 | if err != nil { |
| 82 | inst.Status = limatype.StatusBroken |
| 83 | inst.Errors = append(inst.Errors, fmt.Errorf("failed to get Info from %#q: %w", haSock, err)) |
| 84 | } else { |
| 85 | inst.SSHLocalPort = info.SSHLocalPort |
| 86 | inst.AutoStartedIdentifier = info.AutoStartedIdentifier |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | if inst.SSHLocalPort == 0 { |
| 91 | sshConfigPath := filepath.Join(instDir, filenames.SSHConfig) |
| 92 | if port, err := sshPortFromConfig(sshConfigPath); err == nil { |
| 93 | inst.SSHLocalPort = port |
| 94 | } else if !errors.Is(err, os.ErrNotExist) { |
| 95 | inst.Errors = append(inst.Errors, fmt.Errorf("failed to extract SSH local port from %#q: %w", sshConfigPath, err)) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | inst.CPUs = *y.CPUs |
| 100 | memory, err := units.RAMInBytes(*y.Memory) |
| 101 | if err == nil { |
| 102 | inst.Memory = memory |
| 103 | } |
| 104 | disk, err := units.RAMInBytes(*y.Disk) |
| 105 | if err == nil { |
| 106 | inst.Disk = disk |
| 107 | } |
| 108 | inst.AdditionalDisks = y.AdditionalDisks |
| 109 | inst.Networks = y.Networks |
| 110 | |
| 111 | |
| 112 | if inst.VMType == limatype.WSL2 { |
| 113 | inst.Memory = 0 |
| 114 | inst.CPUs = 0 |
| 115 | inst.Disk = 0 |
| 116 | } |
| 117 | |
| 118 | protected := filepath.Join(instDir, filenames.Protected) |
| 119 | if _, err := os.Lstat(protected); !errors.Is(err, os.ErrNotExist) { |
| 120 | inst.Protected = true |
| 121 | } |
| 122 | |
| 123 | inspectStatus(ctx, instDir, inst, y) |
| 124 | |
| 125 | tmpl, err := template.New("format").Parse(y.Message) |
| 126 | if err != nil { |
| 127 | inst.Errors = append(inst.Errors, fmt.Errorf("message %#q is not a valid template: %w", y.Message, err)) |
| 128 | inst.Status = limatype.StatusBroken |
| 129 | } else { |
| 130 | data, err := AddGlobalFields(inst) |
| 131 | if err != nil { |
| 132 | inst.Errors = append(inst.Errors, fmt.Errorf("cannot add global fields to instance data: %w", err)) |
| 133 | inst.Status = limatype.StatusBroken |
| 134 | } else { |
| 135 | data.Param = y.Param |
| 136 | var message strings.Builder |
| 137 | err = tmpl.Execute(&message, data) |
| 138 | if err != nil { |
| 139 | inst.Errors = append(inst.Errors, fmt.Errorf("cannot execute template %#q: %w", y.Message, err)) |
| 140 | inst.Status = limatype.StatusBroken |
| 141 | } else { |
| 142 | inst.Message = message.String() |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | limaVersionFile := filepath.Join(instDir, filenames.LimaVersion) |
| 148 | if version, err := os.ReadFile(limaVersionFile); err == nil { |
| 149 | inst.LimaVersion = strings.TrimSpace(string(version)) |
| 150 | if _, err = versionutil.Parse(inst.LimaVersion); err != nil { |
| 151 | logrus.Warnf("treating lima version %#q from %#q as very latest release", inst.LimaVersion, limaVersionFile) |
| 152 | } |
| 153 | } else if !errors.Is(err, os.ErrNotExist) { |
| 154 | inst.Errors = append(inst.Errors, err) |
| 155 | } |
| 156 | inst.Param = y.Param |
| 157 | return inst, nil |
| 158 | } |
| 159 | |
| 160 | func inspectStatus(ctx context.Context, instDir string, inst *limatype.Instance, y *limatype.LimaYAML) { |
| 161 | status, err := driverutil.InspectStatus(ctx, inst) |
| 162 | if err != nil { |
| 163 | inst.Status = limatype.StatusBroken |
| 164 | inst.Errors = append(inst.Errors, fmt.Errorf("failed to inspect status: %w", err)) |
| 165 | return |
| 166 | } |
| 167 | |
| 168 | if status == "" { |
| 169 | inspectStatusWithPIDFiles(instDir, inst, y) |
| 170 | return |
| 171 | } |
| 172 | |
| 173 | inst.Status = status |
| 174 | } |
| 175 | |
| 176 | func inspectStatusWithPIDFiles(instDir string, inst *limatype.Instance, y *limatype.LimaYAML) { |
| 177 | var err error |
| 178 | inst.DriverPID, err = ReadPIDFile(filepath.Join(instDir, filenames.PIDFile(*y.VMType))) |
| 179 | if err != nil { |
| 180 | inst.Status = limatype.StatusBroken |
| 181 | inst.Errors = append(inst.Errors, err) |
| 182 | } |
| 183 | |
| 184 | if inst.Status == limatype.StatusUnknown { |
| 185 | switch { |
| 186 | case inst.HostAgentPID > 0 && inst.DriverPID > 0: |
| 187 | inst.Status = limatype.StatusRunning |
| 188 | case inst.HostAgentPID == 0 && inst.DriverPID == 0: |
| 189 | inst.Status = limatype.StatusStopped |
| 190 | case inst.HostAgentPID > 0 && inst.DriverPID == 0: |
| 191 | inst.Errors = append(inst.Errors, errors.New("host agent is running but driver is not")) |
| 192 | inst.Status = limatype.StatusBroken |
| 193 | default: |
| 194 | inst.Errors = append(inst.Errors, fmt.Errorf("%s driver is running but host agent is not", inst.VMType)) |
| 195 | inst.Status = limatype.StatusBroken |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | func ReadPIDFile(path string) (int, error) { |
| 204 | |
| 205 | |
| 206 | if previousBoot, err := pidFileFromPreviousBoot(path); err != nil { |
| 207 | return 0, err |
| 208 | } else if previousBoot { |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | logrus.Debugf("Ignoring PID file %#q left behind by a previous boot", path) |
| 214 | return 0, nil |
| 215 | } |
| 216 | b, err := os.ReadFile(path) |
| 217 | if err != nil { |
| 218 | if errors.Is(err, os.ErrNotExist) { |
| 219 | return 0, nil |
| 220 | } |
| 221 | return 0, err |
| 222 | } |
| 223 | pid, err := strconv.Atoi(strings.TrimSpace(string(b))) |
| 224 | if err != nil { |
| 225 | return 0, err |
| 226 | } |
| 227 | proc, err := os.FindProcess(pid) |
| 228 | if runtime.GOOS == "windows" { |
| 229 | |
| 230 | if err == nil { |
| 231 | return pid, nil |
| 232 | } |
| 233 | var errno syscall.Errno |
| 234 | const ErrorInvalidParameter syscall.Errno = 0x57 |
| 235 | if errors.As(err, &errno) && errno == ErrorInvalidParameter { |
| 236 | _ = os.Remove(path) |
| 237 | return 0, nil |
| 238 | } |
| 239 | } |
| 240 | if err != nil { |
| 241 | return 0, err |
| 242 | } |
| 243 | err = proc.Signal(syscall.Signal(0)) |
| 244 | if err != nil { |
| 245 | if errors.Is(err, os.ErrProcessDone) { |
| 246 | _ = os.Remove(path) |
| 247 | return 0, nil |
| 248 | } |
| 249 | |
| 250 | |
| 251 | if !errors.Is(err, os.ErrPermission) { |
| 252 | return 0, err |
| 253 | } |
| 254 | } |
| 255 | return pid, nil |
| 256 | } |
| 257 | |
| 258 | |
| 259 | func sshPortFromConfig(configPath string) (int, error) { |
| 260 | b, err := os.ReadFile(configPath) |
| 261 | if err != nil { |
| 262 | return 0, err |
| 263 | } |
| 264 | for line := range strings.SplitSeq(string(b), "\n") { |
| 265 | line = strings.TrimSpace(line) |
| 266 | if port, ok := strings.CutPrefix(line, "Port "); ok { |
| 267 | return strconv.Atoi(port) |
| 268 | } |
| 269 | } |
| 270 | return 0, fmt.Errorf("port not found in %#q", configPath) |
| 271 | } |
| 272 | |
| 273 | type FormatData struct { |
| 274 | limatype.Instance `yaml:",inline"` |
| 275 | |
| 276 | |
| 277 | |
| 278 | HostOS string `json:"HostOS" yaml:"HostOS" lima:"deprecated"` |
| 279 | HostArch string `json:"HostArch" yaml:"HostArch" lima:"deprecated"` |
| 280 | LimaHome string `json:"LimaHome" yaml:"LimaHome" lima:"deprecated"` |
| 281 | IdentityFile string `json:"IdentityFile" yaml:"IdentityFile" lima:"deprecated"` |
| 282 | } |
| 283 | |
| 284 | var FormatHelp = "\n" + |
| 285 | "These functions are available to go templates:\n\n" + |
| 286 | textutil.IndentString(2, |
| 287 | strings.Join(textutil.FuncHelp, "\n")+"\n") |
| 288 | |
| 289 | func AddGlobalFields(inst *limatype.Instance) (FormatData, error) { |
| 290 | var data FormatData |
| 291 | data.Instance = *inst |
| 292 | |
| 293 | data.HostOS = runtime.GOOS |
| 294 | |
| 295 | data.HostArch = limatype.NewArch(runtime.GOARCH) |
| 296 | |
| 297 | configDir, err := dirnames.LimaConfigDir() |
| 298 | if err != nil { |
| 299 | return FormatData{}, err |
| 300 | } |
| 301 | data.IdentityFile = filepath.Join(configDir, filenames.UserPrivateKey) |
| 302 | |
| 303 | data.LimaHome, err = dirnames.LimaDir() |
| 304 | if err != nil { |
| 305 | return FormatData{}, err |
| 306 | } |
| 307 | return data, nil |
| 308 | } |
| 309 | |
| 310 | type PrintOptions struct { |
| 311 | AllFields bool |
| 312 | TerminalWidth int |
| 313 | } |
| 314 | |
| 315 | |
| 316 | |
| 317 | func PrintInstances(w io.Writer, instances []*limatype.Instance, format string, options *PrintOptions) error { |
| 318 | switch format { |
| 319 | case "json": |
| 320 | format = "{{json .}}" |
| 321 | case "yaml": |
| 322 | format = "{{yaml .}}" |
| 323 | case "table": |
| 324 | types := map[string]int{} |
| 325 | archs := map[string]int{} |
| 326 | for _, instance := range instances { |
| 327 | types[instance.VMType]++ |
| 328 | archs[instance.Arch]++ |
| 329 | } |
| 330 | all := options != nil && options.AllFields |
| 331 | width := 0 |
| 332 | if options != nil { |
| 333 | width = options.TerminalWidth |
| 334 | } |
| 335 | columnWidth := 8 |
| 336 | hideType := false |
| 337 | hideArch := false |
| 338 | hideDir := false |
| 339 | |
| 340 | |
| 341 | |
| 342 | columns := 1 |
| 343 | columns += 2 |
| 344 | columns += 2 |
| 345 | |
| 346 | if width != 0 && (columns+7)*columnWidth > width && !all { |
| 347 | hideType = len(types) == 1 |
| 348 | } |
| 349 | if !hideType { |
| 350 | columns++ |
| 351 | } |
| 352 | |
| 353 | goarch := limatype.NewArch(runtime.GOARCH) |
| 354 | |
| 355 | if width != 0 && (columns+6)*columnWidth > width && !all { |
| 356 | hideArch = len(archs) == 1 && instances[0].Arch == goarch |
| 357 | } |
| 358 | if !hideArch { |
| 359 | columns++ |
| 360 | } |
| 361 | columns++ |
| 362 | columns++ |
| 363 | columns++ |
| 364 | |
| 365 | if width != 0 && (columns+2)*columnWidth > width && !all { |
| 366 | hideDir = true |
| 367 | } |
| 368 | if !hideDir { |
| 369 | columns += 2 |
| 370 | } |
| 371 | _ = columns |
| 372 | |
| 373 | w := tabwriter.NewWriter(w, 4, 8, 4, ' ', 0) |
| 374 | fmt.Fprint(w, "NAME\tSTATUS\tSSH") |
| 375 | if !hideType { |
| 376 | fmt.Fprint(w, "\tVMTYPE") |
| 377 | } |
| 378 | if !hideArch { |
| 379 | fmt.Fprint(w, "\tARCH") |
| 380 | } |
| 381 | fmt.Fprint(w, "\tCPUS\tMEMORY\tDISK") |
| 382 | if !hideDir { |
| 383 | fmt.Fprint(w, "\tDIR") |
| 384 | } |
| 385 | fmt.Fprintln(w) |
| 386 | |
| 387 | homeDir, err := os.UserHomeDir() |
| 388 | if err != nil { |
| 389 | return err |
| 390 | } |
| 391 | |
| 392 | for _, instance := range instances { |
| 393 | dir := instance.Dir |
| 394 | if strings.HasPrefix(dir, homeDir) { |
| 395 | dir = strings.Replace(dir, homeDir, "~", 1) |
| 396 | } |
| 397 | fmt.Fprintf(w, "%s\t%s\t%s", |
| 398 | instance.Name, |
| 399 | instance.Status, |
| 400 | fmt.Sprintf("%s:%d", instance.SSHAddress, instance.SSHLocalPort), |
| 401 | ) |
| 402 | if !hideType { |
| 403 | fmt.Fprintf(w, "\t%s", |
| 404 | instance.VMType, |
| 405 | ) |
| 406 | } |
| 407 | if !hideArch { |
| 408 | fmt.Fprintf(w, "\t%s", |
| 409 | instance.Arch, |
| 410 | ) |
| 411 | } |
| 412 | fmt.Fprintf(w, "\t%d\t%s\t%s", |
| 413 | instance.CPUs, |
| 414 | units.BytesSize(float64(instance.Memory)), |
| 415 | units.BytesSize(float64(instance.Disk)), |
| 416 | ) |
| 417 | if !hideDir { |
| 418 | fmt.Fprintf(w, "\t%s", |
| 419 | dir, |
| 420 | ) |
| 421 | } |
| 422 | fmt.Fprint(w, "\n") |
| 423 | } |
| 424 | return w.Flush() |
| 425 | default: |
| 426 | |
| 427 | } |
| 428 | tmpl, err := template.New("format").Funcs(textutil.TemplateFuncMap).Parse(format) |
| 429 | if err != nil { |
| 430 | return fmt.Errorf("invalid go template: %w", err) |
| 431 | } |
| 432 | for _, instance := range instances { |
| 433 | data, err := AddGlobalFields(instance) |
| 434 | if err != nil { |
| 435 | return err |
| 436 | } |
| 437 | data.Message = strings.TrimSuffix(instance.Message, "\n") |
| 438 | err = tmpl.Execute(w, data) |
| 439 | if err != nil { |
| 440 | return err |
| 441 | } |
| 442 | fmt.Fprintln(w) |
| 443 | } |
| 444 | return nil |
| 445 | } |