您的位置:首页 > 编程语言

VMware vSphere Web Services SDK编程指南(七)- 7.5 清单遍历

2017-08-13 23:45 411 查看

7.5 清单遍历(Inventory Traversal)

vSphere 服务器为数据访问和变化监控提供了 PropertyCollector 服务。

使用 PropertyCollector 可获取到托管对象的引用,获取托管对象属性的值,并监控和获取修改后的属性值。

本章包括以下主题:

7.1 PropertyCollector 介绍

7.2 用于属性收集的 vSphere 数据对象

7.3 用于属性收集的 vSphere 方法

7.4 PropertyCollector 示例 (RetrievePropertiesEx)

7.5 清单遍历

7.6 客户端数据同步(WaitForUpdatesEx)

7.7 服务器数据传输

7.8 PropertyCollector 性能

7.9 SearchIndex

本小节续前面章节继续翻译清单遍历

上一小节的 PropertyCollector 示例(Java)使用一个 ContainerView 指定开始收集过程的对象,这是建立一个过滤器最简单的方式,使用一个对视图的单引用,为 PropertyCollector 提供一组对象的访问。

要从清单选择对象,一个过滤器包含 TraversalSpec 和可能用到的 SelectionSpec 对象。

使用这些对象基于一个视图引用实现对象的选择,并且当超出这些对象(或者超过对象指定的 ObjectSpec.obj)时,扩展清单遍历范围。

7.5.1 TraversalSpec 遍历

使用一个 TraversalSpec 对象确定一个托管对象类型和一个该类型的遍历属性,TraversalSpec 包含下列属性:

■ type - 确定一个清单对象类型

■ path - 在 type 对象中指定一个托管对象引用属性,这个属性提供从该对象延伸的遍历路径

■ selectSet - 为额外的对象遍历路径指定一个选择对象的可选列表,

PropertyCollector 将 SelectSet 数组中的 TraversalSpec 对象 应用于遍历结果(即 TraversalSpec.path 的目标)。

SelectSet 数组也可以包含 SelectionSpec 对象,SelectionSpec 是一个 TraversalSpec 引用。具体查看下面会介绍的 SelectionSpec Traversal

■ skip- 表示是否为 path 对象收集属性

在清单遍历期间,PropertyCollector 将 PropertySpec 对象 或 对象集合(PropertyFilterSpec.propSet)应用于遍历
4000
对象,清单遍历从 ObjectSpec.obj 确认的对象开始并沿着 TraversalSpec 的路径继续遍历。

如果 PropertySpec.type 匹配当前对象类型,而 skip 属性是 false,那么 PropertyCollector 发送 PropertySpec.pathSet 属性到你的客户端。

下面的清单导航图表示了一个定义虚拟机对象遍历的 PropertyFilterSpec,该过滤器使用 ContainerView 作为起点。ContainerView 的 TraversalSpec 规范指定了访问视图的虚拟机 的 view 属性。

下图显示了 TraversalSpec 对象,该对象将导航范围从一个虚拟机对象扩展到关联的 Network 和 ResourcePool 对象,

PropertyCollector 将这些 TraversalSpec 规范对象应用到视图列表中的每个 VirtualMachine 对象。

下图也显示了从 VirtualMachine, Network 和 ResourcePool 对象中收集数据的 PropertySpec 对象。

清单导航



下面的清单遍历示例显示了一个基于前一节 简单 PropertyCollector 示例的 Java 代码片段,

该代码实现了显示于上图的清单遍历功能。

要定义清单遍历,需做如下步骤:

1 为虚拟机创建一个 ContainerView;

2 使用容器视图创建一个 ObjectSpec 对象作为收集起点;

3 创建一个 TraversalSpec 应用于 ContainerView 来选择 VirtualMachine 对象;

4 创建额外的 TraversalSpec 对象来选择额外的对象;

容器视图 TraversalSpec 的 SelectSet 列表有两个 TraversalSpec 对象,都指定一个 VirtualMachine 对象上下文。

一个对象 使用 network 属性将遍历扩展到 Network 托管对象;另外一个使用 resourcePool 属性将遍历扩展到 ResourcePool 托管对象。

5 创建 PropertySpec 对象提取 VirtualMachine、Network 和 ResourcePool 属性。

要提取嵌套数据对象的属性,PropertySpec.PathSet 属性使用 点(.)符号来指定属性路径。

示例:清单遍历

import com.vmware.vim25.*;

import java.util.*;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.soap.SOAPFaultException;

// PropertyCollector example
// command line input: server name, user name, password

public class PCollector_traversal {

private static void collectProperties(VimPortType methods,
ServiceContent sContent) throws Exception {

// Get references to the ViewManager and PropertyCollector
ManagedObjectReference viewMgrRef = sContent.getViewManager();
ManagedObjectReference propColl = sContent.getPropertyCollector();

// use a container view for virtual machines to define the traversal
// - invoke the VimPortType method createContainerView (corresponds
// to the ViewManager method) - pass the ViewManager MOR and
// the other parameters required for the method invocation
// (use a List<String> for the type parameter's string[])
List<String> vmList = new ArrayList<String>();
vmList.add("VirtualMachine");

ManagedObjectReference cViewRef = methods.createContainerView(
viewMgrRef, sContent.getRootFolder(), vmList, true);

// create an object spec to define the beginning of the traversal;
// container view is the root object for this traversal
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(cViewRef);
oSpec.setSkip(true);

// create a traversal spec to select all objects in the view
TraversalSpec tSpec = new TraversalSpec();
tSpec.setName("traverseEntities");
tSpec.setPath("view");
tSpec.setSkip(false);
tSpec.setType("ContainerView");

// add the traversal spec to the object spec;
// the accessor method (getSelectSet) returns a reference
// to the mapped XML representation of the list; using this
// reference to add the spec will update the selectSet list
oSpec.getSelectSet().add(tSpec);

// extend from virtual machine to network
TraversalSpec tSpecVmN = new TraversalSpec();
tSpecVmN.setType("VirtualMachine");
tSpecVmN.setPath("network");
tSpecVmN.setSkip(false);

// extend from virtual machine to resourcepool
TraversalSpec tSpecVmRp = new TraversalSpec();
tSpecVmRp.setType("VirtualMachine");
tSpecVmRp.setPath("resourcePool");
tSpecVmRp.setSkip(false);

// add the network and resource pool traversal specs
// to the virtual machine traversal;
// the accessor method (getSelectSet) returns a reference
// to the mapped XML representation of the list; using this
// reference to add the spec will update the selectSet list
tSpec.getSelectSet().add(tSpecVmN);
tSpec.getSelectSet().add(tSpecVmRp);

// specify the properties for retrieval
// (virtual machine name, network summary accessible, rp runtime props);
// the accessor method (getPathSet) returns a reference to the mapped
// XML representation of the list; using this reference to add the
// property names will update the pathSet list
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
pSpec.getPathSet().add("name");

PropertySpec pSpecNs = new PropertySpec();
pSpecNs.setType("Network");
pSpecNs.getPathSet().add("summary.accessible");

PropertySpec pSpecRPr = new PropertySpec();
pSpecRPr.setType("ResourcePool");
pSpecRPr.getPathSet().add("runtime.cpu.maxUsage");
pSpecRPr.getPathSet().add("runtime.memory.maxUsage");
pSpecRPr.getPathSet().add("runtime.overallStatus");

// create a PropertyFilterSpec and add the object and
// property specs to it; use the getter methods to reference
// the mapped XML representation of the lists and add the specs
// directly to the objectSet and propSet lists
PropertyFilterSpec fSpec = new PropertyFilterSpec();
fSpec.getObjectSet().add(oSpec);
fSpec.getPropSet().add(pSpec);
fSpec.getPropSet().add(pSpecNs);
fSpec.getPropSet().add(pSpecRPr);

// Create a list for the filters and add the spec to it
List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>();
fSpecList.add(fSpec);

// get the data from the server
RetrieveOptions ro = new RetrieveOptions();
RetrieveResult props = methods.retrievePropertiesEx(propColl,
fSpecList, ro);

// go through the returned list and print out the data
if (props != null) {
for (ObjectContent oc : props.getObjects()) {
String value = null;
String path = null;
List<DynamicProperty> dps = oc.getPropSet();
if (dps != null) {
for (DynamicProperty dp : dps) {
path = dp.getName();
if (path.equals("name")) {
value = (String) dp.getVal();
} else if (path.equals("summary.accessible")) {
// summary.accessible is a boolean
value = String.valueOf(dp.getVal());
} else if (path.equals("runtime.cpu.maxUsage")) {
// runtime.cpu.maxUsage is an xsd:long
value = String.valueOf(dp.getVal());
} else if (path.equals("runtime.memory.maxUsage")) {
// runtime.memory.maxUsage is an xsd:long
value = String.valueOf(dp.getVal());
} else if (path.equals("runtime.overallStatus")) {
// runtime.overallStatus is a ManagedEntityStatus
// enum
value = String.valueOf(dp.getVal());
}

System.out.println(path + " = " + value);
}
}
}
}
}// end collectProperties()

// Authentication is handled by using a TrustManager and supplying
// a host name verifier method. (The host name verifier is declared
// in the main function.)
//
// For the purposes of this example, this TrustManager implementation
// will accept all certificates. This is only appropriate for
// a development environment. Production code should implement certificate
// support.
private static class TrustAllTrustManager implements
javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {

public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}

public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}

public static void main(String[] args) throws Exception {

// arglist variables
String serverName = args[0];
String userName = args[1];
String password = args[2];
String url = "https://" + serverName + "/sdk/vimService";

// Variables of the following types for access to the API methods
// and to the vSphere inventory.
// -- ManagedObjectReference for the ServiceInstance on the Server
// -- VimService for access to the vSphere Web service
// -- VimPortType for access to methods
// -- ServiceContent for access to managed object services

1149d
ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
VimService vimService;
VimPortType vimPort;
ServiceContent serviceContent;

// Declare a host name verifier that will automatically enable
// the connection. The host name verifier is invoked during
// the SSL handshake.
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};

// Create the trust manager.
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
trustAllCerts[0] = tm;

// Create the SSL context
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");

// Create the session context
javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();

// Initialize the contexts; the session context takes the trust manager.
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);

// Use the default socket factory to create the socket for the secure
// connection
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());

// Set the default host name verifier to enable the connection.
HttpsURLConnection.setDefaultHostnameVerifier(hv);

// Set up the manufactured managed object reference for the
// ServiceInstance
SVC_INST_REF.setType("ServiceInstance");
SVC_INST_REF.setValue("ServiceInstance");

// Create a VimService object to obtain a VimPort binding provider.
// The BindingProvider provides access to the protocol fields
// in request/response messages. Retrieve the request context
// which will be used for processing message requests.
vimService = new VimService();
vimPort = vimService.getVimPort();
Map<String, Object> ctxt = ((BindingProvider) vimPort)
.getRequestContext();

// Store the Server URL in the request context and specify true
// to maintain the connection between the client and server.
// The client API will include the Server's HTTP cookie in its
// requests to maintain the session. If you do not set this to true,
// the Server will start a new session with each request.
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
// Retrieve the ServiceContent object and login
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
vimPort.login(serviceContent.getSessionManager(), userName, password,
null);

// retrieve data
collectProperties(vimPort, serviceContent);

// close the connection
vimPort.logout(serviceContent.getSessionManager());

}
}


7.5.2 SelectionSpec 遍历

在 ObjectSpec 和 TraversalSpec 对象中的 selectSet 数组可以包含 TraversalSpec 对象和 SelectionSpec 对象。SelectionSpec 是 TraversalSpec 对象的基类,SelectionSpec 定义了 name 属性,你可以使用 SelectSpec 对象在一个 SelectSet 数组作为一个到名为 TraversalSpec 对象的引用。通过使用 SelectSpec 引用,你可以重复使用一个 TraversalSpec 并且可以定义递归遍历。

SelectSpec 简单引用

使用 SelectionSpec 引用避免写重复的 TraversalSpec 声明。在 SelectionSpec 引用中确定的 TraversalSpec 必须在同一个 PropertyFilterSpec 范围内。

下面的 SelectSpec 引用图显示了 SelectionSpec 引用对虚拟机 TraversalSpec 的使用过程。SelectionSpec 引用和 Network 及 Datastore 遍历相关联。

SelectSpec 引用



如果 ObjectSpec.selectSet 数组包含一个 SelectionSpec,所引用的 TraversalSpec 必须确定相同的对象类型。TraversalSpec.type 必须匹配在 ObjectSpec.obj 中指定的对象类型,PropertyCollector 将 TraversalSpec 应用于对象并使用 TraversalSpec.path 属性来扩展它的遍历。

递归遍历

使用 SelectionSpec 将其自身遍历的结果应用到 TraversalSpec 规范中。要使用递归过滤器结构,创建一个 SelectionSpec 指定 TraversalSpec 的名称并将其添加到名为 TraversalSpec 的选择集。递归的构造扩展了清单遍历范围,超出了由 TraversalSpec 直接表示的路径。

你可以在任何可嵌套的清单对象上使用递归遍历。查阅清单层次结构及 ServiceInstance了解清单结构的一般表示。

例如,在一个 vCenter 服务器上,folders 可以嵌套到任意深度。

要描述一个遍历路径(通过一系列 folders), 你可以添加一个 SelectionSpec 到 Folder TraversalSpec,SelectionSpec 必须引用 TraversalSpec。

下图显示了一种用于嵌套 folder 遍历的一个 TraversalSpec 和关联的 SelectionSpec 的表示。

递归 TraversalSpec 和 SelectionSpec



要定义递归清单遍历,按如下步骤:

1 使用 SearchIndex 托管对象为顶层虚拟机 folder 提取托管对象引用

这个 folder 用作清单遍历的起点。想了解更多信息可查阅 SearchIndex

2 创建一个 ObjectSpec 对象引用顶层虚拟机 folder

3 创建一个 SelectionSpec 对象通过名称引用 Folder TraversalSpec

4 为 Folder 对象创建一个名为 TraversalSpec 对象

TraversalSpec.path 属性确定了用于遍历任何子对象的 Folder.childEntity 属性

5 将 SelectionSpec 添加到 TraversalSpec ,以创建递归过滤器

6 将 TraversalSpec 添加到 ObjectSpec 对象

7 为 Folder 名称创建一个 PropertySpec 对象

8 将对象和属性规范添加到 PropertyFilterSpec 中

9 调用 RetrievePropertiesEx 方法提取托管实体数据

下面的示例显示了创建一个用于嵌套 folder 遍历的递归过滤器的 Java 代码片段。

示例: 嵌套 Folder 遍历

import com.vmware.vim25.*;

import java.util.*;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.soap.SOAPFaultException;

// PropertyCollector example
// command line input: server name, user name, password

public class NestedTraversal {

private static void collectProperties(VimPortType methods,
ServiceContent sContent) throws Exception {

// Get reference to the PropertyCollector
ManagedObjectReference propColl = sContent.getPropertyCollector();

// get the top-level vm folder mor
ManagedObjectReference sIndex = sContent.getSearchIndex();
ManagedObjectReference rootVmFolder = methods.findByInventoryPath(
sIndex, "datacenter1/vm");

// create an object spec to define the beginning of the traversal;
// root vm folder is the root object for this traversal
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(rootVmFolder);
oSpec.setSkip(true);

// folder traversal reference
SelectionSpec sSpecF = new SelectionSpec();
sSpecF.setName("traverseFolder");

// create a folder traversal spec to select childEntity
TraversalSpec tSpecF = new TraversalSpec();
tSpecF.setType("Folder");
tSpecF.setPath("childEntity");
tSpecF.setSkip(false);
tSpecF.setName("traverseFolder");

// use the SelectionSpec as a reflexive spec for the folder traversal;
// the accessor method (getSelectSet) returns a reference to the
// mapped XML representation of the list; using this reference
// to add the spec will update the list
tSpecF.getSelectSet().add(sSpecF);

// add folder traversal to object spec
oSpec.getSelectSet().add(tSpecF);

// specify the property for retrieval (folder name)
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Folder");
pSpec.getPathSet().add("name");

// create a PropertyFilterSpec and add the object and
// property specs to it; use the getter method to reference
// the mapped XML representation of the lists and add the specs
// directly to the lists
PropertyFilterSpec fSpec = new PropertyFilterSpec();
fSpec.getObjectSet().add(oSpec);
fSpec.getPropSet().add(pSpec);

// Create a list for the filter and add the spec to it
List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>();
fSpecList.add(fSpec);

// get the data from the server
RetrieveOptions ro = new RetrieveOptions();
RetrieveResult props = methods.retrievePropertiesEx(propColl,
fSpecList, ro);

// go through the returned list and print out the data
if (props != null) {
for (ObjectContent oc : props.getObjects()) {
String folderName = null;
String path = null;
List<DynamicProperty> dps = oc.getPropSet();
if (dps != null) {
for (DynamicProperty dp : dps) {
folderName = (String) dp.getVal();
path = dp.getName();
System.out.println(path + " = " + folderName);
}
}
}
}
}// end collectProperties()

// Authentication is handled by using a TrustManager and supplying
// a host name verifier method. (The host name verifier is declared
// in the main function.)
//
// For the purposes of this example, this TrustManager implementation
// will accept all certificates. This is only appropriate for
// a development environment. Production code should implement certificate
// support.
private static class TrustAllTrustManager implements
javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {

public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}

public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}

public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}

public static void main(String[] args) throws Exception {

// arglist variables
String serverName = args[0];
String userName = args[1];
String password = args[2];
String url = "https://" + serverName + "/sdk/vimService";

// Variables of the following types for access to the API methods
// and to the vSphere inventory.
// -- ManagedObjectReference for the ServiceInstance on the Server
// -- VimService for access to the vSphere Web service
// -- VimPortType for access to methods
// -- ServiceContent for access to managed object services
ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
VimService vimService;
VimPortType vimPort;
ServiceContent serviceContent;

// Declare a host name verifier that will automatically enable
// the connection. The host name verifier is invoked during
// the SSL handshake.
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};

// Create the trust manager.
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
trustAllCerts[0] = tm;
// Create the SSL context
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");
// Create the session context
javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
// Initialize the contexts; the session context takes the trust manager.
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);

// Use the default socket factory to create the socket for the secure
// connection
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());

// Set the default host name verifier to enable the connection.
HttpsURLConnection.setDefaultHostnameVerifier(hv);

// Set up the manufactured managed object reference for the
// ServiceInstance
SVC_INST_REF.setType("ServiceInstance");
SVC_INST_REF.setValue("ServiceInstance");

// Create a VimService object to obtain a VimPort binding provider.
// The BindingProvider provides access to the protocol fields
// in request/response messages. Retrieve the request context
// which will be used for processing message requests.
vimService = new VimService();
vimPort = vimService.getVimPort();
Map<String, Object> ctxt = ((BindingProvider) vimPort)
.getRequestContext();

// Store the Server URL in the request context and specify true
// to maintain the connection between the client and server.
// The client API will include the Server's HTTP cookie in its
// requests to maintain the session. If you do not set this to true,
// the Server will start a new session with each request.
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

// Retrieve the ServiceContent object and login
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
vimPort.login(serviceContent.getSessionManager(), userName, password,
null);

// retrieve data
collectProperties(vimPort, serviceContent);

// close the connection
vimPort.logout(serviceContent.getSessionManager());

}
}


原文:

VMware vSphere 6.5 Documentation Center:Inventory Traversal
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐