VMware VI (vSphere) Java API
To Design the Applications for VMware Infrastructure
VMware VI (vSphere) Java API
VI Java is a set of client-side libraries designed to ease the burden of developing applications for
VMware Infrastructure (VI) using the Java language. VI Java brings true OOP design to the VI SDK.
VI java provides us the required API to manage the vCenter Server Infrastructure management.
To implement VIJava we need to add the respective libraries in the Project.
VI java is hosted by sourceforge.net with BSD license and readily available
Guide for Implementing VI Java:
Go to the VI Java API web site( http://vijava.sf.net ) and click on the download link at the top.
On the download page, select the latest release and click the download link as follows:
http://sourceforge.net/projects/vijava/files/vijava/VI%20Java%20API%202.1/
Choose the binary vijava**********.zip (Note: the name can be different for future releases. Just pick up latest one) and start to download it. Optionally, you can download the package with source code -- vijava*src.jar
Unzip the vijava*********.zip file to a folder of your choice and you will get two jar files, one for VI Java API itself, and the other is dom4j-1.6.1.jar.
Include both the files in the library.
Make sure that you do not include the rest of Library files offered by the vSphere WebService SDK as it will lead to confusion for system from where to fetch the library files.
Error:
Exception in thread "main" java.lang.InstantiationError: com.vmware.vim25.VimPortType
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:82)
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:69)
at com.wipro.dummy.CreateVM.main(CreateVM.java:97)
Check the library Files make sure only viJava***.jar along with dom4j***.jar is included as shown below.
Writing First Program with VIJava
Kindly go through the tutorials/samples In case you are unable to use any of the feature
Inorder to setup a connection with vCenter Server
public static String serverip = "10.XXX.XXX.XX";
public static String userName = "administrator";
public static String password = "secret";
public static String centerServer = "https://”+ serverip + “/sdk/vimService";
public static String[] details = {centerServer,userName,password};
Create a service instance to a server
ServiceInstance si = new ServiceInstance(
new URL(centerServer), userName, password, true);
Folder rootFolder = si.getRootFolder();
To create a instance of HostSystem
HostSystem hostSystem= (HostSystem) new InventoryNavigator(rootFolder).searchManagedEntity("HostSystem", "hostName");
System.out.println("Max Vm Supported: "+hostSystem.getCapability().maxSupportedVcpus);
System.out.println("Max Vm Supported:"+hostSystem.getCapability().maxSupportedVcpus +" ");
Explore all the functions which are required to obtain respective information of HostSystem
Using this you can also explore the various configspec of the Host System
HostVirtualSwitch[] vSwitch = hostSystem.getConfig().getNetwork().getVswitch();
if(vSwitch!=null)
{
System.out.println(vSwitch.length);
System.out.println(vSwitch[1].getPnic()[1]);
}
In Order to obtain the Details of all the VM present in the HostSystem
VirtualMachine[] vMachine = hostSystem.getVms();
To obtain the details of all the VM Machines
for(VirtualMachine vm:vMachine)
{
System.out.println("Virtual Machine Name: " + vm.getName());
System.out.println("Virtual Machine Address: " + vm.getGuest().ipAddress );
System.out.println("Virtual Machine ID: " + vm.getGuest().guestId );
System.out.println("" + vm.getSummary().overallStatus );
System.out.println("Vm Power State: " + vm.getRuntime().getPowerState());
}
VM Creation:
To Create new VM provide the following parameters such as
String dcName = "DataCenter01"; //Name of data center
String vmName = "VjavaAPIVM"; //Name of VM
long memorySizeMB = 500; //Size of RAM
int cupCount = 1; //Number of Virtual CPU
String guestOsId = "sles10Guest"; //Guest Os IS
long diskSizeKB = 1000000; //Size of Hard Disk
String diskMode = "persistent"; //Disk Mode
String datastoreName = "software"; //DataStore for the VM
String netName = "VM Network"; //Network to be used
String nicName = "Network Adapter 1"; //Name of network Adapter
int cKey = 1000;
Create a service Instance as stated above
Folder rootFolder = si.getRootFolder();
Datacenter dc = (Datacenter) new InventoryNavigator( rootFolder).searchManagedEntity("Datacenter", dcName);
ResourcePool rp = (ResourcePool) new InventoryNavigator(
dc).searchManagedEntities("ResourcePool")[0];
Folder vmFolder = dc.getVmFolder();
Create a VM Config Spec
VirtualMachineConfigSpec vmSpec =
new VirtualMachineConfigSpec();
vmSpec.setName(vmName);
vmSpec.setAnnotation("VirtualMachine Annotation");
vmSpec.setMemoryMB(memorySizeMB);
vmSpec.setNumCPUs(cupCount);
vmSpec.setGuestId(guestOsId);
Adding Virtual Devices to VM:
Create a Scsi spec for the Storage of VM:
/**
Create a DeviceConfigSpec for the SCSI
Perform operation in order to add the Virtaul Device in VirtualDeviceConfigSpec */
/**
Create the type of SCSI you would require to add in your Virtual Machine such as LSILogicController Parallel, LSILogicController SAS, Bus Logic Controller , VM ware Parairtual
for every operating system there are recommended Scsi type Make sure you use the same
VirtualLsiLogicController scsiCtrl =
new VirtualLsiLogicController();
*/
static VirtualDeviceConfigSpec createScsiSpec(int cKey)
{
VirtualDeviceConfigSpec scsiSpec =
new VirtualDeviceConfigSpec();
scsiSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
VirtualLsiLogicController scsiCtrl =
new VirtualLsiLogicController();
scsiCtrl.setKey(cKey);
scsiCtrl.setBusNumber(0);
scsiCtrl.setSharedBus(VirtualSCSISharing.noSharing);
//Add the scsi controller to SCSi device
scsiSpec.setDevice(scsiCtrl);
return scsiSpec;
}
/**
Create the HARDDISK you would require to add in your Virtual Machine
Define the dataStore Name
DataStore : dsName
Size of Hard disk: diskSizeKB
VirtualDeviceConfigSpecFileOperation.create); to create A .vmdk file
Adding the Virtaul Disk
diskSpec.setDevice(vd);
*/
static VirtualDeviceConfigSpec createDiskSpec(String dsName,
int cKey, long diskSizeKB, String diskMode)
{
VirtualDeviceConfigSpec diskSpec =
new VirtualDeviceConfigSpec();
diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
diskSpec.setFileOperation(
VirtualDeviceConfigSpecFileOperation.create);
VirtualDisk vd = new VirtualDisk();
vd.setCapacityInKB(diskSizeKB);
diskSpec.setDevice(vd);
vd.setKey(0);
vd.setUnitNumber(0);
vd.setControllerKey(cKey);
/**
Setting up vmdk file for VM, Setting the various parameters for the Storage file
*/
VirtualDiskFlatVer2BackingInfo diskfileBacking =
new VirtualDiskFlatVer2BackingInfo();
String fileName = "["+ dsName +"]";
diskfileBacking.setFileName(fileName);
diskfileBacking.setDiskMode(diskMode);
diskfileBacking.setThinProvisioned(true);
vd.setBacking(diskfileBacking);
/**
Will return the Diskspec which will be used to add in the virtual machine Virtual Device
*/
return diskSpec;
}
/**
Creation of NIC
Parameters to passed : Network Name, Network Card Name
To add the Network we need to create a Instance of Virtual Device Config Spec.
than we have to create Specification for the NIC such as
NIC Name for that purpose we will use a NIC predefined
After Creating instance of “VirtualEthernetCardNetworkBackingInfo”
Set the various parameters as:
setDeviceName
Create the basic description of the Nic such as label Description info = new Description();
and add the description to Nic.setDeviceInfo(info)
*/
static VirtualDeviceConfigSpec createNicSpec(String netName,
String nicName) throws Exception
{
VirtualDeviceConfigSpec nicSpec =
new VirtualDeviceConfigSpec();
nicSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
VirtualEthernetCard nic = new VirtualPCNet32();
VirtualEthernetCardNetworkBackingInfo nicBacking =
new VirtualEthernetCardNetworkBackingInfo();
nicBacking.setDeviceName(netName);
Description info = new Description();
info.setLabel(nicName);
info.setSummary(netName);
nic.setDeviceInfo(info);
// type: "generated", "manual", "assigned" by VC
nic.setAddressType("generated");
/**Set the backing for NIC*/
nic.setBacking(nicBacking);
nic.setKey(0);
/**
Add the NIC spec in Virtual Device
*/
nicSpec.setDevice(nic);
return nicSpec;
}
Add the respective function in order to populate the VM virtual Devices
VirtualDeviceConfigSpec scsiSpec = createScsiSpec(cKey);
VirtualDeviceConfigSpec diskSpec = createDiskSpec(datastoreName, cKey, diskSizeKB, diskMode);
VirtualDeviceConfigSpec nicSpec = createNicSpec(
netName, nicName);
After calling the respective function in the and obtaining all the VirtualDeviceConfigSpec
set the VirtualDeviceConfigSpec for the VM.
vmSpec.setDeviceChange(new VirtualDeviceConfigSpec[]
{scsiSpec, diskSpec, nicSpec});
// Create vm file info for the vmx file
VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();
vmfi.setVmPathName("["+ datastoreName +"]");
vmSpec.setFiles(vmfi);
Create a task to in-order to create a VM
// call the createVM_Task method on the vm folder
Task task = vmFolder.createVM_Task(vmSpec, rp, null);
String result = task.waitForMe();
if(result == Task.SUCCESS)
{
System.out.println("VM Created Sucessfully");
}
else
{
System.out.println("VM could not be created. ");
}
}
Instance to Control the DataStore:
try
{
dc = (Datacenter) new InventoryNavigator(
rootFolder).searchManagedEntity("Datacenter", dcName);
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
Datastore[] dStore = dc.getDatastores();
if(dStore!=null)
{
for(int i=0;ilength;i++)
{
System.out.println("Data Store Name: " + dStore[i].getSummary().name);
System.out.println("Data Store Capacity: " + dStore[i].getSummary().capacity + "KB");
System.out.println("Data Store Free Space: " + dStore[i].getSummary().freeSpace+ "KB");
System.out.println("Data Store Type: " + dStore[i].getSummary().type);
System.out.println("Data Store URL: " + dStore[i].getSummary().url);
}
}
For better results on Controlling the VM using VIJavaAPI its better to install Vmware tools in the VM created. This will provide much better controls on VM.
Java Program to Power on or off the VM
public static String vmName="ViJAVAAPI";
public static String op="poweron"; //Operation to be performed
ServiceInstance si = new ServiceInstance(
new URL(centerServer), userName, password, true);
if("reboot".equalsIgnoreCase(op))
{
vm.rebootGuest();
System.out.println(vmname + " guest OS rebooted");
}
else if("poweron".equalsIgnoreCase(op))
{
Task task = vm.powerOnVM_Task(null); //to Power On
if(task.waitForMe()==Task.SUCCESS)
{
System.out.println(vmname + " powered on");
}
}
else if("poweroff".equalsIgnoreCase(op))
{
Task task = vm.powerOffVM_Task();
if(task.waitForMe()==Task.SUCCESS)
{
System.out.println(vmname + " powered off");
}
}
else if("reset".equalsIgnoreCase(op))
{
Task task = vm.resetVM_Task();
if(task.waitForMe()==Task.SUCCESS)
{
System.out.println(vmname + " reset");
}
}
else if("standby".equalsIgnoreCase(op))
{
vm.standbyGuest();
System.out.println(vmname + " guest OS stoodby");
}
else if("suspend".equalsIgnoreCase(op))
{
Task task = vm.suspendVM_Task();
if(task.waitForMe()==Task.SUCCESS)
{
System.out.println(vmname + " suspended");
}
}
else if("shutdown".equalsIgnoreCase(op))
{
Task task = vm.suspendVM_Task();
if(task.waitForMe()==Task.SUCCESS)
{
System.out.println(vmname + " suspended");
}
}
The above code can be used to Start and Stop the VM from remote.
No comments:
Post a Comment