「Sparse File」- 稀疏文件

解决方案

与常规文件的创建方式不同,当创建 Sparse-File 时:
1)不会将组成块的实际字节写入磁盘,
2)而是在元数据中记录文件大小,并将元数据写入磁盘。
3)当向文件写入数据时,才会分配实际的数据块。
4)当读取稀疏文件时,文件系统透明地将表示空块的元数据转换为在运行时填充 NULL 字节的“真实”块;

所以,能否使用 Sparse-File 取决于文件系统是否支持。

常用操作

判断稀疏文件

archlinux/Sparse file
Finding sparse files?

# 通过 find 判断文件是否为稀疏文件
# 最左边一列(%S)显示的值是(BLOCK-SIZE * st_blocks / st_size),在稀疏文件的情况下通常小于 1.0

# find /var/lib/libvirt/images f -printf "%S\t%p\n"
0.217076       ./cnicd-02.qcow2
0.152867       ./cnicd-01.qcow2
0.925253       ./ci-node-01.qcow2
1              ./develop.qcow2
0.48236        ./cluster-08.qcow2
0.100322       ./develop-235.qcow2
1              ./develop-354.qcow2


# ls shows the gray+green areas, the logical length of the file. 
# du (without --apparent-size) shows only the green areas, since those are the ones that take up space.

# ls -lh  cnicd-01.qcow2 
-rw------- 1 libvirt-qemu kvm 101G Mar 30 02:24 cnicd-01.qcow2

# du -h cnicd-01.qcow2
16G     cnicd-01.qcow2

# stat -c '%b*%B-%s' -- "$file"                                                 # 或使用 stat 命令

创建稀疏文件

# dd count=0 bs=1M seek=100 of=/path/to/myfile

复制稀疏文件

方法还是由很多的,性能可能会有所差异,使用场景以有些不一样的地方:「What is fastest way to copy a sparse file? What method results in the smallest file?

可以使用cp、dd、cpio、rsync、virt-sparsify等命令,其中virt-sparsify是用于虚拟机迁移,当时是为了迁移虚拟机镜像文件,才有所涉猎。

这里不再深入,有需要的时候再研究,详细内容参考各个命令的手册。

稀疏文件的实际大小

So what is the size of that file? Sparse Files on Linux

TODO 关于稀疏文件的实际大小

参考文献

Wikipedia/Sparse file
What is fastest way to copy a sparse file? What method results in the smallest file?
Sparse Files – GeeksforGeeks
unix – what is the most reliable command to find actual size of a file linux – Stack Overflow
How to find all the sparse files in Linux