| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "strings" |
| 14 | |
| 15 | "github.com/sirupsen/logrus" |
| 16 | "github.com/spf13/cobra" |
| 17 | "github.com/spf13/pflag" |
| 18 | |
| 19 | "github.com/lima-vm/lima/v2/cmd/limactl/editflags" |
| 20 | "github.com/lima-vm/lima/v2/pkg/autostart" |
| 21 | "github.com/lima-vm/lima/v2/pkg/driver/external/server" |
| 22 | "github.com/lima-vm/lima/v2/pkg/driverutil" |
| 23 | "github.com/lima-vm/lima/v2/pkg/editutil" |
| 24 | "github.com/lima-vm/lima/v2/pkg/instance" |
| 25 | "github.com/lima-vm/lima/v2/pkg/limatmpl" |
| 26 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 27 | "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 28 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 29 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 30 | "github.com/lima-vm/lima/v2/pkg/networks/reconcile" |
| 31 | "github.com/lima-vm/lima/v2/pkg/registry" |
| 32 | "github.com/lima-vm/lima/v2/pkg/store" |
| 33 | "github.com/lima-vm/lima/v2/pkg/templatestore" |
| 34 | "github.com/lima-vm/lima/v2/pkg/uiutil" |
| 35 | "github.com/lima-vm/lima/v2/pkg/yqutil" |
| 36 | ) |
| 37 | |
| 38 | func registerCreateFlags(cmd *cobra.Command, commentPrefix string) { |
| 39 | flags := cmd.Flags() |
| 40 | flags.String("name", "", commentPrefix+"Override the instance name") |
| 41 | flags.Bool("list-templates", false, commentPrefix+"List available templates and exit") |
| 42 | flags.Bool("list-drivers", false, commentPrefix+"List available drivers and exit") |
| 43 | editflags.RegisterCreate(cmd, commentPrefix) |
| 44 | _ = cmd.RegisterFlagCompletionFunc("set", setFlagCompletion) |
| 45 | } |
| 46 | |
| 47 | func newCreateCommand() *cobra.Command { |
| 48 | createCommand := &cobra.Command{ |
| 49 | Use: "create FILE.yaml|URL", |
| 50 | Example: ` |
| 51 | To create an instance "default" from the default Ubuntu template: |
| 52 | $ limactl create |
| 53 | |
| 54 | To create an instance "default" from a template "docker": |
| 55 | $ limactl create --name=default template:docker |
| 56 | |
| 57 | To create an instance "default" with modified parameters: |
| 58 | $ limactl create --cpus=2 --memory=2 |
| 59 | |
| 60 | To create an instance "default" with yq expressions: |
| 61 | $ limactl create --set='.cpus = 2 | .memory = "2GiB"' |
| 62 | Note: Some yq operators are restricted. See 'limactl help yq-restrictions'. |
| 63 | |
| 64 | To create an instance "default" with a template parameter: |
| 65 | $ limactl create --name=default --param containerdSnapshotter=false template:docker |
| 66 | |
| 67 | To see the template list: |
| 68 | $ limactl create --list-templates |
| 69 | |
| 70 | To create an instance "default" from a local file: |
| 71 | $ limactl create --name=default /usr/local/share/lima/templates/fedora.yaml |
| 72 | |
| 73 | To create an instance "default" from a remote URL (use carefully, with a trustable source): |
| 74 | $ limactl create --name=default https://raw.githubusercontent.com/lima-vm/lima/master/templates/alpine.yaml |
| 75 | |
| 76 | To create an instance "local" from a template passed to stdin (--name parameter is required): |
| 77 | $ cat template.yaml | limactl create --name=local - |
| 78 | `, |
| 79 | Short: "Create an instance of Lima", |
| 80 | Args: WrapArgsError(cobra.MaximumNArgs(1)), |
| 81 | ValidArgsFunction: createBashComplete, |
| 82 | RunE: createAction, |
| 83 | GroupID: basicCommand, |
| 84 | } |
| 85 | registerCreateFlags(createCommand, "") |
| 86 | return createCommand |
| 87 | } |
| 88 | |
| 89 | func newStartCommand() *cobra.Command { |
| 90 | startCommand := &cobra.Command{ |
| 91 | Use: "start NAME|FILE.yaml|URL", |
| 92 | Example: ` |
| 93 | To create an instance "default" (if not created yet) from the default Ubuntu template, and start it: |
| 94 | $ limactl start |
| 95 | |
| 96 | To create an instance "default" from a template "docker", and start it: |
| 97 | $ limactl start --name=default template:docker |
| 98 | `, |
| 99 | Short: "Start an instance of Lima", |
| 100 | Args: WrapArgsError(cobra.MaximumNArgs(1)), |
| 101 | ValidArgsFunction: startBashComplete, |
| 102 | RunE: startAction, |
| 103 | GroupID: basicCommand, |
| 104 | } |
| 105 | registerCreateFlags(startCommand, "[limactl create] ") |
| 106 | if runtime.GOOS != "windows" { |
| 107 | startCommand.Flags().Bool("foreground", false, "Run the hostagent in the foreground") |
| 108 | } |
| 109 | startCommand.Flags().Duration("timeout", instance.DefaultWatchHostAgentEventsTimeout, "Duration to wait for the instance to be running before timing out") |
| 110 | startCommand.Flags().Bool("progress", false, "Show provision script progress by tailing cloud-init logs") |
| 111 | startCommand.SetHelpFunc(func(cmd *cobra.Command, _ []string) { |
| 112 | printCommandSummary(cmd) |
| 113 | |
| 114 | allFlags, createFlags := collectFlags(cmd) |
| 115 | printFlags(allFlags, createFlags) |
| 116 | |
| 117 | printGlobalFlags(cmd) |
| 118 | }) |
| 119 | |
| 120 | return startCommand |
| 121 | } |
| 122 | |
| 123 | func printCommandSummary(cmd *cobra.Command) { |
| 124 | fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n", cmd.Short) |
| 125 | fmt.Fprintf(cmd.OutOrStdout(), "Usage:\n %s\n\n", cmd.UseLine()) |
| 126 | |
| 127 | if cmd.Example != "" { |
| 128 | fmt.Fprintf(cmd.OutOrStdout(), "Examples:\n%s\n\n", cmd.Example) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | func getFlagType(flag *pflag.Flag) string { |
| 133 | switch flag.Value.Type() { |
| 134 | case "bool": |
| 135 | return "" |
| 136 | case "string": |
| 137 | return "string" |
| 138 | case "int": |
| 139 | return "int" |
| 140 | case "duration": |
| 141 | return "duration" |
| 142 | case "stringSlice", "stringArray": |
| 143 | return "strings" |
| 144 | case "ipSlice": |
| 145 | return "ipSlice" |
| 146 | case "uint16": |
| 147 | return "uint16" |
| 148 | case "float32": |
| 149 | return "float32" |
| 150 | default: |
| 151 | return flag.Value.Type() |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | func formatFlag(flag *pflag.Flag) (flagName, shorthand string) { |
| 156 | flagName = "--" + flag.Name |
| 157 | |
| 158 | if flag.Shorthand != "" { |
| 159 | shorthand = "-" + flag.Shorthand |
| 160 | } |
| 161 | |
| 162 | flagType := getFlagType(flag) |
| 163 | if flagType != "" { |
| 164 | flagName += " " + flagType |
| 165 | } |
| 166 | |
| 167 | return flagName, shorthand |
| 168 | } |
| 169 | |
| 170 | func collectFlags(cmd *cobra.Command) (allFlags, createFlags []string) { |
| 171 | cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) { |
| 172 | flagName, shorthand := formatFlag(flag) |
| 173 | flagUsage := flag.Usage |
| 174 | |
| 175 | var formattedFlag string |
| 176 | if shorthand != "" { |
| 177 | formattedFlag = fmt.Sprintf(" %s, %s", shorthand, flagName) |
| 178 | } else { |
| 179 | formattedFlag = fmt.Sprintf(" %s", flagName) |
| 180 | } |
| 181 | |
| 182 | if strings.HasPrefix(flagUsage, "[limactl create]") { |
| 183 | cleanUsage := strings.TrimPrefix(flagUsage, "[limactl create] ") |
| 184 | createFlags = append(createFlags, fmt.Sprintf("%-25s %s", formattedFlag, cleanUsage)) |
| 185 | } else { |
| 186 | allFlags = append(allFlags, fmt.Sprintf("%-25s %s", formattedFlag, flagUsage)) |
| 187 | } |
| 188 | }) |
| 189 | return allFlags, createFlags |
| 190 | } |
| 191 | |
| 192 | func printFlags(allFlags, createFlags []string) { |
| 193 | if len(allFlags) > 0 { |
| 194 | fmt.Fprint(os.Stdout, "Flags:\n") |
| 195 | for _, flag := range allFlags { |
| 196 | fmt.Fprintln(os.Stdout, flag) |
| 197 | } |
| 198 | fmt.Fprint(os.Stdout, "\n") |
| 199 | } |
| 200 | |
| 201 | if len(createFlags) > 0 { |
| 202 | fmt.Fprint(os.Stdout, "Flags inherited from `limactl create`:\n") |
| 203 | for _, flag := range createFlags { |
| 204 | fmt.Fprintln(os.Stdout, flag) |
| 205 | } |
| 206 | fmt.Fprint(os.Stdout, "\n") |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func printGlobalFlags(cmd *cobra.Command) { |
| 211 | if cmd.HasAvailableInheritedFlags() { |
| 212 | fmt.Fprintf(cmd.OutOrStdout(), "Global Flags:\n%s", cmd.InheritedFlags().FlagUsages()) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | func loadOrCreateInstance(cmd *cobra.Command, args []string, createOnly bool) (*limatype.Instance, error) { |
| 217 | ctx := cmd.Context() |
| 218 | var arg string |
| 219 | if len(args) > 0 { |
| 220 | arg = args[0] |
| 221 | } |
| 222 | |
| 223 | flags := cmd.Flags() |
| 224 | |
| 225 | |
| 226 | tty, err := flags.GetBool("tty") |
| 227 | if err != nil { |
| 228 | return nil, err |
| 229 | } |
| 230 | |
| 231 | name, err := flags.GetString("name") |
| 232 | if err != nil { |
| 233 | return nil, err |
| 234 | } |
| 235 | if name != "" { |
| 236 | err := dirnames.ValidateInstName(name) |
| 237 | if err != nil { |
| 238 | return nil, err |
| 239 | } |
| 240 | } |
| 241 | if isTemplateURL, templateName := limatmpl.SeemsTemplateURL(arg); isTemplateURL { |
| 242 | switch templateName { |
| 243 | case "experimental/vz": |
| 244 | logrus.Warn("template:experimental/vz was merged into the default template in Lima v1.0. See also <https://lima-vm.io/docs/config/vmtype/>.") |
| 245 | case "experimental/riscv64": |
| 246 | logrus.Warn("template:experimental/riscv64 was merged into the default template in Lima v1.0. Use `limactl create --arch=riscv64 template:default` instead.") |
| 247 | case "experimental/armv7l": |
| 248 | logrus.Warn("template:experimental/armv7l was merged into the default template in Lima v1.0. Use `limactl create --arch=armv7l template:default` instead.") |
| 249 | case "vmnet": |
| 250 | logrus.Warn("template:vmnet was removed in Lima v1.0. Use `limactl create --network=lima:shared template:default` instead. See also <https://lima-vm.io/docs/config/network/>.") |
| 251 | case "experimental/net-user-v2": |
| 252 | logrus.Warn("template:experimental/net-user-v2 was removed in Lima v1.0. Use `limactl create --network=lima:user-v2 template:default` instead. See also <https://lima-vm.io/docs/config/network/>.") |
| 253 | case "experimental/9p": |
| 254 | logrus.Warn("template:experimental/9p was removed in Lima v1.0. Use `limactl create --vm-type=qemu --mount-type=9p template:default` instead. See also <https://lima-vm.io/docs/config/mount/>.") |
| 255 | case "experimental/virtiofs-linux": |
| 256 | logrus.Warn("template:experimental/virtiofs-linux was removed in Lima v1.0. Use `limactl create --mount-type=virtiofs template:default` instead. See also <https://lima-vm.io/docs/config/mount/>.") |
| 257 | } |
| 258 | } |
| 259 | if arg == "-" { |
| 260 | if name == "" { |
| 261 | return nil, errors.New("must pass instance name with --name when reading template from stdin") |
| 262 | } |
| 263 | |
| 264 | ttySet := cmd.Flags().Changed("tty") |
| 265 | if ttySet && tty { |
| 266 | return nil, errors.New("cannot use --tty=true when reading template from stdin") |
| 267 | } |
| 268 | tty = false |
| 269 | } |
| 270 | var tmpl *limatmpl.Template |
| 271 | if err := dirnames.ValidateInstName(arg); arg == "" || err == nil { |
| 272 | tmpl = &limatmpl.Template{Name: name} |
| 273 | if arg == "" { |
| 274 | if name == "" { |
| 275 | tmpl.Name = DefaultInstanceName |
| 276 | } |
| 277 | } else { |
| 278 | logrus.Debugf("interpreting argument %#q as an instance name", arg) |
| 279 | if name != "" && name != arg { |
| 280 | return nil, fmt.Errorf("instance name %#q and CLI flag --name=%#q cannot be specified together", arg, tmpl.Name) |
| 281 | } |
| 282 | tmpl.Name = arg |
| 283 | } |
| 284 | |
| 285 | inst, err := store.Inspect(ctx, tmpl.Name) |
| 286 | if err == nil { |
| 287 | configErr := errors.Join(inst.Errors...) |
| 288 | if configErr != nil { |
| 289 | logrus.WithError(configErr).Errorf("Instance %q has configuration errors", tmpl.Name) |
| 290 | } |
| 291 | if inst.Config == nil { |
| 292 | if configErr != nil { |
| 293 | return nil, fmt.Errorf("instance %q has configuration errors: %w", tmpl.Name, configErr) |
| 294 | } |
| 295 | return nil, fmt.Errorf("instance %q has no configuration", tmpl.Name) |
| 296 | } |
| 297 | if createOnly { |
| 298 | return nil, fmt.Errorf("instance %#q already exists", tmpl.Name) |
| 299 | } |
| 300 | logrus.Infof("Using the existing instance %#q", tmpl.Name) |
| 301 | yqExprs, err := editflags.YQExpressions(flags, false, inst.Config.Param) |
| 302 | if err != nil { |
| 303 | return nil, err |
| 304 | } |
| 305 | if len(yqExprs) > 0 { |
| 306 | yq := yqutil.Join(yqExprs) |
| 307 | inst, err = applyYQExpressionToExistingInstance(ctx, inst, yq) |
| 308 | if err != nil { |
| 309 | return nil, fmt.Errorf("failed to apply yq expression %#q to instance %#q: %w", yq, tmpl.Name, err) |
| 310 | } |
| 311 | } |
| 312 | return inst, nil |
| 313 | } |
| 314 | if !errors.Is(err, os.ErrNotExist) { |
| 315 | return nil, err |
| 316 | } |
| 317 | if arg != "" && arg != DefaultInstanceName { |
| 318 | logrus.Infof("Creating an instance %#q from template:default (Not from template:%s)", tmpl.Name, tmpl.Name) |
| 319 | logrus.Warnf("This form is deprecated. Use `limactl create --name=%s template:default` instead", tmpl.Name) |
| 320 | } |
| 321 | |
| 322 | tmpl.Bytes, err = templatestore.Read(templatestore.Default) |
| 323 | if err != nil { |
| 324 | return nil, err |
| 325 | } |
| 326 | } else { |
| 327 | tmpl, err = limatmpl.Read(ctx, name, arg) |
| 328 | if err != nil { |
| 329 | return nil, err |
| 330 | } |
| 331 | if createOnly { |
| 332 | |
| 333 | if _, err := store.Inspect(ctx, tmpl.Name); err == nil { |
| 334 | return nil, fmt.Errorf("instance %#q already exists", tmpl.Name) |
| 335 | } |
| 336 | } else if err := dirnames.ValidateInstName(tmpl.Name); err != nil { |
| 337 | return nil, err |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | if err := tmpl.Embed(ctx, true, true); err != nil { |
| 342 | return nil, err |
| 343 | } |
| 344 | if err := tmpl.Unmarshal(); err != nil { |
| 345 | return nil, err |
| 346 | } |
| 347 | if tmpl.Config != nil && tmpl.Config.OS != nil && *tmpl.Config.OS != limatype.LINUX { |
| 348 | logrus.Warn("Support for non-Linux guests is experimental") |
| 349 | } |
| 350 | yqExprs, err := editflags.YQExpressions(flags, true, tmpl.Config.Param) |
| 351 | if err != nil { |
| 352 | return nil, err |
| 353 | } |
| 354 | yq := yqutil.Join(yqExprs) |
| 355 | if tty { |
| 356 | var err error |
| 357 | tmpl, err = chooseNextCreatorState(ctx, tmpl, yq) |
| 358 | if err != nil { |
| 359 | return nil, err |
| 360 | } |
| 361 | } else { |
| 362 | logrus.Info("Terminal is not available, proceeding without opening an editor") |
| 363 | if err := modifyInPlace(ctx, tmpl, yq); err != nil { |
| 364 | return nil, err |
| 365 | } |
| 366 | } |
| 367 | saveBrokenYAML := tty |
| 368 | return instance.Create(ctx, tmpl.Name, tmpl.Bytes, saveBrokenYAML) |
| 369 | } |
| 370 | |
| 371 | func applyYQExpressionToExistingInstance(ctx context.Context, inst *limatype.Instance, yq string) (*limatype.Instance, error) { |
| 372 | if strings.TrimSpace(yq) == "" { |
| 373 | return inst, nil |
| 374 | } |
| 375 | filePath := filepath.Join(inst.Dir, filenames.LimaYAML) |
| 376 | yContent, err := os.ReadFile(filePath) |
| 377 | if err != nil { |
| 378 | return nil, err |
| 379 | } |
| 380 | logrus.Debugf("Applying yq expression %#q to an existing instance %#q", yq, inst.Name) |
| 381 | yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent) |
| 382 | if err != nil { |
| 383 | return nil, err |
| 384 | } |
| 385 | y, err := limayaml.Load(ctx, yBytes, filePath) |
| 386 | if err != nil { |
| 387 | return nil, err |
| 388 | } |
| 389 | |
| 390 | if err := driverutil.ResolveVMType(y); err != nil { |
| 391 | return nil, err |
| 392 | } |
| 393 | inst.Config = y |
| 394 | limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) |
| 395 | if err != nil { |
| 396 | return nil, err |
| 397 | } |
| 398 | if err := limaDriver.Validate(ctx); err != nil { |
| 399 | return nil, saveRejectedYAML(yBytes, err) |
| 400 | } |
| 401 | if err := limayaml.Validate(inst.Config, true); err != nil { |
| 402 | return nil, saveRejectedYAML(yBytes, err) |
| 403 | } |
| 404 | if err := os.WriteFile(filePath, yBytes, 0o644); err != nil { |
| 405 | return nil, err |
| 406 | } |
| 407 | |
| 408 | return store.Inspect(ctx, inst.Name) |
| 409 | } |
| 410 | |
| 411 | func modifyInPlace(ctx context.Context, st *limatmpl.Template, yq string) error { |
| 412 | out, err := yqutil.EvaluateExpression(ctx, yq, st.Bytes) |
| 413 | if err != nil { |
| 414 | return err |
| 415 | } |
| 416 | st.Bytes = out |
| 417 | return nil |
| 418 | } |
| 419 | |
| 420 | |
| 421 | type exitSuccessError struct { |
| 422 | Msg string |
| 423 | } |
| 424 | |
| 425 | |
| 426 | func (e exitSuccessError) Error() string { |
| 427 | return e.Msg |
| 428 | } |
| 429 | |
| 430 | |
| 431 | func (exitSuccessError) ExitCode() int { |
| 432 | return 0 |
| 433 | } |
| 434 | |
| 435 | func chooseNextCreatorState(ctx context.Context, tmpl *limatmpl.Template, yq string) (*limatmpl.Template, error) { |
| 436 | for { |
| 437 | if err := modifyInPlace(ctx, tmpl, yq); err != nil { |
| 438 | logrus.WithError(err).Warn("Failed to evaluate yq expression") |
| 439 | return tmpl, err |
| 440 | } |
| 441 | message := fmt.Sprintf("Creating an instance %#q", tmpl.Name) |
| 442 | options := []string{ |
| 443 | "Proceed with the current configuration", |
| 444 | "Open an editor to review or modify the current configuration", |
| 445 | "Choose another template (docker, podman, archlinux, fedora, ...)", |
| 446 | "Exit", |
| 447 | } |
| 448 | ans, err := uiutil.Select(message, options) |
| 449 | if err != nil { |
| 450 | if errors.Is(err, uiutil.InterruptErr) { |
| 451 | logrus.Fatal("Interrupted by user") |
| 452 | } |
| 453 | logrus.WithError(err).Warn("Failed to open TUI") |
| 454 | return tmpl, nil |
| 455 | } |
| 456 | switch ans { |
| 457 | case 0: |
| 458 | return tmpl, nil |
| 459 | case 1: |
| 460 | hdr := fmt.Sprintf("# Review and modify the following configuration for Lima instance %#q.\n", tmpl.Name) |
| 461 | if tmpl.Name == DefaultInstanceName { |
| 462 | hdr += "# - In most cases, you do not need to modify this file.\n" |
| 463 | } |
| 464 | hdr += "# - To cancel starting Lima, just save this file as an empty file.\n" |
| 465 | hdr += "\n" |
| 466 | hdr += editutil.GenerateEditorWarningHeader() |
| 467 | var err error |
| 468 | tmpl.Bytes, err = editutil.OpenEditor(ctx, tmpl.Bytes, hdr) |
| 469 | tmpl.Config = nil |
| 470 | if err != nil { |
| 471 | return tmpl, err |
| 472 | } |
| 473 | if len(tmpl.Bytes) == 0 { |
| 474 | const msg = "Aborting, as requested by saving the file with empty content" |
| 475 | logrus.Info(msg) |
| 476 | return nil, exitSuccessError{Msg: msg} |
| 477 | } |
| 478 | err = tmpl.Embed(ctx, true, true) |
| 479 | if err != nil { |
| 480 | return nil, err |
| 481 | } |
| 482 | return tmpl, nil |
| 483 | case 2: |
| 484 | templates, err := filterHiddenTemplates() |
| 485 | if err != nil { |
| 486 | return tmpl, err |
| 487 | } |
| 488 | message := "Choose a template" |
| 489 | options := make([]string, len(templates)) |
| 490 | for i := range templates { |
| 491 | options[i] = templates[i].Name |
| 492 | } |
| 493 | ansEx, err := uiutil.Select(message, options) |
| 494 | if err != nil { |
| 495 | return tmpl, err |
| 496 | } |
| 497 | if ansEx > len(templates)-1 { |
| 498 | return tmpl, fmt.Errorf("invalid answer %d for %d entries", ansEx, len(templates)) |
| 499 | } |
| 500 | yamlPath := templates[ansEx].Location |
| 501 | if tmpl.Name == "" { |
| 502 | tmpl.Name, err = limatmpl.InstNameFromYAMLPath(yamlPath) |
| 503 | if err != nil { |
| 504 | return nil, err |
| 505 | } |
| 506 | } |
| 507 | tmpl, err = limatmpl.Read(ctx, tmpl.Name, yamlPath) |
| 508 | if err != nil { |
| 509 | return nil, err |
| 510 | } |
| 511 | err = tmpl.Embed(ctx, true, true) |
| 512 | if err != nil { |
| 513 | return nil, err |
| 514 | } |
| 515 | continue |
| 516 | case 3: |
| 517 | return nil, exitSuccessError{Msg: "Choosing to exit"} |
| 518 | default: |
| 519 | return tmpl, fmt.Errorf("unexpected answer %d", ans) |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | |
| 525 | func createStartActionCommon(cmd *cobra.Command, _ []string) (exit bool, err error) { |
| 526 | if listTemplates, err := cmd.Flags().GetBool("list-templates"); err != nil { |
| 527 | return true, err |
| 528 | } else if listTemplates { |
| 529 | templates, err := filterHiddenTemplates() |
| 530 | if err != nil { |
| 531 | return true, err |
| 532 | } |
| 533 | w := cmd.OutOrStdout() |
| 534 | for _, f := range templates { |
| 535 | _, _ = fmt.Fprintln(w, f.Name) |
| 536 | } |
| 537 | return true, nil |
| 538 | } else if listDrivers, err := cmd.Flags().GetBool("list-drivers"); err != nil { |
| 539 | return true, err |
| 540 | } else if listDrivers { |
| 541 | w := cmd.OutOrStdout() |
| 542 | for k := range registry.List() { |
| 543 | _, _ = fmt.Fprintln(w, k) |
| 544 | } |
| 545 | return true, nil |
| 546 | } |
| 547 | return false, nil |
| 548 | } |
| 549 | |
| 550 | func filterHiddenTemplates() ([]templatestore.Template, error) { |
| 551 | templates, err := templatestore.Templates() |
| 552 | if err != nil { |
| 553 | return nil, err |
| 554 | } |
| 555 | var filtered []templatestore.Template |
| 556 | for _, f := range templates { |
| 557 | |
| 558 | if !strings.HasPrefix(f.Name, "_") { |
| 559 | filtered = append(filtered, f) |
| 560 | } |
| 561 | } |
| 562 | return filtered, nil |
| 563 | } |
| 564 | |
| 565 | func createAction(cmd *cobra.Command, args []string) error { |
| 566 | if exit, err := createStartActionCommon(cmd, args); err != nil { |
| 567 | return err |
| 568 | } else if exit { |
| 569 | return nil |
| 570 | } |
| 571 | inst, err := loadOrCreateInstance(cmd, args, true) |
| 572 | if err != nil { |
| 573 | return err |
| 574 | } |
| 575 | if len(inst.Errors) > 0 { |
| 576 | return fmt.Errorf("errors inspecting instance: %+v", inst.Errors) |
| 577 | } |
| 578 | if _, err = instance.Prepare(cmd.Context(), inst, ""); err != nil { |
| 579 | return err |
| 580 | } |
| 581 | server.Stop(inst.Dir, true) |
| 582 | logrus.Infof("Run `limactl start %s` to start the instance.", inst.Name) |
| 583 | return nil |
| 584 | } |
| 585 | |
| 586 | func startAction(cmd *cobra.Command, args []string) error { |
| 587 | if exit, err := createStartActionCommon(cmd, args); err != nil { |
| 588 | return err |
| 589 | } else if exit { |
| 590 | return nil |
| 591 | } |
| 592 | inst, err := loadOrCreateInstance(cmd, args, false) |
| 593 | if err != nil { |
| 594 | return err |
| 595 | } |
| 596 | if len(inst.Errors) > 0 { |
| 597 | return fmt.Errorf("errors inspecting instance: %+v", inst.Errors) |
| 598 | } |
| 599 | switch inst.Status { |
| 600 | case limatype.StatusRunning: |
| 601 | logrus.Infof("The instance %#q is already running. Run `%s` to open the shell.", |
| 602 | inst.Name, instance.LimactlShellCmd(inst.Name)) |
| 603 | |
| 604 | return nil |
| 605 | case limatype.StatusStopped: |
| 606 | |
| 607 | default: |
| 608 | logrus.Warnf("expected status %#q, got %#q", limatype.StatusStopped, inst.Status) |
| 609 | } |
| 610 | ctx := cmd.Context() |
| 611 | |
| 612 | if registered, err := autostart.IsRegistered(ctx, inst); err != nil && !errors.Is(err, autostart.ErrNotSupported) { |
| 613 | return fmt.Errorf("failed to check if the autostart entry for instance %#q is registered: %w", inst.Name, err) |
| 614 | } else if (registered && autostart.AutoStartedIdentifier() != "") || !registered { |
| 615 | err = reconcile.Reconcile(ctx, inst.Name) |
| 616 | if err != nil { |
| 617 | return err |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | launchHostAgentForeground := false |
| 622 | if runtime.GOOS != "windows" { |
| 623 | foreground, err := cmd.Flags().GetBool("foreground") |
| 624 | if err != nil { |
| 625 | return err |
| 626 | } |
| 627 | launchHostAgentForeground = foreground |
| 628 | } |
| 629 | timeout, err := cmd.Flags().GetDuration("timeout") |
| 630 | if err != nil { |
| 631 | return err |
| 632 | } |
| 633 | |
| 634 | if !cmd.Flags().Changed("timeout") && *inst.Config.OS == limatype.WINDOWS { |
| 635 | if _, err := os.Stat(filepath.Join(inst.Dir, filenames.WinDoneInstallation)); err != nil { |
| 636 | timeout = instance.WinDefaultWatchHostAgentEventsTimeout |
| 637 | logrus.Infof("Extended the default timeout to %v for Windows guest initial boot.", timeout) |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | if timeout > 0 { |
| 642 | ctx = instance.WithWatchHostAgentTimeout(ctx, timeout) |
| 643 | } |
| 644 | |
| 645 | progress, err := cmd.Flags().GetBool("progress") |
| 646 | if err != nil { |
| 647 | return err |
| 648 | } |
| 649 | |
| 650 | return instance.Start(ctx, inst, launchHostAgentForeground, progress) |
| 651 | } |
| 652 | |
| 653 | func createBashComplete(cmd *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 654 | return bashCompleteTemplateNames(cmd, toComplete) |
| 655 | } |
| 656 | |
| 657 | func startBashComplete(cmd *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 658 | compInst, _ := bashCompleteInstanceNames(cmd) |
| 659 | compTmpl, _ := bashCompleteTemplateNames(cmd, toComplete) |
| 660 | return append(compInst, compTmpl...), cobra.ShellCompDirectiveDefault |
| 661 | } |