Vijava (模板部署虚拟机,并指定自定义规范(终极版本))

源代码:

package com.vmware.customzation;

import com.vmware.util.Session;
import com.vmware.util.StringRandom;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;

import java.rmi.RemoteException;

/**
 * 测试代码;
 * 配置虚拟机网卡指定静态IP地址
 * Created by vixuan-008 on 2015/6/12.
 */
public class UpdateCustomzation {
    public static void main(String[] args){

        // vijava
        com.vmware.vim25.mo.VirtualMachine templateVM = null;
        com.vmware.vim25.mo.ResourcePool pool = null;
        ComputeResource computerResource = null;
        com.vmware.vim25.mo.Datastore datastore = null;
        InventoryNavigator inventoryNavigator = null;
        Task task = null;
        ServiceInstance instance = null;

        String ip="***";
        String username="****";
        String password="****";


        String templateName="template1";  //模板名称
        String datastoreName="datastore1";//datastore 名称
        String poolName="Company";//资源池名称
        String hostName="";
        String virtualmachineName="vm8";//虚拟机名称





        // 逻辑处理
        try {
            instance = Session.getInstance(ip, username, password);
            Folder rootFolder = instance.getRootFolder();
            inventoryNavigator = new InventoryNavigator(rootFolder);
            try {
                templateVM = (com.vmware.vim25.mo.VirtualMachine) inventoryNavigator
                        .searchManagedEntity("VirtualMachine",
                                templateName);

            } catch (RemoteException e) {
                e.printStackTrace();
                System.out.println("模板虚拟机查询失败");

            }
            try {
                datastore = (com.vmware.vim25.mo.Datastore) inventoryNavigator
                        .searchManagedEntity("Datastore",
                                datastoreName);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("DataStore查询失败");

            }

            VirtualMachineRelocateSpec virtualMachineRelocateSpec = new VirtualMachineRelocateSpec();
            if (null != poolName
                    && !"".equals(poolName)) {
                try {
                    pool = (com.vmware.vim25.mo.ResourcePool) inventoryNavigator
                            .searchManagedEntity("ResourcePool",
                                    poolName);
                    virtualMachineRelocateSpec.setPool(pool.getMOR());

                    virtualMachineRelocateSpec.setDatastore(datastore
                            .getMOR());
                    if (pool != null) {
                        System.out.println("pool 查询成功");
                    } else {
                        System.out.println("pool 查询失败,请仔细检查配置资源池是否存在");
                    }
                } catch (RemoteException e) {
                    System.out.println("Vcenter资源池存在问题:"
                            + e.getMessage());

                }

            } else {

                try {
                    computerResource = (ComputeResource) inventoryNavigator
                            .searchManagedEntity("ComputeResource",
                                    hostName);
                    if (computerResource != null) {
                        if (computerResource.getResourcePool() != null) {
                            virtualMachineRelocateSpec
                                    .setPool(computerResource
                                            .getResourcePool().getMOR());
                        }
                        virtualMachineRelocateSpec
                                .setDatastore(datastore.getMOR());
                        virtualMachineRelocateSpec
                                .setHost(computerResource.getHosts()[0]
                                        .getMOR());
                    }

                } catch (RemoteException e) {
                    e.printStackTrace();
                    System.out.println("Vcenter下Esxi存在问题:"
                            + e.getMessage());
                }

            }
            VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
            // 设置CPU核数
            configSpec.setNumCPUs(4);
            // 设置内存大小
            configSpec.setMemoryMB((long)2048);
            // 设置虚拟机名称
            configSpec.setName(virtualmachineName);
            // 设置虚拟机描述
            configSpec.setAnnotation("VirtualMachine Annotation");

            VirtualDeviceConfigSpec diskSpec = createDiskSpec(
                    datastoreName,
                    10*1024*1024, "persistent",templateVM);
            if (diskSpec != null) {
               System.out.println("创建disk不为空");
            } else {
                System.out.println("创建disk为空");
            }

            configSpec
                    .setDeviceChange(new VirtualDeviceConfigSpec[] { diskSpec });

            VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
            cloneSpec.setLocation(virtualMachineRelocateSpec);

            cloneSpec.setPowerOn(true);
            cloneSpec.setTemplate(false);
            cloneSpec.setConfig(configSpec);
         //  CustomizationSpec customizationSpec=getCustomizationSpec(instance,"windows 7 x86");
            CustomizationSpec customizationSpec=createCustomizations();
            cloneSpec.setCustomization(customizationSpec);

//                    }

            try {

                task = templateVM.cloneVM_Task(
                        (Folder) templateVM.getParent(),
                        virtualmachineName, cloneSpec);
                String result = task.waitForTask();
                if (result.equals(Task.SUCCESS)) {
                   System.out.println("模板生成虚拟机成功");

                } else {
                    System.out.println("模板生成虚拟机失败,请查询Vcenter 上相关日志信息");
                }

            } catch (RemoteException e) {
                System.out.println("message:"+e.getMessage());

                if (instance != null) {
                    instance.getServerConnection().logout();

                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询用户已经创建的自定义规范
    public static CustomizationSpec getCustomizationSpec( ServiceInstance instance,String customizationName){
        CustomizationSpec customizationSpec=null;
        CustomizationSpecItem customizationSpecItem=null;
        com.vmware.vim25.mo.CustomizationSpecManager manager=instance.getCustomizationSpecManager();
        CustomizationSpecInfo[] infos=manager.getInfo();
        if(infos!=null && infos.length>0){
            for(CustomizationSpecInfo info:infos){
                if(info.getName().equalsIgnoreCase(customizationName)){
                    try{
                        customizationSpecItem=manager.getCustomizationSpec(customizationName);
                        customizationSpec=customizationSpecItem.getSpec();
                    }catch (Exception e){
                        e.printStackTrace();
                        return customizationSpec;
                    }

                }
            }
        }
        return customizationSpec;
    }

    public static CustomizationSpec createCustomizations(){
        CustomizationSpec spec=new CustomizationSpec();

        //创建文件类型windows
        CustomizationWinOptions options = new CustomizationWinOptions();
        options.setChangeSID(true);
        options.setDeleteAccounts(false);
        spec.setOptions(options);
        //创建应答文件
        CustomizationSysprep sysprep=new CustomizationSysprep();
        //
        CustomizationGuiUnattended unattended=new CustomizationGuiUnattended();
        unattended.setTimeZone(4);
        unattended.setAutoLogon(false);
        unattended.setAutoLogonCount(0);
        sysprep.setGuiUnattended(unattended);

        CustomizationUserData userData=new CustomizationUserData();
        userData.setFullName("viuxan.com");
        userData.setOrgName("vixuan.com");
        CustomizationVirtualMachineName virtualMachineName=new CustomizationVirtualMachineName();
        userData.setComputerName(virtualMachineName);
        userData.setProductId("HWRFF-2FFYX-XFXP2-DYFC3-BX3B7");
        sysprep.setUserData(userData);

        CustomizationIdentification identification=new CustomizationIdentification();
        identification.setJoinWorkgroup("WORKGROUP");
        sysprep.setIdentification(identification);

        spec.setIdentity(sysprep);

        CustomizationGlobalIPSettings globalIPSettings=new CustomizationGlobalIPSettings();
        spec.setGlobalIPSettings(globalIPSettings);

        //设置IP地址
        CustomizationAdapterMapping[] adapterMappings =new   CustomizationAdapterMapping[1];
        CustomizationIPSettings ipSetting=new CustomizationIPSettings();
        //重新设置自定义规范 IP 地址
        //设置dns
        String[] dnss=new String[1];
        dnss[0]="8.8.8.8";
        ipSetting.setDnsServerList(dnss);
        //设置gateway
        String[] gateways=new String[1];
        gateways[0]="192.168.0.1";
        ipSetting.setGateway(gateways);
        //设置子网掩码
        String subnetMask="255.255.255.0";
        ipSetting.setSubnetMask(subnetMask);
        // 设置IP地址
        CustomizationFixedIp ip=new CustomizationFixedIp();
        ip.setIpAddress("192.168.0.111");
        ipSetting.setIp(ip);

        CustomizationAdapterMapping adapter=new CustomizationAdapterMapping();
        adapter.setAdapter(ipSetting);
        adapterMappings[0]=adapter;

        spec.setNicSettingMap(adapterMappings);
        CustomizationSpecItem customizationSpecItem=new CustomizationSpecItem();
        customizationSpecItem.setSpec(spec);
        CustomizationSpecInfo info=new CustomizationSpecInfo();
        info.setName("123456");
        info.setDescription("123456");
        customizationSpecItem.setInfo(info);













        return spec;
    }

    public static VirtualDeviceConfigSpec createDiskSpec(String dsName,
                                                         long diskSizeKB, String diskMode, VirtualMachine vm) {
        VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec();
        diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
        diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create);
        VirtualDisk vd = new VirtualDisk();
        vd.setCapacityInKB(diskSizeKB);
        diskSpec.setDevice(vd);
        vd.setKey(getkey(vm));
        vd.setUnitNumber(getUnitNumber(vm));
        vd.setControllerKey(getcontrollerkey(vm));
        VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo();
        String diskName = StringRandom.getStringRandom(12);
        String fileName = "[" + dsName + "] " + vm.getName() + "/" + diskName
                + ".vmdk";
        diskfileBacking.setFileName(fileName);
        diskfileBacking.setDiskMode(diskMode);
        diskfileBacking.setThinProvisioned(true);
        vd.setBacking(diskfileBacking);
        return diskSpec;
    }

    // 获取虚拟机磁盘管理的controlerkey
    public static int getcontrollerkey(VirtualMachine vm) {
        int controllerkey = 0;
        if (vm != null) {
            VirtualDevice[] devices = vm.getConfig().getHardware().getDevice();
            if (devices != null && devices.length > 0) {
                for (int i = 0; i < devices.length; i++) {
                    VirtualDevice device = devices[i];
                    if (device instanceof VirtualDisk) {
                        controllerkey = device.getControllerKey();
                    }
                }
            }
        }
        return controllerkey;
    }

    // 获取虚拟机已生成key
    public static int getkey(VirtualMachine vm) {
        int key = 0;
        if (vm != null) {
            VirtualDevice[] devices = vm.getConfig().getHardware().getDevice();
            if (devices != null && devices.length > 0) {
                for (int i = 0; i < devices.length; i++) {
                    VirtualDevice device = devices[i];
                    if (device instanceof VirtualDisk) {
                        key = device.getKey();
                    }
                }
            }
        }
        key = key + 1;
        return key;
    }

    // 获取虚拟机已生成UnitNumber
    public static int getUnitNumber(VirtualMachine vm) {
        int UnitNumber = 0;
        if (vm != null) {
            VirtualDevice[] devices = vm.getConfig().getHardware().getDevice();
            if (devices != null && devices.length > 0) {
                for (int i = 0; i < devices.length; i++) {
                    VirtualDevice device = devices[i];
                    if (device instanceof VirtualDisk) {
                        UnitNumber = device.getUnitNumber();
                    }
                }
            }
        }
        UnitNumber = UnitNumber + 1;
        return UnitNumber;
    }


}
Session 工具类
package com.vmware.util;

import com.vmware.vim25.mo.ServiceInstance;

import java.net.URL;

/**
 * Created by vixuan-008 on 2015/4/17.
 */
public class Session {
    private static String __serverName = "";
    private static String __userName = "";
    private static String __passWord = "";
    private static String __url = "";


    private static ServiceInstance serviceInstance = null;


    public synchronized static ServiceInstance getInstance(String serverName, String userName, String passWord) throws Exception{

        initServiceInstance(serverName, userName, passWord);
        return serviceInstance;

    }


    public static void initServiceInstance(String ip, String userName, String passWord) throws Exception {
        __serverName = ip;
        __userName = userName;
        __passWord = passWord;

        __url = "https://" + __serverName + "/sdk";
         if(serviceInstance==null){
             serviceInstance = new ServiceInstance(
                     new URL(__url), userName, passWord, true);
         }



    }

}



你可能感兴趣的:(Vmware,Vsphere,Vijava开发笔记)