#!/bin/sh

. ./live-migration-functions.sh

MEM_SIZE=5G
VCPU_NUM=6
GUEST_IMG=/other/vm/fc16-raw.img
CLIENT=192.168.122.89

if [ $1 == "pre" ]
then
  auto_ssh_login $CLIENT
  exit
fi

if [ $1 == "netpre" ]
then
  prepare_network
  exit
fi

mkfifo /var/my.sock >& /dev/null

# start the source
qemu-kvm -enable-kvm -smp $VCPU_NUM -m $MEM_SIZE $GUEST_IMG -chardev socket,id=hmp_id_hmp1,path=/var/my.sock,server,nowait -mon chardev=hmp_id_hmp1,mode=readline -netdev tap,id=tapnet,ifname=tap0,script=no -device virtio-net,netdev=tapnet &

echo "start the distance guest..."

# start the distance
qemu-kvm -enable-kvm -smp $VCPU_NUM -m $MEM_SIZE $GUEST_IMG -incoming tcp:0:99 -netdev tap,id=tapnet,ifname=tap1,script=no -device virtio-net,netdev=tapnet &

wait_boot $CLIENT

# Start runing some workload on source guest
ssh -f $CLIENT "cd ~; rm -f result; nohup /home/eric/mmtest/mmtest -m 3500 -c 36 > result &"
sleep 1

# live-migration
echo "start live migration..."
echo "migrate -d tcp:0:99" | nc -U /var/my.sock

for ((;1;)) {
  sleep 5
  echo "info migrate" | nc -U /var/my.sock >& live.log
#  status=`cat live.log | grep "Migration status" | awk '{print $3}'`
  status=$(sed 's/\r//g' live.log | grep "Migration status" | awk '{print $3}')
  if [ "$status" = "completed" ]
  then
    cat live.log | grep "total time"
    break
  fi
#  echo "Live Status: $status"
  cat live.log | grep "remaining"
}
echo "finished..."

# show benchmark result
scp $CLIENT:~/result ./
cat ./result | grep "Avg time"



