我们有的时候,我做Devops自动化运维的时候,需要在一个管理平台上操作VMWare,从而去管理VMSphere上的虚拟机,比如要添加一个新的虚拟机,为一个已有的虚拟机添加磁盘,内存或者调整CPU的个数,有的时候,我们还需要自动的从管理平台去把相应的虚拟机,打一个快照(SnapShot),或者回滚到某个快照并重启虚拟机,甚至删除某个快照。这些操作,如果登陆到VMSphere的管理系统里面,能做。但是如果需要在非VMSphere的管理系统,也要做同样的事情,那么应该如何集成呢?有没有简单的办法?


经过研究,操作VMSphere,其提供了两类的API:

@ SDK API

@Restful API


下面笔者分别分享一下如何用这两类API来操作VMSphere。

@首先需要联系VMSphere的管理员,让其给我们创建一个账号,并让其能够对指定的VM进行指定的操作。

这一步很重要,否则后面的步骤都无法进行。

@ 联系VMSphere的管理员,让其高速我们管理VM的服务器的IP地址或者机器名

@ 引入操作的API的jar包,其Maven的依赖如下

<!-- https://mvnrepository.com/artifact/com.vmware/vijava -->
<dependency>
    <groupId>com.vmware</groupId>
    <artifactId>vijava</artifactId>
    <version>5.1</version>
</dependency>

前期准备工作做好后,下面请分别参考其提供的示范代码。

SDK API

import java.net.URL;

import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VirtualMachineSnapshotInfo;
import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.Task;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.VirtualMachineSnapshot;

public class VMSnapshotSDK 
{
  public static void main(String[] args) throws Exception 
  {
   
    String vmname = "W7";
    String op = "list";
    //please change the following three depending your op
    String snapshotname = "w7test";
    String desc = "A description for sample snapshot";
    boolean removechild = true;
    
    URL url=new URL("https://10.10.8.8/sdk");
    
    ServiceInstance si = new ServiceInstance(url, "root", "password",true);

    Folder rootFolder = si.getRootFolder();
    VirtualMachine vm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmname);

    if(vm==null)
    {
      System.out.println("No VM " + vmname + " found");
      si.getServerConnection().logout();
      return;
    }

    if("create".equalsIgnoreCase(op))
    {
      Task task = vm.createSnapshot_Task(snapshotname, desc, false, false);
      if(task.waitForMe()==Task.SUCCESS)
      {
        System.out.println("Snapshot was created.");
      }
    }
    else if("list".equalsIgnoreCase(op))
    {
      listSnapshots(vm);
    }
    else if(op.equalsIgnoreCase("revert")) 
    {
      VirtualMachineSnapshot vmsnap = getSnapshotInTree(
          vm, snapshotname);
      if(vmsnap!=null)
      {
        Task task = vmsnap.revertToSnapshot_Task(null);
        if(task.waitForMe()==Task.SUCCESS)
        {
          System.out.println("Reverted to snapshot:" 
              + snapshotname);
        }
      }
    }
    else if(op.equalsIgnoreCase("removeall")) 
    {
      Task task = vm.removeAllSnapshots_Task();      
      if(task.waitForMe()== Task.SUCCESS) 
      {
        System.out.println("Removed all snapshots");
      }
    }
    else if(op.equalsIgnoreCase("remove")) 
    {
      VirtualMachineSnapshot vmsnap = getSnapshotInTree(
          vm, snapshotname);
      if(vmsnap!=null)
      {
        Task task = vmsnap.removeSnapshot_Task(removechild);
        if(task.waitForMe()==Task.SUCCESS)
        {
          System.out.println("Removed snapshot:" + snapshotname);
        }
      }
    }
    else 
    {
      System.out.println("Invalid operation");
      return;
    }
    si.getServerConnection().logout();
  }
  
  static VirtualMachineSnapshot getSnapshotInTree(
      VirtualMachine vm, String snapName)
  {
    if (vm == null || snapName == null) 
    {
      return null;
    }

    VirtualMachineSnapshotTree[] snapTree = 
        vm.getSnapshot().getRootSnapshotList();
    if(snapTree!=null)
    {
      ManagedObjectReference mor = findSnapshotInTree(
          snapTree, snapName);
      if(mor!=null)
      {
        return new VirtualMachineSnapshot(
            vm.getServerConnection(), mor);
      }
    }
    return null;
  }

  static ManagedObjectReference findSnapshotInTree(
      VirtualMachineSnapshotTree[] snapTree, String snapName)
  {
    for(int i=0; i <snapTree.length; i++) 
    {
      VirtualMachineSnapshotTree node = snapTree[i];
      if(snapName.equals(node.getName()))
      {
        return node.getSnapshot();
      } 
      else 
      {
        VirtualMachineSnapshotTree[] childTree = 
            node.getChildSnapshotList();
        if(childTree!=null)
        {
          ManagedObjectReference mor = findSnapshotInTree(
              childTree, snapName);
          if(mor!=null)
          {
            return mor;
          }
        }
      }
    }
    return null;
  }

  static void listSnapshots(VirtualMachine vm)
  {
    if(vm==null)
    {
      return;
    }
    VirtualMachineSnapshotInfo snapInfo = vm.getSnapshot();
    VirtualMachineSnapshotTree[] snapTree = 
      snapInfo.getRootSnapshotList();
    printSnapshots(snapTree);
  }

  static void printSnapshots(
      VirtualMachineSnapshotTree[] snapTree)
  {
    for (int i = 0; snapTree!=null && i < snapTree.length; i++) 
    {
      VirtualMachineSnapshotTree node = snapTree[i];
      System.out.println("Snapshot Name : " + node.getName());           
      VirtualMachineSnapshotTree[] childTree = 
        node.getChildSnapshotList();
      if(childTree!=null)
      {
        printSnapshots(childTree);
      }
    }
  }
}

Rest API

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;
import com.vmware.vim.rest.RestClient;


public class VMSnapshotRest {

	public static List<String> GetVMMachines(RestClient rc) throws DocumentException, IOException
	{
	    String contentXml = rc.get("moid=ha-folder-vm");
	    SAXReader reader=new SAXReader();
	    Document document=reader.read(new InputSource(new StringReader(contentXml)));
	    Element e=document.getRootElement();
	    Element e1=(Element)e.elements("object").get(0);
	    Element e2=(Element)e1.elements("childEntity").get(0);
	    Iterator<?> it=e2.elements("ManagedObjectReference").iterator();
	    List<String> machines=new ArrayList<String>();
	    while(it.hasNext())
	    {
	    	Element versionMachine=(Element)it.next();
	    	String moid=versionMachine.getText();
	    	String vmXml = rc.get("moid="+moid);
	    	Document vmdoc=reader.read(new InputSource(new StringReader(vmXml)));
	    	Element ve=vmdoc.getRootElement();
	 	    Element ve1=(Element)ve.elements("object").get(0);
	 	    Element ve2=(Element)ve1.elements("config").get(0);
	 	    Element ve3=(Element)ve2.elements("name").get(0);
	    	machines.add(moid);
	    }
	    return machines;
	}
	public static void GetSnapShotList(RestClient rc,String moid) throws Exception
	{
	    //String contentXml = rc.post("moid="+moid+"&method=createSnapshot");
	    Map<String, String> para = new Hashtable<String, String>();
	    //para.put("name", "first snapshot");
	    //para.put("description ", "first snapshot");
	    //para.put("memory", "false");
	    //para.put("quiesce", "false");
	    String message1=rc.get("moid="+moid+"&method=createSnapshot");
	    para.put("newName", "Melody_SuSe");
	    String message=rc.post("moid="+moid+"&method=rename", para);
	    SAXReader reader=new SAXReader();
	    
	}
	public static void main(String[] args) throws Exception
	  {	
	    RestClient rc = new RestClient("https://10.10.8.8", "root", "password");
	   
	    List<String> vmMachines = GetVMMachines(rc);
	    GetSnapShotList(rc,vmMachines.get(0));
	    
	    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder = factory.newDocumentBuilder();  

	  }


}

其中,VMWare的管理平台的URL地址为:https://10.10.8.8/sdk, 用户名和密码为:root/password.
是不是感觉很简单啊!!!!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐