public static void main(String[] args) throws Exception { ServiceInstance si = new ServiceInstance(new URL(VCENTERURL), USERNAME, PASSWORD, true); Folder rootFolder = si.getRootFolder(); ManagedEntity[] hosts = new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem"); if (hosts == null || hosts.length == 0) { return; } for (int i = 0; i < hosts.length; i++) { // get all vm in Vhost System.out.println("vHost loop ******************"); System.out.println("HostName: " + hosts[i].getName()); ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine"); for (int j = 0; j < mes.length; j++) { VirtualMachine vm = (VirtualMachine) mes[j]; VirtualMachineConfigInfo vminfo = vm.getConfig(); vm.getResourcePool(); System.out.println("vHost: " + vm.getParent().getName()); System.out.println("Guest: " + vm.getName()); System.out.println("GuestOS: " + vminfo.getGuestFullName()); System.out.println("GuestState: " + vm.getGuest().guestState); System.out.println("Guest Ip address: " + vm.getGuest().getIpAddress()); pingByIP(vm.getGuest().getIpAddress()); // ping VM } HostSystem newHost = (HostSystem) hosts[i]; String vHost_IP = newHost.getConfig().getNetwork().getVnic()[0].getSpec().getIp().getIpAddress(); System.out.println("vHost IP address: " + vHost_IP); // test for ping vHost pingByIP(vHost_IP); // ping vHost } } // end of main
/** * 克隆虚拟机<br> * 虚拟机的操作:克隆、克隆为模板、转换成模板(markAsTemplate)<br> * 模板的操作:克隆、转换成虚拟机(markAsVirtualMachine)、从该模板部署虚拟机<br> * 只有"从该模板部署虚拟机"时才需要rpId * * @param url * @param username * @param password * @param dcId * @param vmId * @param cloneName * @param isKeep * @param rpId * @return */ private static Map<String, Object> cloneVM( String url, String username, String password, String dcId, String vmId, String cloneName, boolean isKeep, String rpId) { HashMap<String, Object> resultMap = new HashMap<String, Object>(); try { VIMCache cache = VIMCache.getInstance(url, username, password); ManagedObjectReference vmMor = cache.getVirtualMachine(vmId); if (vmMor != null) { ExtendedAppUtil ecb = getECB(url, username, password); // VirtualMachine.config(VirtualMachineConfigInfo).template标识虚拟机是否为模板 // VirtualMachine.summary(VirtualMachineSummary).config(VirtualMachineConfigSummary).template标识虚拟机是否为模板 VirtualMachineConfigInfo config = (VirtualMachineConfigInfo) getDynamicProperty(ecb, vmMor, DYNAMICPROPERTY_CONFIG); // 当前虚拟机的模板状态 boolean currTemp = config.isTemplate(); // 期望的虚拟机的模板状态 boolean expectTemp = false; if (isKeep) { expectTemp = currTemp; } else { expectTemp = !currTemp; } cloneVM(resultMap, url, username, password, dcId, vmMor, cloneName, expectTemp, rpId); } else { if (vmMor == null) { recordResultMapError(resultMap, "虚拟机'" + vmId + "'不存在"); } } } catch (Exception e) { LOGGER.error("cloneVM error, ", e); recordResultMapException(resultMap, e); } return resultMap; }
/** * Replaces the NICs in the given VM. * * @param vmw connected VMware client entity * @param paramHandler entity which holds all properties of the instance * @param vmwInstance the virtual machine that gets reconfigured */ public static void configureNetworkAdapter( VMwareClient vmw, VirtualMachineConfigSpec vmConfigSpec, VMPropertyHandler paramHandler, ManagedObjectReference vmwInstance) throws Exception { logger.debug(""); VirtualMachineConfigInfo configInfo = (VirtualMachineConfigInfo) vmw.getServiceUtil().getDynamicProperty(vmwInstance, "config"); List<VirtualEthernetCard> vmNics = getNetworkAdapter(configInfo); int numberOfNICs = Integer.parseInt(paramHandler.getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS)); if (numberOfNICs != vmNics.size()) { throw new Exception( "the number of NICs in virtual machine does not match the service parameter. VM: " + configInfo.getName() + " NICs: " + vmNics.size() + " " + VMPropertyHandler.TS_NUMBER_OF_NICS + ": " + numberOfNICs); } for (int i = 1; i <= numberOfNICs; i++) { String newNetworkName = paramHandler.getNetworkAdapter(i); VirtualEthernetCard vmNic = vmNics.get(i - 1); String vmNetworkName = getNetworkName(vmw, vmwInstance, i); if (newNetworkName != null && newNetworkName.length() > 0 && !newNetworkName.equals(vmNetworkName)) { ManagedObjectReference newNetworkRef = getNetworkFromHost(vmw, vmwInstance, newNetworkName); replaceNetworkAdapter(vmConfigSpec, vmNic, newNetworkRef, newNetworkName); } else { connectNIC(vmConfigSpec, vmNic, vmNetworkName); } } }
public static List<VirtualEthernetCard> getNetworkAdapter(VirtualMachineConfigInfo configInfo) { List<VirtualEthernetCard> nics = new ArrayList<VirtualEthernetCard>(); List<VirtualDevice> devices = configInfo.getHardware().getDevice(); for (VirtualDevice vd : devices) { if (vd instanceof VirtualEthernetCard) { nics.add((VirtualEthernetCard) vd); } } return nics; }
/** * 修改虚拟机,ReconfigVM_Task<br> * 只提供修改CPU数,内存数,增加一个新的磁盘等功能,不支持其他如增减磁盘、增加光驱、增减网络等操作<br> * CPU数(2个)、内存数、磁盘数只有大于0时才会引发变化,其中磁盘为新增加一块磁盘。 * * @param url * @param username * @param password * @param dcId * @param numCpus * @param numCores * @param memoryMB * @param diskSizeMB * @return */ public static Map<String, Object> reconfigVM( String url, String username, String password, String dcId, String vmId, int numCpus, int numCores, long memoryMB, long diskSizeMB) { HashMap<String, Object> resultMap = new HashMap<String, Object>(); try { VIMCache cache = VIMCache.getInstance(url, username, password); ManagedObjectReference dcMor = cache.getDatacenter(dcId); ManagedObjectReference vmMor = cache.getVirtualMachine(vmId); if ((dcMor != null) && (vmMor != null)) { ExtendedAppUtil ecb = getECB(url, username, password); VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); if (numCpus > 0) { vmConfig.setNumCPUs(numCpus); } if (numCores > 0) { vmConfig.setNumCoresPerSocket(numCores); } if (memoryMB > 0) { vmConfig.setMemoryMB(memoryMB); } // 增加一个新磁盘 if (diskSizeMB > 0) { // 获取虚拟机原有配置信息 VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo) ecb.getServiceUtil3().getDynamicProperty(vmMor, DYNAMICPROPERTY_CONFIG); if (vmConfigInfo != null) { // 设置device的变化 VirtualDeviceConfigSpec diskConfig = new VirtualDeviceConfigSpec(); vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] {diskConfig}); diskConfig.setFileOperation(VirtualDeviceConfigSpecFileOperation.create); diskConfig.setOperation(VirtualDeviceConfigSpecOperation.add); // 磁盘 VirtualDisk disk = new VirtualDisk(); diskConfig.setDevice(disk); // SCSI控制器 VirtualLsiLogicController scsiCtrl = null; // 已有磁盘 VirtualDisk oldDisk = null; for (VirtualDevice vDevice : vmConfigInfo.getHardware().getDevice()) { if (vDevice instanceof VirtualLsiLogicController) { scsiCtrl = (VirtualLsiLogicController) vDevice; } if (vDevice instanceof VirtualDisk) { oldDisk = (VirtualDisk) vDevice; } if ((scsiCtrl != null) && (oldDisk != null)) { break; } } if ((scsiCtrl != null) && (oldDisk != null)) { disk.setControllerKey(scsiCtrl.getKey()); disk.setUnitNumber(vmConfigInfo.getHardware().getDevice().length + 1); disk.setCapacityInKB(diskSizeMB * 1024); disk.setKey(-1); VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); disk.setBacking(backingInfo); if (oldDisk.getBacking() instanceof VirtualDiskFlatVer2BackingInfo) { VirtualDiskFlatVer2BackingInfo oldBacking = (VirtualDiskFlatVer2BackingInfo) oldDisk.getBacking(); backingInfo.setDiskMode(oldBacking.getDiskMode()); backingInfo.setThinProvisioned(oldBacking.getThinProvisioned()); backingInfo.setEagerlyScrub(oldBacking.getEagerlyScrub()); backingInfo.setDatastore(oldBacking.getDatastore()); backingInfo.setFileName(""); } else { // VirtualDeviceBackingInfo类型不对 } } else { // SCSI和磁盘为空 } } else { // 配置信息为空 } } ManagedObjectReference taskMor = ecb.getServiceConnection3().getService().reconfigVM_Task(vmMor, vmConfig); execTaskAndRecordResultMap(ecb, taskMor, resultMap); } else { if (dcMor == null) { recordResultMapError(resultMap, "数据中心'" + dcId + "'不存在"); } if (vmMor == null) { recordResultMapError(resultMap, "虚拟机'" + vmId + "'不存在"); } } } catch (Exception e) { LOGGER.error("cloneVM error, ", e); recordResultMapException(resultMap, e); } return resultMap; }
/** * 获取虚拟机的摘要信息 * * @param url * @param username * @param password * @param vmId * @return */ public static Map<String, Object> getSummary( String url, String username, String password, String vmId) { HashMap<String, Object> resultMap = new HashMap<String, Object>(); try { VIMCache cache = VIMCache.getInstance(url, username, password); ManagedObjectReference mor = cache.getVirtualMachine(vmId); // System.out.println("vmId--:"+vmId+"===mor-是否存在---------------------------"+mor); if (mor != null) { ExtendedAppUtil ecb = getECB(url, username, password); // 配置 VirtualMachineConfigInfo config = (VirtualMachineConfigInfo) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_CONFIG); // 运行 VirtualMachineRuntimeInfo runtime = (VirtualMachineRuntimeInfo) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_RUNTIME); // 摘要 VirtualMachineSummary summary = (VirtualMachineSummary) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_SUMMARY); // 存储列表 ManagedObjectReference[] dsList = (ManagedObjectReference[]) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_DATASTORE); // 网络列表 ManagedObjectReference[] netList = (ManagedObjectReference[]) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_NETWORK); // List<Object> properties = getDynamicProperties(ecb, mor, // new String[] { DYNAMICPROPERTY_CONFIG, // DYNAMICPROPERTY_SUMMARY, // DYNAMICPROPERTY_DATASTORE, // DYNAMICPROPERTY_NETWORK }); // VirtualMachineConfigInfo config = (VirtualMachineConfigInfo) // properties // .get(0); // VirtualMachineSummary summary = (VirtualMachineSummary) // properties // .get(1); // ManagedObjectReference[] dsList = (ManagedObjectReference[]) // properties // .get(2); // ManagedObjectReference[] netList = (ManagedObjectReference[]) // properties // .get(3); String hoId = ""; if ((runtime != null) && (runtime.getHost() != null)) { hoId = runtime.getHost().get_value(); } resultMap.put(SYNC_VM_HOID, hoId); resultMap.put(SYNC_COMMON_VID, mor.get_value()); resultMap.put(SYNC_COMMON_NAME, config.getName()); int numCore = config.getHardware().getNumCoresPerSocket(); resultMap.put(SYNC_VM_NUMCORE, numCore); if ((config != null) && (summary != null)) { // 常规 // 客户机操作系统 resultMap.put(SUMMARY_COMMON_GUESTFULLNAME, config.getGuestFullName()); // 虚拟机版本,样本数据vmx-08 resultMap.put(SUMMARY_COMMON_VERSION, config.getVersion()); // CPU resultMap.put(SUMMARY_COMMON_CPU, summary.getConfig().getNumCpu()); // 内存,单位为MB resultMap.put( SUMMARY_COMMON_MEMORYSIZEMB, getByteSizeStrFromMB(summary.getConfig().getMemorySizeMB())); // 内存开销,current overhead reservation,单位为字节 resultMap.put( SUMMARY_COMMON_MEMORYOVERHEAD, getByteSizeStrFromBytes(summary.getRuntime().getMemoryOverhead())); // VMware Tools: // 运行状态toolsRunningStatus // VirtualMachineToolsRunningStatus:guestToolsExecutingScripts,guestToolsNotRunning,guestToolsRunning // 状态(toolsStatus,toolsVersionStatus[Since4.0],toolsVersionStatus2[Since5.0]) // VirtualMachineToolsVersionStatus:guestToolsBlacklisted[Since5.0],guestToolsCurrent,guestToolsNeedUpgrade,guestToolsNotInstalled, // guestToolsSupportedNew[Since5.0],guestToolsSupportedOld[Since5.0],guestToolsTooNew[Since5.0],guestToolsTooOld[Since5.0],guestToolsUnmanaged // 正在运行(当前版本) // http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.vm.Summary.GuestSummary.html // toolsStatus // toolsVersionStatus[Since4.0] // toolsVersionStatus2[Since5.0] // 暂时只获取toolsVersionStatus resultMap.put( SUMMARY_COMMON_VMWARETOOLS, cache.getEnum(summary.getGuest().getToolsRunningStatus()) + "(" + cache.getEnum(summary.getGuest().getToolsVersionStatus()) + ")"); // IP地址 resultMap.put( SUMMARY_COMMON_IPADDRESS, Util.normalizeString(summary.getGuest().getIpAddress())); // DNS名称 resultMap.put( SUMMARY_COMMON_HOSTNAME, Util.normalizeString(summary.getGuest().getHostName())); // XXX EVC模式,暂时无法获取 // String SUMMARY_COMMON_EVCMODEL = "evcmodel"; // 状况,poweredOff,poweredOn,suspended // powerstate在alarmDesc中有翻译 // resultMap.put(SUMMARY_COMMON_POWERSTATE, cache // .getAlarmDesc(summary.getRuntime().getPowerState() // .getValue())); String powerState = ""; if (runtime != null) { powerState = runtime.getPowerState().toString(); } resultMap.put(SYNC_VM_POWERSTATE, powerState); // 主机 resultMap.put(SUMMARY_COMMON_HOST, getEntityName(ecb, summary.getRuntime().getHost())); // XXX 活动任务,暂时无法获取 // String SUMMARY_COMMON_ACTIVETASK = "activetask"; // XXX vSphere HA保护,暂时无法获取 // String SUMMARY_COMMON_VSPHEREHA = "vsphereha"; // 资源 // 已消耗的主机CPU,Basic CPU performance // statistics,单位MHz,大概是这个值此值变化比较快 resultMap.put( SUMMARY_RESOURCE_OVERALLCPUUSAGE, summary.getQuickStats().getOverallCpuUsage() + MHZ); // 已消耗的主机内存:consumed host memory,单位为MB resultMap.put( SUMMARY_RESOURCE_HOSTMEMORYUSAGE, getByteSizeStrFromMB(summary.getQuickStats().getHostMemoryUsage())); // 活动客户机内存:active guest memory,单位为MB resultMap.put( SUMMARY_RESOURCE_GUESTMEMORYUSAGE, getByteSizeStrFromMB(summary.getQuickStats().getGuestMemoryUsage())); // 未共享的存储 resultMap.put( SUMMARY_RESOURCE_STORAGE_UNSHARED, getByteSizeStrFromBytes(summary.getStorage().getUnshared())); // 已使用的存储 resultMap.put( SUMMARY_RESOURCE_STORAGE_COMMITTED, getByteSizeStrFromBytes(summary.getStorage().getCommitted())); // 置备的存储 resultMap.put( SUMMARY_RESOURCE_STORAGE_ALL, getByteSizeStrFromBytes( summary.getStorage().getCommitted() + summary.getStorage().getUncommitted())); // 存储列表 DatastoreMgr.recordResultMapDsList(resultMap, ecb, dsList); // 网络列表 NetworkMgr.recordResultMapNetList(resultMap, ecb, netList); // 记录处理正确的标识 recordResultMapSuccess(resultMap); } else { recordResultMapError( resultMap, "获取'" + DYNAMICPROPERTY_CONFIG + "'或'" + DYNAMICPROPERTY_SUMMARY + "'信息为空"); } } else { recordResultMapError(resultMap, "虚拟机'" + vmId + "'不存在"); } } catch (Exception e) { LOGGER.error("getSummary error, ", e); recordResultMapException(resultMap, e); } return resultMap; }