Skip to content

Commit

Permalink
Merge pull request #1496 from stgraber/storage
Browse files Browse the repository at this point in the history
incusd/storage/drivers/common: Truncate/Discard ahead of sparse write
  • Loading branch information
stgraber authored Dec 12, 2024
2 parents bcd25fc + c9a1dfd commit 721e2e5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions internal/server/storage/drivers/generic_vfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,12 @@ func genericVFSCreateVolumeFromMigration(d Driver, initVolume func(vol Volume) (

defer func() { _ = to.Close() }()

// Reset the disk.
err = clearDiskData(path, to)
if err != nil {
return err
}

// Setup progress tracker.
fromPipe := io.ReadCloser(conn)
if wrapper != nil {
Expand Down Expand Up @@ -787,6 +793,13 @@ func genericVFSBackupUnpack(d Driver, sysOS *sys.OS, vol Volume, snapshots []str
logMsg = "Unpacking custom block volume"
}

// Reset the disk.
err = clearDiskData(targetPath, to)
if err != nil {
return err
}

// Copy the data.
d.Logger().Debug(logMsg, logger.Ctx{"source": srcFile, "target": targetPath})
_, err = io.Copy(NewSparseFileWrapper(to), tr)
if err != nil {
Expand Down
35 changes: 35 additions & 0 deletions internal/server/storage/drivers/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,3 +957,38 @@ func roundAbove(above, val int64) int64 {

return rounded
}

// clearDiskData resets a disk file or device to a zero value.
func clearDiskData(diskPath string, disk *os.File) error {
st, err := disk.Stat()
if err != nil {
return err
}

if linux.IsBlockdev(st.Mode()) {
// If dealing with a block device, discard its current content.
// This saves space and avoids issues with leaving zero blocks to their original value.
_, err = subprocess.RunCommand("blkdiscard", diskPath)
if err != nil {
return err
}
} else {
// Otherwise truncate the file.
err = disk.Truncate(0)
if err != nil {
return err
}

err = disk.Truncate(st.Size())
if err != nil {
return err
}

_, err = disk.Seek(0, 0)
if err != nil {
return err
}
}

return nil
}

0 comments on commit 721e2e5

Please sign in to comment.