Skip to content

Instantly share code, notes, and snippets.

@gersilex
Created July 24, 2019 12:27

Revisions

  1. gersilex created this gist Jul 24, 2019.
    55 changes: 55 additions & 0 deletions migrate_live_ssh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    #!/usr/bin/env bash
    #
    # Live migration-over-SSH script for use with OpenNebula.
    # Set the 'migrate' action to run this script in /etc/one/oned.conf
    # for your respective virtualization type. Only KVM is supported right now.
    #
    # Author: Leroy Förster <leroy.foerster@immonet.de>
    # Contributor: Paul Jost <paul.jost.immonet.de>
    #
    # (c) 2019 Immowelt Hamburg GmbH
    # Released under the MIT License.
    #

    set -xeuo pipefail

    source "$(dirname "$0")/kvmrc"
    source "$(dirname "$0")/../../scripts_common.sh"

    VIRSH_COMMAND="virsh --connect $LIBVIRT_URI"

    get_disks(){
    ssh -n "$src_host" -- "$VIRSH_COMMAND" domblklist "$deploy_id" | strings | tail -n+3 | awk '{print $2}'
    }

    get_size_of_disk_img(){
    qemu_img_path="$1"

    ssh -n "$src_host" -- qemu-img info -U "$qemu_img_path" --output json | sed -nE 's/^.*"virtual-size": ([0-9]+).*/\1/p'
    }

    create_target_disk_img(){
    qemu_img_path="$1"
    size="$2"

    ssh -n "$dest_host" -- mkdir -v -p "$(dirname "$qemu_img_path")"
    ssh -n "$dest_host" -- qemu-img create -f qcow2 "$qemu_img_path" "$size"
    }

    deploy_id="$1"
    dest_host="$2"
    src_host="$3"

    get_disks | while read -r disk
    do
    create_target_disk_img "$disk" "$(get_size_of_disk_img "$disk")"
    done

    # Snapshots must be removed before migration
    snapshots="$(ssh -n "$src_host" -- "$VIRSH_COMMAND" snapshot-list "$deploy_id" --name)"
    for snapshot in $snapshots
    do
    ssh -n "$src_host" -- "$VIRSH_COMMAND" snapshot-delete "$deploy_id" --snapshotname "$snapshot" --metadata
    done

    ssh -n "$src_host" -- "$VIRSH_COMMAND" migrate "$deploy_id" "$QEMU_PROTOCOL://$dest_host/system" --live --copy-storage-all