利用VMware Infrastructure SDK编程控制虚拟机集群(3)
接上回,继续整理针对虚拟机的各种操作。7、跨主机克隆虚拟机
网上资料比较少,当时费了很大劲才成功的,与同一台主机上的虚拟机克隆有区别。
[*]/// <summary>
[*]/// 从模板部署虚拟机
[*]/// </summary>
[*]public void Deploy()
[*]{
[*] //模板路径,我们假设template100这个模板在另一台主机上
[*] //后续的几步都与同一台主机上克隆没有区别
[*] string templatePath = "DataCenter/vm/template100";
[*] ManagedObjectReference templateRef = m_Service.FindByInventoryPath(m_Content.searchIndex, templatePath);
[*] ManagedObjectReference folderRef = m_Service.FindByInventoryPath(m_Content.searchIndex, "DataCenter/vm");
[*] ManagedObjectReference poolRef = m_Service.FindByInventoryPath(m_Content.searchIndex, "DataCenter/host/host10/Resources");
[*]
[*] //此处开始是关键
[*] //获取目标host的引用,路径是“数据中心/host/主机名/资源名”,默认资源名与主机名相同
[*] ManagedObjectReference hostRef = m_Service.FindByInventoryPath(m_Content.searchIndex, "DataCenter/host/host10/host10");
[*]
[*] //还需要获取目标主机存储的引用,用到的RetrievePropertiesForSingleObject方法是自定义的,主要是封装一下服务上的RetrieveProperties方法
[*] //获取hostRef上的datastore属性,最终的dataRef就是存储对象的引用
[*] ObjectContent[] contents = RetrievePropertiesForSingleObject(hostRef, new string[] { "datastore" });
[*] ManagedObjectReference[] datastores = (ManagedObjectReference[])contents.propSet.val;
[*] ManagedObjectReference dataRef = datastores;
[*]
[*] //指定位置参数
[*] VirtualMachineRelocateSpec vmRelocSpec = new VirtualMachineRelocateSpec();
[*] vmRelocSpec.pool = poolRef;
[*] vmRelocSpec.datastore = dataRef; //这个很重要
[*] vmRelocSpec.transform = VirtualMachineRelocateTransformation.sparse;
[*]
[*] //指定复制相关参数,与同主机复制相同
[*] VirtualMachineCloneSpec vmCloneSpec = new VirtualMachineCloneSpec();
[*] vmCloneSpec.template = true;
[*] vmCloneSpec.location = vmRelocSpec;
[*] vmCloneSpec.powerOn = true;
[*]
[*] //还是调用CloneVM_Task来克隆虚拟机(异步),此处没有等待任务完成
[*] ManagedObjectReference taskRef = m_Service.CloneVM_Task(templateRef, folderRef, destName, vmCloneSpec);
[*]}
[*]
[*]/// <summary>
[*]/// 获取单一对象的属性
[*]/// </summary>
[*]/// <param name="obj">对象</param>
[*]/// <param name="properties">属性集合</param>
[*]/// <returns>内容集合</returns>
[*]private ObjectContent[] RetrievePropertiesForSingleObject(ManagedObjectReference obj, string[] properties)
[*]{
[*] PropertySpec[] pSpec = new PropertySpec[] { new PropertySpec() };
[*] pSpec.type = obj.type;
[*] pSpec.all = false;
[*] pSpec.pathSet = properties;
[*]
[*] ObjectSpec[] obSpec = new ObjectSpec[] { new ObjectSpec() };
[*] obSpec.obj = obj;
[*] obSpec.skip = true;
[*]
[*] PropertyFilterSpec spec = new PropertyFilterSpec();
[*] spec.propSet = pSpec;
[*] spec.objectSet = obSpec;
[*]
[*] ObjectContent[] contents = m_Service.RetrieveProperties(m_Collector, new PropertyFilterSpec[] { spec });
[*]
[*] return contents;
[*]}
未完待续……
页:
[1]