我使用yavijava并且需要遍历vCenter并在其上构建所有主机和VM的列表。对于每个主机和VM,我需要检索一些属性,例如名称,RAM / CPU等等。我当前的代码如下所示:
ManagedEntity[] hosts = new InventoryNavigator.searchManagedEntities("VirtualMachine");
for(int i=0;i<hosts.length;i++) {
String name = hosts[i].getName();
String xxx = hosts[i].XXXXX;
.....
对于VM也是如此。
我的问题是,考虑到存在大量对象并且每个调用(例如getName)向vSphere发送新请求,是否有更有效的方法来执行此操作?
答案 0 :(得分:3)
您需要手动构建属性收集器,具体取决于您要创建库存系统以关联对象的库存。我在集群的github上有一个示例:https://github.com/yavijava/yavijava_cluster_prop_example
RetrieveOptions options = new RetrieveOptions();
options.setMaxObjects(100);
String[] vmProps = new String[2];
vmProps[0] = "name";
vmProps[1] = "runtime.host";
PropertySpec vmSpec = new PropertySpec();
vmSpec.setAll(false);
vmSpec.setType("VirtualMachine");
vmSpec.setPathSet(vmProps);
String[] hostProps = new String[4];
hostProps[0] = "name";
hostProps[1] = "summary.hardware.numCpuCores";
hostProps[2] = "summary.hardware.cpuModel";
hostProps[3] = "summary.hardware.memorySize";
PropertySpec hostSpec = new PropertySpec();
hostSpec.setAll(false);
hostSpec.setType("HostSystem");
hostSpec.setPathSet(hostProps);
String[] clusterProps = new String[2];
clusterProps[0] = "name";
clusterProps[1] = "parent";
PropertySpec clusterSpec = new PropertySpec();
clusterSpec.setAll(false);
clusterSpec.setType("ClusterComputeResource");
clusterSpec.setPathSet(clusterProps);
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(clusterMe.getMOR());
oSpec.setSelectSet(com.vmware.vim25.mo.util.PropertyCollectorUtil.buildFullTraversalV4());
PropertyFilterSpec[] pfSpec = new PropertyFilterSpec[1];
pfSpec[0] = new PropertyFilterSpec();
ObjectSpec[] oo = new ObjectSpec[1];
oo[0] = oSpec;
pfSpec[0].setObjectSet(oo);
PropertySpec[] pp = new PropertySpec[3];
pp[0] = vmSpec;
pp[1] = hostSpec;
pp[2] = clusterSpec;
pfSpec[0].setPropSet(pp);
RetrieveResult ret = serviceInstance.getPropertyCollector().retrievePropertiesEx(pfSpec, options);
for (ObjectContent aRet : ret.getObjects()) {
if(aRet.getObj().type.equalsIgnoreCase("ClusterComputeResource")) {
printInfo(aRet);
}
if(aRet.getObj().type.equalsIgnoreCase("HostSystem")) {
System.out.println("Host Info: ");
printInfo(aRet);
System.out.println("#######################");
}
if(aRet.getObj().type.equalsIgnoreCase("VirtualMachine")) {
System.out.println("VirtualMachine: ");
printInfo(aRet);
System.out.println("#######################################");
}
}
}
private static void printInfo(ObjectContent objectContent) {
// This is super generic here... To actually relate the objects so you
// know which HostSystem a VirtualMachine lives on you need to implement
// some kind of inventory system and use the MOR from the HostSystem
// and the MOR from the vm.runtime.host
for(DynamicProperty props: objectContent.getPropSet()) {
System.out.println(props.val);
}
}