a2005147 发表于 2018-6-7 08:31:06

利用VMware Infrastructure SDK编程控制虚拟机集群(1)

  两年前的一个老项目了,基于VMware Infrastructure 3.5的,整理一下当时的技术资料。至于VMware Infrastructure是什么以及它能干什么,不详细介绍了,感兴趣的同学可以自己百度一下。
  
1、通过什么方式访问VI中心
  VMware Infrastructure对外提供WebService,供第三方应用调用,以实现针对主机、虚拟机等资源的控制。针对.Net,提供了一个VimService2003.dll,开发时需要把它加入项目引用。
  
2、如何查看VI集群中各资源的信息
  除了使用Vmware Infrastructure Client以外,可以使用浏览器查看,地址是http://localhost:8080/mob。 其中的8080是vfxd服务设置的监听端口。
  
3、如何登录VI中心


[*]public class ViDemo
[*]{
[*]    //以下是VI开发中会用到的所有对象
[*]    private VimService m_Service;
[*]    private ServiceContent m_Content;
[*]    private ManagedObjectReference m_SvcRef;
[*]    private ManagedObjectReference m_Collector;
[*]    private UserSession m_Session;
[*]
[*]    /// <summary>
[*]    /// 登录,耗时会比较长
[*]    /// </summary>
[*]    public void Connect()
[*]    {
[*]      m_SvcRef = new ManagedObjectReference();
[*]      m_SvcRef.type = &quot;ServiceInstance&quot;;
[*]      m_SvcRef.Value = &quot;ServiceInstance&quot;;
[*]   
[*]      m_Service = new VimService();
[*]      m_Service.Url = &quot;http://localhost:8080/sdk&quot;;
[*]      m_Content = m_Service.RetrieveServiceContent(m_SvcRef);
[*]      m_Collector = m_Content.propertyCollector;
[*]      if(m_Content.sessionManager != null)
[*]      {
[*]            m_Session = m_Service.Login(m_Content.sessionManager, &quot;USER&quot;, &quot;PASS&quot;, null);
[*]      }
[*]    }
[*]
[*]    /// <summary>
[*]    /// 注销
[*]    /// </summary>
[*]    public void Disconnect()
[*]    {
[*]      if(m_Service != null)
[*]      {
[*]            m_Service.Logout(m_Content.sessionManager);
[*]            m_Service.Dispose();
[*]            m_Service = null;
[*]            m_Content = null;
[*]            m_Session = null;
[*]      }
[*]    }
[*]}

  
4、虚拟机开机及关机


[*]/// <summary>
[*]/// 虚拟机关机
[*]/// </summary>
[*]public void PowerOff()
[*]{
[*]    //虚拟机的资源路径,格式是“中心/vm/虚拟机名称”,本例中中心叫DataCenter,虚拟机是vm100
[*]    //不用关心虚拟机在哪台主机上,因为对VI来说,集群是一个整体
[*]    string path = &quot;DataCenter/vm/vm100&quot;;
[*]
[*]    //根据虚拟机的资源路径获取资源的引用
[*]    ManagedObjectReference vmRef = m_Service.FindByInventoryPath(m_Content.searchIndex, path);
[*]    if(vmRef != null)
[*]    {
[*]      //调用服务上的PowerOffVM_Task来关闭虚拟机(异步),此处没有等待任务完成
[*]      //如果是开机,调用PowerOnVM_Task方法
[*]      ManagedObjectReference taskRef = m_Service.PowerOffVM_Task(vmRef);
[*]    }
[*]}

  
未完待续……
页: [1]
查看完整版本: 利用VMware Infrastructure SDK编程控制虚拟机集群(1)