concept
- Snapshots are special Logical Volumes that are an exact copy of an existing Logical Volume at the time the snapshot is created(创建时只拷贝源卷数据的metadata)
- Snapshots are perfect for backups and other operations where a temporary copy of an existing dataset is needed
- Snapshots only consume space where they are different from the original Logical Volume
- Snapshots are allocated space at creation but do not use it until changes are made to the original Logical Volume or the Snapshot
- When data is changed on the original Logical Volume the older data is copied to the Snapshot
- Snapshots contain only data that has changed on the original Logical Volume or the Snapshot since the Snapshot was created.
创建快照
# lvcreate -s -l 64 -n datasnap /dev/vg0/data <--- 在该时间点建立快照,不能指定组,自动划分出一个名为 datasnap 的 LV
# mount -o [ro,][nouuid] /dev/vg0/datasnap /mnt/databackup <--- 快照是可挂载,可读,可写的
# df -h; lvs <--- df -h 看到源卷与快照卷的两个挂载点使用情况是一模一样的, lvs 可以看到快照 lv 的真实使用情况
# lvremove /dev/vg0/datasnap <--- 删除快照卷
还原快照
# umount /dev/vgdemo/lv1snap <--- 如果快照卷已经挂载,请务必先卸载
方法1:先把源卷卸载,然后还原
# umount /dev/vgdemo/lv1
# lvconvert --merge /dev/vgdemo/lv1snap <--- 完成后,快照卷自动删除,数据卷变成快照卷的内容
方法二:源卷未卸载,直接还原,但需要对源卷做一个 flush 的动作:
# lvconvert --merge /dev/vgdemo/lv1snap
Can't merge over open origin volume
Merging of snapshot rootsnap will start next activation.
# umount /dev/vgdemo/lv1
# lvchange -an /dev/vgdemo/lv1
# lvchange -ay /dev/vgdemo/lv1
使用场景
利用 LVM 的快照与还原技术,我们主要使用在如下三个场景:
- 一致性备份(只读挂载快照卷,然后对基本进行备份)
- 测试恢复(使用源卷测试完成后,使用 lvconvert 对源卷进行恢复)
- 模版迭代(使用源卷创建任意个快照,使用快照,当某个快照更优时,使用该快照 lvconvert 源卷以对其进行更新)
快照大小
快照大小不能达到100%,达到100%后,使用 lvdsiplay 可以看到其状态为 INACTIVE:
LV snapshot status INACTIVE destination for lv1
此时,该快照卷损坏,即使 lvextend 也没有用,正在进行的备份会失败,IO subsystem 将 failed。
为了避免此类问题,一开始就要规划好快照大小。另外一个有限的办法是借助 lvm2-monitor 服务,它可以监控 LV 的使用情况,达到设定的使用率,则按设定的比例自动拉伸快照卷。
# vi /etc/lvm/lvm.conf
snapshot_autoextend_threshold = 80 <--- 默认值100,表示禁用自动扩展,最小50,低于50将被自动调整为50
snapshot_autoextend_percent = 20 <--- 拉伸比例
# service lvm2-monitor restart
注意:自动拉伸是需要花费时间的,不要把 threshold 的值设置得太高,否则还没来得及拉伸,快照卷就已经达到100%了。
例如,按照上面的配置,快照卷 60M,如果直接 dd 一个 70M 的文件,快照卷将损坏,如果 dd 一个 50M 的文件,快照卷会拉伸到 72M(dd 完成后,立即 lvs 查看会卡一小会儿)。