Skip to content

Commit

Permalink
incusd/storage/drivers/common: Truncate/Discard ahead of sparse write
Browse files Browse the repository at this point in the history
As we use a sparse writer which will skip any zero blocks, we need to
discard (block) or truncate (file) prior to processing the data or we
risk having leftover data from a previous snapshot interfere with the
new state.

Closes #1264

Signed-off-by: Stéphane Graber <[email protected]>
  • Loading branch information
stgraber committed Dec 12, 2024
1 parent aaad08a commit 24c7c08
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions internal/server/storage/drivers/generic_vfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/lxc/incus/v6/shared/ioprogress"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/subprocess"
"github.com/lxc/incus/v6/shared/util"
)

Expand Down Expand Up @@ -332,6 +333,36 @@ func genericVFSCreateVolumeFromMigration(d Driver, initVolume func(vol Volume) (

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

st, err := to.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", path)
if err != nil {
return err
}
} else {
// Otherwise truncate the file.
err = to.Truncate(0)
if err != nil {
return err
}

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

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

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

st, err := to.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", targetPath)
if err != nil {
return err
}
} else {
// Otherwise truncate the file.
err = to.Truncate(0)
if err != nil {
return err
}

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

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

d.Logger().Debug(logMsg, logger.Ctx{"source": srcFile, "target": targetPath})
_, err = io.Copy(NewSparseFileWrapper(to), tr)
if err != nil {
Expand Down

0 comments on commit 24c7c08

Please sign in to comment.