#!/usr/bin/python
import sys
import xml.etree.ElementTree as thing
from distutils.version import LooseVersion
import argparse
import subprocess
import time
import re
import os
import socket

def restore_backup(backup_file):
    print("Restoring original configuration.")
    if os.path.isfile(backup_file):
        restore_return = subprocess.call(['virsh', 'define', str(backup_file)], stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
        if restore_return == 0:
            print("Original confiuration restored")
        else:
            print("There was a problem when restoring the original configuration \""+str(backup_file)+"\"")
            quit(1)
    else:
        print("Cannot find backup to restore, \""+str(backup_file)+"\"")
        quit(1)

path_for_stuff = '/root/migration_reseller'  # Path to hold temporary files
new_cpu_model  = 'cpu64-rhel6'
sshkey = '/root/.ssh/id_rsa'
bandwidth = 85                  # MiB/s
timeout = 23400			# 23400 = 6.5 hours, then will suspend guest and finish faster
ipaddr = socket.gethostbyname(socket.gethostname())

# Command line option stuff
parser = argparse.ArgumentParser()
group2 = parser.add_argument_group('setup')
group2.add_argument('--setup', help='things to help setup servers', action='store_true')
group3 = parser.add_argument_group('migrate')
group3.add_argument('-s', '--server', help='the virsh server name')
group3.add_argument('-d', '--destination', '--dest', help='the destination node address')
group3.add_argument('-m', '--migrate', '--mig', help='start the actual migration', action='store_true')
group3.add_argument('--destroy', help='graceful destroy server if cannot shutdown', action='store_true')
group3.add_argument('-b', '--bandwidth', help='bandwidth to limit to, in MiB/s')
group3.add_argument('-t', '--timeout', help='timeout, in seconds, when guest will suspend itself for migration to complete faster')
args = parser.parse_args()
if not ( args.setup or ( args.server and args.destination )):
    print("Need to specify either --setup, or --server and --destination")
    quit(0)

if args.bandwidth:
    bandwidth = int(args.bandwidth)

if args.timeout:
    timeout = int(args.timeout)

# Check for SSH key on server. Create if needed.
if args.setup:
    if not os.path.isfile(sshkey):
        print("No ssh key found. Generating new key...")
        subprocess.call(['ssh-keygen', '-N', '', '-f', sshkey], stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
        if not os.path.isfile(sshkey) or not os.path.isfile(sshkey+'.pub'):
            print("Could not create \""+sshkey+"\".")
            quit(1)
    # Some output that the user should execute on the destination server
    print("Run these on destination"+('',' '+str(args.destination))[bool(args.destination)]+":")
    print
    print('# iptables -I INPUT -s '+ipaddr+'/32 -m comment --comment migration -j ACCEPT')
    pubkey = open(sshkey+'.pub', 'r').read().rstrip()
    print('# echo -e "---\\nip: \''+ipaddr+'\'\\nkey: \'from=\\"'+ipaddr+'\\" '+pubkey+'\'" >/root/.migration_key')
    print('# chmod 600 /root/.migration_key')
    print('# nice -n-15 puppet agent -t --tags=sshd_eig')
    print
    quit(0)

# Make sure our pathf or things exists and create some variables
if not os.path.exists(path_for_stuff):
    os.makedirs(path_for_stuff)
backup_xml_filename = path_for_stuff+'/'+args.server+'_'+str(int(time.time()))+'.xml'
new_xml_filename = path_for_stuff+'/'+args.server+'_new.xml'
regex_shutoff = r"\s*\-\s+" + re.escape(args.server) + r"\s+shut off"
regex_running = r"\s*\d+\s+" + re.escape(args.server) + r"\s+running"

# Get and backup the initial XML for the specified guest
print("-- Fixing XML")
print("Pulling and backing up XML for " + args.server + " to \"" + backup_xml_filename + "\"")
sys.stdout.flush()
xmldata = subprocess.Popen(['virsh','dumpxml',args.server], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")).communicate()[0]
if '<domain' not in xmldata:
    print("OH NO We didn't get the expected data from virsh")
    quit(1)
with open(backup_xml_filename, 'w') as original_file:
    original_file.write(xmldata)

# Change the guest CPU to something generic that we can migrate to new mroe different hardware without
# virsh complaining about the CPU differences, and write it out to a file.
# Also inject custom metadata so qemu destination hook knows is part of this process.
print("Making CPU generic...")
sys.stdout.flush()
doc = thing.fromstring(xmldata)
sec = doc.find('seclabel')
if sec:
    doc.remove(sec)
metadata = thing.SubElement(doc, 'metadata')
eigmig = thing.SubElement(metadata, 'eigmig')
eigmig.text = 'HG reseller migration'
cpu = doc.find('cpu')
cpu.clear()
cpu.set('mode','custom')
cpu.set('match','exact')
cpu_model = thing.SubElement(cpu, 'model', attrib={'fallback':'allow'})
if LooseVersion(os.uname()[2])>=LooseVersion('2.6.32-754.2.1.el6.x86_64'):
    feature1 = thing.SubElement(cpu, 'feature', attrib={'policy':'force', 'name':'virt-ssbd'})
    feature2 = thing.SubElement(cpu, 'feature', attrib={'policy':'force', 'name':'ibpb'})
cpu_model.text = new_cpu_model
with open(new_xml_filename, 'w') as new_file:
    new_file.write(thing.tostring(doc))

# If we actually want to go through with the migration
if args.migrate:
    print
    print("-- Migration")
    print("Restarting guest into new XML...")
    if not os.path.isfile(new_xml_filename):
        print("Cannot find file "+new_xml_filename+". Aborting.")
        quit(1)
    if not os.environ.get('STY'):
        print("You should probably be running this in a SCREEN")
        quit(0)
    # We issue a shutdown, and loop for awhile waiting for the guest to stop
    sys.stdout.write("Stopping...")
    sys.stdout.flush()
    is_off = False
    counter = 0
    virshdata = subprocess.Popen(['virsh','list','--all'], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")).communicate()[0]
    if not re.search(regex_shutoff, virshdata):
        subprocess.call(['virsh','shutdown',args.server], stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
    while not is_off:
        time.sleep(30) # 20*30 = 10min
        sys.stdout.write(".")
        sys.stdout.flush()
        virshdata = subprocess.Popen(['virsh','list','--all'], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")).communicate()[0]
        if re.search(regex_shutoff, virshdata):
            is_off = True
        counter += 1
        if counter > 20:
            print("Took to long to shutdown.")
            sys.stdout.flush()
            if args.destroy:
                sys.stdout.write("Destroying...")
                sys.stdout.flush()
                counter = 0
                subprocess.call(['virsh', 'destroy', '--graceful', args.server], stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
                while not is_off:
                    sys.stdout.write(".")
                    sys.stdout.flush()
                    time.sleep(2) # 20*2 = 40sec
                    virshdata = subprocess.Popen(['virsh','list','--all'], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")).communicate()[0]
                    if re.search(regex_shutoff, virshdata):
                        is_off = True
                    counter += 1
                    if counter > 20:
                        print("Took to long to destroy. Aborting.")
                        quit(1)
            else:
                # If couldn't shutdown, maybe need package instaleld inside guest
                print("Make sure \"acpid-2\" is installed in guest, or shut down manually")
                restore_backup(backup_xml_filename)
                quit(1)
    print
    # Server should be stopped now, so we re-define the guest with the new configuration
    print("Re-defining...")
    sys.stdout.flush()
    if not os.path.isfile(new_xml_filename):
        print("Cannot find file "+new_xml_filename+". Aborting.")
        quit(1)
    subprocess.call(['virsh','define',new_xml_filename], stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
    # Start guest and wait awhile for it to come up.
    sys.stdout.write("Starting...")
    sys.stdout.flush()
    counter = 0
    subprocess.call(['virsh','start',args.server], stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w"))
    while is_off:
        time.sleep(5)    # 48*5 = 4 minutes
        sys.stdout.write(".")
        sys.stdout.flush()
        virshdata = subprocess.Popen(['virsh','list','--all'], stdout=subprocess.PIPE, stderr=open("/dev/null", "w")).communicate()[0]
        if bool(re.search(regex_running, virshdata)):
            is_off = False
        counter += 1
        if counter > 48:
            print("Took to long to start. Aborting.")
            restore_backup(backup_xml_filename)
            quit(1)
    print

    # Set out bandwidth limits so we dont max out our disk 0 leave some IO for the running guest during the migration
    print("Setting BW limit to %s MiB/s (approx. %d%% of available BW)..." % (str(bandwidth),(bandwidth/1.05)))
    bw_return = subprocess.call(['virsh', 'migrate-setspeed', '--bandwidth', str(bandwidth), args.server])

    # Kick off the actual live migration
    if bool(re.search(r"^(\d+\.){3}\d+$", args.destination)):
        print("Running \"virsh migrate --live --persistent --verbose --timeout "+str(timeout)+" --copy-storage-all "+args.server+" qemu+ssh://root@"+str(args.destination)+"/system tcp://"+str(args.destination)+"\"...")
        migrate_return = subprocess.call(['virsh', 'migrate', '--live', '--persistent', '--verbose', '--timeout', str(timeout), '--copy-storage-all', args.server, "qemu+ssh://root@"+str(args.destination)+"/system", "tcp://"+str(args.destination)])
    else:
        print("Running \"virsh migrate --live --persistent --verbose --timeout "+str(timeout)+" --copy-storage-all "+args.server+" qemu+ssh://root@"+str(args.destination)+"/system\"...")
        migrate_return = subprocess.call(['virsh', 'migrate', '--live', '--persistent', '--verbose', '--timeout', str(timeout), '--copy-storage-all', args.server, "qemu+ssh://root@"+str(args.destination)+"/system"])
    print
    if migrate_return == 0:
        print("Virsh migration completed.")
    else:
        print("Migration FAILED!")
        restore_backup(backup_xml_filename)
        quit(1)

    # After the migration completes, we need to kick off the post-migration script on the destination
    # which will fix the CPU and its tunings to something appropriate for the new hardware
    print("Running post migration script on destination")
    if args.destroy:
        post_mig = subprocess.call(['ssh', 'root@'+str(args.destination), '/etc/libvirt/hooks/qemu', args.server, 'post', 'destroy'])
    else:
        post_mig = subprocess.call(['ssh', 'root@'+str(args.destination), '/etc/libvirt/hooks/qemu', args.server, 'post'])
    if post_mig == 0:
        print("Post migration script completed.")
    else:
        print("Post miration FAILED!")
        restore_backup(backup_xml_filename)
        quit(1)

    print
    restore_backup(backup_xml_filename)
    print('Done')
