Skip to content

Support: limactl disk import command #3439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions cmd/limactl/disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ import (
"fmt"
"io/fs"
"os"
"path/filepath"
"text/tabwriter"

contfs "github.com/containerd/continuity/fs"
"github.com/docker/go-units"
"github.com/lima-vm/go-qcow2reader"
"github.com/lima-vm/lima/pkg/nativeimgutil"
"github.com/lima-vm/lima/pkg/qemu"
"github.com/lima-vm/lima/pkg/store"
"github.com/lima-vm/lima/pkg/store/filenames"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -44,6 +48,7 @@ func newDiskCommand() *cobra.Command {
newDiskDeleteCommand(),
newDiskUnlockCommand(),
newDiskResizeCommand(),
newDiskImportCommand(),
)
return diskCommand
}
Expand Down Expand Up @@ -418,3 +423,64 @@ func diskResizeAction(cmd *cobra.Command, args []string) error {
func diskBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return bashCompleteDiskNames(cmd)
}

func newDiskImportCommand() *cobra.Command {
diskImportCommand := &cobra.Command{
Use: "import DISK FILE",
Example: `
Import a disk:
$ limactl disk import DISK DISKPATH
`,
Short: "Import an existing disk to Lima",
Args: WrapArgsError(cobra.ExactArgs(2)),
RunE: diskImportAction,
ValidArgsFunction: diskBashComplete,
}
return diskImportCommand
}

func diskImportAction(_ *cobra.Command, args []string) error {
diskName := args[0]
fName := args[1]

diskDir, err := store.DiskDir(diskName)
if err != nil {
return err
}

if _, err := os.Stat(diskDir); !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("disk %q already exists (%q)", diskName, diskDir)
}

f, err := os.Open(fName)
if err != nil {
return err
}
defer f.Close()

img, err := qcow2reader.Open(f)
if err != nil {
return err
}

diskSize := img.Size()
format := img.Type()

switch format {
case "qcow2", "raw":
default:
return fmt.Errorf(`disk format %q not supported, use "qcow2" or "raw" instead`, format)
}

if err := os.MkdirAll(diskDir, 0o755); err != nil {
return err
}

if err := contfs.CopyFile(filepath.Join(diskDir, filenames.DataDisk), fName); err != nil {
return nil
}

logrus.Infof("Imported %s with size %s", diskName, units.BytesSize(float64(diskSize)))

return nil
}