#!/usr/bin/python

# ============================================================================
# Author:    	 Jim Fehlig, <jfehlig@novell.com>
# Contributors:  Raj Subrahmanian, <Raj.Subrahmanian@Unisys.com>
#		 Luke Szymanski, <Lukasz.Szymanski@Unisys.com>
#
# Description:	 Basic test to check the lifecycle of a vm
# 
# Copyright (C) 2007 Novell Corporation, Unisys Corporation
# ============================================================================

import sys
import pywbem
import os
import time

def ChangeState(state, VM_Inst):
# Invoke RequestStateChange on vm
  try:
    (rval, out_params) = conn.InvokeMethod('RequestStateChange', VM_Inst, RequestedState=str(state))
    print 'Return Value of RequestStateChange: %s' % rval
    print 'Output = %s' % out_params

  except pywbem.CIMError, arg:
    print 'Caught exception when calling InvokeMethod'
    if arg[0] != pywbem.CIM_ERR_NOT_SUPPORTED:
        print 'InvokeMethod(instancename): %s' % arg[1]
        sys.exit(1)

  except ValueError, e:
    pass

  time.sleep(2)
  os.system('xm list')

# End of ChangeState

# =================
# There are a few things you need to change for your system
# Name of your VM ...
VM_Name = 'vm2'
# ... the CIMOM connection, BootloaderOptions and DiskConfigInfo attributes below
# =================

# Connect to cimom
conn = pywbem.WBEMConnection('http://localhost', ('', ''))

# Enumerate instances of Xen_ComputerSystem
print '==== Enumerating instances of Xen_ComputerSystem: ===='
inst_names = conn.EnumerateInstanceNames('Xen_ComputerSystem')
for n in inst_names:
    inst = conn.GetInstance(n)

    for key, value in inst.items():
        if key in ('Name', 'RequestedState'):
            print '    %s = %s' % (key, value)
		
# Get instance of Virtual System Management Service
print '==== Looking for Virtual System Management Service... ===='
vsms = conn.EnumerateInstanceNames("Xen_VirtualSystemManagementService")
print 'Got Virtual System Management Service: %s' % str(vsms[0])

# Create virtual system settings for new VM
vssd = '''
instance of Xen_ComputerSystemSettingData {
'''
vssd = vssd + 'VirtualSystemIdentifier = "%s";' % VM_Name
vssd_1 = '''
VirtualSystemType = "Xen Paravirtual";
Bootloader = "/usr/lib/xen/boot/domUloader.py";
BootloaderOptions = "--entry=hda2:/boot/vmlinuz-xen,/boot/initrd-xen";
Root = "/dev/hda2 ro";
KernelOptions = "Term=xterm";
};
'''
vssd = vssd + vssd_1

# Create resource settings for the new VM
proc_rasd = '''
instance of Xen_ProcessorSettingData {
ResourceType = 3;
VirtualQuantity = 1;
AllocationUnits = "Cores";
};
'''

mem_rasd = '''
instance of Xen_MemorySettingData {
ResourceType = 4;
VirtualQuantity = 256;
AllocationUnits = "MegaBytes";
};
'''

disk_rasd = '''
instance of Xen_DiskSettingData {
ResourceType = 19;
DiskConfigInfo =  "file:/tmp/images/sles10gm-x64-clean.img,hda,w";
};
'''

nic_rasd = '''
instance of Xen_NetworkPortSettingData {
ResourceType = 10;
NICConfigInfo = "mac=00:16:3e:9d:9e:ad";
};
'''

console_rasd = '''
instance of Xen_ConsoleSettingData {
ResourceType = 24;
Protocol = 1;
};
'''

rasds = [proc_rasd, mem_rasd, disk_rasd, nic_rasd, console_rasd]

in_params = {'SystemSettings': vssd, 'ResourceSettings': rasds}

print '==== Before VM creation ===='
os.system('xm list')

# Invoke DefineSystem on Virtual System Management Service to define a new VM,
# providing the new VM settings and its resource settings.
try:
    print '==== Calling DefineSystem to create a new VM ... ===='
    (rval, out_params) = conn.InvokeMethod('DefineSystem', vsms[0], **in_params)
    print 'Return Value of DefineSystem: %s' % rval
    print 'Output = %s' % out_params

except pywbem.CIMError, arg:
    print 'Caught exception when calling InvokeMethod'
    if arg[0] != pywbem.CIM_ERR_NOT_SUPPORTED:
        print 'InvokeMethod(instancename): %s' % arg[1]
        sys.exit(1)

except ValueError, e:
    pass


# Get instance of newly created vm
print '==== Enumerating instances of Xen_ComputerSystem: ===='
inst_names = conn.EnumerateInstanceNames('Xen_ComputerSystem')
for n in inst_names:
    inst = conn.GetInstance(n)

    for key, value in inst.items():
        if key in ('Name', 'RequestedState'):
            print '    %s = %s' % (key, value)
	    if value == VM_Name:
		# Find newly created VM instance from enumerated list
		VM_Inst = n

print '==== Starting new VM ===='
ChangeState(2, VM_Inst)

print '==== Deactivating new VM ===='
ChangeState(3, VM_Inst)

"""
#print '==== Shutting down new VM ===='
#ChangeState(4, VM_Inst)

# inst_names = conn.EnumerateInstanceNames('Xen_ComputerSystem')
# for n in inst_names:
#    inst = conn.GetInstance(n)


# Get instance of newly activated vm

# os.system('xm delete vm2')
"""

