How to clone LVM thin provisioning volume?

I googled many times but couldn't find an answer. What I want is cloning an LVM thin provisioning volume to another thin volume.

For now I know dd can clone a thin volume as following:

dd if=/dev/mapper/vg_thin01 of=/dev/mapper/vg_thin02 bs=1M

But the new cloned volume will be full size! How can I make it to sparse/thin volume?

(Actually the thin volume will be used for DomU storage in Xen or KVM )


Solution 1:

Cloning a thin volume is as simple as taking a snapshot of the to-be-cloned volume. When using thin volumes, snapshot and new volumes really are the same thing, with different default flags.

From the kernel docs:

Once created, the user doesn't have to worry about any connection between the origin and the snapshot. Indeed the snapshot is no different from any other thinly-provisioned device and can be snapshotted itself via the same method. It's perfectly legal to have only one of them active, and there's no ordering requirement on activating or removing them both. (This differs from conventional device-mapper snapshots.)

So it is perfectly legal to snapshot a thinly-provisioned volume to create a CoW clone. From the man page:

Example
       Create first snapshot of an existing ThinLV:
       # lvcreate -n thin1s1 -s vg/thin1

Solution 2:

I believe this hasn't been correctly answered (yet) because the OP appears to be indicating two different volume groups, a source and a destination. So I'll try to answer it.

Note: This response assumes that a reference like /dev/mapper/vg_thin02 indicates a volume group in accordance with the usual Linux convention, and that any pool or thin volume in that group would be followed by a dash like so: /dev/mapper/vg_thin02-volA.

When cloning between two volume groups (or two thin pools) on the same machine, for each source volume do:

fstrim /mnt/volA
umount /mnt/volA
lvcreate -kn -ay -V sizeofvolA -T vg_thin02/poolname -n volA
dd if=/dev/mapper/vg_thin01-volA of=/dev/mapper/vg_thin02-volA conv=sparse

Continue with "volB", "volC", etc. as necessary. The conv=sparse argument stores the new copy in a sparse, thin-provisioned way.

The fstrim and umount lines show that some form of trim/discard is necessary on the source volume before it is taken offline and duplicated. If the volume is normally mounted with the discard option this may not be necessary.

For cloning between two different machines, you can use ssh on the source machine in conjunction with dd on the destination:

gzip -2 </dev/mapper/vg_thin01-volA | ssh user@address "zcat | sudo dd of=/dev/mapper/vg_thin02-volA conv=sparse"