AUTHOR = 'ryanh@us.ibm.com (Ryan Harper)'
TIME = 'SHORT'
NAME = 'KVM Test with KVM module build'
TEST_TYPE = 'client'
TEST_CLASS = 'Kernel'
TEST_CATEGORY = 'Functional'
DOC = '''
Run kvm-test after first downloading, building and installing the KVM module.
'''

# CHANGEME  - point to kvm release tarball
#
#
# nightly kvm snapshot base URL
SNAPBASE = 'http://people.qumranet.com/avi/snapshots/'

#CHAGEME - point to your kvmtest test dir
TESTDIR = '/opt/kvmtest_tests'

# change this value to point to older snapshots , defaults to
# look for yesterday's snapshot
DAYSOLD=1

import test
import os, sys
from datetime import *
from utils import *



def install_kvm_external_modules(tarball=None, base=SNAPBASE, daysold=DAYSOLD):
    dldir = os.environ['AUTODIR']+'/tmp'
    srcdir = os.environ['AUTODIR']+'/tmp/kvm'
    print "kvm dldir->%s"%(dldir)
    print "kvm srcdir->%s"%(srcdir)

    # ex: http://people.qumranet.com/avi/snapshots/kvm-snapshot-20071021.tar.gz
    if tarball is None:
        d = (date.today() - timedelta(days=daysold)).strftime('%Y%m%d')
        tarball = base+'kvm-snapshot-%s.tar.gz' %(d)
        sys.stderr.write("tarball url: %s\n" %(tarball))

    tarball = unmap_url("/", tarball, dldir)
    extract_tarball_to_dir(tarball, srcdir)
    os.chdir(srcdir)

    print "detecting cpu vendor..."
    vendor = "intel"
    if os.system("grep vmx /proc/cpuinfo 1>/dev/null") != 0:
        vendor = "amd"
    print "detected cpu vendor as '%s'" %(vendor)

    print "building kvm..."
    system('./configure')
    system('make')
    system('make install')
    print "done building and installing kvm"

    # remove existing in kernel kvm modules
    print "unloading loaded kvm modules (if present) ..."
    if system("grep kvm_%s /proc/modules 1>/dev/null" %(vendor), 1) == 0:
        system("rmmod -f kvm_%s" %(vendor))
    if system("grep kvm /proc/modules 1>/dev/null", 1) == 0:
        system("rmmod -f kvm")

    # load new modules
    print "loading new kvm modules..."
    os.chdir(srcdir+'/kernel')
    system("insmod ./kvm.ko && sleep 1 && insmod ./kvm-%s.ko" %(vendor))


# build and install kvm external modules
install_kvm_external_modules()

# run kvmtest on all tests in testdir
job.run_test('kvmtest', testdir=TESTDIR)