Skip to content

Instantly share code, notes, and snippets.

@XavM
Last active December 3, 2015 17:00
Show Gist options
  • Save XavM/cb987bb0502305985faa to your computer and use it in GitHub Desktop.
Save XavM/cb987bb0502305985faa to your computer and use it in GitHub Desktop.
Clone a (ploop) openVZ CT with base image dedup
#!/bin/bash
# Clone a (ploop) openVZ CT with base image dedup
# Ex : ./vzclone $CTID | xargs vzctl start
set -eo pipefail
if [ -z $1 ]; then
>&2 echo "Usage: vzclone CTID"
exit 1
fi
get_ctid() {
local CTID="$1"
vzlist ${CTID} -Ho ctid \
| xargs # xargs to Remove leading and trailing white spaces / tabs when they exist
}
main() {
local SRC_CT="$1"
local SRC_CTID=$(get_ctid ${SRC_CT} || echo 0)
# Exit when CT can't be found
[[ "${SRC_CTID}" == 0 ]] && exit 3
# Get the current nbr of snapshot for SRC CT
local SNAPSHOTS_NBR=$(ploop snapshot-list -H /vz/private/$SRC_CTID/root.hdd/DiskDescriptor.xml | wc -l)
# Exit when snapshot-list didn't work
[[ "${SNAPSHOTS_NBR}" == 0 ]] && exit 3
# Get the snapshot id so that we can merge it back to the base image when cloning is done
local SNAPSHOT_ID="$(uuidgen)"
# Take a live snapshot of the CT (Should be merged back to parent snapshot after cloning)
vzctl --quiet snapshot $SRC_CTID \
--id ${SNAPSHOT_ID} \
--name cloneProcess \
--description "Temporary snapshot for clone process" \
--skip-suspend --skip-config \
|| exit 3
local SRC_CT_PRIVATE="$(vzlist -Ho private $SRC_CTID)"
local DEST_CTID=$(date +%s)
local DEST_CT_PRIVATE="${SRC_CT_PRIVATE/${SRC_CTID}/${DEST_CTID}}"
# Clone CT conf from SRC to DEST
cp /etc/vz/conf/$SRC_CTID.conf /etc/vz/conf/$DEST_CTID.conf \
|| exit 3
# Unset description, hostname, ip and name in DEST CT
for PARAM in IP_ADDRESS HOSTNAME NAME DESCRIPTION; do
sed -i "s/${PARAM}=\".*\"/${PARAM}=\"\"/" /etc/vz/conf/${DEST_CTID}.conf \
|| exit 3
done
# Set hostname to clonedCT in DEST CT
sed -i "s/HOSTNAME=\".*\"/HOSTNAME=\"clonedCT\"/" /etc/vz/conf/${DEST_CTID}.conf \
# Create DEST CT folders
mkdir -p $DEST_CT_PRIVATE/root.hdd /vz/root/$DEST_CTID \
|| exit 3
# Hard link base image from SRC to DEST
ln $SRC_CT_PRIVATE/root.hdd/root.hdd ${DEST_CT_PRIVATE}/root.hdd/root.hdd \
|| exit 3
# Copy * from SRC to DEST (except for the hard linked root.hdd : cp -n)
2>/dev/null cp -nr ${SRC_CT_PRIVATE}/root.hdd ${DEST_CT_PRIVATE}/ || true
# Don't if the parent is the base image
[[ ${SNAPSHOTS_NBR} > 1 ]] && {
# Merge back the newly created snapshot to parent snapshot for SRC CT
ploop snapshot-merge -u ${SNAPSHOT_ID} \
${SRC_CT_PRIVATE}/root.hdd/DiskDescriptor.xml >/dev/null
# Delete the newly created snapshot to parent snapshot for DEST CT
vzctl --quiet mount $DEST_CTID
while killall --quiet -0 ext4lazyinit; do sleep 1; done
vzctl --quiet umount $DEST_CTID
ploop snapshot-delete -u "${SNAPSHOT_ID}" \
${DEST_CT_PRIVATE}/root.hdd/DiskDescriptor.xml >/dev/null
}
echo $DEST_CTID
}
main "${1}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment