Vous êtes sur la page 1sur 27

VI SDK PropertyFilter Getting Started Community Guide Samples: Java, C# References: VMware Infrastructure SDK Programming Guide Property

collectors are used when clients want to find or monitor managed entities such as Virtual Machine and hosts or Managed Object References. The main use of property collectors is to retrieve the property data as well as getting updates on the properties. Clients can use blocking call (Notification) or use polling to get the updates for the properties. Property collector uses filter mechanism with help of another managed object Property Filter. This object is responsible for filtering out properties and provides information about only those properties that the property collector is interested in monitoring or retrieving values. The filter object is always associated with Property Collector and can not be accessed independently. Property Collectors are managed objects and are only available per session. These objects can be shared across This document will separate out the steps involved in creating the property filters to simplify them. These pieces can be put together to create different levels of complexities in property filter. Creating Property Filter comprises of following 3 main tasks:

Step 1: Create PropertySpec


Getting one or more specific properties PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(new Boolean(false)); // We are interested in 'name' property of Virtual Machines propertySpec.setPathSet(new String[] { "name" }); propertySpec.setType(VirtualMachine); Notice that following code snippet gets name and guestState property. The guestState property is a nested property and child of guest property available on VirtualMachine managed entity. PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(new Boolean(false)); // Get 'name' and guest stateproperty of VM propertySpec.setPathSet(new String[] { "name", "guest.guestState" }); propertySpec.setType("VirtualMachine"); Get all the properties of the managed object: When retrieving all the properties of the given type of managed entity, notice that setAll is set to true and PathSet setting is ignored. Following code snippet will fetch all the properties of the Host. PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(new Boolean(true)); // We are interested in all properties of Host propertySpec.setType("HostSystem");

Getting properties of different type of entities: Following example shows how multiple Property Specs can be used to collect properties of different types of managed entities. Property Filter accepts an array of Property Specs. It is necessary to create a property spec for every type of managed entity we are interested in. Single property spec in turn can ask for one or more or all the properties of given type of entity. Following example shows how multiple Property Sepcs for virtual machine and host system can be used in given Property Filter. // Create Property Spec for Host PropertySpec hostPropertySpec = new PropertySpec(); // We are interested in 'name' property of Host hostPropertySpec.setPathSet(new String[] { "name" }); hostPropertySpec.setType("HostSystem"); // Create Property Spec for VM PropertySpec vmPropertySpec = new PropertySpec(); // We are interested in 'name' and uestState property of VM vmPropertySpec.setPathSet(new String[] { "name", "guest.guestState" }); vmPropertySpec.setType("VirtualMachine"); // Add the above to array to be added to the PropertyFilter PropertySpec[] propertySpecs = new PropertySpec[] {hostPropertySpec, vmPropertySpec}; PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs);

Step 2: Create ObjectSpec


ObjectSpec decided which objects are used to select the properties. It can be a specific object or objects found by traversing the inventory tree using the traversal spec. Select set of managed objects to fetch properties Following snippet shows how to select the objects by specifying traversal spec. The traversal spec is responsible for selecting certain types of objects. The object spec can specify the starting object using setObj(). When skip attribute is set to false the object being visited is also checked for the desired properties. // Now create Object Spec ObjectSpec objectSpec= new ObjectSpec(); objectSpec.setObj(rootFolder); objectSpec.setSkip(new Boolean(false)); objectSpec.setSelectSet( new SelectionSpec[] { completeTraversalSpec }); Select single managed object to retrieve properties The simplest case of using Object Spec is to get properties of specific object. This can be done by using a managed object reference of specific object and setting it using setObj() and ignoring the SelectSet. The example below will get the properties of only the rootFolder managed object. ObjectSpec objectSpec= new ObjectSpec(); objectSpec.setObj(rootFolder); objectSpec.setSkip(new Boolean(false));

Create TraversalSpec
Imp. Note: It will help tremendously to keep the following diagram in front of you while

you are writing traversal specs. (Page 21 : VMware Infrastructure Getting Started Guide) Example 1: Create TraversalSpec to traverse whole inventory. This is typically required when we want to check all the objects in the tree and/or we do not know to what depth we may have to traverse the tree. Lets take top down approach here so that we can map it to the inventory tree shown above. Traversal Spec to traverse from Root Folder to Data Center: TraversalSpec traversalSpec = new TraversalSpec( "Folder", "childEntity", Boolean.FALSE, new SelectionSpec[] { new SelectionSpec("VisitFolders"), // This handles nested folders } ); traversalSpec.setName("VisitFolders"); The above traversal spec will traverse all the child entities of any Folder not just Data Center. Since the skip parameter is set to false it will visit the managed object to inspect. Data Center being child entity of root folder it will be traversed. The next step is to traverse from Data Center to its child folders. (We will revise this traversal spec as we walk through the tree.) Traversal Spec to traverse from Data Center to its child folders: The data center contains two types of child folders. Vmfolder (containing Virtual machines) and hostfolder (containing hosts and ComupteResource) So we will need two traversal specs to be able to traverse both the paths to vmfolder and hostfolder. Notice that since the folders can be nested to traverse the tree below the child folders (child entities of Datacenter) the selection spec includes the VisitFolders traversal spec. // Traversal through hostFolder branch TraversalSpec dataCenterToHostFolder = new TraversalSpec( "Datacenter", "hostFolder", Boolean.FALSE, new SelectionSpec[] { // Visit all folders (Folders can be nested) new SelectionSpec("VisitFolders"), } ); dataCenterToHostFolder.setName("DataCenterToHostFolder"); // Traversal through Virtual Machines Folder branch TraversalSpec dataCenterToVMFolder = new TraversalSpec( "Datacenter", "vmFolder", Boolean.FALSE, new SelectionSpec[] { //Visit all types of folders (Folders can be nested)

new SelectionSpec("VisitFolders"), } ); dataCenterToVMFolder.setName("DataCenterToVMFolder"); The above traversal spec needs to be added to the VisitFolders traversal spec so that it can continue to traverse beyond data center entity. So now our VisitFolder traversal spec which can traverse from Any Folder child entities Folder Child Entity (Datacenter) vmFolder Folder Child Entity (Datacenter) hostFolder looks like following. TraversalSpec traversalSpec = new TraversalSpec( "Folder", "childEntity", Boolean.FALSE, new SelectionSpec[] { new SelectionSpec("VisitFolders"), // This handles nested folders
dataCenterToHostFolder, dataCenterToVMFolder

} ); traversalSpec.setName("VisitFolders"); Above traversal spec can NOT traverse the ComputeResources entities found in hostFolder. When computeResouceToHost, computeResouceToResPool, nestedResourcePools traversal specs are added to VisitFolders traversal spec as shown below, it adds navigation paths to folder traversal to handle ResourcePool and Host entities. Notice that since the ResourcePool can be nested it is necessary to add a nestedResourcePools traversal spec as well to visit all the resource pools. This gives question how to traverse from a folder (hostFolder) to its ComputeResources child entity. ? Notice in the inventory tree that hostFolder has only one type of child entity which is ComputeResources. The first entry in SelectionSpec array of VisitFolders traversal spec, recursively traverses all the child entity (ComputeResources in this case). Same is applicable when we traverse from RootFolder to Datacenter since there is no specific traversal spec to traverse from RootFolder (folder entity) to Datacenter entity. // Traverse the Host branch from Compute Resources. TraversalSpec computeResouceToHost = new TraversalSpec( "ComputeResource", "host", Boolean.FALSE, new SelectionSpec[] { //Hosts does not have sub tree or nested structure // Nothing to traverse further in this branch. } ); computeResouceToHost.setName("ComputeResouceToHost"); // Traverse the Resource Pool branch from Compute Resources. TraversalSpec computeResouceToResPool = new TraversalSpec(

"ComputeResource", "resourcePool", Boolean.FALSE, new SelectionSpec[] { //Resource Pools can be nested so traverse thro them new SelectionSpec("NestedResourcePools") } ); computeResouceToResPool.setName("ComputeResouceToResPool"); // Traverse Nested Resource Pools TraversalSpec nestedResourcePools = new TraversalSpec( "ComputeResource", "resourcePool", Boolean.FALSE, new SelectionSpec[] { //Resource Pools can be nested so traverse thro them new SelectionSpec("NestedResourcePools") } ); nestedResourcePools.setName("NestedResourcePools"); The final traversal spec is as following raversalSpec traversalSpec = new TraversalSpec( "Folder", "childEntity", Boolean.FALSE, new SelectionSpec[] { new SelectionSpec("VisitFolders"), // This handles nested folders dataCenterToHostFolder, dataCenterToVMFolder, computeResouceToHost, computeResouceToResPool, nestedResourcePools } ); traversalSpec.setName("VisitFolders"); Example 2: Traversing the inventory to find ONLY Virtual Machines: When traversing the Virtual Machine managed entities it is not necessary to traverse the host folder and its sub tree. Following traversal spec can optimize the tree traversal by avoiding the host folder traversal. TraversalSpec traversalSpec = new TraversalSpec( "Folder", "childEntity", Boolean.FALSE, new SelectionSpec[] {

new SelectionSpec("VisitFolders"), // This handles nested folders dataCenterToVMFolder } ); traversalSpec.setName("VisitFolders"); Notice that the election spec contains traversal spec that can traverse the VM Folder. The selection spec in VisitFolders traversal spec does not include any traversal spec for host folder and thus avoid the host folder sub tree traversal.

Lets put it together:


Reference: Source Code Samples. Java Samples Sample 1.
/** * */ package com.vmware.cde.PropCollectorSample; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; import import import import import import import import import import import import import import com.vmware.cde.utils.TraversalSpecLib; com.vmware.vim.DynamicProperty; com.vmware.vim.InvalidProperty; com.vmware.vim.ManagedObjectReference; com.vmware.vim.ObjectContent; com.vmware.vim.ObjectSpec; com.vmware.vim.PropertyFilterSpec; com.vmware.vim.PropertySpec; com.vmware.vim.RuntimeFault; com.vmware.vim.SelectionSpec; com.vmware.vim.ServiceContent; com.vmware.vim.TraversalSpec; com.vmware.vim.VimPortType; com.vmware.vim.VimServiceLocator;

/** * @author ppimplas * */ public class example1 { private String url; private String userName; private String password; private VimPortType service; private VimServiceLocator serviceLocator; private ServiceContent serviceContent;

/** * @param string * @param string2 * @param string3 */ public example1(String url, String userName, String password) { this.url = url; this.userName = userName; this.password = password; ManagedObjectReference serviceRef = new ManagedObjectReference(); serviceRef.setType("ServiceInstance"); serviceRef.set_value("ServiceInstance"); if (service != null) { disconnect(); } serviceLocator = new VimServiceLocator(); serviceLocator.setMaintainSession(true); try { URL(this.url)); service = serviceLocator.getVimPort(new

((org.apache.axis.client.Stub)service).setTimeout(1200000); serviceContent = service.retrieveServiceContent(serviceRef); if (serviceContent.getSessionManager() != null) { service.login(serviceContent.getSessionManager(), this.userName, this.password, null); } } catch (MalformedURLException e) { System.err.println("Invalid URL: <" + this.url + ">" + e.getMessage()); } catch (ServiceException e) { System.err.println("Service Error: " + e.getMessage()); } catch (RuntimeFault e) { System.err.println("Runtime Error: " + e.getMessage()); } catch (RemoteException e) { System.err.println("Remote Error: " + e.getMessage()); } } /** *

*/ private void disconnect() { if (service != null) { try { service.logout(serviceContent.getSessionManager()); } catch (RuntimeFault e) { System.err.println("Disconnect failed: " + e.getMessage()); } catch (RemoteException e) { System.err.println("Disconnect failed: " + e.getMessage()); } service = null; serviceContent = null; } } public static void main(String[] args) { if (args == null || args.length != 3) { System.out.println( "Usage : example1 <webserviceurl> <username> <password>" ); System.exit(0); } args[2]); example1 client = new example1(args[0], args[1],

ManagedObjectReference rootFolder = client.serviceContent.getRootFolder(); client.getMORefProperties(rootFolder, "Datacenter"); client.getHostProperties(rootFolder); client.getHostAndVmProperties(rootFolder); client.getVirtualMachineProperties(rootFolder); } /** * @param root */ private void getVirtualMachineProperties(ManagedObjectReference root) { // Get property Collector ManagedObjectReference propertyCollector = serviceContent.getPropertyCollector(); // Create PropertyFilterSpec that filters out 'name' property // for given type of managed objects. // First create Traversal Spec that can traverse up to the Host Folder TraversalSpec completeTraversalSpec = TraversalSpecLib.getVMTraversalSpec(); // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(new Boolean(false));

object

// We are interested in 'name' property of given type of

propertySpec.setPathSet(new String[] { "name", "guest.guestState" }); propertySpec.setType("VirtualMachine"); // Add the above to array - We have only one ... PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec}; // Now create Object Spec ObjectSpec objectSpec= new ObjectSpec(); objectSpec.setObj(root); objectSpec.setSkip(new Boolean(false)); objectSpec.setSelectSet( new SelectionSpec[] { completeTraversalSpec }); ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec}; ObjectPec // Create PropertyFilterSpec using the PropertySpec and // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; // Now get the contents ObjectContent[] objectContents = null; try { objectContents = service.retrieveProperties( propertyCollector, propertyFilterSpecs); } 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(); } } printProperties(objectContents);

/** * @param rootFolder

* @param string */ private void getHostProperties(ManagedObjectReference root) { // Get property Collector ManagedObjectReference propertyCollector = serviceContent.getPropertyCollector(); property // Create PropertyFilterSpec that filters out 'name' // for given type of managed objects. the Host Folder // First create Traversal Spec that can traverse up to

TraversalSpec completeTraversalSpec = TraversalSpecLib.getHostTraversalSpec(); // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(new Boolean(true)); // We are interested in 'name' property of given type of //propertySpec.setPathSet(new String[] { "name" }); propertySpec.setType("HostSystem"); // Add the above to array - We have only one ... PropertySpec[] propertySpecs = new PropertySpec[]

object

{propertySpec};

// Now create Object Spec ObjectSpec objectSpec= new ObjectSpec(); objectSpec.setObj(root); objectSpec.setSkip(new Boolean(false)); objectSpec.setSelectSet( new SelectionSpec[] { completeTraversalSpec }); {objectSpec}; ObjectPec ObjectSpec[] objectSpecs = new ObjectSpec[] // Create PropertyFilterSpec using the PropertySpec and // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; // Now get the contents ObjectContent[] objectContents = null; try { objectContents = service.retrieveProperties(

propertyCollector, propertyFilterSpecs); } 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(); } printProperties(objectContents); } root) { private void getHostAndVmProperties( ManagedObjectReference // Get property Collector ManagedObjectReference propertyCollector = serviceContent.getPropertyCollector(); // Create PropertyFilterSpec that filters out 'name' property // for given type of managed objects. // First create Traversal Spec that can traverse up to the Host Folder TraversalSpec completeTraversalSpec = TraversalSpecLib.getCompleteTraversalSpec(); // Create Property Spec for Host PropertySpec hostPropertySpec = new PropertySpec(); // We are interested in 'name' property of given type of hostPropertySpec.setPathSet(new String[] { "name" }); hostPropertySpec.setType("HostSystem"); // Create Property Spec for Host PropertySpec vmPropertySpec = new PropertySpec(); // We are interested in 'name' property of given type of object vmPropertySpec.setPathSet(new String[] { "name", "guest.guestState" }); vmPropertySpec.setType("VirtualMachine"); // Add the above to array - We have only one ... PropertySpec[] propertySpecs = new PropertySpec[] {hostPropertySpec, vmPropertySpec}; // Now create Object Spec ObjectSpec objectSpec= new ObjectSpec(); objectSpec.setObj(root);

object

objectSpec.setSkip(new Boolean(false)); objectSpec.setSelectSet( new SelectionSpec[] { completeTraversalSpec }); ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec}; ObjectPec // Create PropertyFilterSpec using the PropertySpec and // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; // Now get the contents ObjectContent[] objectContents = null; try { objectContents = service.retrieveProperties( propertyCollector, propertyFilterSpecs); } 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(); } } printProperties(objectContents);

private void getMORefProperties( ManagedObjectReference root, String type) { // Get property Collector ManagedObjectReference propertyCollector = serviceContent.getPropertyCollector(); // Create PropertyFilterSpec that filters out 'name' property // for given type of managed objects. // First create Traversal Spec that decides which part of inventory we // traverse - We will traverse complete inventory TraversalSpec completeTraversalSpec = TraversalSpecLib.getCompleteTraversalSpec();

// Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.setAll(new Boolean(false)); // We are interested in 'name' property of given type of object propertySpec.setPathSet(new String[] { "name" }); propertySpec.setType(type); // Add the above to array - We have only one ... PropertySpec[] propertySpecs = new PropertySpec[] {propertySpec}; // Now create Object Spec ObjectSpec objectSpec= new ObjectSpec(); objectSpec.setObj(root); objectSpec.setSkip(new Boolean(false)); objectSpec.setSelectSet( new SelectionSpec[] { completeTraversalSpec }); ObjectSpec[] objectSpecs = new ObjectSpec[] {objectSpec}; ObjectPec // Create PropertyFilterSpec using the PropertySpec and // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.setPropSet(propertySpecs); propertyFilterSpec.setObjectSet(objectSpecs); PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] {propertyFilterSpec}; // Now get the contents ObjectContent[] objectContents = null; try { objectContents = service.retrieveProperties( propertyCollector, propertyFilterSpecs); } 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(); } } printProperties(objectContents);

/** * @param type

* @param name */ private void printProperties(ObjectContent[] objectContents) { ManagedObjectReference mor = null; DynamicProperty[] properties = null; System.out.println("object contents #: " + objectContents.length); // We should get only one Object with one property for (ObjectContent oc: objectContents) { mor = oc.getObj(); System.out.println(mor.get_value() + "\t" + mor.getType()); properties = oc.getPropSet(); if(properties != null) { for(DynamicProperty prop: properties) { System.out.println(mor.get_value() + "\t" + \t" + } } } } } prop.getName() + " prop.getVal());

End

Java Sample 2.
/** * */ package com.vmware.cde.PropCollectorSample; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; import import import import import import import import com.vmware.cde.utils.SDKToolkit; com.vmware.cde.utils.TraversalSpecLib; com.vmware.vim.DynamicProperty; com.vmware.vim.InvalidProperty; com.vmware.vim.ManagedObjectReference; com.vmware.vim.ObjectContent; com.vmware.vim.ObjectSpec; com.vmware.vim.PropertyFilterSpec;

import import import import import import import

com.vmware.vim.PropertySpec; com.vmware.vim.RuntimeFault; com.vmware.vim.SelectionSpec; com.vmware.vim.ServiceContent; com.vmware.vim.TraversalSpec; com.vmware.vim.VimPortType; com.vmware.vim.VimServiceLocator;

/** * @author ppimplas * */ public class example2 { private String url; private String userName; private String password; private VimPortType service; private VimServiceLocator serviceLocator; private ServiceContent serviceContent; private SDKToolkit sdkToolKit; /** * @param string * @param string2 * @param string3 */ public example2(String url, String userName, String password) { this.url = url; this.userName = userName; this.password = password; ManagedObjectReference serviceRef = new ManagedObjectReference(); serviceRef.setType("ServiceInstance"); serviceRef.set_value("ServiceInstance"); if (service != null) { disconnect(); } serviceLocator = new VimServiceLocator(); serviceLocator.setMaintainSession(true); try { URL(this.url)); ((org.apache.axis.client.Stub)service).setTimeout(1200000); serviceContent = service.retrieveServiceContent(serviceRef); if (serviceContent.getSessionManager() != null) { service.login(serviceContent.getSessionManager(), service = serviceLocator.getVimPort(new

this.password, null);

this.userName,

">" +

} } catch (MalformedURLException e) { System.err.println("Invalid URL: <" + this.url +

e.getMessage()); } catch (ServiceException e) { System.err.println("Service Error: " + e.getMessage()); } catch (RuntimeFault e) { System.err.println("Runtime Error: " + e.getMessage()); } catch (RemoteException e) { System.err.println("Remote Error: " + e.getMessage()); } sdkToolKit = new SDKToolkit(service,serviceContent); } /** * */ private void disconnect() { if (service != null) { try { service.logout(serviceContent.getSessionManager()); } catch (RuntimeFault e) { System.err.println("Disconnect failed: " + e.getMessage()); } catch (RemoteException e) { System.err.println("Disconnect failed: " + e.getMessage()); } service = null; serviceContent = null; } } public static void main(String[] args) { if (args == null || args.length != 3) { System.out.println( "Usage : example2 <webserviceurl> <username> <password>" ); System.exit(0); } example2 client = new example2(args[0], args[1], args[2]); ManagedObjectReference mor = null; ManagedObjectReference rootFolder = client.serviceContent.getRootFolder();

+ "\t" +

mor = client.sdkToolKit.getHostByName(rootFolder, "ppimplas-dev1.eng.vmware.com"); System.out.println("Verify Host MORef: " + mor.getType() mor.get_value() + "\t" +

client.sdkToolKit.getManagedEntityName(mor)); mor = client.sdkToolKit.getMORefByName(rootFolder, "Datacenter", "Datacenter1"); System.out.println("Verify Datacenter MORef: " + mor.getType() + "\t" + mor.get_value()+ "\t" + client.sdkToolKit.getManagedEntityName(mor)); mor = client.sdkToolKit.getVirtualMachineByName(rootFolder, "rhel3"); System.out.println("Verify VM MORef: " + mor.getType() + "\t" + mor.get_value()+ "\t" + client.sdkToolKit.getManagedEntityName(mor)); }

End C# Samples
This sample takes the username, password, server name and the name of the host system as the arguments. It then lists all the virtual machines on the specified host, with the name of the vm and its power state using the virtual machine properties, config.name and runtime.powerState. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Net; using System.Text; using System.Web.Services; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Globalization; using System.Collections; using VimApi; namespace VMlist

{ class VMlist { static VimService _service; protected ManagedObjectReference _svcRef = new ManagedObjectReference(); protected ServiceContent _sic; private UserSession _session; // Connects to a server private void connect(string url, string usid, string pwd) { System.Net.ServicePointManager.CertificatePolicy = new CertPolicy(); //Gets service contents _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; // _service is VimService _service = new VimService(); _service.Url = url; _service.CookieContainer = new CookieContainer(); // _sic is ServiceContent _sic = _service.RetrieveServiceContent(_svcRef); _session = _service.Login(_sic.sessionManager, usid, pwd, null); } // Disconnects from a server private void Disconnect() { if (_service != null) { _service.Logout(_sic.sessionManager); _service.Dispose(); _service = null; _sic = null; } } public PropertySpec[] BuildPropertySpecArray(string[][] typeinfo) { // Eliminate duplicates Hashtable tInfo = new Hashtable(); for (int ti = 0; ti < typeinfo.Length; ++ti) { Hashtable props = (Hashtable)tInfo[typeinfo[ti][0]]; if (props == null) { props = new Hashtable(); tInfo[typeinfo[ti][0]] = props; } bool typeSkipped = false; for (int pi = 0; pi < typeinfo[ti].Length; ++pi) { String prop = typeinfo[ti][pi]; if (typeSkipped)

{ if (!props.Contains(prop)) { // some value, not important props[prop] = String.Empty; } } else { typeSkipped = true; } } } // Create PropertySpecs ArrayList pSpecs = new ArrayList(); foreach (String type in tInfo.Keys) { PropertySpec pSpec = new PropertySpec(); Hashtable props = (Hashtable)tInfo[type]; pSpec.type = type; pSpec.all = props.Count == 0 ? true : false; pSpec.pathSet = new String[props.Count]; int index = 0; foreach (String prop in props.Keys) { pSpec.pathSet[index++] = prop; } pSpecs.Add(pSpec); } return (PropertySpec[])pSpecs.ToArray(typeof(PropertySpec)); } public SelectionSpec[] buildFullTraversal() { // Recurse through all ResourcePools TraversalSpec rpToVm = new TraversalSpec(); rpToVm.name = "rpToVm"; rpToVm.type = "ResourcePool"; rpToVm.path = "vm"; rpToVm.skip = false; rpToVm.skipSpecified = true; // Recurse through all ResourcePools TraversalSpec rpToRp = new TraversalSpec(); rpToRp.name = "rpToRp"; rpToRp.type = "ResourcePool"; rpToRp.path = "resourcePool"; rpToRp.skip = false; rpToRp.skipSpecified = true; rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() };

rpToRp.selectSet[0].name = "rpToRp"; rpToRp.selectSet[1].name = "rpToVm"; // Traversal through ResourcePool branch TraversalSpec crToRp = new TraversalSpec(); crToRp.name = "crToRp"; crToRp.type = "ComputeResource"; crToRp.path = "resourcePool"; crToRp.skip = false; crToRp.skipSpecified = true; crToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() }; crToRp.selectSet[0].name = "rpToRp"; crToRp.selectSet[1].name = "rpToVm"; // Traversal through host branch TraversalSpec crToH = new TraversalSpec(); crToH.name = "crToH"; crToH.type = "ComputeResource"; crToH.path = "host"; crToH.skip = false; crToH.skipSpecified = true; // Traversal through hostFolder branch TraversalSpec dcToHf = new TraversalSpec(); dcToHf.name = "dcToHf"; dcToHf.type = "Datacenter"; dcToHf.path = "hostFolder"; dcToHf.skip = false; dcToHf.skipSpecified = true; dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToHf.selectSet[0].name = "visitFolders"; // Traversal through vmFolder branch TraversalSpec dcToVmf = new TraversalSpec(); dcToVmf.name = "dcToVmf"; dcToVmf.type = "Datacenter"; dcToVmf.path = "vmFolder"; dcToVmf.skip = false; dcToVmf.skipSpecified = true; dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToVmf.selectSet[0].name = "visitFolders"; // Recurse through all Hosts TraversalSpec HToVm = new TraversalSpec(); HToVm.name = "HToVm"; HToVm.type = "HostSystem"; HToVm.path = "vm"; HToVm.skip = false; HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() }; HToVm.selectSet[0].name = "visitFolders";

// Recurse through the folders TraversalSpec visitFolders = new TraversalSpec(); visitFolders.name = "visitFolders"; visitFolders.type = "Folder"; visitFolders.path = "childEntity"; visitFolders.skip = false; visitFolders.skipSpecified = true; visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec(), new SelectionSpec() }; visitFolders.selectSet[0].name = "visitFolders"; visitFolders.selectSet[1].name = "dcToHf"; visitFolders.selectSet[2].name = "dcToVmf"; visitFolders.selectSet[3].name = "crToH"; visitFolders.selectSet[4].name = "crToRp"; visitFolders.selectSet[5].name = "HToVm"; visitFolders.selectSet[6].name = "rpToVm"; return new SelectionSpec[] { visitFolders, dcToVmf, dcToHf, crToH, crToRp, rpToRp, HToVm, rpToVm }; } public ObjectContent[] GetContentsRecursively(ManagedObjectReference collector, ManagedObjectReference root, string[][] typeinfo, bool recurse) { if (typeinfo == null || typeinfo.Length == 0) { return null; } ManagedObjectReference usecoll = collector; if (usecoll == null) { usecoll = _sic.propertyCollector; } ManagedObjectReference useroot = root; if (useroot == null) { useroot = _sic.rootFolder; } SelectionSpec[] selectionSpecs = null; if (recurse) { selectionSpecs = buildFullTraversal(); } PropertySpec[] propspecary = BuildPropertySpecArray(typeinfo); PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = propspecary; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = useroot; spec.objectSet[0].skip = false; spec.objectSet[0].selectSet = selectionSpecs;

//spec.objectSet[0].selectSet = new SelectionSpec[] { traversalSpec }; ObjectContent[] retoc = _service.RetrieveProperties(usecoll, new PropertyFilterSpec[] { spec }); return retoc; } public ManagedObjectReference GetDecendentMoRef(ManagedObjectReference root, string type, string name) { if (name == null || name.Length == 0) { return null; } string[][] typeinfo = new string[][] { new string[] { type, "name", }, }; ObjectContent[] ocary = GetContentsRecursively(null, root, typeinfo, true); if (ocary == null || ocary.Length == 0) { return null; } ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] propary = null; string propval = null; bool found = false; for (int oci = 0; oci < ocary.Length && !found; oci++) { oc = ocary[oci]; mor = oc.obj; propary = oc.propSet; if ((type == null) || (type != null && mor.type.Equals(type))) { if (propary.Length > 0) { propval = (string)propary[0].val; } found = propval != null && name.Equals(propval); propval = null; } } if (!found) { mor = null; } return mor; }

public static Object[] getProperties(ManagedObjectReference moRef, String[] properties) { // PropertySpec specifies what properties to // retrieve and from type of Managed Object PropertySpec pSpec = new PropertySpec(); pSpec.type = moRef.type; pSpec.pathSet = properties; // ObjectSpec specifies the starting object and // any TraversalSpecs used to specify other objects // for consideration ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = moRef; // PropertyFilterSpec is used to hold the ObjectSpec and // PropertySpec for the call PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet = new PropertySpec[] { pSpec }; pfSpec.objectSet = new ObjectSpec[] { oSpec }; ManagedObjectReference _svcRef1 = new ManagedObjectReference(); _svcRef1.type = "ServiceInstance"; _svcRef1.Value = "ServiceInstance"; ServiceContent sic1 = _service.RetrieveServiceContent(_svcRef1); ObjectContent[] ocs = new ObjectContent[20]; ocs = _service.RetrieveProperties(sic1.propertyCollector, new PropertyFilterSpec[] { pfSpec }); // Return value, one object for each property specified Object[] ret = new Object[properties.Length]; if (ocs != null) { for (int i = 0; i < ocs.Length; ++i) { ObjectContent oc = ocs[i]; DynamicProperty[] dps = oc.propSet; if (dps != null) { for (int j = 0; j < dps.Length; ++j) { DynamicProperty dp = dps[j]; // find property path index for (int p = 0; p < ret.Length; ++p) { if (properties[p].Equals(dp.name)) { ret[p] = dp.val; } } } } } } return ret; }

private void printhsInfo(string hsname) { ManagedObjectReference hsRef = new ManagedObjectReference(); // Get host MOR hsRef = GetDecendentMoRef(_sic.rootFolder, "HostSystem", hsname); if (hsRef != null) { //Get Virtual Machine properties Object[] VmListArray = getProperties(hsRef, new string[] {"vm"}); ManagedObjectReference[] VmList = (ManagedObjectReference[])VmListArray[0]; for (int i = 0; i < VmList.Length; i++) { Console.WriteLine("Virtual machine: " + (i+1)); ManagedObjectReference Vmref = (ManagedObjectReference)VmList[i]; Object[] properties = getProperties(Vmref, new string[] {"config.name","runtime.powerState" }); Console.WriteLine("\nVM name: " + properties[0] + "\nPower State: " + properties[1] ); } Console.Read(); } else { Console.WriteLine("The host with the specified name does not exist"); } } static void Main(string[] args) { VMlist vmInfo = new VMlist(); vmInfo.connect(args[0], args[1], args[2]); if (vmInfo._session != null) { vmInfo.printhsInfo(args[3]); //Disconnect from the server vmInfo.Disconnect(); } } } public class CertPolicy : ICertificatePolicy { private enum CertificateProblem : uint { CertEXPIRED = 0x800B0101,

CertVALIDITYPERIODNESTING = 0x800B0102, CertROLE = 0x800B0103, CertPATHLENCONST = 0x800B0104, CertCRITICAL = 0x800B0105, CertPURPOSE = 0x800B0106, CertISSUERCHAINING = 0x800B0107, CertMALFORMED = 0x800B0108, CertUNTRUSTEDROOT = 0x800B0109, CertCHAINING = 0x800B010A, CertREVOKED = 0x800B010C, CertUNTRUSTEDTESTROOT = 0x800B010D, CertREVOCATION_FAILURE = 0x800B010E, CertCN_NO_MATCH = 0x800B010F, CertWRONG_USAGE = 0x800B0110, CertUNTRUSTEDCA = 0x800B0112 } private static Hashtable problem2text_; private Hashtable request2problems_; // WebRequest -> ArrayList of error codes public CertPolicy() { if (problem2text_ == null) { problem2text_ = new Hashtable(); problem2text_.Add((uint)CertificateProblem.CertEXPIRED, "A required certificate is not within its validity period."); problem2text_.Add((uint)CertificateProblem.CertVALIDITYPERIODNESTING, "The validity periods of the certification chain do not nest correctly."); problem2text_.Add((uint)CertificateProblem.CertROLE, "A certificate that can only be used as an end-entity is being used as a CA or visa versa."); problem2text_.Add((uint)CertificateProblem.CertPATHLENCONST, "A path length constraint in the certification chain has been violated."); problem2text_.Add((uint)CertificateProblem.CertCRITICAL, "An extension of unknown type that is labeled 'critical' is present in a certificate."); problem2text_.Add((uint)CertificateProblem.CertPURPOSE, "A certificate is being used for a purpose other than that for which it is permitted."); problem2text_.Add((uint)CertificateProblem.CertISSUERCHAINING, "A parent of a given certificate in fact did not issue that child certificate."); problem2text_.Add((uint)CertificateProblem.CertMALFORMED, "A certificate is missing or has an empty value for an important field, such as a subject or issuer name."); problem2text_.Add((uint)CertificateProblem.CertUNTRUSTEDROOT, "A certification chain processed correctly, but terminated in a root certificate which isn't trusted by the trust provider."); problem2text_.Add((uint)CertificateProblem.CertCHAINING, "A chain of certs didn't chain as they should in a certain application of chaining."); problem2text_.Add((uint)CertificateProblem.CertREVOKED, "A certificate was explicitly revoked by its issuer."); problem2text_.Add((uint)CertificateProblem.CertUNTRUSTEDTESTROOT, "The root certificate is a testing certificate and the policy settings disallow test certificates."); problem2text_.Add((uint)CertificateProblem.CertREVOCATION_FAILURE, "The revocation process could not continue - the certificate(s) could not be checked."); problem2text_.Add((uint)CertificateProblem.CertCN_NO_MATCH, "The certificate's CN name does not match the passed value.");

problem2text_.Add((uint)CertificateProblem.CertWRONG_USAGE, "The certificate is not valid for the requested usage."); problem2text_.Add((uint)CertificateProblem.CertUNTRUSTEDCA, "Untrusted CA"); } request2problems_ = new Hashtable(); } // ICertificatePolicy public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest request, int problem) { if (problem == 0) { // Check whether we have accumulated any problems so far: ArrayList problemArray = (ArrayList)request2problems_[request]; if (problemArray == null) { // No problems so far return true; } string problemList = ""; foreach (uint problemCode in problemArray) { string problemText = (string)problem2text_[problemCode]; if (problemText == null) { problemText = "Unknown problem"; } problemList += "* " + problemText + "\n\n"; } request2problems_.Remove(request); System.Console.WriteLine("There were one or more problems with the server certificate:\n\n" + problemList); return true; } else { // Stash the problem in the problem array: ArrayList problemArray = (ArrayList)request2problems_[request]; if (problemArray == null) { problemArray = new ArrayList(); request2problems_[request] = problemArray; } problemArray.Add((uint)problem); return true; } } } }

A note from our legal department about VMware Sample Code:


The sample code is provided "AS-IS" for use, modification, and redistribution in source and binary forms, provided that the copyright notice and this following list of conditions are retained and/or reproduced in your distribution. To the maximum extent permitted by law, VMware, Inc., its subsidiaries and affiliates hereby disclaim all express, implied and/or statutory warranties, including duties or conditions of merchantability, fitness for a particular purpose, and non-infringement of intellectual property rights. IN NO EVENT WILL VMWARE, ITS SUBSIDIARIES OR AFFILIATES BE LIABLE TO ANY OTHER PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES, ARISING OUT OF THIS OR ANY OTHER AGREEMENT RELATING TO THE SAMPLE CODE. You agree to defend, indemnify and hold harmless VMware, and any of its directors, officers, employees, agents, affiliates, or subsidiaries from and against all losses, damages, costs and liabilities arising from your use, modification and distribution of the sample code. VMware does not certify or endorse your use of the sample code, nor is any support or other service provided in connection with the sample code.