ESXi: RestrictedVersionFault

When using ESXi free licenses, you might get an error message referencing a fault called RestrictedVersionFault e.g.:

SOAP Fault:

————–

Fault string: Current license or ESXi Version prohibits execution of the requested operation.

Fault detail: RestrictedVersionFault

Or:

Failed : Current license or ESXi version prohibits execution of the requested operation.

This happens when you start, stop or suspend a VM using the command line interface ( vCLI or PowerCLI) or the SOAP interface (using VI for Java or directly the vSphere API). But it might also happen when configuring SNMP, performing scheduled backups or putting an ESXi host in maintenance mode.

This is caused by a restriction based on the VMWare license you are using. The free ESXi license (also known as the vSphere Hypervisor license) only allows read-only access to the vSphere API. This not only affects you when using the vSphere API directly but also when using any of the vSphere toolkits or management tools.

You’ll notice that when using the vSphere Client to manage your ESXi hosts, you will not face this problem. Using the vSphere Client, you have access to this functionality without read-only restriction. But as soon as you try to automate this, you will be affected.

So even though the fault message tells you it’s a problem with the version you’re using, it is not the case. It is only a problem with the license type you’re using. So instead of using a vSphere Hypervisor license, you should invest a few dollars and upgrade to a vSphere Essentials Kit or the vSphere Standard, Enterprise or Enterprise Plus editions.

If you were using the free edition waiting for some other licenses to be received, you should rather use the trial license (evaluation license) instead of the free license. This will provide access to the feature set of vSphere Enterprise Plus until the end of the 60-days evaluation period.

 

VMWare: The path “/usr/bin/gcc” is not valid path to the gcc binary

Since I’ve wasted way too much time with this problem, I thought I’d share how I solved it…

But first the problem:

I wanted to install the vmware tools in a Debian Squeeze virtual machine. So I chose Install VMWare Tools in VMWare Workstation. Then mounted the CD:

mount /dev/cdrom

Unpacked the tools to the /tmp directory:

cd /tmp
tar xvfz /media/cdrom0/VMwareTools-8.8.4-743747.tar.gz

I then started the tools installation:

cd vmware-tools-distrib/
./vmware-install.pl

Most of it went fine but I reached the point where the installer looks for gcc and got the following message:

Searching for GCC...
The path "" is not valid path to the gcc binary.
Would you like to change it? [yes]

I said yes, looked for the path to gcc and saw it wasn’t installed. So I stopped the installer and installed gcc:

# apt-get install gcc

I restarted the installer and same problem… I now checked the path to gcc:

# which gcc
/usr/bin/gcc

And entered it at the prompt:

What is the location of the gcc program on your machine? /usr/bin/gcc

The path "/usr/bin/gcc" is not valid path to the gcc binary.
Would you like to change it? [yes]

So gcc is now there but somehow the tools installer doesn’t like it.

After googling for ages, I ended up installing the following packages:

  • make
  • gcc-4.3
  • libglib2.0-0
  • linux-headers-2.6.32-5-amd64

Of course if you have another kernel, you should install the appropriate version of the Linux kernel headers. You can install it all like this:

aptitude install make gcc-4.3 linux-headers-`uname -r` libglib2.0-0

gcc-4.3 is required and not the version 4.4 which got installed when I ran apt-get install gcc because it’s the version which was used to compile the kernel. You can check this on your system using:

# cat /proc/version
Linux version 2.6.32-5-amd64 (Debian 2.6.32-45) (dannf@debian.org) (gcc version 4.3.5 (Debian 4.3.5-4) ) #1 SMP Sun May 6 04:00:17 UTC 2012

After that the installation of the vmware tools was at last successful.

I’m not 100% sure that all 4 packages are needed but in the end after installing all 4 it worked and I really don’t want to test the different combination with 3 packages to see whether I could have installed one package less.

VI Java API: Performance historical intervals

In my previous post, I’ve shown how to get performance counters using the VI Java API. I used there PerformanceManager.queryPerfProviderSummary(host).getRefreshRate() to get a performance interval for queryAvailablePerfMetric and queryPerf. This returns refreshRate for real-time performance statistics (20 seconds). Instead of the real-time performance, you might be interested in historical performance counters.

To retrieve available metrics for historical performance statistics, you have to use existing historical intervals. In order to query for acceptable historical intervals, you can use the getHistoricalInterval method of the PerformanceManager:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.PerfInterval;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.PerformanceManager;
import com.vmware.vim25.mo.ServiceInstance;

public class PerformanceIntervals {

	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			PerformanceManager perfMgr = si.getPerformanceManager();

			PerfInterval[] perfIntervals = perfMgr.getHistoricalInterval();
			for (PerfInterval perfInterval : perfIntervals) {
				System.out.println("key = " + perfInterval.getKey());
				System.out.println("length = " + perfInterval.getLength());
				System.out.println("samplingPeriod = " + perfInterval.getSamplingPeriod());
				System.out.println("level = " + perfInterval.getLevel());
				System.out.println("name = " + perfInterval.getName());
				System.out.println();
			}
			si.getServerConnection().logout();
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

The sampling period can then be used in your queries.

By default a vCenter Server will save collection data for the following time periods:

  • 5-minute samples for the past day
  • 30-minute samples for the past week
  • 2-hour samples for the past month
  • 1-day samples for the past year

You can change the sampling rate for an interval using the updatePerfInterval method of the PerformanceManager.

VI Java API: monitoring task completion

In a previous post, I’ve shown how to create a snapshot. It is done by creating a background task:

Task task = vm.createSnapshot_Task("benohead1", "Benohead's first snapshot", false /* memory */, true /* quiesce */);

The call to createSnapshot_Task immediately returns with a Task object. Using this Task instance, you can monitor what’s the progress of the task. It is done:

  • Getting a TaskInfo instance from the task object
  • Checking for the current state

You can do it in a loop like this:

TaskInfoState state;
do {
	Thread.sleep(1000);
	state = task.getTaskInfo().getState();
	System.out.println("State="+state);
}
while (state != TaskInfoState.error && state != TaskInfoState.success);

This will loop until the task succeeds or fails. During each iteration in the loop, it will sleep for 1 second and print the current state of the task.

Additionally, you could also print the current progress of the task:

TaskInfoState state;
do {
	Thread.sleep(1000);
	state = task.getTaskInfo().getState();
	Integer progress = task.getTaskInfo().getProgress();
	if (state == TaskInfoState.success) {
		progress = 100;
	}
	else if (progress == null) {
		progress = 0;
	}
	System.out.println("State="+state+"("+progress+"%)");
}
while (state != TaskInfoState.error && state != TaskInfoState.success);

If the task hasn’t yet done anything task.getTaskInfo().getProgress() will return null. And if the task is already finished, it will also return 0.

If you want to check all recent tasks (basically the lower part of the screen in the vSphere client) it’s pretty easy.
You can get the list of recent tasks from the ServiceInstance:

Task[] tasks = si.getTaskManager().getRecentTasks();

And get for each task some info e.g.:

for (int i = 0; i < tasks.length; i++) {
	TaskInfo info = tasks[i].getTaskInfo();
	String name = info.getName();
	String target = info.getEntityName();
	TaskInfoState state = info.getState();
	Integer progress = info.getProgress();
	if (state == TaskInfoState.success) {
		progress = 100;
	} else if (progress == null) {
		progress = 0;
	}
	LocalizableMessage desc = info.getDescription();
	String description = desc != null ? desc.getMessage() : "";
	TaskReason reason = info.getReason();
	String initiatedBy = "";
	if (reason != null) {
		if (reason instanceof TaskReasonUser) {
			initiatedBy = ((TaskReasonUser) reason).getUserName();
		} else if (reason instanceof TaskReasonSystem) {
			initiatedBy = "System";
		} else if (reason instanceof TaskReasonSchedule) {
			initiatedBy = ((TaskReasonSchedule) reason).getName();
		} else if (reason instanceof TaskReasonAlarm) {
			initiatedBy = ((TaskReasonAlarm) reason).getAlarmName();
		}
	}
	Calendar queueT = info.getQueueTime();
	String queueTime = queueT != null ? queueT.getTime().toString() : "";
	Calendar startT = info.getStartTime();
	String startTime = startT != null ? startT.getTime().toString() : "";
	Calendar completeT = info.getCompleteTime();
	String completeTime = completeT != null ? completeT.getTime().toString() : "";
	System.out.println(name + "t" + target + "t" + state + " " + progress + "%t" + description + "t" + initiatedBy + "t" + queueTime
			+ "t" + startTime + "t" + completeTime);
}

Getting info from your ESX server using the VMware Infrastructure (vSphere) Java API (Part 4)

In the first part, we’ve seen how to get general information about the ESX hosts.

In the second part, we’ve read some information about the virtual machines running on a given host.

In the third part, we’ve seen how to list performance counters and get statistics out of it.

In this part, we’ll be working with snapshots, creating snapshots, listing existing snapshots, selecting an existing snapshot and deleting snapshots.

First let’s create a snapshot:

You need to perform the following steps:

  • Get a new ServiceInstance
  • Search for the virtual machine
  • Create a snapshot task

The created snapshot task will run asynchronously in the background.

Here the code:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.Task;
import com.vmware.vim25.mo.VirtualMachine;

public class CreateVmSnapshot {
	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	private static final String VM_NAME = "MyVMName";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List host systems
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", VM_NAME);
			Task task = vm.createSnapshot_Task("benohead1", "Benohead's first snapshot", false /* memory */, true /* quiesce */);
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Using the returned task instance, you can monitor the progress of the task. You will also see in the lower part of the UI of the vSphere client (Recent Tasks) that the task is running.

Now that we can create snapshots let’s see how to get the tree view of the existing snapshots like in the vSphere client snapshot manager. Here are the steps to follow:

  • get the list of Root snapshots
  • go through list and print whatever info you required
  • for each snapshot get the list of child snapshots and process them like the root snapshots

To get the list of Root snapshots:

VirtualMachineSnapshotTree[] rootSnapshotList = vm.getSnapshot().getRootSnapshotList();

We’ll call a method to walk through the tree:

listSnapshotTree(rootSnapshotList, 0, vm.getSnapshot().getCurrentSnapshot());

We provide vm.getSnapshot().getCurrentSnapshot() to the method so that it can write “You are here” next to the snapshot which is the current one.

Here the method:

private static void listSnapshotTree(VirtualMachineSnapshotTree[] rootSnapshotList, int level, ManagedObjectReference currentSnapshot) {
	if (rootSnapshotList != null) {
		for (int i = 0; i < rootSnapshotList.length; i++) {
			VirtualMachineSnapshotTree snapshot = rootSnapshotList[i];
			String name = snapshot.getName();
			for(int j=0;j<level;j++) {
				System.out.print("t");
			}
			String currentString = snapshot.getSnapshot().equals(currentSnapshot) ? " (You are here)" : "";
			System.out.println(name + currentString);
			
			listSnapshotTree(snapshot.childSnapshotList, level+1, currentSnapshot);
		}
	}
}

The level variable is just used to add the appropriate number of tabs so that it looks like a tree (of course if I had a UI, we could actually show a nice tree…).
We need to compare the snapshots with the current snapshot because there is no attribute in the snapshot tree which says “hey ! I’m the current snapshot”.

The complete sample class for listing the snapshots looks this:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;

public class ListVmSnapshots {
	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	private static final String VM_NAME = "MyVMName";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List host systems
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", VM_NAME);
			VirtualMachineSnapshotTree[] rootSnapshotList = vm.getSnapshot().getRootSnapshotList();
			listSnapshotTree(rootSnapshotList, 0, vm.getSnapshot().getCurrentSnapshot());
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void listSnapshotTree(VirtualMachineSnapshotTree[] rootSnapshotList, int level, ManagedObjectReference currentSnapshot) {
		if (rootSnapshotList != null) {
			for (int i = 0; i < rootSnapshotList.length; i++) {
				VirtualMachineSnapshotTree snapshot = rootSnapshotList[i];
				String name = snapshot.getName();
				for (int j = 0; j < level; j++) {
					System.out.print("t");
				}
				String currentString = snapshot.getSnapshot().equals(currentSnapshot) ? " (You are here)" : "";
				System.out.println(name + currentString);

				listSnapshotTree(snapshot.childSnapshotList, level + 1, currentSnapshot);
			}
		}
	}
}

Now let’s see how to go to (revert to) an existing snapshot (i.e. change the execution state of the VM to the state of this snapshot).

First you have to get an object representing the snapshot you want to revert to. You have to start with the list of root snapshots and walk through the tree until you’ve found the snapshot you’re looking for:

private static VirtualMachineSnapshotTree findInSnapshotTree(String snapshotName, VirtualMachineSnapshotTree[] rootSnapshotList) {
	if (rootSnapshotList != null) {
		for (int i = 0; i < rootSnapshotList.length; i++) {
			VirtualMachineSnapshotTree virtualMachineSnapshotTree = rootSnapshotList[i];
			String name = virtualMachineSnapshotTree.getName();
			System.out.println("checking " + name);
			if (snapshotName.equals(name)) {
				return virtualMachineSnapshotTree;
			} else {
				VirtualMachineSnapshotTree snapshot = findInSnapshotTree(snapshotName, virtualMachineSnapshotTree.childSnapshotList);
				if (snapshot != null) {
					return snapshot;
				}
			}
		}
	}
	return null;
}

Once you have it, you can revert to it:

VirtualMachineSnapshot snapshot = new VirtualMachineSnapshot(si.getServerConnection(), snapshotTree.getSnapshot());
snapshot.revertToSnapshot_Task(null);

The argument null to revertToSnapshot_Task means that if vBalance feature is configured for automatic load balancing, a host is automatically selected otherwise, the VM stays on it’s current host.

Here the complete code of the class:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.VirtualMachineSnapshot;

public class GoToVmSnapshot {
	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	private static final String VM_NAME = "MyVMName";
	private static final String SNAPSHOT_NAME = "othersnapshot";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List host systems
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", VM_NAME);
			VirtualMachineSnapshotTree[] rootSnapshotList = vm.getSnapshot().getRootSnapshotList();
			VirtualMachineSnapshotTree snapshotTree = findInSnapshotTree(SNAPSHOT_NAME, rootSnapshotList);
			VirtualMachineSnapshot snapshot = new VirtualMachineSnapshot(si.getServerConnection(), snapshotTree.getSnapshot());
			snapshot.revertToSnapshot_Task(null);
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static VirtualMachineSnapshotTree findInSnapshotTree(String snapshotName, VirtualMachineSnapshotTree[] rootSnapshotList) {
		if (rootSnapshotList != null) {
			for (int i = 0; i < rootSnapshotList.length; i++) {
				VirtualMachineSnapshotTree virtualMachineSnapshotTree = rootSnapshotList[i];
				String name = virtualMachineSnapshotTree.getName();
				System.out.println("checking " + name);
				if (snapshotName.equals(name)) {
					return virtualMachineSnapshotTree;
				} else {
					VirtualMachineSnapshotTree snapshot = findInSnapshotTree(snapshotName, virtualMachineSnapshotTree.childSnapshotList);
					if (snapshot != null) {
						return snapshot;
					}
				}
			}
		}
		return null;
	}
}

Now the only thing left is to delete snapshots. Basically it’s really a lot like reverting to a snapshot:

  • First you need to get an object representing the snapshot
  • Then you need to call the removeSnapshot_Task method to create a background task

Here the code:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.Description;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualHardware;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.Task;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.VirtualMachineSnapshot;

public class DeleteVmSnapshot {
	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	private static final String VM_NAME = "MyVMName";
	private static final String SNAPSHOT_NAME = "benohead1";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List host systems
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", VM_NAME);
			VirtualMachineSnapshotTree[] rootSnapshotList = vm.getSnapshot().getRootSnapshotList();
			VirtualMachineSnapshotTree snapshotTree = findInSnapshotTree(SNAPSHOT_NAME, rootSnapshotList);
			VirtualMachineSnapshot snapshot = new VirtualMachineSnapshot(si.getServerConnection(), snapshotTree.getSnapshot());
			snapshot.removeSnapshot_Task(false);
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static VirtualMachineSnapshotTree findInSnapshotTree(String snapshotName, VirtualMachineSnapshotTree[] rootSnapshotList) {
		if (rootSnapshotList != null) {
			for (int i = 0; i < rootSnapshotList.length; i++) {
				VirtualMachineSnapshotTree virtualMachineSnapshotTree = rootSnapshotList[i];
				String name = virtualMachineSnapshotTree.getName();
				System.out.println("checking " + name);
				if (snapshotName.equals(name)) {
					return virtualMachineSnapshotTree;
				} else {
					VirtualMachineSnapshotTree snapshot = findInSnapshotTree(snapshotName, virtualMachineSnapshotTree.childSnapshotList);
					if (snapshot != null) {
						return snapshot;
					}
				}
			}
		}
		return null;
	}
}

Getting info from your ESX server using the VMware Infrastructure (vSphere) Java API (Part 3)

In the first part, we’ve seen how to get general information about the ESX hosts.

In the second part, we’ve read some information about the virtual machines running on a given host.

In this part, we’ll get started with performance counters. Your ESX system collects data at runtime about performance for all aspects of the system—CPU, disk, memory, network, and so on. The data in the counters is accessible through the PerformanceManager class.

You can get an instance of the PerformanceMangager like this:

ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
PerformanceManager perfMgr = si.getPerformanceManager();

The performance manager has a getPerfCounters method which will return a list of all available counters:

PerfCounterInfo[] perfCounters = perfMgr.getPerfCounter();
for (int i = 0; i < perfCounters.length; i++) {
	PerfCounterInfo perfCounterInfo = perfCounters[i];
	String perfCounterString = perfCounterInfo.getNameInfo().getLabel() + " (" + perfCounterInfo.getGroupInfo().getKey() + ") in "
			+ perfCounterInfo.getUnitInfo().getLabel() + " (" + perfCounterInfo.getStatsType().toString() + ")";
		System.out.println(perfCounterInfo.getKey() + " : " + perfCounterString);
}

This will return a list like this:

1 : Usage (cpu) in Percent (rate)
...
336 : Queue write latency (disk) in Millisecond (absolute)
337 : Physical device command latency (disk) in Millisecond (absolute)
338 : Kernel command latency (disk) in Millisecond (absolute)

perfCounterInfo.getKey() returns the key with which you can identify the counter to get some information about the performance of the system.

Here the whole code for this example:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.PerfCounterInfo;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.PerformanceManager;
import com.vmware.vim25.mo.ServiceInstance;

public class ListCounters {

	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List counters
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			PerformanceManager perfMgr = si.getPerformanceManager();

			PerfCounterInfo[] perfCounters = perfMgr.getPerfCounter();
			for (int i = 0; i < perfCounters.length; i++) {
				PerfCounterInfo perfCounterInfo = perfCounters[i];
				String perfCounterString = perfCounterInfo.getNameInfo().getLabel() + " (" + perfCounterInfo.getGroupInfo().getKey() + ") in "
						+ perfCounterInfo.getUnitInfo().getLabel() + " (" + perfCounterInfo.getStatsType().toString() + ")";
				System.out.println(perfCounterInfo.getKey() + " : " + perfCounterString);
			}
			si.getServerConnection().logout();
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

A query for performance counter is done using the PerformanceManager. In order to query for counters you need to create an instance of PerfQuerySpec which defines what we’ll be querying. You need to define the following:

  • which entity should be queried (in our case the host)
  • which metrics should be queried (e.g. the counter number 25 (active memory in KB)
  • the query interval: The interval (sampling period) in seconds for which performance statistics are queried. There is a set of intervals for historical statistics. To retrieve the greatest available level of detail, the provider’s refreshRate may be used for this property

First let’s get the metric ID we want to use to filter the results:

PerfMetricId[] queryAvailablePerfMetric = perfMgr.queryAvailablePerfMetric(host, null, null, perfInterval);
ArrayList<PerfMetricId> list = new ArrayList<PerfMetricId>();
for (int i2 = 0; i2 < queryAvailablePerfMetric.length; i2++) {
	PerfMetricId perfMetricId = queryAvailablePerfMetric[i2];
	if (SELECTED_COUNTER_ID == perfMetricId.getCounterId()) {
		list.add(perfMetricId);
	}
}
PerfMetricId[] pmis = list.toArray(new PerfMetricId[list.size()]);

where SELECTED_COUNTER_ID is a constant we’ve define containing the counter ID we want to retrieve (e.g. 25).

Then let’s get the interval ID:

PerfProviderSummary summary = perfMgr.queryPerfProviderSummary(host);
int perfInterval = summary.getRefreshRate();

This will return the greatest available level of detail (i.e. 20 seconds).

Now we can create a PerfQuerySpec:

PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(host.getMOR());
qSpec.setMetricId(pmis);
qSpec.intervalId = perfInterval;

Running the query is just a call to the queryPerf method of the performance manager:

PerfEntityMetricBase[] pembs = perfMgr.queryPerf(new PerfQuerySpec[] { qSpec });

Now we can iterate through the results and print the counter values:

for (int i = 0; pembs != null && i < pembs.length; i++) {
	PerfEntityMetricBase val = pembs[i];
	PerfEntityMetric pem = (PerfEntityMetric) val;
	PerfMetricSeries[] vals = pem.getValue();
	PerfSampleInfo[] infos = pem.getSampleInfo();

	for (int j = 0; vals != null && j < vals.length; ++j) {
		PerfMetricIntSeries val1 = (PerfMetricIntSeries) vals[j];
		long[] longs = val1.getValue();
		for (int k = 0; k < longs.length; k++) {
			System.out.println(infos[k].getTimestamp().getTime() + " : " + longs[k]);
		}
		System.out.println();
	}
}

This will return something like:

Tue Jul 31 12:30:15 CEST 2012 : 1165824
Tue Jul 31 12:30:35 CEST 2012 : 1333596
Tue Jul 31 12:30:55 CEST 2012 : 1165824
Tue Jul 31 12:31:15 CEST 2012 : 1244900
Tue Jul 31 12:31:35 CEST 2012 : 1244900
Tue Jul 31 12:31:55 CEST 2012 : 1244900
Tue Jul 31 12:32:15 CEST 2012 : 1256692
Tue Jul 31 12:32:35 CEST 2012 : 1256692
Tue Jul 31 12:32:55 CEST 2012 : 1592236
Tue Jul 31 12:33:15 CEST 2012 : 1639196
Tue Jul 31 12:33:35 CEST 2012 : 1982884
Tue Jul 31 12:33:55 CEST 2012 : 1647340
Tue Jul 31 12:34:15 CEST 2012 : 1652860
Tue Jul 31 12:34:35 CEST 2012 : 1023712
Tue Jul 31 12:34:55 CEST 2012 : 1023712
Tue Jul 31 12:35:15 CEST 2012 : 949708
Tue Jul 31 12:35:35 CEST 2012 : 1201368
Tue Jul 31 12:35:55 CEST 2012 : 1209508
Tue Jul 31 12:36:15 CEST 2012 : 1209508
Tue Jul 31 12:36:35 CEST 2012 : 957852
Tue Jul 31 12:36:55 CEST 2012 : 974136
Tue Jul 31 12:37:15 CEST 2012 : 1009320
Tue Jul 31 12:37:35 CEST 2012 : 1040628
Tue Jul 31 12:37:55 CEST 2012 : 1040628
Tue Jul 31 12:38:15 CEST 2012 : 997300
Tue Jul 31 12:38:35 CEST 2012 : 1123128
Tue Jul 31 12:38:55 CEST 2012 : 1123128
Tue Jul 31 12:39:15 CEST 2012 : 1107476
Tue Jul 31 12:39:35 CEST 2012 : 1652732
Tue Jul 31 12:39:55 CEST 2012 : 1652732
Tue Jul 31 12:40:15 CEST 2012 : 1647840
Tue Jul 31 12:40:35 CEST 2012 : 1621556
Tue Jul 31 12:40:55 CEST 2012 : 1286012
Tue Jul 31 12:41:15 CEST 2012 : 1301032
Tue Jul 31 12:41:35 CEST 2012 : 1091316
Tue Jul 31 12:41:55 CEST 2012 : 1091316
Tue Jul 31 12:42:15 CEST 2012 : 1076296
Tue Jul 31 12:42:35 CEST 2012 : 1411840
Tue Jul 31 12:42:55 CEST 2012 : 1747384
Tue Jul 31 12:43:15 CEST 2012 : 1720340
Tue Jul 31 12:43:35 CEST 2012 : 1468684
Tue Jul 31 12:43:55 CEST 2012 : 1141280
Tue Jul 31 12:44:15 CEST 2012 : 1170316
Tue Jul 31 12:44:35 CEST 2012 : 1002540
Tue Jul 31 12:44:55 CEST 2012 : 1002540
Tue Jul 31 12:45:15 CEST 2012 : 1003172
Tue Jul 31 12:45:35 CEST 2012 : 919288
Tue Jul 31 12:45:55 CEST 2012 : 1087060
Tue Jul 31 12:46:15 CEST 2012 : 1057116
Tue Jul 31 12:46:35 CEST 2012 : 1308772
Tue Jul 31 12:46:55 CEST 2012 : 1141000
Tue Jul 31 12:47:15 CEST 2012 : 1133760
Tue Jul 31 12:47:35 CEST 2012 : 1133760
Tue Jul 31 12:47:55 CEST 2012 : 1133760
Tue Jul 31 12:48:15 CEST 2012 : 1292764
Tue Jul 31 12:48:35 CEST 2012 : 1208880
Tue Jul 31 12:48:55 CEST 2012 : 1208880
Tue Jul 31 12:49:15 CEST 2012 : 1264212
Tue Jul 31 12:49:35 CEST 2012 : 1515868
Tue Jul 31 12:49:55 CEST 2012 : 1524008
Tue Jul 31 12:50:15 CEST 2012 : 1340856
Tue Jul 31 12:50:35 CEST 2012 : 1718344
Tue Jul 31 12:50:55 CEST 2012 : 1550572
Tue Jul 31 12:51:15 CEST 2012 : 1513116
Tue Jul 31 12:51:35 CEST 2012 : 1515736
Tue Jul 31 12:51:55 CEST 2012 : 1431848
Tue Jul 31 12:52:15 CEST 2012 : 1662864
Tue Jul 31 12:52:35 CEST 2012 : 1411208
Tue Jul 31 12:52:55 CEST 2012 : 1662868
Tue Jul 31 12:53:15 CEST 2012 : 1480704
Tue Jul 31 12:53:35 CEST 2012 : 1564588
Tue Jul 31 12:53:55 CEST 2012 : 1483324
Tue Jul 31 12:54:15 CEST 2012 : 1426964
Tue Jul 31 12:54:35 CEST 2012 : 1343080
Tue Jul 31 12:54:55 CEST 2012 : 1190960
Tue Jul 31 12:55:15 CEST 2012 : 1182816
Tue Jul 31 12:55:35 CEST 2012 : 1098928
Tue Jul 31 12:55:55 CEST 2012 : 1157156
Tue Jul 31 12:56:15 CEST 2012 : 1165296
Tue Jul 31 12:56:35 CEST 2012 : 1416956
Tue Jul 31 12:56:55 CEST 2012 : 1291128
Tue Jul 31 12:57:15 CEST 2012 : 1282712
Tue Jul 31 12:57:35 CEST 2012 : 1114940
Tue Jul 31 12:57:55 CEST 2012 : 1031052
Tue Jul 31 12:58:15 CEST 2012 : 1039468
Tue Jul 31 12:58:35 CEST 2012 : 1139004
Tue Jul 31 12:58:55 CEST 2012 : 1139004
Tue Jul 31 12:59:15 CEST 2012 : 1196276
Tue Jul 31 12:59:35 CEST 2012 : 1206760
Tue Jul 31 12:59:55 CEST 2012 : 1332588
Tue Jul 31 13:00:15 CEST 2012 : 1291880
Tue Jul 31 13:00:35 CEST 2012 : 1291880
Tue Jul 31 13:00:55 CEST 2012 : 1585484
Tue Jul 31 13:01:15 CEST 2012 : 1534920
Tue Jul 31 13:01:35 CEST 2012 : 1534920
Tue Jul 31 13:01:55 CEST 2012 : 1660748
Tue Jul 31 13:02:15 CEST 2012 : 1694676
Tue Jul 31 13:02:35 CEST 2012 : 1789048
Tue Jul 31 13:02:55 CEST 2012 : 2040704
Tue Jul 31 13:03:15 CEST 2012 : 2040704
Tue Jul 31 13:03:35 CEST 2012 : 2292360
Tue Jul 31 13:03:55 CEST 2012 : 2124588
Tue Jul 31 13:04:15 CEST 2012 : 1836664
Tue Jul 31 13:04:35 CEST 2012 : 1532428
Tue Jul 31 13:04:55 CEST 2012 : 1532428
Tue Jul 31 13:05:15 CEST 2012 : 1406600
Tue Jul 31 13:05:35 CEST 2012 : 1409220
Tue Jul 31 13:05:55 CEST 2012 : 1414464
Tue Jul 31 13:06:15 CEST 2012 : 1307132
Tue Jul 31 13:06:35 CEST 2012 : 1223248
Tue Jul 31 13:06:55 CEST 2012 : 1055476
Tue Jul 31 13:07:15 CEST 2012 : 907644
Tue Jul 31 13:07:35 CEST 2012 : 991528
Tue Jul 31 13:07:55 CEST 2012 : 1007180
Tue Jul 31 13:08:15 CEST 2012 : 1071056
Tue Jul 31 13:08:35 CEST 2012 : 1322716
Tue Jul 31 13:08:55 CEST 2012 : 1322716
Tue Jul 31 13:09:15 CEST 2012 : 1293120
Tue Jul 31 13:09:35 CEST 2012 : 1377004
Tue Jul 31 13:09:55 CEST 2012 : 1379624
Tue Jul 31 13:10:15 CEST 2012 : 1481656
Tue Jul 31 13:10:35 CEST 2012 : 1649428
Tue Jul 31 13:10:55 CEST 2012 : 1649428
Tue Jul 31 13:11:15 CEST 2012 : 1665988
Tue Jul 31 13:11:35 CEST 2012 : 1414332
Tue Jul 31 13:11:55 CEST 2012 : 1414332
Tue Jul 31 13:12:15 CEST 2012 : 1325204
Tue Jul 31 13:12:35 CEST 2012 : 1249460
Tue Jul 31 13:12:55 CEST 2012 : 1417232
Tue Jul 31 13:13:15 CEST 2012 : 1362736
Tue Jul 31 13:13:35 CEST 2012 : 1619412
Tue Jul 31 13:13:55 CEST 2012 : 1619412
Tue Jul 31 13:14:15 CEST 2012 : 2476068
Tue Jul 31 13:14:35 CEST 2012 : 2476068
Tue Jul 31 13:14:55 CEST 2012 : 2308296
Tue Jul 31 13:15:15 CEST 2012 : 2867220
Tue Jul 31 13:15:35 CEST 2012 : 2752024
Tue Jul 31 13:15:55 CEST 2012 : 2754644
Tue Jul 31 13:16:15 CEST 2012 : 3030724
Tue Jul 31 13:16:35 CEST 2012 : 2870816
Tue Jul 31 13:16:55 CEST 2012 : 3208984
Tue Jul 31 13:17:15 CEST 2012 : 3033068
Tue Jul 31 13:17:35 CEST 2012 : 3316036
Tue Jul 31 13:17:55 CEST 2012 : 3148264
Tue Jul 31 13:18:15 CEST 2012 : 2873848
Tue Jul 31 13:18:35 CEST 2012 : 3109852
Tue Jul 31 13:18:55 CEST 2012 : 3109852
Tue Jul 31 13:19:15 CEST 2012 : 3065288
Tue Jul 31 13:19:35 CEST 2012 : 2394200
Tue Jul 31 13:19:55 CEST 2012 : 2394200
Tue Jul 31 13:20:15 CEST 2012 : 2360120
Tue Jul 31 13:20:35 CEST 2012 : 2527892
Tue Jul 31 13:20:55 CEST 2012 : 2527892
Tue Jul 31 13:21:15 CEST 2012 : 2684896
Tue Jul 31 13:21:35 CEST 2012 : 2113348
Tue Jul 31 13:21:55 CEST 2012 : 1945576
Tue Jul 31 13:22:15 CEST 2012 : 1910668
Tue Jul 31 13:22:35 CEST 2012 : 1826780
Tue Jul 31 13:22:55 CEST 2012 : 1826780
Tue Jul 31 13:23:15 CEST 2012 : 1807876
Tue Jul 31 13:23:35 CEST 2012 : 2117132
Tue Jul 31 13:23:55 CEST 2012 : 2452676
Tue Jul 31 13:24:15 CEST 2012 : 2447156
Tue Jul 31 13:24:35 CEST 2012 : 2442140
Tue Jul 31 13:24:55 CEST 2012 : 2190480
Tue Jul 31 13:25:15 CEST 2012 : 2182336
Tue Jul 31 13:25:35 CEST 2012 : 2271240
Tue Jul 31 13:25:55 CEST 2012 : 2271240
Tue Jul 31 13:26:15 CEST 2012 : 2260480
Tue Jul 31 13:26:35 CEST 2012 : 2092708
Tue Jul 31 13:26:55 CEST 2012 : 1715224
Tue Jul 31 13:27:15 CEST 2012 : 1712324
Tue Jul 31 13:27:35 CEST 2012 : 1681020
Tue Jul 31 13:27:55 CEST 2012 : 1848792
Tue Jul 31 13:28:15 CEST 2012 : 1867976
Tue Jul 31 13:28:35 CEST 2012 : 2043612
Tue Jul 31 13:28:55 CEST 2012 : 1917780
Tue Jul 31 13:29:15 CEST 2012 : 1917780
Tue Jul 31 13:29:35 CEST 2012 : 1781312
Tue Jul 31 13:29:55 CEST 2012 : 1781312

Here the complete code for the counter query:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.PerfEntityMetric;
import com.vmware.vim25.PerfEntityMetricBase;
import com.vmware.vim25.PerfMetricId;
import com.vmware.vim25.PerfMetricIntSeries;
import com.vmware.vim25.PerfMetricSeries;
import com.vmware.vim25.PerfProviderSummary;
import com.vmware.vim25.PerfQuerySpec;
import com.vmware.vim25.PerfSampleInfo;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.PerformanceManager;
import com.vmware.vim25.mo.ServiceInstance;

public class DiplayHostCounter {

	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	private static final String HOSTNAME = "192.168.190.34";
	private static final int SELECTED_COUNTER_ID = 25; // Active (mem) in KB (absolute)

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			HostSystem host = (HostSystem) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("HostSystem", HOSTNAME);
			PerformanceManager perfMgr = si.getPerformanceManager();
			System.out.println("Counter ID = " + SELECTED_COUNTER_ID);

			PerfProviderSummary summary = perfMgr.queryPerfProviderSummary(host);
			int perfInterval = summary.getRefreshRate();
			System.out.println("Refresh rate = " + perfInterval);

			PerfMetricId[] queryAvailablePerfMetric = perfMgr.queryAvailablePerfMetric(host, null, null, perfInterval);
			ArrayList<PerfMetricId> list = new ArrayList<PerfMetricId>();
			for (int i2 = 0; i2 < queryAvailablePerfMetric.length; i2++) {
				PerfMetricId perfMetricId = queryAvailablePerfMetric[i2];
				if (SELECTED_COUNTER_ID == perfMetricId.getCounterId()) {
					list.add(perfMetricId);
				}
			}
			PerfMetricId[] pmis = list.toArray(new PerfMetricId[list.size()]);

			PerfQuerySpec qSpec = new PerfQuerySpec();
			qSpec.setEntity(host.getMOR());
			qSpec.setMetricId(pmis);
			qSpec.intervalId = perfInterval;

			PerfEntityMetricBase[] pembs = perfMgr.queryPerf(new PerfQuerySpec[] { qSpec });
			for (int i = 0; pembs != null && i < pembs.length; i++) {
				PerfEntityMetricBase val = pembs[i];
				PerfEntityMetric pem = (PerfEntityMetric) val;
				PerfMetricSeries[] vals = pem.getValue();
				PerfSampleInfo[] infos = pem.getSampleInfo();

				for (int j = 0; vals != null && j < vals.length; ++j) {
					PerfMetricIntSeries val1 = (PerfMetricIntSeries) vals[j];
					long[] longs = val1.getValue();
					for (int k = 0; k < longs.length; k++) {
						System.out.println(infos[k].getTimestamp().getTime() + " : " + longs[k]);
					}
					System.out.println();
				}
			}
			si.getServerConnection().logout();
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

In the vShpere client, it looks like this:

Getting info from your ESX server using the VMware Infrastructure (vSphere) Java API (Part 2)

In the first part, we’ve seen how to get general information about the ESX hosts.

In this part, we’ll read some information about the virtual machines running on a given host.

VirtualMachines like almost everything in ESX are managed entities. So you can query them using InventoryNavigator.searchManagedEntities:

ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
HostSystem host = (HostSystem) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("HostSystem", HOSTNAME);
ManagedEntity[] managedEntities = new InventoryNavigator(host).searchManagedEntities("VirtualMachine");

Note: if you use si.getRootFolder() instead of host you will get all VMs running on all hosts managed by your ESX infrastructure.

Once you have a virtual machine, you can get the virtual machine configuration information using:

VirtualMachineConfigInfo config = vm.getConfig();

And from this VirtualMachineConfigInfo you can get data related to the configured virtual hardware:

private static void writeVmInfo(VirtualMachine vm) {
	System.out.println("Virtual Machine:" + vm.getName());
	VirtualMachineConfigInfo config = vm.getConfig();
	VirtualHardware hw = config.getHardware();
	System.out.println("Memory in MB: " + hw.getMemoryMB());
	System.out.println("# of CPUs: " + hw.getNumCPU());
	VirtualDevice[] devices = hw.getDevice();
	for (int i = 0; i < devices.length; i++) {
		VirtualDevice device = devices[i];
		Description deviceInfo = device.getDeviceInfo();
		System.out.println("Device (" + device.getKey() + "): " + deviceInfo.getLabel() + " : " + deviceInfo.getSummary());
	}
}

The virtual machine configuration information contains more than just the virtual hardware configuration:

  • Affinity settings for CPU and memory
  • Resource limits for CPU and memory
  • Datastores
  • And more…

Here the full code of our example class:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.Description;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualHardware;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;

public class ListVms {
	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "xxxxxx";
	private static final String HOSTNAME = "192.168.190.34";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List host systems
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			HostSystem host = (HostSystem) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("HostSystem", HOSTNAME);
			ManagedEntity[] managedEntities = new InventoryNavigator(host).searchManagedEntities("VirtualMachine");
			for (int i = 0; i < managedEntities.length; i++) {
				VirtualMachine vm = (VirtualMachine) managedEntities[i];
				writeVmInfo(vm);
				System.out.println();
			}
			si.getServerConnection().logout();
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void writeVmInfo(VirtualMachine vm) {
		System.out.println("Virtual Machine:" + vm.getName());
		VirtualMachineConfigInfo config = vm.getConfig();
		VirtualHardware hw = config.getHardware();
		System.out.println("Memory in MB: " + hw.getMemoryMB());
		System.out.println("# of CPUs: " + hw.getNumCPU());
		VirtualDevice[] devices = hw.getDevice();
		for (int i = 0; i < devices.length; i++) {
			VirtualDevice device = devices[i];
			Description deviceInfo = device.getDeviceInfo();
			System.out.println("Device (" + device.getKey() + "): " + deviceInfo.getLabel() + " : " + deviceInfo.getSummary());
		}
	}
}

Getting info from your ESX server using the VMware Infrastructure (vSphere) Java API (Part 1)

VMware Infrastructure (vSphere) Java API provides a full set of libraries to manage VMware Infrastructure and vSphere. It is hosted on.

In order to use it you have to add both the vijava5 and dom4j jar files to your classpath.

First to connect to the ESX server, you need to get an instance of the vim server:

String url = "https://" + SERVER_NAME + "/sdk/vimService";
ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);

You should use the username and password you use in the VMWare vSphere Client. The server name is either the name or IP address of the ESX server or of the vCenter Server (if you manage multiple hosts).

Now you can use the InventoryNavigator to retrieve container contents from specified parent i.e. get data regarding hosts, virtual machines…

For example, if you want to get the list of hosts, you can use the following:

ManagedEntity[] managedEntities = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("HostSystem");
for (ManagedEntity managedEntity : managedEntities) {
	HostSystem host = (HostSystem) managedEntity;
	System.out.println("Host: '" + host.getName() + "'");
}

This will return something like:

Host: '192.168.190.34'
Host: '192.168.190.40'

You basically always use new InventoryNavigator(rootFolder).searchManagedEntities(…) to get objects corresponding to the different entities in your virtual infrastucture:

  • HostSystem
  • Datacenter
  • VirtualMachine
  • ResourcePool

Once you have the entity you’re looking for you can navigate through the object tree to get more data e.g. if you want to get some info about the hardware of each host:

HostHardwareInfo hw = host.getHardware();
System.out.println("Model: " + hw.getSystemInfo().getModel());
System.out.println("Memory in Bytes: " + hw.getMemorySize());
System.out.println("# of CPU Cores: " + hw.getCpuInfo().getNumCpuCores());
HostCpuPackage[] cpuPkg = hw.getCpuPkg();
for (int i = 0; i < cpuPkg.length; i++) {
	HostCpuPackage pkg = cpuPkg[i];
	System.out.println(pkg.getIndex() + " : " + pkg.getDescription() + " (vendor: " + pkg.getVendor() + ")");
}

This will return the following for host 192.168.190.34:

Model: ProLiant DL380 G6
Memory in Bytes: 42937085952
# of CPU Cores: 8
0 : Intel(R) Xeon(R) CPU           E5530  @ 2.40GHz (vendor: intel)
1 : Intel(R) Xeon(R) CPU           E5530  @ 2.40GHz (vendor: intel)

Here the complete sample code:

package com.benohead.esx;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.HostCpuPackage;
import com.vmware.vim25.HostHardwareInfo;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ServiceInstance;

public class ListHosts {
	static final String SERVER_NAME = "192.168.190.87";
	static final String USER_NAME = "Administrator";
	static final String PASSWORD = "AdminXXXX";

	public static void main(String[] args) {
		String url = "https://" + SERVER_NAME + "/sdk/vimService";
		// List host systems
		try {
			ServiceInstance si = new ServiceInstance(new URL(url), USER_NAME, PASSWORD, true);
			ManagedEntity[] managedEntities = new InventoryNavigator(si.getRootFolder()).searchManagedEntities("HostSystem");
			for (ManagedEntity managedEntity : managedEntities) {
				HostSystem host = (HostSystem) managedEntity;
				System.out.println("Host: '" + host.getName() + "'");
				HostHardwareInfo hw = host.getHardware();
				System.out.println("Model: " + hw.getSystemInfo().getModel());
				System.out.println("Memory in Bytes: " + hw.getMemorySize());
				System.out.println("# of CPU Cores: " + hw.getCpuInfo().getNumCpuCores());
				HostCpuPackage[] cpuPkg = hw.getCpuPkg();
				for (int i = 0; i < cpuPkg.length; i++) {
					HostCpuPackage pkg = cpuPkg[i];
					System.out.println(pkg.getIndex() + " : " + pkg.getDescription() + " (vendor: " + pkg.getVendor() + ")");
				}
			}
			si.getServerConnection().logout();
		} catch (InvalidProperty e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}