Skip to content
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

incusd/storage/drivers/common: Truncate/Discard ahead of sparse write #1496

Merged
merged 1 commit into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
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
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
}
Loading