Skip to content

Commit

Permalink
Merge pull request lima-vm#2718 from nirs/convert-to-raw
Browse files Browse the repository at this point in the history
Fix nativeimgutil.ConvertToRaw()
  • Loading branch information
AkihiroSuda authored Oct 15, 2024
2 parents 6f7569f + 4a24c29 commit 9705b66
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions pkg/nativeimgutil/nativeimgutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ func ConvertToRaw(source, dest string, size *int64, allowSourceWithBackingFile b
defer os.RemoveAll(destTmp)
defer destTmpF.Close()

// Truncating before copy eliminates the seeks during copy and provide a
// hint to the file system that may minimize allocations and fragmanation
// of the file.
if err := MakeSparse(destTmpF, srcImg.Size()); err != nil {
return err
}

// Copy
srcImgR := io.NewSectionReader(srcImg, 0, srcImg.Size())
bar, err := progressbar.New(srcImg.Size())
Expand Down Expand Up @@ -124,8 +131,8 @@ func convertRawToRaw(source, dest string, size *int64) error {

func copySparse(w *os.File, r io.Reader, bufSize int64) (int64, error) {
var (
n int64
eof, hasWrites bool
n int64
eof bool
)

zeroBuf := make([]byte, bufSize)
Expand All @@ -139,31 +146,22 @@ func copySparse(w *os.File, r io.Reader, bufSize int64) (int64, error) {
}
}
// TODO: qcow2reader should have a method to notify whether buf is zero
if bytes.Equal(buf, zeroBuf) {
if _, sErr := w.Seek(int64(rN), io.SeekCurrent); sErr != nil {
return n, fmt.Errorf("failed seek: %w", sErr)
}
// no need to ftruncate here
if bytes.Equal(buf[:rN], zeroBuf[:rN]) {
n += int64(rN)
} else {
hasWrites = true
wN, wErr := w.Write(buf)
wN, wErr := w.WriteAt(buf[:rN], n)
if wN > 0 {
n += int64(wN)
}
if wErr != nil {
return n, fmt.Errorf("failed to read: %w", wErr)
return n, fmt.Errorf("failed to write: %w", wErr)
}
if wN != rN {
return n, fmt.Errorf("read %d, but wrote %d bytes", rN, wN)
}
}
}

// Ftruncate must be run if the file contains only zeros
if !hasWrites {
return n, MakeSparse(w, n)
}
return n, nil
}

Expand Down

0 comments on commit 9705b66

Please sign in to comment.