From 780ac2a9c6eb09ced59107c13c840e4938db9859 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 31 Jan 2013 10:32:05 -0800 Subject: [PATCH 01/17] Introduce POM dependency on VSphere 5.1 SDK, not done yet, WIP. --- deps/install-non-oss.sh | 7 + plugins/hypervisors/vmware/pom.xml | 12 - pom.xml | 2 +- vmware-base/pom.xml | 12 - .../vmware/mo/VirtualMachineMO.java | 830 +++++++++--------- .../vmware/util/VmwareGuestOsMapper.java | 276 +++--- .../hypervisor/vmware/util/VmwareHelper.java | 271 +++--- 7 files changed, 705 insertions(+), 705 deletions(-) diff --git a/deps/install-non-oss.sh b/deps/install-non-oss.sh index 28eb03e1562..3476ea9922f 100755 --- a/deps/install-non-oss.sh +++ b/deps/install-non-oss.sh @@ -29,3 +29,10 @@ mvn install:install-file -Dfile=manageontap.jar -DgroupId=com.cloud.com.netapp mvn install:install-file -Dfile=vim25.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim25 -Dversion=4.1 -Dpackaging=jar mvn install:install-file -Dfile=apputils.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-apputils -Dversion=4.1 -Dpackaging=jar mvn install:install-file -Dfile=vim.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim -Dversion=4.1 -Dpackaging=jar + +# +# From https://my.vmware.com/group/vmware/get-download?downloadGroup=VSP510-WEBSDK-510 +# Version: 5.1, Release-date: 2012-09-10, Build: 774886 +mvn install:install-file -Dfile=vim25_51.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim25 -Dversion=5.1 -Dpackaging=jar + + diff --git a/plugins/hypervisors/vmware/pom.xml b/plugins/hypervisors/vmware/pom.xml index d990e89b388..ad27ab7300a 100644 --- a/plugins/hypervisors/vmware/pom.xml +++ b/plugins/hypervisors/vmware/pom.xml @@ -38,18 +38,6 @@ ${cs.vmware.api.version} compile - - com.cloud.com.vmware - vmware-vim - ${cs.vmware.api.version} - compile - - - com.cloud.com.vmware - vmware-apputils - ${cs.vmware.api.version} - compile - org.apache.axis axis diff --git a/pom.xml b/pom.xml index 35d6520ce6b..c5081f2e969 100644 --- a/pom.xml +++ b/pom.xml @@ -81,7 +81,7 @@ 2.4 1.2 1.0-20081010.060147 - 4.1 + 5.1 1.9.5 1.3.21.1 2.6 diff --git a/vmware-base/pom.xml b/vmware-base/pom.xml index bd536fb574a..09509981f2d 100644 --- a/vmware-base/pom.xml +++ b/vmware-base/pom.xml @@ -43,18 +43,6 @@ ${cs.vmware.api.version} compile - - com.cloud.com.vmware - vmware-vim - ${cs.vmware.api.version} - compile - - - com.cloud.com.vmware - vmware-apputils - ${cs.vmware.api.version} - compile - org.apache.axis axis diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index cd54127fcc2..0dc41a1f597 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -103,22 +103,22 @@ public class VirtualMachineMO extends BaseMO { public VirtualMachineMO(VmwareContext context, ManagedObjectReference morVm) { super(context, morVm); } - + public VirtualMachineMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public Pair getOwnerDatacenter() throws Exception { return DatacenterMO.getOwnerDatacenter(getContext(), getMor()); } - + public Pair getOwnerDatastore(String dsFullPath) throws Exception { String dsName = DatastoreFile.getDatastoreNameFromPath(dsFullPath); - + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); pSpec.setPathSet(new String[] { "name" }); - + TraversalSpec vmDatastoreTraversal = new TraversalSpec(); vmDatastoreTraversal.setType("VirtualMachine"); vmDatastoreTraversal.setPath("datastore"); @@ -132,11 +132,11 @@ public class VirtualMachineMO extends BaseMO { PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.setPropSet(new PropertySpec[] { pSpec }); pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - + ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + _context.getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec }); - + if(ocs != null) { for(ObjectContent oc : ocs) { DynamicProperty prop = oc.getPropSet(0); @@ -145,23 +145,23 @@ public class VirtualMachineMO extends BaseMO { } } } - + return null; } - + public HostMO getRunningHost() throws Exception { VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo(); return new HostMO(_context, runtimeInfo.getHost()); } - + public String getVmName() throws Exception { return (String)getContext().getServiceUtil().getDynamicProperty(_mor, "name"); } - + public GuestInfo getVmGuestInfo() throws Exception { return (GuestInfo)getContext().getServiceUtil().getDynamicProperty(_mor, "guest"); } - + public boolean isVMwareToolsRunning() throws Exception { GuestInfo guestInfo = getVmGuestInfo(); if(guestInfo != null) { @@ -170,13 +170,13 @@ public class VirtualMachineMO extends BaseMO { } return false; } - + public boolean powerOn() throws Exception { if(getPowerState() == VirtualMachinePowerState.poweredOn) return true; - + ManagedObjectReference morTask = _context.getService().powerOnVM_Task(_mor, null); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -184,64 +184,64 @@ public class VirtualMachineMO extends BaseMO { } else { s_logger.error("VMware powerOnVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public boolean powerOff() throws Exception { if(getPowerState() == VirtualMachinePowerState.poweredOff) return true; - + return powerOffNoCheck(); } - + public boolean safePowerOff(int shutdownWaitMs) throws Exception { - + if(getPowerState() == VirtualMachinePowerState.poweredOff) return true; - + if(isVMwareToolsRunning()) { try { String vmName = this.getName(); - + s_logger.info("Try gracefully shut down VM " + vmName); shutdown(); - + long startTick = System.currentTimeMillis(); while(getPowerState() != VirtualMachinePowerState.poweredOff && System.currentTimeMillis() - startTick < shutdownWaitMs) { - try { + try { Thread.sleep(1000); } catch(InterruptedException e) { } } - + if(getPowerState() != VirtualMachinePowerState.poweredOff) { s_logger.info("can not gracefully shutdown VM within " + (shutdownWaitMs/1000) + " seconds, we will perform force power off on VM " + vmName); return powerOffNoCheck(); } - + return true; } catch(Exception e) { - s_logger.warn("Failed to do guest-os graceful shutdown due to " + VmwareHelper.getExceptionMessage(e)); + s_logger.warn("Failed to do guest-os graceful shutdown due to " + VmwareHelper.getExceptionMessage(e)); } } - + return powerOffNoCheck(); } - + private boolean powerOffNoCheck() throws Exception { ManagedObjectReference morTask = _context.getService().powerOffVM_Task(_mor); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); - + // It seems that even if a power-off task is returned done, VM state may still not be marked, // wait up to 5 seconds to make sure to avoid race conditioning for immediate following on operations // that relies on a powered-off VM long startTick = System.currentTimeMillis(); while(getPowerState() != VirtualMachinePowerState.poweredOff && System.currentTimeMillis() - startTick < 5000) { - try { + try { Thread.sleep(1000); } catch(InterruptedException e) { } @@ -249,21 +249,21 @@ public class VirtualMachineMO extends BaseMO { return true; } else { if(getPowerState() == VirtualMachinePowerState.poweredOff) { - // to help deal with possible race-condition + // to help deal with possible race-condition s_logger.info("Current power-off task failed. However, VM has been switched to the state we are expecting for"); return true; } - + s_logger.error("VMware powerOffVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public VirtualMachinePowerState getPowerState() throws Exception { - + VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; - + // This is really ugly, there is a case that when windows guest VM is doing sysprep, the temporary // rebooting process may let us pick up a "poweredOff" state during VMsync process, this can trigger // a series actions. Unfortunately, from VMware API we can not distinguish power state into such details. @@ -282,13 +282,13 @@ public class VirtualMachineMO extends BaseMO { break; } } - + return powerState; } - + public boolean reset() throws Exception { ManagedObjectReference morTask = _context.getService().resetVM_Task(_mor); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -298,28 +298,28 @@ public class VirtualMachineMO extends BaseMO { } return false; } - + public void shutdown() throws Exception { _context.getService().shutdownGuest(_mor); } - + public void rebootGuest() throws Exception { _context.getService().rebootGuest(_mor); } - + public void markAsTemplate() throws Exception { _context.getService().markAsTemplate(_mor); } - + public boolean isTemplate() throws Exception { VirtualMachineConfigInfo configInfo = this.getConfigInfo(); return configInfo.isTemplate(); } - + public boolean migrate(ManagedObjectReference morRp, ManagedObjectReference morTargetHost) throws Exception { ManagedObjectReference morTask = _context.getService().migrateVM_Task(_mor, morRp, morTargetHost, VirtualMachineMovePriority.defaultPriority, null); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -327,17 +327,17 @@ public class VirtualMachineMO extends BaseMO { } else { s_logger.error("VMware migrateVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public boolean relocate(ManagedObjectReference morTargetHost) throws Exception { VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); relocateSpec.setHost(morTargetHost); - - ManagedObjectReference morTask = _context.getService().relocateVM_Task(_mor, + + ManagedObjectReference morTask = _context.getService().relocateVM_Task(_mor, relocateSpec, null); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -345,20 +345,20 @@ public class VirtualMachineMO extends BaseMO { } else { s_logger.error("VMware relocateVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public VirtualMachineSnapshotInfo getSnapshotInfo() throws Exception { return (VirtualMachineSnapshotInfo)_context.getServiceUtil().getDynamicProperty(_mor, "snapshot"); } - - public boolean createSnapshot(String snapshotName, String snapshotDescription, + + public boolean createSnapshot(String snapshotName, String snapshotDescription, boolean dumpMemory, boolean quiesce) throws Exception { - - ManagedObjectReference morTask = _context.getService().createSnapshot_Task(_mor, snapshotName, + + ManagedObjectReference morTask = _context.getService().createSnapshot_Task(_mor, snapshotName, snapshotDescription, dumpMemory, quiesce); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -371,28 +371,28 @@ public class VirtualMachineMO extends BaseMO { if(morSnapshot != null) { break; } - + try { Thread.sleep(1000); } catch(InterruptedException e) {} } - + if(morSnapshot == null) s_logger.error("We've been waiting for over 10 seconds for snapshot MOR to be appearing in vCenter after CreateSnapshot task is done, but it is still not there?!"); - + return true; } else { s_logger.error("VMware createSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public boolean removeSnapshot(String snapshotName, boolean removeChildren) throws Exception { ManagedObjectReference morSnapshot = getSnapshotMor(snapshotName); if(morSnapshot == null) { s_logger.warn("Unable to find snapshot: " + snapshotName); return false; } - + ManagedObjectReference morTask = _context.getService().removeSnapshot_Task(morSnapshot, removeChildren); String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { @@ -401,13 +401,13 @@ public class VirtualMachineMO extends BaseMO { } else { s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public boolean removeAllSnapshots() throws Exception { VirtualMachineSnapshotInfo snapshotInfo = getSnapshotInfo(); - + if(snapshotInfo != null && snapshotInfo.getRootSnapshotList() != null) { VirtualMachineSnapshotTree[] tree = snapshotInfo.getRootSnapshotList(); for(VirtualMachineSnapshotTree treeNode : tree) { @@ -421,88 +421,88 @@ public class VirtualMachineMO extends BaseMO { } } } - + return true; } - - public String getSnapshotDiskFileDatastorePath(VirtualMachineFileInfo vmFileInfo, + + public String getSnapshotDiskFileDatastorePath(VirtualMachineFileInfo vmFileInfo, List> datastoreMounts, String snapshotDiskFile) throws Exception { - + // if file path start with "/", need to search all datastore mounts on the host in order - // to form fully qualified datastore path + // to form fully qualified datastore path if(snapshotDiskFile.startsWith("/")) { for(Pair mount: datastoreMounts) { if(snapshotDiskFile.startsWith(mount.second())) { DatastoreMO dsMo = new DatastoreMO(_context, mount.first()); - + String dsFullPath = String.format("[%s] %s", dsMo.getName(), snapshotDiskFile.substring(mount.second().length() + 1)); s_logger.info("Convert snapshot disk file name to datastore path. " + snapshotDiskFile + "->" + dsFullPath); return dsFullPath; } } - + s_logger.info("Convert snapshot disk file name to datastore path. " + snapshotDiskFile + "->" + snapshotDiskFile); return snapshotDiskFile; } else { - - // snapshot directory string from VirtualMachineFileInfo ends with / + + // snapshot directory string from VirtualMachineFileInfo ends with / String dsFullPath = vmFileInfo.getSnapshotDirectory() + snapshotDiskFile; s_logger.info("Convert snapshot disk file name to datastore path. " + snapshotDiskFile + "->" + dsFullPath); return dsFullPath; } } - + public SnapshotDescriptor getSnapshotDescriptor() throws Exception { Pair dcPair = getOwnerDatacenter(); - + String dsPath = getSnapshotDescriptorDatastorePath(); assert(dsPath != null); String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), dsPath); byte[] content = getContext().getResourceContent(url); - + if(content == null || content.length < 1) { s_logger.warn("Snapshot descriptor file (vsd) does not exist anymore?"); } - + SnapshotDescriptor descriptor = new SnapshotDescriptor(); descriptor.parse(content); return descriptor; } - + public String getSnapshotDescriptorDatastorePath() throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); pSpec.setPathSet(new String[] { "name", "config.files" }); - + ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.FALSE); - + PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.setPropSet(new PropertySpec[] { pSpec }); pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - + ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + _context.getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec }); assert(ocs != null); String vmName = null; VirtualMachineFileInfo fileInfo = null; - + assert(ocs.length == 1); for(ObjectContent oc : ocs) { DynamicProperty[] props = oc.getPropSet(); if(props != null) { assert(props.length == 2); - + for(DynamicProperty prop : props) { if(prop.getName().equals("name")) { vmName = prop.getVal().toString(); } else { - fileInfo = (VirtualMachineFileInfo)prop.getVal(); + fileInfo = (VirtualMachineFileInfo)prop.getVal(); } } } @@ -514,29 +514,29 @@ public class VirtualMachineMO extends BaseMO { DatastoreFile vmxFile = new DatastoreFile(fileInfo.getVmPathName()); return vmxFile.getCompanionPath(vmName + ".vmsd"); } - + public ManagedObjectReference getSnapshotMor(String snapshotName) throws Exception { VirtualMachineSnapshotInfo info = getSnapshotInfo(); if(info != null) { - VirtualMachineSnapshotTree[] snapTree = info.getRootSnapshotList(); - return VmwareHelper.findSnapshotInTree(snapTree, snapshotName); + List snapTree = info.getRootSnapshotList(); + return VmwareHelper.findSnapshotInTree(snapTree, snapshotName); } return null; } - - public boolean createFullClone(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, + + public boolean createFullClone(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, ManagedObjectReference morDs) throws Exception { - + VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec(); cloneSpec.setLocation(relocSpec); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); - + relocSpec.setDatastore(morDs); relocSpec.setPool(morResourcePool); - ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec); - + ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec); + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -544,19 +544,19 @@ public class VirtualMachineMO extends BaseMO { } else { s_logger.error("VMware cloneVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - - public boolean createLinkedClone(String cloneName, ManagedObjectReference morBaseSnapshot, - ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, + + public boolean createLinkedClone(String cloneName, ManagedObjectReference morBaseSnapshot, + ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, ManagedObjectReference morDs) throws Exception { - + assert(morBaseSnapshot != null); assert(morFolder != null); assert(morResourcePool != null); assert(morDs != null); - + VirtualDisk[] independentDisks = getAllIndependentDiskDevice(); VirtualMachineRelocateSpec rSpec = new VirtualMachineRelocateSpec(); if(independentDisks.length > 0) { @@ -567,22 +567,22 @@ public class VirtualMachineMO extends BaseMO { diskLocator[i].setDiskId(independentDisks[i].getKey()); diskLocator[i].setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._moveAllDiskBackingsAndDisallowSharing); } - + rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._createNewChildDiskBacking); rSpec.setDisk(diskLocator); } else { rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._createNewChildDiskBacking); } rSpec.setPool(morResourcePool); - + VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); cloneSpec.setLocation(rSpec); cloneSpec.setSnapshot(morBaseSnapshot); - - ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec); - + + ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec); + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -590,30 +590,30 @@ public class VirtualMachineMO extends BaseMO { } else { s_logger.error("VMware cloneVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public VirtualMachineRuntimeInfo getRuntimeInfo() throws Exception { return (VirtualMachineRuntimeInfo)_context.getServiceUtil().getDynamicProperty( _mor, "runtime"); } - + public VirtualMachineConfigInfo getConfigInfo() throws Exception { return (VirtualMachineConfigInfo)_context.getServiceUtil().getDynamicProperty( _mor, "config"); } - + public VirtualMachineConfigSummary getConfigSummary() throws Exception { return (VirtualMachineConfigSummary)_context.getServiceUtil().getDynamicProperty( _mor, "summary.config"); } - + public VirtualMachineFileInfo getFileInfo() throws Exception { return (VirtualMachineFileInfo)_context.getServiceUtil().getDynamicProperty( _mor, "config.files"); } - + public ManagedObjectReference getParentMor() throws Exception { return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty( _mor, "parent"); @@ -623,7 +623,7 @@ public class VirtualMachineMO extends BaseMO { PropertySpec pSpec = new PropertySpec(); pSpec.setType("Network"); pSpec.setPathSet(new String[] {"name"}); - + TraversalSpec vm2NetworkTraversal = new TraversalSpec(); vm2NetworkTraversal.setType("VirtualMachine"); vm2NetworkTraversal.setPath("network"); @@ -637,11 +637,11 @@ public class VirtualMachineMO extends BaseMO { PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.setPropSet(new PropertySpec[] { pSpec }); pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - + ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + _context.getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec }); - + List networks = new ArrayList(); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { @@ -655,16 +655,16 @@ public class VirtualMachineMO extends BaseMO { List networks = new ArrayList(); int gcTagKey = getCustomFieldKey("Network", CustomFieldConstants.CLOUD_GC); - + if(gcTagKey == 0) { gcTagKey = getCustomFieldKey("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP); s_logger.debug("The custom key for dvPortGroup is : " + gcTagKey); } - + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Network"); pSpec.setPathSet(new String[] {"name", "vm", String.format("value[%d]", gcTagKey)}); - + TraversalSpec vm2NetworkTraversal = new TraversalSpec(); vm2NetworkTraversal.setType("VirtualMachine"); vm2NetworkTraversal.setPath("network"); @@ -678,11 +678,11 @@ public class VirtualMachineMO extends BaseMO { PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.setPropSet(new PropertySpec[] { pSpec }); pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - + ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + _context.getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec }); - + if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { ArrayOfManagedObjectReference morVms = null; @@ -700,29 +700,29 @@ public class VirtualMachineMO extends BaseMO { gcTagValue = val.getValue(); } } - - NetworkDetails details = new NetworkDetails(name, oc.getObj(), - (morVms != null ? morVms.getManagedObjectReference() : null), + + NetworkDetails details = new NetworkDetails(name, oc.getObj(), + (morVms != null ? morVms.getManagedObjectReference() : null), gcTagValue); - + networks.add(details); } s_logger.debug("Retrieved " + networks.size() + " networks with key : " + gcTagKey); } - + return networks; } - + /** - * Retrieve path info to access VM files via vSphere web interface - * @return [0] vm-name, [1] data-center-name, [2] datastore-name + * Retrieve path info to access VM files via vSphere web interface + * @return [0] vm-name, [1] data-center-name, [2] datastore-name * @throws Exception */ public String[] getHttpAccessPathInfo() throws Exception { String[] pathInfo = new String[3]; - + Pair dcInfo = getOwnerDatacenter(); - + VirtualMachineFileInfo fileInfo = getFileInfo(); String vmxFilePath = fileInfo.getVmPathName(); String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/"); @@ -732,14 +732,14 @@ public class VirtualMachineMO extends BaseMO { pathInfo[3] = vmxPathTokens[0].trim(); // vSphere datastore name return pathInfo; } - + public String getVmxHttpAccessUrl() throws Exception { Pair dcInfo = getOwnerDatacenter(); - + VirtualMachineFileInfo fileInfo = getFileInfo(); String vmxFilePath = fileInfo.getVmPathName(); String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/"); - + StringBuffer sb = new StringBuffer("https://" + _context.getServerAddress() + "/folder/"); sb.append(URLEncoder.encode(vmxPathTokens[2].trim())); sb.append("/"); @@ -748,16 +748,16 @@ public class VirtualMachineMO extends BaseMO { sb.append(URLEncoder.encode(dcInfo.second())); sb.append("&dsName="); sb.append(URLEncoder.encode(vmxPathTokens[1].trim())); - + return sb.toString(); } - + public boolean setVncConfigInfo(boolean enableVnc, String vncPassword, int vncPort, String keyboard) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); OptionValue[] vncOptions = VmwareHelper.composeVncOptions(null, enableVnc, vncPassword, vncPort, keyboard); vmConfigSpec.setExtraConfig(vncOptions); ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, vmConfigSpec); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -767,10 +767,10 @@ public class VirtualMachineMO extends BaseMO { } return false; } - + public boolean configureVm(VirtualMachineConfigSpec vmConfigSpec) throws Exception { ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, vmConfigSpec); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -780,12 +780,12 @@ public class VirtualMachineMO extends BaseMO { } return false; } - - public boolean configureVm(Ternary[] devices) throws Exception { - + assert(devices != null); - + VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[devices.length]; int i = 0; @@ -799,7 +799,7 @@ public class VirtualMachineMO extends BaseMO { configSpec.setDeviceChange(deviceConfigSpecArray); ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, configSpec); - + String result = _context.getServiceUtil().waitForTask(morTask); if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); @@ -809,14 +809,14 @@ public class VirtualMachineMO extends BaseMO { } return false; } - + public Pair getVncPort(String hostNetworkName) throws Exception { HostMO hostMo = getRunningHost(); VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(hostNetworkName); VirtualMachineConfigInfo configInfo = getConfigInfo(); OptionValue[] values = configInfo.getExtraConfig(); - + if(values != null) { for(OptionValue option : values) { if(option.getKey().equals("RemoteDisplay.vnc.port")) { @@ -829,32 +829,32 @@ public class VirtualMachineMO extends BaseMO { } return new Pair(summary.getHostIp(), 0); } - + // vmdkDatastorePath: [datastore name] vmdkFilePath public void createDisk(String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, int controllerKey) throws Exception { createDisk(vmdkDatastorePath, VirtualDiskType.thin, VirtualDiskMode.persistent, null, sizeInMb, morDs, controllerKey); } - + // vmdkDatastorePath: [datastore name] vmdkFilePath public void createDisk(String vmdkDatastorePath, VirtualDiskType diskType, VirtualDiskMode diskMode, String rdmDeviceName, int sizeInMb, ManagedObjectReference morDs, int controllerKey) throws Exception { - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + vmdkDatastorePath - + ", sizeInMb: " + sizeInMb + ", diskType: " + diskType + ", diskMode: " + diskMode + ", rdmDeviceName: " + rdmDeviceName + + ", sizeInMb: " + sizeInMb + ", diskType: " + diskType + ", diskMode: " + diskMode + ", rdmDeviceName: " + rdmDeviceName + ", datastore: " + morDs.get_value() + ", controllerKey: " + controllerKey); - + assert(vmdkDatastorePath != null); assert(morDs != null); - + if(controllerKey < 0) { controllerKey = getIDEDeviceControllerKey(); } - + VirtualDisk newDisk = new VirtualDisk(); if(diskType == VirtualDiskType.thin || diskType == VirtualDiskType.preallocated || diskType == VirtualDiskType.eagerZeroedThick) { - + VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); backingInfo.setDiskMode(diskMode.persistent.toString()); if(diskType == VirtualDiskType.thin) { @@ -862,19 +862,19 @@ public class VirtualMachineMO extends BaseMO { } else { backingInfo.setThinProvisioned(false); } - + if(diskType == VirtualDiskType.eagerZeroedThick) { backingInfo.setEagerlyScrub(true); } else { backingInfo.setEagerlyScrub(false); } - + backingInfo.setDatastore(morDs); backingInfo.setFileName(vmdkDatastorePath); newDisk.setBacking(backingInfo); } else if(diskType == VirtualDiskType.rdm || diskType == VirtualDiskType.rdmp) { - VirtualDiskRawDiskMappingVer1BackingInfo backingInfo = - new VirtualDiskRawDiskMappingVer1BackingInfo(); + VirtualDiskRawDiskMappingVer1BackingInfo backingInfo = + new VirtualDiskRawDiskMappingVer1BackingInfo(); if(diskType == VirtualDiskType.rdm) { backingInfo.setCompatibilityMode("virtualMode"); } else { @@ -884,118 +884,118 @@ public class VirtualMachineMO extends BaseMO { if(diskType == VirtualDiskType.rdm) { backingInfo.setDiskMode(diskMode.persistent.toString()); } - + backingInfo.setDatastore(morDs); backingInfo.setFileName(vmdkDatastorePath); newDisk.setBacking(backingInfo); } - + int deviceNumber = getNextDeviceNumber(controllerKey); - + newDisk.setControllerKey(controllerKey); newDisk.setKey(-deviceNumber); newDisk.setUnitNumber(deviceNumber); newDisk.setCapacityInKB(sizeInMb*1024); - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - + deviceConfigSpec.setDevice(newDisk); deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); - + deviceConfigSpecArray[0] = deviceConfigSpec; reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createDisk() done(failed)"); throw new Exception("Unable to create disk " + vmdkDatastorePath + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + _context.waitForTaskProgressDone(morTask); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createDisk() done(successfully)"); } - + public void attachDisk(String[] vmdkDatastorePathChain, ManagedObjectReference morDs) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + new Gson().toJson(vmdkDatastorePathChain) + ", datastore: " + morDs.get_value()); - - VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, getScsiDeviceControllerKey(), + + VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, getScsiDeviceControllerKey(), vmdkDatastorePathChain, morDs, -1, 1); - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - + deviceConfigSpec.setDevice(newDisk); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); - + deviceConfigSpecArray[0] = deviceConfigSpec; reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk() done(failed)"); + s_logger.trace("vCenter API trace - attachDisk() done(failed)"); throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + _context.waitForTaskProgressDone(morTask); - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk() done(successfully)"); + s_logger.trace("vCenter API trace - attachDisk() done(successfully)"); } - + public void attachDisk(Pair[] vmdkDatastorePathChain, int controllerKey) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + new Gson().toJson(vmdkDatastorePathChain)); - - VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, controllerKey, + + VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, controllerKey, vmdkDatastorePathChain, -1, 1); - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - + deviceConfigSpec.setDevice(newDisk); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); - + deviceConfigSpecArray[0] = deviceConfigSpec; reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk() done(failed)"); + s_logger.trace("vCenter API trace - attachDisk() done(failed)"); throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + _context.waitForTaskProgressDone(morTask); - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk() done(successfully)"); + s_logger.trace("vCenter API trace - attachDisk() done(successfully)"); } - + // vmdkDatastorePath: [datastore name] vmdkFilePath public List> detachDisk(String vmdkDatastorePath, boolean deleteBackingFile) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + vmdkDatastorePath + ", deleteBacking: " + deleteBackingFile); - + // Note: if VM has been taken snapshot, original backing file will be renamed, therefore, when we try to find the matching // VirtualDisk, we only perform prefix matching Pair deviceInfo = getDiskDevice(vmdkDatastorePath, false); @@ -1004,29 +1004,29 @@ public class VirtualMachineMO extends BaseMO { s_logger.trace("vCenter API trace - detachDisk() done (failed)"); throw new Exception("No such disk device: " + vmdkDatastorePath); } - + List> chain = getDiskDatastorePathChain(deviceInfo.first(), true); - - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - + deviceConfigSpec.setDevice(deviceInfo.first()); if(deleteBackingFile) { deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.destroy); } deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.remove); - + deviceConfigSpecArray[0] = deviceConfigSpec; reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachDisk() done (failed)"); - + throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } _context.waitForTaskProgressDone(morTask); @@ -1038,65 +1038,65 @@ public class VirtualMachineMO extends BaseMO { } catch(Exception e) { s_logger.info("Unable to retrieve snapshot descriptor, will skip updating snapshot reference"); } - + if(snapshotDescriptor != null) { for(Pair pair: chain) { DatastoreFile dsFile = new DatastoreFile(pair.first()); snapshotDescriptor.removeDiskReferenceFromSnapshot(dsFile.getFileName()); } - + Pair dcPair = getOwnerDatacenter(); String dsPath = getSnapshotDescriptorDatastorePath(); assert(dsPath != null); String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), dsPath); getContext().uploadResourceContent(url, snapshotDescriptor.getVmsdContent()); } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachDisk() done (successfully)"); return chain; } - + public void detachAllDisks() throws Exception { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachAllDisk(). target MOR: " + _mor.get_value()); - + VirtualDisk[] disks = getAllDiskDevice(); if(disks.length > 0) { - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[disks.length]; - + for(int i = 0; i < disks.length; i++) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(disks[i]); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.remove); } reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachAllDisk() done(failed)"); throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + _context.waitForTaskProgressDone(morTask); } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachAllDisk() done(successfully)"); } - + // isoDatastorePath: [datastore name] isoFilePath public void attachIso(String isoDatastorePath, ManagedObjectReference morDs, boolean connect, boolean connectAtBoot) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " + s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " + isoDatastorePath + ", datastore: " + morDs.get_value() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot); - + assert(isoDatastorePath != null); assert(morDs != null); @@ -1106,54 +1106,54 @@ public class VirtualMachineMO extends BaseMO { newCdRom = true; cdRom = new VirtualCdrom(); cdRom.setControllerKey(getIDEDeviceControllerKey()); - + int deviceNumber = getNextIDEDeviceNumber(); - cdRom.setUnitNumber(deviceNumber); + cdRom.setUnitNumber(deviceNumber); cdRom.setKey(-deviceNumber); } - + VirtualDeviceConnectInfo cInfo = new VirtualDeviceConnectInfo(); cInfo.setConnected(connect); cInfo.setStartConnected(connectAtBoot); cdRom.setConnectable(cInfo); - + VirtualCdromIsoBackingInfo backingInfo = new VirtualCdromIsoBackingInfo(); backingInfo.setFileName(isoDatastorePath); backingInfo.setDatastore(morDs); cdRom.setBacking(backingInfo); - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - + deviceConfigSpec.setDevice(cdRom); if(newCdRom) { deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); } else { deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.edit); } - + deviceConfigSpecArray[0] = deviceConfigSpec; reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso() done(failed)"); throw new Exception("Failed to attach ISO due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + _context.waitForTaskProgressDone(morTask); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso() done(successfully)"); } - + public void detachIso(String isoDatastorePath) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " + s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " + isoDatastorePath); VirtualDevice device = getIsoDevice(); @@ -1162,48 +1162,48 @@ public class VirtualMachineMO extends BaseMO { s_logger.trace("vCenter API trace - detachIso() done(failed)"); throw new Exception("Unable to find a CDROM device"); } - + VirtualCdromRemotePassthroughBackingInfo backingInfo = new VirtualCdromRemotePassthroughBackingInfo(); backingInfo.setDeviceName(""); device.setBacking(backingInfo); - - VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); + + VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - + deviceConfigSpec.setDevice(device); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.edit); - + deviceConfigSpecArray[0] = deviceConfigSpec; reConfigSpec.setDeviceChange(deviceConfigSpecArray); - + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); String result = _context.getServiceUtil().waitForTask(morTask); - + if(!result.equals("sucess")) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso() done(failed)"); throw new Exception("Failed to detachIso due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } _context.waitForTaskProgressDone(morTask); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso() done(successfully)"); } - + public Pair getVmdkFileInfo(String vmdkDatastorePath) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getVmdkFileInfo(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - getVmdkFileInfo(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + vmdkDatastorePath); - + Pair dcPair = getOwnerDatacenter(); - + String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), vmdkDatastorePath); byte[] content = getContext().getResourceContent(url); VmdkFileDescriptor descriptor = new VmdkFileDescriptor(); descriptor.parse(content); - + Pair result = new Pair(descriptor, content); if(s_logger.isTraceEnabled()) { s_logger.trace("vCenter API trace - getVmdkFileInfo() done"); @@ -1211,32 +1211,32 @@ public class VirtualMachineMO extends BaseMO { } return result; } - + public void exportVm(String exportDir, String exportName, boolean packToOva, boolean leaveOvaFileOnly) throws Exception { ManagedObjectReference morOvf = _context.getServiceContent().getOvfManager(); - + VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo(); HostMO hostMo = new HostMO(_context, runtimeInfo.getHost()); String hostName = hostMo.getHostName(); String vmName = getVmName(); - + DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter()); - + if(runtimeInfo.getPowerState() != VirtualMachinePowerState.poweredOff) { String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName; s_logger.error(msg); throw new Exception(msg); } - + ManagedObjectReference morLease = _context.getService().exportVm(getMor()); if(morLease == null) { s_logger.error("exportVm() failed"); throw new Exception("exportVm() failed"); } - + HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(_context, morLease); HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error }); - + try { if(state == HttpNfcLeaseState.ready) { final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter(); @@ -1247,24 +1247,24 @@ public class VirtualMachineMO extends BaseMO { HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo(); final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024; long totalBytesDownloaded = 0; - + HttpNfcLeaseDeviceUrl[] deviceUrls = leaseInfo.getDeviceUrl(); if(deviceUrls != null) { - OvfFile[] ovfFiles = new OvfFile[deviceUrls.length]; - for (int i = 0; i < deviceUrls.length; i++) { - String deviceId = deviceUrls[i].getKey(); - String deviceUrlStr = deviceUrls[i].getUrl(); + OvfFile[] ovfFiles = new OvfFile[deviceUrls.length]; + for (int i = 0; i < deviceUrls.length; i++) { + String deviceId = deviceUrls[i].getKey(); + String deviceUrlStr = deviceUrls[i].getUrl(); String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1); String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk")); String diskUrlStr = deviceUrlStr.replace("*", hostName); diskUrlStr = HypervisorHostHelper.resolveHostNameInUrl(dcMo, diskUrlStr); String diskLocalPath = exportDir + File.separator + diskFileName; fileNames.add(diskLocalPath); - + if(s_logger.isInfoEnabled()) { s_logger.info("Download VMDK file for export. url: " + deviceUrlStr); } - long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded, + long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded, new ActionDelegate () { @Override public void action(Long param) { @@ -1275,33 +1275,33 @@ public class VirtualMachineMO extends BaseMO { } }); totalBytesDownloaded += lengthOfDiskFile; - + OvfFile ovfFile = new OvfFile(); - ovfFile.setPath(diskFileName); - ovfFile.setDeviceId(deviceId); - ovfFile.setSize(lengthOfDiskFile); - ovfFiles[i] = ovfFile; + ovfFile.setPath(diskFileName); + ovfFile.setDeviceId(deviceId); + ovfFile.setSize(lengthOfDiskFile); + ovfFiles[i] = ovfFile; } - + // write OVF descriptor file - OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams(); - ovfDescParams.setOvfFiles(ovfFiles); - OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams); + OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams(); + ovfDescParams.setOvfFiles(ovfFiles); + OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams); String ovfPath = exportDir + File.separator + exportName + ".ovf"; fileNames.add(ovfPath); - + FileWriter out = new FileWriter(ovfPath); - out.write(ovfCreateDescriptorResult.getOvfDescriptor()); + out.write(ovfCreateDescriptorResult.getOvfDescriptor()); out.close(); - + // tar files into OVA if(packToOva) { // Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature) s_logger.info("Sync file system before we package OVA..."); - + Script commandSync = new Script(true, "sync", 0, s_logger); commandSync.execute(); - + Script command = new Script(false, "tar", 0, s_logger); command.setWorkDir(exportDir); command.add("-cf", exportName + ".ova"); @@ -1309,10 +1309,10 @@ public class VirtualMachineMO extends BaseMO { for(String name: fileNames) { command.add((new File(name).getName())); } - + s_logger.info("Package OVA with commmand: " + command.toString()); command.execute(); - + // to be safe, physically test existence of the target OVA file if((new File(exportDir + File.separator + exportName + ".ova")).exists()) { success = true; @@ -1331,7 +1331,7 @@ public class VirtualMachineMO extends BaseMO { new File(name).delete(); } } - + if(!success) throw new Exception("Unable to finish the whole process to package as a OVA file"); } @@ -1341,7 +1341,7 @@ public class VirtualMachineMO extends BaseMO { leaseMo.completeLease(); } } - + // snapshot directory in format of: /vmfs/volumes// @Deprecated public void setSnapshotDirectory(String snapshotDir) throws Exception { @@ -1349,15 +1349,15 @@ public class VirtualMachineMO extends BaseMO { Pair dcInfo = getOwnerDatacenter(); String vmxUrl = _context.composeDatastoreBrowseUrl(dcInfo.second(), fileInfo.getVmPathName()); byte[] vmxContent = _context.getResourceContent(vmxUrl); - + BufferedReader in = null; BufferedWriter out = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); - + boolean replaced = false; try { in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmxContent))); - out = new BufferedWriter(new OutputStreamWriter(bos)); + out = new BufferedWriter(new OutputStreamWriter(bos)); String line; while((line = in.readLine()) != null) { if(line.startsWith("workingDir")) { @@ -1369,7 +1369,7 @@ public class VirtualMachineMO extends BaseMO { out.newLine(); } } - + if(!replaced) { out.newLine(); out.write(String.format("workingDir=\"%s\"", snapshotDir)); @@ -1389,30 +1389,30 @@ public class VirtualMachineMO extends BaseMO { // its disk backing info anyway. // redoRegistration(); } - + // destName does not contain extension name - public void backupCurrentSnapshot(String deviceName, ManagedObjectReference morDestDs, + public void backupCurrentSnapshot(String deviceName, ManagedObjectReference morDestDs, String destDsDirectory, String destName, boolean includeBase) throws Exception { - + SnapshotDescriptor descriptor = getSnapshotDescriptor(); SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain(); if(snapshotInfo.length == 0) { String msg = "No snapshot found in this VM"; throw new Exception(msg); } - + HostMO hostMo = getRunningHost(); DatacenterMO dcMo = getOwnerDatacenter().first(); List> mounts = hostMo.getDatastoreMountsOnHost(); VirtualMachineFileInfo vmFileInfo = getFileInfo(); - - List> backupInfo = new ArrayList>(); - + + List> backupInfo = new ArrayList>(); + for(int i = 0; i < snapshotInfo.length; i++) { if(!includeBase && i == snapshotInfo.length - 1) { break; } - + SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks(); if(disks != null) { String destBaseFileName; @@ -1420,10 +1420,10 @@ public class VirtualMachineMO extends BaseMO { String destParentFileName; for(SnapshotDescriptor.DiskInfo disk : disks) { if(deviceName == null || deviceName.equals(disk.getDeviceName())) { - String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, + String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, mounts, disk.getDiskFileName()); Pair srcDsInfo = getOwnerDatastore(srcVmdkFullDsPath); - + Pair vmdkInfo = getVmdkFileInfo(srcVmdkFullDsPath); String srcVmdkBaseFilePath = DatastoreFile.getCompanionDatastorePath( srcVmdkFullDsPath, vmdkInfo.first().getBaseFileName()); @@ -1436,19 +1436,19 @@ public class VirtualMachineMO extends BaseMO { destBaseFileName = destName + (snapshotInfo.length - i - 1) + "-flat.vmdk"; destParentFileName = null; } - + s_logger.info("Copy VMDK base file " + srcVmdkBaseFilePath + " to " + destDsDirectory + "/" + destBaseFileName); - srcDsInfo.first().copyDatastoreFile(srcVmdkBaseFilePath, dcMo.getMor(), + srcDsInfo.first().copyDatastoreFile(srcVmdkBaseFilePath, dcMo.getMor(), morDestDs, destDsDirectory + "/" + destBaseFileName, dcMo.getMor(), true); - + byte[] newVmdkContent = VmdkFileDescriptor.changeVmdkContentBaseInfo( vmdkInfo.second(), destBaseFileName, destParentFileName); - String vmdkUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), + String vmdkUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), destDsDirectory + "/" + destFileName); - + s_logger.info("Upload VMDK content file to " + destDsDirectory + "/" + destFileName); getContext().uploadResourceContent(vmdkUploadUrl, newVmdkContent); - + backupInfo.add(new Ternary( destFileName, destBaseFileName, destParentFileName) ); @@ -1456,21 +1456,21 @@ public class VirtualMachineMO extends BaseMO { } } } - + byte[] vdiskInfo = VmwareHelper.composeDiskInfo(backupInfo, snapshotInfo.length, includeBase); - String vdiskUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), + String vdiskUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), destDsDirectory + "/" + destName + ".vdisk"); getContext().uploadResourceContent(vdiskUploadUrl, vdiskInfo); } - + public String[] getCurrentSnapshotDiskChainDatastorePaths(String diskDevice) throws Exception { HostMO hostMo = getRunningHost(); List> mounts = hostMo.getDatastoreMountsOnHost(); VirtualMachineFileInfo vmFileInfo = getFileInfo(); - + SnapshotDescriptor descriptor = getSnapshotDescriptor(); SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain(); - + List diskDsFullPaths = new ArrayList(); for(int i = 0; i < snapshotInfo.length; i++) { SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks(); @@ -1478,7 +1478,7 @@ public class VirtualMachineMO extends BaseMO { for(SnapshotDescriptor.DiskInfo disk: disks) { String deviceNameInDisk = disk.getDeviceName(); if(diskDevice == null || diskDevice.equalsIgnoreCase(deviceNameInDisk)) { - String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, + String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, mounts, disk.getDiskFileName()); diskDsFullPaths.add(vmdkFullDsPath); } @@ -1487,37 +1487,37 @@ public class VirtualMachineMO extends BaseMO { } return diskDsFullPaths.toArray(new String[0]); } - - public void cloneFromCurrentSnapshot(String clonedVmName, int cpuSpeedMHz, int memoryMb, String diskDevice, + + public void cloneFromCurrentSnapshot(String clonedVmName, int cpuSpeedMHz, int memoryMb, String diskDevice, ManagedObjectReference morDs) throws Exception { assert(morDs != null); String[] disks = getCurrentSnapshotDiskChainDatastorePaths(diskDevice); cloneFromDiskChain(clonedVmName, cpuSpeedMHz, memoryMb, disks, morDs); } - - public void cloneFromDiskChain(String clonedVmName, int cpuSpeedMHz, int memoryMb, + + public void cloneFromDiskChain(String clonedVmName, int cpuSpeedMHz, int memoryMb, String[] disks, ManagedObjectReference morDs) throws Exception { assert(disks != null); assert(disks.length >= 1); - + HostMO hostMo = getRunningHost(); VirtualMachineConfigInfo vmConfigInfo = getConfigInfo(); - + if(!hostMo.createBlankVm(clonedVmName, 1, cpuSpeedMHz, 0, false, memoryMb, 0, vmConfigInfo.getGuestId(), morDs, false)) throw new Exception("Unable to create a blank VM"); - + VirtualMachineMO clonedVmMo = hostMo.findVmOnHyperHost(clonedVmName); if(clonedVmMo == null) throw new Exception("Unable to find just-created blank VM"); - + boolean bSuccess = false; try { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); - + VirtualDevice device = VmwareHelper.prepareDiskDevice(clonedVmMo, -1, disks, morDs, -1, 1); - + deviceConfigSpecArray[0].setDevice(device); deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add); vmConfigSpec.setDeviceChange(deviceConfigSpecArray); @@ -1530,52 +1530,52 @@ public class VirtualMachineMO extends BaseMO { } } } - + public void plugDevice(VirtualDevice device) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[0].setDevice(device); deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add); - + vmConfigSpec.setDeviceChange(deviceConfigSpecArray); if(!configureVm(vmConfigSpec)) { throw new Exception("Failed to add devices"); } } - + public void tearDownDevice(VirtualDevice device) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[0].setDevice(device); deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.remove); - + vmConfigSpec.setDeviceChange(deviceConfigSpecArray); if(!configureVm(vmConfigSpec)) { throw new Exception("Failed to detach devices"); } } - + public void tearDownDevices(Class[] deviceClasses) throws Exception { VirtualDevice[] devices = getMatchedDevices(deviceClasses); if(devices.length > 0) { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[devices.length]; - + for(int i = 0; i < devices.length; i++) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(devices[i]); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.remove); } - + vmConfigSpec.setDeviceChange(deviceConfigSpecArray); if(!configureVm(vmConfigSpec)) { throw new Exception("Failed to detach devices"); } } } - + public void copyAllVmDiskFiles(DatastoreMO destDsMo, String destDsDir, boolean followDiskChain) throws Exception { VirtualDevice[] disks = getAllDiskDevice(); DatacenterMO dcMo = getOwnerDatacenter().first(); @@ -1584,25 +1584,25 @@ public class VirtualMachineMO extends BaseMO { List> vmdkFiles = this.getDiskDatastorePathChain((VirtualDisk)disk, followDiskChain); for(Pair fileItem : vmdkFiles) { DatastoreMO srcDsMo = new DatastoreMO(_context, fileItem.second()); - + DatastoreFile srcFile = new DatastoreFile(fileItem.first()); DatastoreFile destFile = new DatastoreFile(destDsMo.getName(), destDsDir, srcFile.getFileName()); - + Pair vmdkDescriptor = null; - + vmdkDescriptor = getVmdkFileInfo(fileItem.first()); - + s_logger.info("Copy VM disk file " + srcFile.getPath() + " to " + destFile.getPath()); - srcDsMo.copyDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(), + srcDsMo.copyDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(), destFile.getPath(), dcMo.getMor(), true); - + if(vmdkDescriptor != null) { String vmdkBaseFileName = vmdkDescriptor.first().getBaseFileName(); String baseFilePath = srcFile.getCompanionPath(vmdkBaseFileName); destFile = new DatastoreFile(destDsMo.getName(), destDsDir, vmdkBaseFileName); - + s_logger.info("Copy VM disk file " + baseFilePath + " to " + destFile.getPath()); - srcDsMo.copyDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(), + srcDsMo.copyDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(), destFile.getPath(), dcMo.getMor(), true); } } @@ -1620,40 +1620,40 @@ public class VirtualMachineMO extends BaseMO { List> vmdkFiles = this.getDiskDatastorePathChain((VirtualDisk)disk, followDiskChain); for(Pair fileItem : vmdkFiles) { DatastoreMO srcDsMo = new DatastoreMO(_context, fileItem.second()); - + DatastoreFile srcFile = new DatastoreFile(fileItem.first()); DatastoreFile destFile = new DatastoreFile(destDsMo.getName(), destDsDir, srcFile.getFileName()); - + Pair vmdkDescriptor = null; vmdkDescriptor = getVmdkFileInfo(fileItem.first()); - + s_logger.info("Move VM disk file " + srcFile.getPath() + " to " + destFile.getPath()); - srcDsMo.moveDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(), + srcDsMo.moveDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(), destFile.getPath(), dcMo.getMor(), true); - + if(vmdkDescriptor != null) { String vmdkBaseFileName = vmdkDescriptor.first().getBaseFileName(); String baseFilePath = srcFile.getCompanionPath(vmdkBaseFileName); destFile = new DatastoreFile(destDsMo.getName(), destDsDir, vmdkBaseFileName); - + s_logger.info("Move VM disk file " + baseFilePath + " to " + destFile.getPath()); - srcDsMo.moveDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(), + srcDsMo.moveDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(), destFile.getPath(), dcMo.getMor(), true); } } } } } - + public int getNextScsiDiskDeviceNumber() throws Exception { int scsiControllerKey = getScsiDeviceControllerKey(); return getNextDeviceNumber(scsiControllerKey); } - + public int getScsiDeviceControllerKey() throws Exception { VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualLsiLogicController) { @@ -1661,7 +1661,7 @@ public class VirtualMachineMO extends BaseMO { } } } - + assert(false); throw new Exception("SCSI Controller Not Found"); } @@ -1669,7 +1669,7 @@ public class VirtualMachineMO extends BaseMO { public int getScsiDeviceControllerKeyNoException() throws Exception { VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualLsiLogicController) { @@ -1677,10 +1677,10 @@ public class VirtualMachineMO extends BaseMO { } } } - + return -1; } - + public void ensureScsiDeviceController() throws Exception { int scsiControllerKey = getScsiDeviceControllerKeyNoException(); if(scsiControllerKey < 0) { @@ -1701,54 +1701,54 @@ public class VirtualMachineMO extends BaseMO { } } } - + // return pair of VirtualDisk and disk device bus name(ide0:0, etc) public Pair getDiskDevice(String vmdkDatastorePath, boolean matchExactly) throws Exception { VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil().getDynamicProperty(_mor, "config.hardware.device"); - + s_logger.info("Look for disk device info from volume : " + vmdkDatastorePath); DatastoreFile dsSrcFile = new DatastoreFile(vmdkDatastorePath); String srcBaseName = dsSrcFile.getFileBaseName(); - + if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualDisk) { s_logger.info("Test against disk device, controller key: " + device.getControllerKey() + ", unit number: " + device.getUnitNumber()); - + VirtualDeviceBackingInfo backingInfo = ((VirtualDisk)device).getBacking(); if(backingInfo instanceof VirtualDiskFlatVer2BackingInfo) { VirtualDiskFlatVer2BackingInfo diskBackingInfo = (VirtualDiskFlatVer2BackingInfo)backingInfo; do { s_logger.info("Test against disk backing : " + diskBackingInfo.getFileName()); - + DatastoreFile dsBackingFile = new DatastoreFile(diskBackingInfo.getFileName()); String backingBaseName = dsBackingFile.getFileBaseName(); if(matchExactly) { if(backingBaseName .equalsIgnoreCase(srcBaseName)) { String deviceNumbering = getDeviceBusName(devices, device); - + s_logger.info("Disk backing : " + diskBackingInfo.getFileName() + " matches ==> " + deviceNumbering); return new Pair((VirtualDisk)device, deviceNumbering); - } + } } else { if(backingBaseName.contains(srcBaseName)) { String deviceNumbering = getDeviceBusName(devices, device); s_logger.info("Disk backing : " + diskBackingInfo.getFileName() + " matches ==> " + deviceNumbering); return new Pair((VirtualDisk)device, deviceNumbering); - } + } } - + diskBackingInfo = diskBackingInfo.getParent(); } while(diskBackingInfo != null); - } + } } } } - + return null; } - + @Deprecated public List> getDiskDatastorePathChain(VirtualDisk disk, boolean followChain) throws Exception { VirtualDeviceBackingInfo backingInfo = disk.getBacking(); @@ -1763,18 +1763,18 @@ public class VirtualMachineMO extends BaseMO { pathList.add(new Pair(diskBackingInfo.getFileName(), diskBackingInfo.getDatastore())); return pathList; } - + Pair dcPair = getOwnerDatacenter(); VirtualMachineFileInfo vmFilesInfo = getFileInfo(); DatastoreFile snapshotDirFile = new DatastoreFile(vmFilesInfo.getSnapshotDirectory()); DatastoreFile vmxDirFile = new DatastoreFile(vmFilesInfo.getVmPathName()); - + do { if(diskBackingInfo.getParent() != null) { pathList.add(new Pair(diskBackingInfo.getFileName(), diskBackingInfo.getDatastore())); diskBackingInfo = diskBackingInfo.getParent(); } else { - // try getting parent info from VMDK file itself + // try getting parent info from VMDK file itself byte[] content = null; try { String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), diskBackingInfo.getFileName()); @@ -1782,7 +1782,7 @@ public class VirtualMachineMO extends BaseMO { if(content == null || content.length == 0) { break; } - + pathList.add(new Pair(diskBackingInfo.getFileName(), diskBackingInfo.getDatastore())); } catch(Exception e) { // if snapshot directory has been changed to place other than default. VMware has a bug @@ -1790,23 +1790,23 @@ public class VirtualMachineMO extends BaseMO { // in snapshot directory one more time DatastoreFile currentFile = new DatastoreFile(diskBackingInfo.getFileName()); String vmdkFullDsPath = snapshotDirFile.getCompanionPath(currentFile.getFileName()); - + String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), vmdkFullDsPath); content = getContext().getResourceContent(url); if(content == null || content.length == 0) { break; } - + pathList.add(new Pair(vmdkFullDsPath, diskBackingInfo.getDatastore())); } - + VmdkFileDescriptor descriptor = new VmdkFileDescriptor(); descriptor.parse(content); if(descriptor.getParentFileName() != null && !descriptor.getParentFileName().isEmpty()) { // create a fake one VirtualDiskFlatVer2BackingInfo parentDiskBackingInfo = new VirtualDiskFlatVer2BackingInfo(); parentDiskBackingInfo.setDatastore(diskBackingInfo.getDatastore()); - + String parentFileName = descriptor.getParentFileName(); if(parentFileName.startsWith("/")) { int fileNameStartPos = parentFileName.lastIndexOf("/"); @@ -1815,16 +1815,16 @@ public class VirtualMachineMO extends BaseMO { } else { parentDiskBackingInfo.setFileName(snapshotDirFile.getCompanionPath(parentFileName)); } - diskBackingInfo = parentDiskBackingInfo; + diskBackingInfo = parentDiskBackingInfo; } else { break; } } } while(diskBackingInfo != null); - + return pathList; } - + private String getDeviceBusName(VirtualDevice[] allDevices, VirtualDevice theDevice) throws Exception { for(VirtualDevice device : allDevices) { if(device.getKey() == theDevice.getControllerKey().intValue()) { @@ -1839,7 +1839,7 @@ public class VirtualMachineMO extends BaseMO { } throw new Exception("Unable to find device controller"); } - + public VirtualDisk[] getAllDiskDevice() throws Exception { List deviceList = new ArrayList(); VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil().getDynamicProperty(_mor, "config.hardware.device"); @@ -1850,7 +1850,7 @@ public class VirtualMachineMO extends BaseMO { } } } - + return deviceList.toArray(new VirtualDisk[0]); } @@ -1871,20 +1871,20 @@ public class VirtualMachineMO extends BaseMO { } else if(disk.getBacking() instanceof VirtualDiskSparseVer2BackingInfo) { diskMode = ((VirtualDiskSparseVer2BackingInfo)disk.getBacking()).getDiskMode(); } - + if(diskMode.indexOf("independent") != -1) { independentDisks.add(disk); } } } - + return independentDisks.toArray(new VirtualDisk[0]); } - + public int tryGetIDEDeviceControllerKey() throws Exception { VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualIDEController) { @@ -1892,14 +1892,14 @@ public class VirtualMachineMO extends BaseMO { } } } - + return -1; } - + public int getIDEDeviceControllerKey() throws Exception { VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualIDEController) { @@ -1907,16 +1907,16 @@ public class VirtualMachineMO extends BaseMO { } } } - + assert(false); throw new Exception("IDE Controller Not Found"); } - + public int getNextIDEDeviceNumber() throws Exception { int controllerKey = getIDEDeviceControllerKey(); return getNextDeviceNumber(controllerKey); } - + public VirtualDevice getIsoDevice() throws Exception { VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); @@ -1929,11 +1929,11 @@ public class VirtualMachineMO extends BaseMO { } return null; } - + public int getPCIDeviceControllerKey() throws Exception { VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualPCIController) { @@ -1941,20 +1941,20 @@ public class VirtualMachineMO extends BaseMO { } } } - + assert(false); throw new Exception("PCI Controller Not Found"); } - + public int getNextPCIDeviceNumber() throws Exception { int controllerKey = getPCIDeviceControllerKey(); return getNextDeviceNumber(controllerKey); } - + public int getNextDeviceNumber(int controllerKey) throws Exception { VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + int deviceNumber = -1; if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { @@ -1967,11 +1967,11 @@ public class VirtualMachineMO extends BaseMO { } return ++deviceNumber; } - + public VirtualDevice[] getNicDevices() throws Exception { VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + List nics = new ArrayList(); if(devices != null) { for(VirtualDevice device : devices) { @@ -1980,14 +1980,14 @@ public class VirtualMachineMO extends BaseMO { } } } - + return nics.toArray(new VirtualDevice[0]); } - + public Pair getNicDeviceIndex(String networkNamePrefix) throws Exception { VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + List nics = new ArrayList(); if(devices != null) { for(VirtualDevice device : devices) { @@ -1996,7 +1996,7 @@ public class VirtualMachineMO extends BaseMO { } } } - + Collections.sort(nics, new Comparator() { @Override public int compare(VirtualDevice arg0, VirtualDevice arg1) { @@ -2009,7 +2009,7 @@ public class VirtualMachineMO extends BaseMO { return 0; } }); - + int index = 0; String attachedNetworkSummary; String dvPortGroupName; @@ -2042,12 +2042,12 @@ public class VirtualMachineMO extends BaseMO { public VirtualDevice[] getMatchedDevices(Class[] deviceClasses) throws Exception { assert(deviceClasses != null); - + List returnList = new ArrayList(); - + VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). getDynamicProperty(_mor, "config.hardware.device"); - + if(devices != null) { for(VirtualDevice device : devices) { for(Class clz : deviceClasses) { @@ -2058,40 +2058,40 @@ public class VirtualMachineMO extends BaseMO { } } } - + return returnList.toArray(new VirtualDevice[0]); } - + public void mountToolsInstaller() throws Exception { _context.getService().mountToolsInstaller(_mor); } - + public void unmountToolsInstaller() throws Exception { _context.getService().unmountToolsInstaller(_mor); } - + public void redoRegistration(ManagedObjectReference morHost) throws Exception { String vmName = getVmName(); VirtualMachineFileInfo vmFileInfo = getFileInfo(); boolean isTemplate = isTemplate(); - + HostMO hostMo; if(morHost != null) hostMo = new HostMO(getContext(), morHost); else hostMo = getRunningHost(); - + ManagedObjectReference morFolder = getParentMor(); ManagedObjectReference morPool = hostMo.getHyperHostOwnerResourcePool(); - + _context.getService().unregisterVM(_mor); - + ManagedObjectReference morTask = _context.getService().registerVM_Task( - morFolder, + morFolder, vmFileInfo.getVmPathName(), - vmName, false, + vmName, false, morPool, hostMo.getMor()); - + String result = _context.getServiceUtil().waitForTask(morTask); if (!result.equalsIgnoreCase("Sucess")) { throw new Exception("Unable to register template due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -2099,7 +2099,7 @@ public class VirtualMachineMO extends BaseMO { _context.waitForTaskProgressDone(morTask); if(isTemplate) { VirtualMachineMO vmNewRegistration = hostMo.findVmOnHyperHost(vmName); - assert(vmNewRegistration != null); + assert(vmNewRegistration != null); vmNewRegistration.markAsTemplate(); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java index 7d26983fcbf..14331481513 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java @@ -24,146 +24,150 @@ import com.vmware.vim25.VirtualMachineGuestOsIdentifier; public class VmwareGuestOsMapper { private static Map s_mapper = new HashMap(); static { - s_mapper.put("DOS", VirtualMachineGuestOsIdentifier.dosGuest); - s_mapper.put("OS/2", VirtualMachineGuestOsIdentifier.os2Guest); + s_mapper.put("DOS", VirtualMachineGuestOsIdentifier.DOS_GUEST); + s_mapper.put("OS/2", VirtualMachineGuestOsIdentifier.OS_2_GUEST); - s_mapper.put("Windows 3.1", VirtualMachineGuestOsIdentifier.win31Guest); - s_mapper.put("Windows 95", VirtualMachineGuestOsIdentifier.win95Guest); - s_mapper.put("Windows 98", VirtualMachineGuestOsIdentifier.win98Guest); - s_mapper.put("Windows NT 4", VirtualMachineGuestOsIdentifier.winNTGuest); - s_mapper.put("Windows XP (32-bit)", VirtualMachineGuestOsIdentifier.winXPProGuest); - s_mapper.put("Windows XP (64-bit)", VirtualMachineGuestOsIdentifier.winXPPro64Guest); - s_mapper.put("Windows XP SP2 (32-bit)", VirtualMachineGuestOsIdentifier.winXPProGuest); - s_mapper.put("Windows XP SP3 (32-bit)", VirtualMachineGuestOsIdentifier.winXPProGuest); - s_mapper.put("Windows Vista (32-bit)", VirtualMachineGuestOsIdentifier.winVistaGuest); - s_mapper.put("Windows Vista (64-bit)", VirtualMachineGuestOsIdentifier.winVista64Guest); - s_mapper.put("Windows 7 (32-bit)", VirtualMachineGuestOsIdentifier.windows7Guest); - s_mapper.put("Windows 7 (64-bit)", VirtualMachineGuestOsIdentifier.windows7_64Guest); + s_mapper.put("Windows 3.1", VirtualMachineGuestOsIdentifier.WIN_31_GUEST); + s_mapper.put("Windows 95", VirtualMachineGuestOsIdentifier.WIN_95_GUEST); + s_mapper.put("Windows 98", VirtualMachineGuestOsIdentifier.WIN_98_GUEST); + s_mapper.put("Windows NT 4", VirtualMachineGuestOsIdentifier.WIN_NT_GUEST); + s_mapper.put("Windows XP (32-bit)", VirtualMachineGuestOsIdentifier.WIN_XP_PRO_GUEST); + s_mapper.put("Windows XP (64-bit)", VirtualMachineGuestOsIdentifier.WIN_XP_PRO_64_GUEST); + s_mapper.put("Windows XP SP2 (32-bit)", VirtualMachineGuestOsIdentifier.WIN_XP_PRO_GUEST); + s_mapper.put("Windows XP SP3 (32-bit)", VirtualMachineGuestOsIdentifier.WIN_XP_PRO_GUEST); + s_mapper.put("Windows Vista (32-bit)", VirtualMachineGuestOsIdentifier.WIN_VISTA_GUEST); + s_mapper.put("Windows Vista (64-bit)", VirtualMachineGuestOsIdentifier.WIN_VISTA_64_GUEST); + s_mapper.put("Windows 7 (32-bit)", VirtualMachineGuestOsIdentifier.WINDOWS_7_GUEST); + s_mapper.put("Windows 7 (64-bit)", VirtualMachineGuestOsIdentifier.WINDOWS_7_64_GUEST); - s_mapper.put("Windows 2000 Professional", VirtualMachineGuestOsIdentifier.win2000ProGuest); - s_mapper.put("Windows 2000 Server", VirtualMachineGuestOsIdentifier.win2000ServGuest); - s_mapper.put("Windows 2000 Server SP4 (32-bit)", VirtualMachineGuestOsIdentifier.win2000ServGuest); - s_mapper.put("Windows 2000 Advanced Server", VirtualMachineGuestOsIdentifier.win2000AdvServGuest); - - s_mapper.put("Windows Server 2003 Enterprise Edition(32-bit)", VirtualMachineGuestOsIdentifier.winNetEnterpriseGuest); - s_mapper.put("Windows Server 2003 Enterprise Edition(64-bit)", VirtualMachineGuestOsIdentifier.winNetEnterprise64Guest); - s_mapper.put("Windows Server 2008 R2 (64-bit)", VirtualMachineGuestOsIdentifier.winLonghorn64Guest); - s_mapper.put("Windows Server 2003 DataCenter Edition(32-bit)", VirtualMachineGuestOsIdentifier.winNetDatacenterGuest); - s_mapper.put("Windows Server 2003 DataCenter Edition(64-bit)", VirtualMachineGuestOsIdentifier.winNetDatacenter64Guest); - s_mapper.put("Windows Server 2003 Standard Edition(32-bit)", VirtualMachineGuestOsIdentifier.winNetStandardGuest); - s_mapper.put("Windows Server 2003 Standard Edition(64-bit)", VirtualMachineGuestOsIdentifier.winNetStandard64Guest); - s_mapper.put("Windows Server 2003 Web Edition", VirtualMachineGuestOsIdentifier.winNetWebGuest); - s_mapper.put("Microsoft Small Bussiness Server 2003", VirtualMachineGuestOsIdentifier.winNetBusinessGuest); - - s_mapper.put("Windows Server 2008 (32-bit)", VirtualMachineGuestOsIdentifier.winLonghornGuest); - s_mapper.put("Windows Server 2008 (64-bit)", VirtualMachineGuestOsIdentifier.winLonghorn64Guest); - - s_mapper.put("Open Enterprise Server", VirtualMachineGuestOsIdentifier.oesGuest); - - s_mapper.put("Asianux 3(32-bit)", VirtualMachineGuestOsIdentifier.asianux3Guest); - s_mapper.put("Asianux 3(64-bit)", VirtualMachineGuestOsIdentifier.asianux3_64Guest); - - s_mapper.put("Debian GNU/Linux 5(64-bit)", VirtualMachineGuestOsIdentifier.debian5_64Guest); - s_mapper.put("Debian GNU/Linux 5.0 (32-bit)", VirtualMachineGuestOsIdentifier.debian5Guest); - s_mapper.put("Debian GNU/Linux 4(32-bit)", VirtualMachineGuestOsIdentifier.debian4Guest); - s_mapper.put("Debian GNU/Linux 4(64-bit)", VirtualMachineGuestOsIdentifier.debian4_64Guest); - - s_mapper.put("Novell Netware 6.x", VirtualMachineGuestOsIdentifier.netware6Guest); - s_mapper.put("Novell Netware 5.1", VirtualMachineGuestOsIdentifier.netware5Guest); - - s_mapper.put("Sun Solaris 10(32-bit)", VirtualMachineGuestOsIdentifier.solaris10Guest); - s_mapper.put("Sun Solaris 10(64-bit)", VirtualMachineGuestOsIdentifier.solaris10_64Guest); - s_mapper.put("Sun Solaris 9(Experimental)", VirtualMachineGuestOsIdentifier.solaris9Guest); - s_mapper.put("Sun Solaris 8(Experimental)", VirtualMachineGuestOsIdentifier.solaris8Guest); - - s_mapper.put("FreeBSD (32-bit)", VirtualMachineGuestOsIdentifier.freebsdGuest); - s_mapper.put("FreeBSD (64-bit)", VirtualMachineGuestOsIdentifier.freebsd64Guest); - - s_mapper.put("SCO OpenServer 5", VirtualMachineGuestOsIdentifier.otherGuest); - s_mapper.put("SCO UnixWare 7", VirtualMachineGuestOsIdentifier.unixWare7Guest); - - s_mapper.put("SUSE Linux Enterprise 8(32-bit)", VirtualMachineGuestOsIdentifier.suseGuest); - s_mapper.put("SUSE Linux Enterprise 8(64-bit)", VirtualMachineGuestOsIdentifier.suse64Guest); - s_mapper.put("SUSE Linux Enterprise 9(32-bit)", VirtualMachineGuestOsIdentifier.suseGuest); - s_mapper.put("SUSE Linux Enterprise 9(64-bit)", VirtualMachineGuestOsIdentifier.suse64Guest); - s_mapper.put("SUSE Linux Enterprise 10(32-bit)", VirtualMachineGuestOsIdentifier.suseGuest); - s_mapper.put("SUSE Linux Enterprise 10(64-bit)", VirtualMachineGuestOsIdentifier.suse64Guest); - s_mapper.put("SUSE Linux Enterprise 10(32-bit)", VirtualMachineGuestOsIdentifier.suseGuest); - s_mapper.put("Other SUSE Linux(32-bit)", VirtualMachineGuestOsIdentifier.suseGuest); - s_mapper.put("Other SUSE Linux(64-bit)", VirtualMachineGuestOsIdentifier.suse64Guest); - - s_mapper.put("CentOS 4.5 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 4.6 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 4.7 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 4.8 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.0 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.0 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 5.1 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.1 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 5.2 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.2 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 5.3 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.3 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 5.4 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.4 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 5.5 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.5 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 5.6 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 5.6 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("CentOS 6.0 (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("CentOS 6.0 (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - s_mapper.put("Other CentOS (32-bit)", VirtualMachineGuestOsIdentifier.centosGuest); - s_mapper.put("Other CentOS (64-bit)", VirtualMachineGuestOsIdentifier.centos64Guest); - - s_mapper.put("Red Hat Enterprise Linux 2", VirtualMachineGuestOsIdentifier.rhel2Guest); - s_mapper.put("Red Hat Enterprise Linux 3(32-bit)", VirtualMachineGuestOsIdentifier.rhel3Guest); - s_mapper.put("Red Hat Enterprise Linux 3(64-bit)", VirtualMachineGuestOsIdentifier.rhel3_64Guest); - s_mapper.put("Red Hat Enterprise Linux 4(32-bit)", VirtualMachineGuestOsIdentifier.rhel4Guest); - s_mapper.put("Red Hat Enterprise Linux 4(64-bit)", VirtualMachineGuestOsIdentifier.rhel4_64Guest); - s_mapper.put("Red Hat Enterprise Linux 5(32-bit)", VirtualMachineGuestOsIdentifier.rhel5Guest); - s_mapper.put("Red Hat Enterprise Linux 5(64-bit)", VirtualMachineGuestOsIdentifier.rhel5_64Guest); - s_mapper.put("Red Hat Enterprise Linux 6(32-bit)", VirtualMachineGuestOsIdentifier.rhel6Guest); - s_mapper.put("Red Hat Enterprise Linux 6(64-bit)", VirtualMachineGuestOsIdentifier.rhel6_64Guest); - - s_mapper.put("Red Hat Enterprise Linux 4.5 (32-bit)", VirtualMachineGuestOsIdentifier.rhel4Guest); - s_mapper.put("Red Hat Enterprise Linux 4.6 (32-bit)", VirtualMachineGuestOsIdentifier.rhel4Guest); - s_mapper.put("Red Hat Enterprise Linux 4.7 (32-bit)", VirtualMachineGuestOsIdentifier.rhel4Guest); - s_mapper.put("Red Hat Enterprise Linux 4.8 (32-bit)", VirtualMachineGuestOsIdentifier.rhel4Guest); - s_mapper.put("Red Hat Enterprise Linux 5.0(32-bit)", VirtualMachineGuestOsIdentifier.rhel5Guest); - s_mapper.put("Red Hat Enterprise Linux 5.0(64-bit)", VirtualMachineGuestOsIdentifier.rhel5_64Guest); - s_mapper.put("Red Hat Enterprise Linux 5.1(32-bit)", VirtualMachineGuestOsIdentifier.rhel5Guest); - s_mapper.put("Red Hat Enterprise Linux 5.1(64-bit)", VirtualMachineGuestOsIdentifier.rhel5_64Guest); - s_mapper.put("Red Hat Enterprise Linux 5.2(32-bit)", VirtualMachineGuestOsIdentifier.rhel5Guest); - s_mapper.put("Red Hat Enterprise Linux 5.2(64-bit)", VirtualMachineGuestOsIdentifier.rhel5_64Guest); - s_mapper.put("Red Hat Enterprise Linux 5.3(32-bit)", VirtualMachineGuestOsIdentifier.rhel5Guest); - s_mapper.put("Red Hat Enterprise Linux 5.3(64-bit)", VirtualMachineGuestOsIdentifier.rhel5_64Guest); - s_mapper.put("Red Hat Enterprise Linux 5.4(32-bit)", VirtualMachineGuestOsIdentifier.rhel5Guest); - s_mapper.put("Red Hat Enterprise Linux 5.4(64-bit)", VirtualMachineGuestOsIdentifier.rhel5_64Guest); - - s_mapper.put("Ubuntu 8.04 (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Ubuntu 8.04 (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); - s_mapper.put("Ubuntu 8.10 (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Ubuntu 8.10 (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); - s_mapper.put("Ubuntu 9.04 (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Ubuntu 9.04 (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); - s_mapper.put("Ubuntu 9.10 (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Ubuntu 9.10 (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); - s_mapper.put("Ubuntu 10.04 (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Ubuntu 10.04 (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); - s_mapper.put("Ubuntu 10.10 (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Ubuntu 10.10 (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); - s_mapper.put("Other Ubuntu (32-bit)", VirtualMachineGuestOsIdentifier.ubuntuGuest); - s_mapper.put("Other Ubuntu (64-bit)", VirtualMachineGuestOsIdentifier.ubuntu64Guest); + s_mapper.put("Windows 2000 Professional", VirtualMachineGuestOsIdentifier.WIN_2000_PRO_GUEST); + s_mapper.put("Windows 2000 Server", VirtualMachineGuestOsIdentifier.WIN_2000_SERV_GUEST); + s_mapper.put("Windows 2000 Server SP4 (32-bit)", VirtualMachineGuestOsIdentifier.WIN_2000_SERV_GUEST); + s_mapper.put("Windows 2000 Advanced Server", VirtualMachineGuestOsIdentifier.WIN_2000_ADV_SERV_GUEST); - s_mapper.put("Other 2.6x Linux (32-bit)", VirtualMachineGuestOsIdentifier.other26xLinuxGuest); - s_mapper.put("Other 2.6x Linux (64-bit)", VirtualMachineGuestOsIdentifier.other26xLinux64Guest); - s_mapper.put("Other Linux (32-bit)", VirtualMachineGuestOsIdentifier.otherLinuxGuest); - s_mapper.put("Other Linux (64-bit)", VirtualMachineGuestOsIdentifier.otherLinux64Guest); - - s_mapper.put("Other (32-bit)", VirtualMachineGuestOsIdentifier.otherGuest); - s_mapper.put("Other (64-bit)", VirtualMachineGuestOsIdentifier.otherGuest64); + s_mapper.put("Windows Server 2003 Enterprise Edition(32-bit)", VirtualMachineGuestOsIdentifier.WIN_NET_ENTERPRISE_GUEST); + s_mapper.put("Windows Server 2003 Enterprise Edition(64-bit)", VirtualMachineGuestOsIdentifier.WIN_NET_ENTERPRISE_64_GUEST); + s_mapper.put("Windows Server 2008 R2 (64-bit)", VirtualMachineGuestOsIdentifier.WIN_LONGHORN_64_GUEST); + s_mapper.put("Windows Server 2003 DataCenter Edition(32-bit)", VirtualMachineGuestOsIdentifier.WIN_NET_DATACENTER_GUEST); + s_mapper.put("Windows Server 2003 DataCenter Edition(64-bit)", VirtualMachineGuestOsIdentifier.WIN_NET_DATACENTER_64_GUEST); + s_mapper.put("Windows Server 2003 Standard Edition(32-bit)", VirtualMachineGuestOsIdentifier.WIN_NET_STANDARD_GUEST); + s_mapper.put("Windows Server 2003 Standard Edition(64-bit)", VirtualMachineGuestOsIdentifier.WIN_NET_STANDARD_64_GUEST); + s_mapper.put("Windows Server 2003 Web Edition", VirtualMachineGuestOsIdentifier.WIN_NET_WEB_GUEST); + s_mapper.put("Microsoft Small Bussiness Server 2003", VirtualMachineGuestOsIdentifier.WIN_NET_BUSINESS_GUEST); + + s_mapper.put("Windows Server 2008 (32-bit)", VirtualMachineGuestOsIdentifier.WIN_LONGHORN_GUEST); + s_mapper.put("Windows Server 2008 (64-bit)", VirtualMachineGuestOsIdentifier.WIN_LONGHORN_64_GUEST); + + s_mapper.put("Windows 8", VirtualMachineGuestOsIdentifier.WINDOWS_8_GUEST); + s_mapper.put("Windows 8 (64 bit)", VirtualMachineGuestOsIdentifier.WINDOWS_8_64_GUEST); + s_mapper.put("Windows 8 Server (64 bit)", VirtualMachineGuestOsIdentifier.WINDOWS_8_SERVER_64_GUEST); + + s_mapper.put("Open Enterprise Server", VirtualMachineGuestOsIdentifier.OES_GUEST); + + s_mapper.put("Asianux 3(32-bit)", VirtualMachineGuestOsIdentifier.ASIANUX_3_GUEST); + s_mapper.put("Asianux 3(64-bit)", VirtualMachineGuestOsIdentifier.ASIANUX_3_64_GUEST); + + s_mapper.put("Debian GNU/Linux 5(64-bit)", VirtualMachineGuestOsIdentifier.DEBIAN_5_64_GUEST); + s_mapper.put("Debian GNU/Linux 5.0 (32-bit)", VirtualMachineGuestOsIdentifier.DEBIAN_5_GUEST); + s_mapper.put("Debian GNU/Linux 4(32-bit)", VirtualMachineGuestOsIdentifier.DEBIAN_4_GUEST); + s_mapper.put("Debian GNU/Linux 4(64-bit)", VirtualMachineGuestOsIdentifier.DEBIAN_4_64_GUEST); + + s_mapper.put("Novell Netware 6.x", VirtualMachineGuestOsIdentifier.NETWARE_6_GUEST); + s_mapper.put("Novell Netware 5.1", VirtualMachineGuestOsIdentifier.NETWARE_5_GUEST); + + s_mapper.put("Sun Solaris 10(32-bit)", VirtualMachineGuestOsIdentifier.SOLARIS_10_GUEST); + s_mapper.put("Sun Solaris 10(64-bit)", VirtualMachineGuestOsIdentifier.SOLARIS_10_64_GUEST); + s_mapper.put("Sun Solaris 9(Experimental)", VirtualMachineGuestOsIdentifier.SOLARIS_9_GUEST); + s_mapper.put("Sun Solaris 8(Experimental)", VirtualMachineGuestOsIdentifier.SOLARIS_8_GUEST); + + s_mapper.put("FreeBSD (32-bit)", VirtualMachineGuestOsIdentifier.FREEBSD_GUEST); + s_mapper.put("FreeBSD (64-bit)", VirtualMachineGuestOsIdentifier.FREEBSD_64_GUEST); + + s_mapper.put("SCO OpenServer 5", VirtualMachineGuestOsIdentifier.OTHER_GUEST); + s_mapper.put("SCO UnixWare 7", VirtualMachineGuestOsIdentifier.UNIX_WARE_7_GUEST); + + s_mapper.put("SUSE Linux Enterprise 8(32-bit)", VirtualMachineGuestOsIdentifier.SUSE_GUEST); + s_mapper.put("SUSE Linux Enterprise 8(64-bit)", VirtualMachineGuestOsIdentifier.SUSE_64_GUEST); + s_mapper.put("SUSE Linux Enterprise 9(32-bit)", VirtualMachineGuestOsIdentifier.SUSE_GUEST); + s_mapper.put("SUSE Linux Enterprise 9(64-bit)", VirtualMachineGuestOsIdentifier.SUSE_64_GUEST); + s_mapper.put("SUSE Linux Enterprise 10(32-bit)", VirtualMachineGuestOsIdentifier.SUSE_GUEST); + s_mapper.put("SUSE Linux Enterprise 10(64-bit)", VirtualMachineGuestOsIdentifier.SUSE_64_GUEST); + s_mapper.put("SUSE Linux Enterprise 10(32-bit)", VirtualMachineGuestOsIdentifier.SUSE_GUEST); + s_mapper.put("Other SUSE Linux(32-bit)", VirtualMachineGuestOsIdentifier.SUSE_GUEST); + s_mapper.put("Other SUSE Linux(64-bit)", VirtualMachineGuestOsIdentifier.SUSE_64_GUEST); + + s_mapper.put("CentOS 4.5 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 4.6 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 4.7 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 4.8 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.0 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.0 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 5.1 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.1 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 5.2 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.2 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 5.3 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.3 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 5.4 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.4 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 5.5 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.5 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 5.6 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 5.6 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("CentOS 6.0 (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("CentOS 6.0 (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + s_mapper.put("Other CentOS (32-bit)", VirtualMachineGuestOsIdentifier.CENTOS_GUEST); + s_mapper.put("Other CentOS (64-bit)", VirtualMachineGuestOsIdentifier.CENTOS_64_GUEST); + + s_mapper.put("Red Hat Enterprise Linux 2", VirtualMachineGuestOsIdentifier.RHEL_2_GUEST); + s_mapper.put("Red Hat Enterprise Linux 3(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_3_GUEST); + s_mapper.put("Red Hat Enterprise Linux 3(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_3_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 4(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_4_GUEST); + s_mapper.put("Red Hat Enterprise Linux 4(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_4_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 6(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_6_GUEST); + s_mapper.put("Red Hat Enterprise Linux 6(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_6_64_GUEST); + + s_mapper.put("Red Hat Enterprise Linux 4.5 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_4_GUEST); + s_mapper.put("Red Hat Enterprise Linux 4.6 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_4_GUEST); + s_mapper.put("Red Hat Enterprise Linux 4.7 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_4_GUEST); + s_mapper.put("Red Hat Enterprise Linux 4.8 (32-bit)", VirtualMachineGuestOsIdentifier.RHEL_4_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.0(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.0(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.1(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.1(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.2(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.2(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.3(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.3(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.4(32-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_GUEST); + s_mapper.put("Red Hat Enterprise Linux 5.4(64-bit)", VirtualMachineGuestOsIdentifier.RHEL_5_64_GUEST); + + s_mapper.put("Ubuntu 8.04 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 8.04 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Ubuntu 8.10 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 8.10 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Ubuntu 9.04 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 9.04 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Ubuntu 9.10 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 9.10 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Ubuntu 10.04 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 10.04 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Ubuntu 10.10 (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Ubuntu 10.10 (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + s_mapper.put("Other Ubuntu (32-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_GUEST); + s_mapper.put("Other Ubuntu (64-bit)", VirtualMachineGuestOsIdentifier.UBUNTU_64_GUEST); + + s_mapper.put("Other 2.6x Linux (32-bit)", VirtualMachineGuestOsIdentifier.OTHER_26_X_LINUX_GUEST); + s_mapper.put("Other 2.6x Linux (64-bit)", VirtualMachineGuestOsIdentifier.OTHER_26_X_LINUX_64_GUEST); + s_mapper.put("Other Linux (32-bit)", VirtualMachineGuestOsIdentifier.OTHER_LINUX_GUEST); + s_mapper.put("Other Linux (64-bit)", VirtualMachineGuestOsIdentifier.OTHER_LINUX_64_GUEST); + + s_mapper.put("Other (32-bit)", VirtualMachineGuestOsIdentifier.OTHER_GUEST); + s_mapper.put("Other (64-bit)", VirtualMachineGuestOsIdentifier.OTHER_GUEST_64); } - + public static VirtualMachineGuestOsIdentifier getGuestOsIdentifier(String guestOsName) { return s_mapper.get(guestOsName); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java index 47ff8e20004..8e6947fd072 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -69,38 +70,38 @@ import com.vmware.vim25.VirtualVmxnet3; public class VmwareHelper { private static final Logger s_logger = Logger.getLogger(VmwareHelper.class); - + public static VirtualDevice prepareNicDevice(VirtualMachineMO vmMo, ManagedObjectReference morNetwork, VirtualEthernetCardType deviceType, String portGroupName, String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { - + VirtualEthernetCard nic; switch(deviceType) { case E1000 : nic = new VirtualE1000(); break; - + case PCNet32 : nic = new VirtualPCNet32(); break; - + case Vmxnet2 : nic = new VirtualVmxnet2(); break; - + case Vmxnet3 : nic = new VirtualVmxnet3(); break; - + default : assert(false); nic = new VirtualE1000(); } - + VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.setDeviceName(portGroupName); nicBacking.setNetwork(morNetwork); nic.setBacking(nicBacking); - + VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); connectInfo.setAllowGuestControl(true); connectInfo.setConnected(conntected); @@ -112,7 +113,7 @@ public class VmwareHelper { nic.setKey(-contextNumber); return nic; } - + public static VirtualDevice prepareDvNicDevice(VirtualMachineMO vmMo, ManagedObjectReference morNetwork, VirtualEthernetCardType deviceType, String dvPortGroupName, String dvSwitchUuid, String macAddress, int deviceNumber, int contextNumber, boolean conntected, boolean connectOnStart) throws Exception { @@ -144,7 +145,7 @@ public class VmwareHelper { final VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); dvPortConnection.setSwitchUuid(dvSwitchUuid); - dvPortConnection.setPortgroupKey(morNetwork.get_value()); + dvPortConnection.setPortgroupKey(morNetwork.getValue()); dvPortBacking.setPort(dvPortConnection); nic.setBacking(dvPortBacking); nic.setKey(30); @@ -162,13 +163,13 @@ public class VmwareHelper { } // vmdkDatastorePath: [datastore name] vmdkFilePath - public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, + public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, int deviceNumber, int contextNumber) throws Exception { - + VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); - backingInfo.setDiskMode(VirtualDiskMode.persistent.toString()); + backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); backingInfo.setThinProvisioned(true); backingInfo.setEagerlyScrub(false); backingInfo.setDatastore(morDs); @@ -180,7 +181,7 @@ public class VmwareHelper { if(deviceNumber < 0) deviceNumber = vmMo.getNextDeviceNumber(controllerKey); disk.setControllerKey(controllerKey); - + disk.setKey(-contextNumber); disk.setUnitNumber(deviceNumber); disk.setCapacityInKB(sizeInMb*1024); @@ -189,19 +190,19 @@ public class VmwareHelper { connectInfo.setConnected(true); connectInfo.setStartConnected(true); disk.setConnectable(connectInfo); - + return disk; } - + // vmdkDatastorePath: [datastore name] vmdkFilePath, create delta disk based on disk from template - public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, + public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, VirtualDisk templateDisk, int deviceNumber, int contextNumber) throws Exception { - + assert(templateDisk != null); VirtualDeviceBackingInfo parentBacking = templateDisk.getBacking(); assert(parentBacking != null); - - // TODO Not sure if we need to check if the disk in template and the new disk needs to share the + + // TODO Not sure if we need to check if the disk in template and the new disk needs to share the // same datastore VirtualDisk disk = new VirtualDisk(); if(parentBacking instanceof VirtualDiskFlatVer1BackingInfo) { @@ -242,13 +243,13 @@ public class VmwareHelper { } else { throw new Exception("Unsupported disk backing: " + parentBacking.getClass().getCanonicalName()); } - + if(controllerKey < 0) controllerKey = vmMo.getIDEDeviceControllerKey(); disk.setControllerKey(controllerKey); if(deviceNumber < 0) deviceNumber = vmMo.getNextDeviceNumber(controllerKey); - + disk.setKey(-contextNumber); disk.setUnitNumber(deviceNumber); disk.setCapacityInKB(sizeInMb*1024); @@ -259,94 +260,94 @@ public class VmwareHelper { disk.setConnectable(connectInfo); return disk; } - + // vmdkDatastorePath: [datastore name] vmdkFilePath - public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePathChain[], + public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePathChain[], ManagedObjectReference morDs, int deviceNumber, int contextNumber) throws Exception { - + assert(vmdkDatastorePathChain != null); assert(vmdkDatastorePathChain.length >= 1); - + VirtualDisk disk = new VirtualDisk(); - + VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); backingInfo.setDatastore(morDs); backingInfo.setFileName(vmdkDatastorePathChain[0]); - backingInfo.setDiskMode(VirtualDiskMode.persistent.toString()); + backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); if(vmdkDatastorePathChain.length > 1) { String[] parentDisks = new String[vmdkDatastorePathChain.length - 1]; for(int i = 0; i < vmdkDatastorePathChain.length - 1; i++) parentDisks[i] = vmdkDatastorePathChain[i + 1]; - + setParentBackingInfo(backingInfo, morDs, parentDisks); } - + disk.setBacking(backingInfo); if(controllerKey < 0) controllerKey = vmMo.getIDEDeviceControllerKey(); if(deviceNumber < 0) deviceNumber = vmMo.getNextDeviceNumber(controllerKey); - + disk.setControllerKey(controllerKey); disk.setKey(-contextNumber); disk.setUnitNumber(deviceNumber); - + VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); connectInfo.setConnected(true); connectInfo.setStartConnected(true); disk.setConnectable(connectInfo); - + return disk; } - - public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, - Pair[] vmdkDatastorePathChain, + + public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, + Pair[] vmdkDatastorePathChain, int deviceNumber, int contextNumber) throws Exception { - + assert(vmdkDatastorePathChain != null); assert(vmdkDatastorePathChain.length >= 1); - + VirtualDisk disk = new VirtualDisk(); - + VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); backingInfo.setDatastore(vmdkDatastorePathChain[0].second()); backingInfo.setFileName(vmdkDatastorePathChain[0].first()); - backingInfo.setDiskMode(VirtualDiskMode.persistent.toString()); + backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); if(vmdkDatastorePathChain.length > 1) { Pair[] parentDisks = new Pair[vmdkDatastorePathChain.length - 1]; for(int i = 0; i < vmdkDatastorePathChain.length - 1; i++) parentDisks[i] = vmdkDatastorePathChain[i + 1]; - + setParentBackingInfo(backingInfo, parentDisks); } - + disk.setBacking(backingInfo); if(controllerKey < 0) controllerKey = vmMo.getIDEDeviceControllerKey(); if(deviceNumber < 0) deviceNumber = vmMo.getNextDeviceNumber(controllerKey); - + disk.setControllerKey(controllerKey); disk.setKey(-contextNumber); disk.setUnitNumber(deviceNumber); - + VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); connectInfo.setConnected(true); connectInfo.setStartConnected(true); disk.setConnectable(connectInfo); - + return disk; } - - private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, + + private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, ManagedObjectReference morDs, String[] parentDatastorePathList) { - + VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); parentBacking.setDatastore(morDs); - parentBacking.setDiskMode(VirtualDiskMode.persistent.toString()); - + parentBacking.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + if(parentDatastorePathList.length > 1) { String[] nextDatastorePathList = new String[parentDatastorePathList.length -1]; for(int i = 0; i < parentDatastorePathList.length -1; i++) @@ -354,17 +355,17 @@ public class VmwareHelper { setParentBackingInfo(parentBacking, morDs, nextDatastorePathList); } parentBacking.setFileName(parentDatastorePathList[0]); - + backingInfo.setParent(parentBacking); } - - private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, + + private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, Pair[] parentDatastorePathList) { - + VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); parentBacking.setDatastore(parentDatastorePathList[0].second()); - parentBacking.setDiskMode(VirtualDiskMode.persistent.toString()); - + parentBacking.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + if(parentDatastorePathList.length > 1) { Pair[] nextDatastorePathList = new Pair[parentDatastorePathList.length -1]; for(int i = 0; i < parentDatastorePathList.length -1; i++) @@ -372,33 +373,33 @@ public class VmwareHelper { setParentBackingInfo(parentBacking, nextDatastorePathList); } parentBacking.setFileName(parentDatastorePathList[0].first()); - + backingInfo.setParent(parentBacking); } - + public static Pair prepareIsoDevice(VirtualMachineMO vmMo, String isoDatastorePath, ManagedObjectReference morDs, boolean connect, boolean connectAtBoot, int deviceNumber, int contextNumber) throws Exception { - + boolean newCdRom = false; VirtualCdrom cdRom = (VirtualCdrom )vmMo.getIsoDevice(); if(cdRom == null) { newCdRom = true; cdRom = new VirtualCdrom(); - + assert(vmMo.getIDEDeviceControllerKey() >= 0); cdRom.setControllerKey(vmMo.getIDEDeviceControllerKey()); if(deviceNumber < 0) deviceNumber = vmMo.getNextIDEDeviceNumber(); - cdRom.setUnitNumber(deviceNumber); + cdRom.setUnitNumber(deviceNumber); cdRom.setKey(-contextNumber); } - + VirtualDeviceConnectInfo cInfo = new VirtualDeviceConnectInfo(); cInfo.setConnected(connect); cInfo.setStartConnected(connectAtBoot); cdRom.setConnectable(cInfo); - + if(isoDatastorePath != null) { VirtualCdromIsoBackingInfo backingInfo = new VirtualCdromIsoBackingInfo(); backingInfo.setFileName(isoDatastorePath); @@ -409,32 +410,32 @@ public class VmwareHelper { backingInfo.setDeviceName(""); cdRom.setBacking(backingInfo); } - + return new Pair(cdRom, newCdRom); } - + public static VirtualDisk getRootDisk(VirtualDisk[] disks) { if(disks.length == 1) return disks[0]; - + // TODO : for now, always return the first disk as root disk return disks[0]; } - - public static ManagedObjectReference findSnapshotInTree(VirtualMachineSnapshotTree[] snapTree, String findName) { + + public static ManagedObjectReference findSnapshotInTree(List snapTree, String findName) { assert(findName != null); - + ManagedObjectReference snapMor = null; - if (snapTree == null) + if (snapTree == null) return snapMor; - - for (int i = 0; i < snapTree.length && snapMor == null; i++) { - VirtualMachineSnapshotTree node = snapTree[i]; + + for (int i = 0; i < snapTree.size() && snapMor == null; i++) { + VirtualMachineSnapshotTree node = snapTree.get(i); if (node.getName().equals(findName)) { snapMor = node.getSnapshot(); } else { - VirtualMachineSnapshotTree[] childTree = node.getChildSnapshotList(); + List childTree = node.getChildSnapshotList(); snapMor = findSnapshotInTree(childTree, findName); } } @@ -442,94 +443,94 @@ public class VmwareHelper { } public static byte[] composeDiskInfo(List> diskInfo, int disksInChain, boolean includeBase) throws IOException { - + BufferedWriter out = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); - + try { - out = new BufferedWriter(new OutputStreamWriter(bos)); + out = new BufferedWriter(new OutputStreamWriter(bos)); out.write("disksInChain=" + disksInChain); out.newLine(); - + out.write("disksInBackup=" + diskInfo.size()); out.newLine(); - + out.write("baseDiskIncluded=" + includeBase); out.newLine(); - + int seq = disksInChain - 1; for(Ternary item : diskInfo) { out.write(String.format("disk%d.fileName=%s", seq, item.first())); out.newLine(); - + out.write(String.format("disk%d.baseFileName=%s", seq, item.second())); out.newLine(); - + if(item.third() != null) { out.write(String.format("disk%d.parentFileName=%s", seq, item.third())); out.newLine(); } seq--; } - + out.newLine(); } finally { if(out != null) out.close(); } - + return bos.toByteArray(); } - - public static OptionValue[] composeVncOptions(OptionValue[] optionsToMerge, + + public static OptionValue[] composeVncOptions(OptionValue[] optionsToMerge, boolean enableVnc, String vncPassword, int vncPort, String keyboardLayout) { - + int numOptions = 3; boolean needKeyboardSetup = false; if(keyboardLayout != null && !keyboardLayout.isEmpty()) { numOptions++; needKeyboardSetup = true; } - + if(optionsToMerge != null) numOptions += optionsToMerge.length; - + OptionValue[] options = new OptionValue[numOptions]; int i = 0; if(optionsToMerge != null) { for(int j = 0; j < optionsToMerge.length; j++) options[i++] = optionsToMerge[j]; } - + options[i] = new OptionValue(); options[i].setKey("RemoteDisplay.vnc.enabled"); options[i++].setValue(enableVnc ? "true" : "false"); - + options[i] = new OptionValue(); options[i].setKey("RemoteDisplay.vnc.password"); options[i++].setValue(vncPassword); - + options[i] = new OptionValue(); options[i].setKey("RemoteDisplay.vnc.port"); options[i++].setValue("" + vncPort); - + if(needKeyboardSetup) { options[i] = new OptionValue(); options[i].setKey("RemoteDisplay.vnc.keymap"); options[i++].setValue(keyboardLayout); } - + return options; } - + public static void setBasicVmConfig(VirtualMachineConfigSpec vmConfig, int cpuCount, int cpuSpeedMHz, int cpuReservedMhz, int memoryMB, int memoryReserveMB, String guestOsIdentifier, boolean limitCpuUse) { - + // VM config basics vmConfig.setMemoryMB((long)memoryMB); vmConfig.setNumCPUs(cpuCount); - + ResourceAllocationInfo cpuInfo = new ResourceAllocationInfo(); if (limitCpuUse) { cpuInfo.setLimit((long)(cpuSpeedMHz * cpuCount)); @@ -539,52 +540,52 @@ public class VmwareHelper { cpuInfo.setReservation((long)cpuReservedMhz); vmConfig.setCpuAllocation(cpuInfo); - + ResourceAllocationInfo memInfo = new ResourceAllocationInfo(); memInfo.setLimit((long)memoryMB); memInfo.setReservation((long)memoryReserveMB); vmConfig.setMemoryAllocation(memInfo); - + vmConfig.setGuestId(guestOsIdentifier); } - + public static ManagedObjectReference getDiskDeviceDatastore(VirtualDisk diskDevice) throws Exception { VirtualDeviceBackingInfo backingInfo = diskDevice.getBacking(); assert(backingInfo instanceof VirtualDiskFlatVer2BackingInfo); return ((VirtualDiskFlatVer2BackingInfo)backingInfo).getDatastore(); } - + public static Object getPropValue(ObjectContent oc, String name) { - DynamicProperty[] props = oc.getPropSet(); - + List props = oc.getPropSet(); + for(DynamicProperty prop : props) { if(prop.getName().equalsIgnoreCase(name)) return prop.getVal(); } - + return null; } - + public static String getFileExtension(String fileName, String defaultExtension) { int pos = fileName.lastIndexOf('.'); if(pos < 0) return defaultExtension; - - return fileName.substring(pos); + + return fileName.substring(pos); } - + public static boolean isSameHost(String ipAddress, String destName) { // TODO : may need to do DNS lookup to compare IP address exactly return ipAddress.equals(destName); } - + public static void deleteVolumeVmdkFiles(DatastoreMO dsMo, String volumeName, DatacenterMO dcMo) throws Exception { String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeName); dsMo.deleteFile(volumeDatastorePath, dcMo.getMor(), true); - + volumeDatastorePath = String.format("[%s] %s-flat.vmdk", dsMo.getName(), volumeName); dsMo.deleteFile(volumeDatastorePath, dcMo.getMor(), true); - + volumeDatastorePath = String.format("[%s] %s-delta.vmdk", dsMo.getName(), volumeName); dsMo.deleteFile(volumeDatastorePath, dcMo.getMor(), true); } @@ -592,38 +593,50 @@ public class VmwareHelper { public static String getExceptionMessage(Throwable e) { return getExceptionMessage(e, false); } - + public static String getExceptionMessage(Throwable e, boolean printStack) { - if(e instanceof MethodFault) { - final StringWriter writer = new StringWriter(); - writer.append("Exception: " + e.getClass().getName() + "\n"); - writer.append("message: " + ((MethodFault)e).getFaultString() + "\n"); - - if(printStack) { - writer.append("stack: "); - e.printStackTrace(new PrintWriter(writer)); - } - return writer.toString(); - } - + //TODO: in vim 5.1, exceptions do not have a base exception class, MethodFault becomes a FaultInfo that we can only get + // from individual exception through getFaultInfo, so we have to use reflection here to get MethodFault information. + try{ + Class cls = e.getClass(); + Method mth = cls.getDeclaredMethod("getFaultInfo", null); + if ( mth != null ){ + Object fault = mth.invoke(e, null); + if (fault instanceof MethodFault) { + final StringWriter writer = new StringWriter(); + writer.append("Exception: " + fault.getClass().getName() + "\n"); + writer.append("message: " + ((MethodFault)fault).getFaultMessage() + "\n"); + + if(printStack) { + writer.append("stack: "); + e.printStackTrace(new PrintWriter(writer)); + } + return writer.toString(); + } + } + } + catch (Exception ex){ + + } + return ExceptionUtil.toString(e, printStack); } - + public static VirtualMachineMO pickOneVmOnRunningHost(List vmList, boolean bFirstFit) throws Exception { List candidates = new ArrayList(); - + for(VirtualMachineMO vmMo : vmList) { HostMO hostMo = vmMo.getRunningHost(); if(hostMo.isHyperHostConnected()) candidates.add(vmMo); } - + if(candidates.size() == 0) return null; - + if(bFirstFit) return candidates.get(0); - + Random random = new Random(); return candidates.get(random.nextInt(candidates.size())); } From 481f4804723c57553e1464fb8876681ffa651cc0 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Mon, 4 Feb 2013 17:41:36 -0800 Subject: [PATCH 02/17] Upgrade to use Vsphere 5.1 SDK jar, fixed all compilation error with new wrapper class VmwareClient. --- .../vmware/VmwareServerDiscoverer.java | 84 +-- .../vmware/manager/VmwareManagerImpl.java | 125 ++--- .../manager/VmwareStorageManagerImpl.java | 262 ++++----- .../vmware/resource/VmwareContextFactory.java | 26 +- .../vmware/resource/VmwareResource.java | 454 ++++++++-------- .../VmwareSecondaryStorageContextFactory.java | 31 +- ...VmwareSecondaryStorageResourceHandler.java | 18 +- .../cloud/hypervisor/vmware/mo/BaseMO.java | 74 +-- .../cloud/hypervisor/vmware/mo/ClusterMO.java | 308 +++++------ .../vmware/mo/CustomFieldsManagerMO.java | 26 +- .../hypervisor/vmware/mo/DatacenterMO.java | 324 +++++------ .../hypervisor/vmware/mo/DatastoreMO.java | 186 +++---- .../vmware/mo/HostDatastoreBrowserMO.java | 58 +- .../vmware/mo/HostDatastoreSystemMO.java | 82 +-- .../vmware/mo/HostFirewallSystemMO.java | 14 +- .../cloud/hypervisor/vmware/mo/HostMO.java | 450 ++++++++-------- .../hypervisor/vmware/mo/HttpNfcLeaseMO.java | 89 +-- .../vmware/mo/HypervisorHostHelper.java | 211 ++++---- .../cloud/hypervisor/vmware/mo/NetworkMO.java | 10 +- .../hypervisor/vmware/mo/PerfManagerMO.java | 89 ++- .../cloud/hypervisor/vmware/mo/TaskMO.java | 24 +- .../vmware/mo/VirtualDiskManagerMO.java | 134 ++--- .../vmware/mo/VirtualMachineMO.java | 458 ++++++++-------- .../hypervisor/vmware/util/VmwareClient.java | 509 ++++++++++++++++++ .../hypervisor/vmware/util/VmwareContext.java | 334 ++++++------ 25 files changed, 2487 insertions(+), 1893 deletions(-) create mode 100644 vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java index 684df54ccd5..653d259bda8 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.vmware; @@ -72,7 +72,7 @@ import com.vmware.vim25.ManagedObjectReference; @Local(value=Discoverer.class) public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter { private static final Logger s_logger = Logger.getLogger(VmwareServerDiscoverer.class); - + @Inject ClusterDao _clusterDao; @Inject VmwareManager _vmwareMgr; @Inject AlertManager _alertMgr; @@ -85,27 +85,27 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer @Inject CiscoNexusVSMDeviceDao _nexusDao; @Inject NetworkModel _netmgr; - + @Override - public Map> find(long dcId, Long podId, Long clusterId, URI url, + public Map> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) throws DiscoveryException { - + if(s_logger.isInfoEnabled()) s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost()); - + if(podId == null) { if(s_logger.isInfoEnabled()) - s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer"); + s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer"); return null; } - + ClusterVO cluster = _clusterDao.findById(clusterId); if(cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) { if(s_logger.isInfoEnabled()) - s_logger.info("invalid cluster id or cluster is not for VMware hypervisors"); + s_logger.info("invalid cluster id or cluster is not for VMware hypervisors"); return null; } - + List hosts = _resourceMgr.listAllHostsInCluster(clusterId); if(hosts.size() >= _vmwareMgr.getMaxHostsPerCluster()) { String msg = "VMware cluster " + cluster.getName() + " is too big to add new host now. (current configured cluster size: " + _vmwareMgr.getMaxHostsPerCluster() + ")"; @@ -117,12 +117,12 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer String publicTrafficLabel = null; String guestTrafficLabel = null; Map vsmCredentials = null; - + privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware); if (privateTrafficLabel != null) { s_logger.info("Detected private network label : " + privateTrafficLabel); } - + if (_vmwareMgr.getNexusVSwitchGlobalParameter()) { DataCenterVO zone = _dcDao.findById(dcId); NetworkType zoneType = zone.getNetworkType(); @@ -145,7 +145,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer context = VmwareContextFactory.create(url.getHost(), username, password); if (privateTrafficLabel != null) context.registerStockObject("privateTrafficLabel", privateTrafficLabel); - + if (_vmwareMgr.getNexusVSwitchGlobalParameter()) { if (vsmCredentials != null) { s_logger.info("Stocking credentials of Nexus VSM"); @@ -163,26 +163,26 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath())); return null; } - + ManagedObjectReference morCluster = null; Map clusterDetails = _clusterDetailsDao.findDetails(clusterId); if(clusterDetails.get("url") != null) { URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url"))); morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath())); - + if(morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) { s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url")); return null; } else { ClusterMO clusterMo = new ClusterMO(context, morCluster); ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig(); - if(dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) { + if(dasConfig != null && dasConfig.isEnabled() != null && dasConfig.isEnabled().booleanValue()) { clusterDetails.put("NativeHA", "true"); _clusterDetailsDao.persist(clusterId, clusterDetails); } } } - + if(!validateDiscoveredHosts(context, morCluster, morHosts)) { if(morCluster == null) s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster"); @@ -195,14 +195,14 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer for(ManagedObjectReference morHost : morHosts) { Map details = new HashMap(); Map params = new HashMap(); - + HostMO hostMo = new HostMO(context, morHost); details.put("url", hostMo.getHostName()); details.put("username", username); details.put("password", password); - String guid = morHost.getType() + ":" + morHost.get_value() + "@"+ url.getHost(); + String guid = morHost.getType() + ":" + morHost.getValue() + "@"+ url.getHost(); details.put("guid", guid); - + params.put("url", hostMo.getHostName()); params.put("username", username); params.put("password", password); @@ -219,8 +219,8 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer if (guestTrafficLabel != null) { params.put("guest.network.vswitch.name", guestTrafficLabel); } - - VmwareResource resource = new VmwareResource(); + + VmwareResource resource = new VmwareResource(); try { resource.configure("VMware", params); } catch (ConfigurationException e) { @@ -228,14 +228,14 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer s_logger.warn("Unable to instantiate " + url.getHost(), e); } resource.start(); - + resources.put(resource, details); } - + // place a place holder guid derived from cluster ID cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString()); _clusterDao.update(clusterId, cluster); - + return resources; } catch (DiscoveredWithErrorException e) { throw e; @@ -247,59 +247,59 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer context.close(); } } - + private boolean validateDiscoveredHosts(VmwareContext context, ManagedObjectReference morCluster, List morHosts) throws Exception { if(morCluster == null) { for(ManagedObjectReference morHost : morHosts) { - ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent"); + ManagedObjectReference morParent = (ManagedObjectReference)context.getVimClient().getDynamicProperty(morHost, "parent"); if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) return false; } } else { for(ManagedObjectReference morHost : morHosts) { - ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent"); + ManagedObjectReference morParent = (ManagedObjectReference)context.getVimClient().getDynamicProperty(morHost, "parent"); if(!morParent.getType().equalsIgnoreCase("ClusterComputeResource")) return false; - - if(!morParent.get_value().equals(morCluster.get_value())) + + if(!morParent.getValue().equals(morCluster.getValue())) return false; } } - + return true; } - + @Override public void postDiscovery(List hosts, long msId) { // do nothing } - + @Override public boolean matchHypervisor(String hypervisor) { if(hypervisor == null) return true; - + return Hypervisor.HypervisorType.VMware.toString().equalsIgnoreCase(hypervisor); } - + @Override public Hypervisor.HypervisorType getHypervisorType() { return Hypervisor.HypervisorType.VMware; } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { if(s_logger.isInfoEnabled()) s_logger.info("Configure VmwareServerDiscoverer, discover name: " + name); - + super.configure(name, params); - + ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); if (configDao == null) { throw new ConfigurationException("Unable to get the configuration dao."); } - + createVmwareToolsIso(); if(s_logger.isInfoEnabled()) { @@ -308,7 +308,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; } - + private void createVmwareToolsIso() { String isoName = "vmware-tools.iso"; VMTemplateVO tmplt = _tmpltDao.findByTemplateName(isoName); @@ -354,11 +354,11 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer if (host.getType() != com.cloud.host.Host.Type.Routing || host.getHypervisorType() != HypervisorType.VMware) { return null; } - + _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage); return new DeleteHostAnswer(true); } - + @Override public boolean stop() { _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java index c450312c1a7..dea6cca431c 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.vmware.manager; @@ -71,6 +71,7 @@ import com.cloud.hypervisor.vmware.mo.TaskMO; import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType; import com.cloud.hypervisor.vmware.mo.VmwareHostType; import com.cloud.utils.ssh.SshHelper; +import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.network.CiscoNexusVSMDeviceVO; import com.cloud.network.NetworkModel; @@ -94,7 +95,6 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; import com.cloud.vm.DomainRouterVO; import com.google.gson.Gson; -import com.vmware.apputils.vim25.ServiceUtil; import com.vmware.vim25.HostConnectSpec; import com.vmware.vim25.ManagedObjectReference; @@ -123,7 +123,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis @Inject SecondaryStorageVmManager _ssvmMgr; @Inject CiscoNexusVSMDeviceDao _nexusDao; @Inject ClusterVSMMapDao _vsmMapDao; - + ConfigurationServer _configServer; String _mountParent; @@ -141,15 +141,15 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis int _additionalPortRangeSize; int _maxHostsPerCluster; int _routerExtraPublicNics = 2; - + String _cpuOverprovisioningFactor = "1"; String _reserveCpu = "false"; - + String _memOverprovisioningFactor = "1"; String _reserveMem = "false"; - + String _rootDiskController = DiskControllerType.ide.toString(); - + Map _storageMounts = new HashMap(); Random _rand = new Random(System.currentTimeMillis()); @@ -217,7 +217,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis throw new ConfigurationException("Unable to find class " + value); } } - + value = configDao.getValue(Config.VmwareUseNexusVSwitch.key()); if(value == null) { _nexusVSwitchActive = false; @@ -261,30 +261,30 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis if(_serviceConsoleName == null) { _serviceConsoleName = "Service Console"; } - + _managemetPortGroupName = configDao.getValue(Config.VmwareManagementPortGroup.key()); if(_managemetPortGroupName == null) { _managemetPortGroupName = "Management Network"; } - + _defaultSystemVmNicAdapterType = configDao.getValue(Config.VmwareSystemVmNicDeviceType.key()); if(_defaultSystemVmNicAdapterType == null) _defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString(); - + _additionalPortRangeStart = NumbersUtil.parseInt(configDao.getValue(Config.VmwareAdditionalVncPortRangeStart.key()), 59000); if(_additionalPortRangeStart > 65535) { s_logger.warn("Invalid port range start port (" + _additionalPortRangeStart + ") for additional VNC port allocation, reset it to default start port 59000"); _additionalPortRangeStart = 59000; } - + _additionalPortRangeSize = NumbersUtil.parseInt(configDao.getValue(Config.VmwareAdditionalVncPortRangeSize.key()), 1000); if(_additionalPortRangeSize < 0 || _additionalPortRangeStart + _additionalPortRangeSize > 65535) { s_logger.warn("Invalid port range size (" + _additionalPortRangeSize + " for range starts at " + _additionalPortRangeStart); _additionalPortRangeSize = Math.min(1000, 65535 - _additionalPortRangeStart); } - + _routerExtraPublicNics = NumbersUtil.parseInt(configDao.getValue(Config.RouterExtraPublicNics.key()), 2); - + _maxHostsPerCluster = NumbersUtil.parseInt(configDao.getValue(Config.VmwarePerClusterHostMax.key()), VmwareManager.MAX_HOSTS_PER_CLUSTER); _cpuOverprovisioningFactor = configDao.getValue(Config.CPUOverprovisioningFactor.key()); if(_cpuOverprovisioningFactor == null || _cpuOverprovisioningFactor.isEmpty()) @@ -293,22 +293,22 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis _memOverprovisioningFactor = configDao.getValue(Config.MemOverprovisioningFactor.key()); if(_memOverprovisioningFactor == null || _memOverprovisioningFactor.isEmpty()) _memOverprovisioningFactor = "1"; - + _reserveCpu = configDao.getValue(Config.VmwareReserveCpu.key()); if(_reserveCpu == null || _reserveCpu.isEmpty()) _reserveCpu = "false"; _reserveMem = configDao.getValue(Config.VmwareReserveMem.key()); if(_reserveMem == null || _reserveMem.isEmpty()) _reserveMem = "false"; - + _recycleHungWorker = configDao.getValue(Config.VmwareRecycleHungWorker.key()); if(_recycleHungWorker == null || _recycleHungWorker.isEmpty()) _recycleHungWorker = "false"; - + _rootDiskController = configDao.getValue(Config.VmwareRootDiskControllerType.key()); if(_rootDiskController == null || _rootDiskController.isEmpty()) _rootDiskController = DiskControllerType.ide.toString(); - + s_logger.info("Additional VNC port allocation range is settled at " + _additionalPortRangeStart + " to " + (_additionalPortRangeStart + _additionalPortRangeSize)); value = configDao.getValue("vmware.host.scan.interval"); @@ -319,7 +319,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis if(_configServer == null) _configServer = (ConfigurationServer)ComponentLocator.getComponent(ConfigurationServer.Name); - + _agentMgr.registerForHostEvents(this, true, true, true); s_logger.info("VmwareManagerImpl has been successfully configured"); @@ -352,6 +352,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis return _name; } + @Override public boolean getNexusVSwitchGlobalParameter() { return _nexusVSwitchActive; } @@ -360,22 +361,22 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis public String composeWorkerName() { return UUID.randomUUID().toString().replace("-", ""); } - + @Override public String getPrivateVSwitchName(long dcId, HypervisorType hypervisorType) { return _netMgr.getDefaultManagementTrafficLabel(dcId, hypervisorType); } - + @Override public String getPublicVSwitchName(long dcId, HypervisorType hypervisorType) { return _netMgr.getDefaultPublicTrafficLabel(dcId, hypervisorType); } - + @Override public String getGuestVSwitchName(long dcId, HypervisorType hypervisorType) { return _netMgr.getDefaultGuestTrafficLabel(dcId, hypervisorType); } - + @Override public List addHostToPodCluster(VmwareContext serviceContext, long dcId, Long podId, Long clusterId, String hostInventoryPath) throws Exception { @@ -392,7 +393,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis List returnedHostList = new ArrayList(); if(mor.getType().equals("ComputeResource")) { - ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getServiceUtil().getDynamicProperty(mor, "host"); + ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getVimClient().getDynamicProperty(mor, "host"); assert(hosts != null); // For ESX host, we need to enable host firewall to allow VNC access @@ -400,7 +401,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis HostFirewallSystemMO firewallMo = hostMo.getHostFirewallSystemMO(); if(firewallMo != null) { if(hostMo.getHostType() == VmwareHostType.ESX) { - + firewallMo.enableRuleset("vncServer"); firewallMo.refreshFirewall(); } @@ -424,15 +425,15 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis returnedHostList.add(hosts[0]); return returnedHostList; } else if(mor.getType().equals("ClusterComputeResource")) { - ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getServiceUtil().getDynamicProperty(mor, "host"); + ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getVimClient().getDynamicProperty(mor, "host"); assert(hosts != null); - + if(hosts.length > _maxHostsPerCluster) { String msg = "vCenter cluster size is too big (current configured cluster size: " + _maxHostsPerCluster + ")"; s_logger.error(msg); throw new DiscoveredWithErrorException(msg); } - + for(ManagedObjectReference morHost: hosts) { // For ESX host, we need to enable host firewall to allow VNC access HostMO hostMo = new HostMO(serviceContext, morHost); @@ -450,8 +451,8 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis if(tokens.length == 2) vlanId = tokens[1]; } - - + + s_logger.info("Calling prepareNetwork : " + hostMo.getContext().toString()); // prepare at least one network on the vswitch to enable OVF importing if(!_nexusVSwitchActive) { @@ -493,7 +494,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis returnedHostList.add(mor); return returnedHostList; } else { - s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.get_value() + " from inventory path: " + hostInventoryPath); + s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.getValue() + " from inventory path: " + hostInventoryPath); return null; } } @@ -506,8 +507,8 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis private ManagedObjectReference addHostToVCenterCluster(VmwareContext serviceContext, ManagedObjectReference morCluster, String host, String userName, String password) throws Exception { - ServiceUtil serviceUtil = serviceContext.getServiceUtil(); - ManagedObjectReference morHost = serviceUtil.getDecendentMoRef(morCluster, "HostSystem", host); + VmwareClient vclient = serviceContext.getVimClient(); + ManagedObjectReference morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host); if(morHost == null) { HostConnectSpec hostSpec = new HostConnectSpec(); hostSpec.setUserName(userName); @@ -515,16 +516,16 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis hostSpec.setHostName(host); hostSpec.setForce(true); // forcely take over the host - ManagedObjectReference morTask = serviceContext.getService().addHost_Task(morCluster, hostSpec, true, null, null); - String taskResult = serviceUtil.waitForTask(morTask); - if(!taskResult.equals("sucess")) { + ManagedObjectReference morTask = serviceContext.getService().addHostTask(morCluster, hostSpec, true, null, null); + boolean taskResult = vclient.waitForTask(morTask); + if(!taskResult) { s_logger.error("Unable to add host " + host + " to vSphere cluster due to " + TaskMO.getTaskFailureInfo(serviceContext, morTask)); throw new CloudRuntimeException("Unable to add host " + host + " to vSphere cluster due to " + taskResult); } serviceContext.waitForTaskProgressDone(morTask); // init morHost after it has been created - morHost = serviceUtil.getDecendentMoRef(morCluster, "HostSystem", host); + morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host); if(morHost == null) { throw new CloudRuntimeException("Successfully added host into vSphere but unable to find it later on?!. Please make sure you are either using IP address or full qualified domain name for host"); } @@ -545,25 +546,27 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis List secStorageHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dcId); if(secStorageHosts.size() > 0) return secStorageHosts.get(0).getStorageUrl(); - + return null; } - public String getServiceConsolePortGroupName() { + @Override + public String getServiceConsolePortGroupName() { return _serviceConsoleName; } - - public String getManagementPortGroupName() { + + @Override + public String getManagementPortGroupName() { return _managemetPortGroupName; } - + @Override public String getManagementPortGroupByHost(HostMO hostMo) throws Exception { if(hostMo.getHostType() == VmwareHostType.ESXi) return this._managemetPortGroupName; return this._serviceConsoleName; } - + @Override public void setupResourceStartupParams(Map params) { params.put("private.network.vswitch.name", _privateNetworkVSwitchName); @@ -585,17 +588,17 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis return _storageMgr; } - + @Override public long pushCleanupCheckpoint(String hostGuid, String vmName) { return _checkPointMgr.pushCheckPoint(new VmwareCleanupMaid(hostGuid, vmName)); } - + @Override public void popCleanupCheckpoint(long checkpoint) { _checkPointMgr.popCheckPoint(checkpoint); } - + @Override public void gcLeftOverVMs(VmwareContext context) { VmwareCleanupMaid.gcLeftOverVMs(context); @@ -623,12 +626,12 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis if(!destIso.exists()) { s_logger.info("Inject SSH key pairs before copying systemvm.iso into secondary storage"); _configServer.updateKeyPairs(); - + try { FileUtil.copyfile(srcIso, destIso); } catch(IOException e) { s_logger.error("Unexpected exception ", e); - + String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso.toString() + ", dest location: " + destIso; s_logger.error(msg); throw new CloudRuntimeException(msg); @@ -645,19 +648,19 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis lock.releaseRef(); } } - + @Override public String getSystemVMIsoFileNameOnDatastore() { String version = ComponentLocator.class.getPackage().getImplementationVersion(); String fileName = "systemvm-" + version + ".iso"; return fileName.replace(':', '-'); } - + @Override public String getSystemVMDefaultNicAdapterType() { return this._defaultSystemVmNicAdapterType; } - + private File getSystemVMPatchIsoFile() { // locate systemvm.iso URL url = ComponentLocator.class.getProtectionDomain().getCodeSource().getLocation(); @@ -866,7 +869,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis if(checkPointIdStr != null) { _checkPointMgr.popCheckPoint(Long.parseLong(checkPointIdStr)); } - + checkPointIdStr = answer.getContextParam("checkpoint2"); if(checkPointIdStr != null) { _checkPointMgr.popCheckPoint(Long.parseLong(checkPointIdStr)); @@ -897,9 +900,9 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis } } } - + protected final int DEFAULT_DOMR_SSHPORT = 3922; - + protected boolean shutdownRouterVM(DomainRouterVO router) { if (s_logger.isDebugEnabled()) { s_logger.debug("Try to shutdown router VM " + router.getInstanceName() + " directly."); @@ -943,27 +946,27 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis public boolean processTimeout(long agentId, long seq) { return false; } - + @Override public boolean beginExclusiveOperation(int timeOutSeconds) { return _exclusiveOpLock.lock(timeOutSeconds); } - + @Override public void endExclusiveOperation() { _exclusiveOpLock.unlock(); } - + @Override public Pair getAddiionalVncPortRange() { return new Pair(_additionalPortRangeStart, _additionalPortRangeSize); } - + @Override public int getMaxHostsPerCluster() { return this._maxHostsPerCluster; } - + @Override public int getRouterExtraPublicNics() { return this._routerExtraPublicNics; @@ -977,7 +980,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis vsmMapVO = _vsmMapDao.findByClusterId(clusterId); long vsmId = 0; if (vsmMapVO != null) { - vsmId = vsmMapVO.getVsmId(); + vsmId = vsmMapVO.getVsmId(); s_logger.info("vsmId is " + vsmId); nexusVSM = _nexusDao.findById(vsmId); s_logger.info("Fetching nexus vsm credentials from database."); @@ -985,7 +988,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis else { s_logger.info("Found empty vsmMapVO."); return null; - } + } Map nexusVSMCredentials = new HashMap(); if (nexusVSM != null) { diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java index 8650274719e..435db748680 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.vmware.manager; @@ -69,24 +69,24 @@ import com.vmware.vim25.VirtualSCSISharing; public class VmwareStorageManagerImpl implements VmwareStorageManager { private static final Logger s_logger = Logger.getLogger(VmwareStorageManagerImpl.class); - + private final VmwareStorageMount _mountService; private final StorageLayer _storage = new JavaStorageLayer(); - + private int _timeout; - + public VmwareStorageManagerImpl(VmwareStorageMount mountService) { assert(mountService != null); _mountService = mountService; } - + public void configure(Map params) { s_logger.info("Configure VmwareStorageManagerImpl"); - + String value = (String)params.get("scripts.timeout"); _timeout = NumbersUtil.parseInt(value, 1440) * 1000; } - + @Override public Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd) { String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); @@ -116,18 +116,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } templateName = cmd.getName(); } - + VmwareContext context = hostService.getServiceContext(cmd); try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - - String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().get_value()).getBytes()).toString(); + + String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().getValue()).getBytes()).toString(); // truncate template name to 32 chars to ensure they work well with vSphere API's. - templateUuidName = templateUuidName.replace("-", ""); - + templateUuidName = templateUuidName.replace("-", ""); + DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true); - + if (templateMo == null) { if(s_logger.isInfoEnabled()) s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName); @@ -153,7 +153,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { return new PrimaryStorageDownloadAnswer(msg); } } - + @Override public Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd) { Long accountId = cmd.getAccountId(); @@ -184,15 +184,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { if (vmMo == null) { if(s_logger.isDebugEnabled()) s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter"); - + vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); if(vmMo == null) { dsMo = new DatastoreMO(hyperHost.getContext(), morDs); - + workerVMName = hostService.getWorkerName(context, cmd, 0); - + // attach a volume to dummay wrapper VM for taking snapshot and exporting the VM for backup - if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier._otherGuest.toString(), morDs, false)) { + if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString(), morDs, false)) { String msg = "Unable to create worker VM to execute BackupSnapshotCommand"; s_logger.error(msg); throw new Exception(msg); @@ -202,17 +202,17 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName); } workerVm = vmMo; - + // attach volume to worker VM String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath); vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); - } - } - + } + } + if (!vmMo.createSnapshot(snapshotUuid, "Snapshot taken for " + cmd.getSnapshotName(), false, false)) { throw new Exception("Failed to take snapshot " + cmd.getSnapshotName() + " on vm: " + cmd.getVmName()); } - + snapshotBackupUuid = backupSnapshotToSecondaryStorage(vmMo, accountId, volumeId, cmd.getVolumePath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid, hostService.getWorkerName(context, cmd, 1)); @@ -220,11 +220,11 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { if (success) { details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage."; } - + } finally { if(vmMo != null) vmMo.removeAllSnapshots(); - + try { if (workerVm != null) { // detach volume and destroy worker vm @@ -233,7 +233,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } catch (Throwable e) { s_logger.warn("Failed to destroy worker VM: " + workerVMName); - } + } } } catch (Throwable e) { if (e instanceof RemoteException) { @@ -260,7 +260,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { VmwareContext context = hostService.getServiceContext(cmd); try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { if(s_logger.isDebugEnabled()) @@ -276,7 +276,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { Ternary result = createTemplateFromVolume(vmMo, accountId, templateId, cmd.getUniqueName(), - secondaryStoragePoolURL, volumePath, + secondaryStoragePoolURL, volumePath, hostService.getWorkerName(context, cmd, 0)); return new CreatePrivateTemplateAnswer(cmd, true, null, @@ -326,7 +326,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { return new CreatePrivateTemplateAnswer(cmd, false, details); } } - + @Override public Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd) { Long volumeId = cmd.getVolumeId(); @@ -375,7 +375,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { return new CopyVolumeAnswer(cmd, false, "CopyVolumeCommand failed due to exception: " + StringUtils.getExceptionStackInfo(e), null, null); } } - + @Override public Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd) { @@ -392,7 +392,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { VmwareContext context = hostService.getServiceContext(cmd); try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - + ManagedObjectReference morPrimaryDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStorageNameLabel); if (morPrimaryDs == null) { String msg = "Unable to find datastore: " + primaryStorageNameLabel; @@ -417,22 +417,22 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); } - + // templateName: name in secondary storage // templateUuid: will be used at hypervisor layer private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl, String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception { - - s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: " + + s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: " + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage + ", templateName: " + templateName); - + String secondaryMountPoint = _mountService.getMountPoint(secondaryStorageUrl); s_logger.info("Secondary storage mount point: " + secondaryMountPoint); - - String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage + + + String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage + templateName + "." + ImageFormat.OVA.getFileExtension(); - + String srcFileName = getOVFFilePath(srcOVAFileName); if(srcFileName == null) { Script command = new Script("tar", 0, s_logger); @@ -447,40 +447,40 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { throw new Exception(msg); } } - + srcFileName = getOVFFilePath(srcOVAFileName); - if(srcFileName == null) { - String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; + if(srcFileName == null) { + String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; s_logger.error(msg); throw new Exception(msg); } - + String vmName = templateUuid; hyperHost.importVmFromOVF(srcFileName, vmName, datastoreMo, "thin"); - + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if(vmMo == null) { - String msg = "Failed to import OVA template. secondaryStorage: " + String msg = "Failed to import OVA template. secondaryStorage: " + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage + ", templateName: " + templateName + ", templateUuid: " + templateUuid; s_logger.error(msg); throw new Exception(msg); } - + if(vmMo.createSnapshot("cloud.template.base", "Base snapshot", false, false)) { vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, templateUuid); vmMo.markAsTemplate(); } else { vmMo.destroy(); - String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid; + String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid; s_logger.error(msg); throw new Exception(msg); } } - - private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName, + + private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName, String secStorageUrl, String volumePath, String workerVmName) throws Exception { - + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); String installFullPath = secondaryMountPoint + "/" + installPath; @@ -488,16 +488,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { Script command = new Script(false, "mkdir", _timeout, s_logger); command.add("-p"); command.add(installFullPath); - + String result = command.execute(); if(result != null) { - String msg = "unable to prepare template directory: " + String msg = "unable to prepare template directory: " + installPath + ", storage: " + secStorageUrl + ", error msg: " + result; s_logger.error(msg); throw new Exception(msg); } } - + VirtualMachineMO clonedVm = null; try { Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false); @@ -506,15 +506,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.error(msg); throw new Exception(msg); } - + if(!vmMo.createSnapshot(templateUniqueName, "Temporary snapshot for template creation", false, false)) { String msg = "Unable to take snapshot for creating template from volume. volume path: " + volumePath; s_logger.error(msg); throw new Exception(msg); } - + // 4 MB is the minimum requirement for VM memory in VMware - vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), + vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName); if(clonedVm == null) { @@ -522,9 +522,9 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.error(msg); throw new Exception(msg); } - + clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false); - + long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); VmdkProcessor processor = new VmdkProcessor(); Map params = new HashMap(); @@ -534,54 +534,54 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); - + } finally { if(clonedVm != null) { clonedVm.detachAllDisks(); clonedVm.destroy(); } - + vmMo.removeSnapshot(templateUniqueName, false); } } - - private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName, + + private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName, String secStorageUrl, long volumeId, String backedUpSnapshotUuid) throws Exception { - + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); String installFullPath = secondaryMountPoint + "/" + installPath; String installFullName = installFullPath + "/" + templateUniqueName + ".ova"; - String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId) + String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId) + "/" + backedUpSnapshotUuid + ".ova"; String result; Script command; - + synchronized(installPath.intern()) { command = new Script(false, "mkdir", _timeout, s_logger); command.add("-p"); command.add(installFullPath); - + result = command.execute(); if(result != null) { - String msg = "unable to prepare template directory: " + String msg = "unable to prepare template directory: " + installPath + ", storage: " + secStorageUrl + ", error msg: " + result; s_logger.error(msg); throw new Exception(msg); } } - + try { command = new Script(false, "cp", _timeout, s_logger); command.add(snapshotFullName); command.add(installFullName); result = command.execute(); if(result != null) { - String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath; + String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath; s_logger.error(msg); throw new Exception(msg); } - + // untar OVA file at template directory command = new Script("tar", 0, s_logger); command.add("--no-same-owner"); @@ -590,12 +590,12 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.info("Executing command: " + command.toString()); result = command.execute(); if(result != null) { - String msg = "unable to untar snapshot " + snapshotFullName + " to " - + installFullPath; + String msg = "unable to untar snapshot " + snapshotFullName + " to " + + installFullPath; s_logger.error(msg); throw new Exception(msg); } - + long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); VmdkProcessor processor = new VmdkProcessor(); Map params = new HashMap(); @@ -605,45 +605,45 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); - + } catch(Exception e) { // TODO, clean up left over files throw e; } } - - private void postCreatePrivateTemplate(String installFullPath, long templateId, + + private void postCreatePrivateTemplate(String installFullPath, long templateId, String templateName, long size, long virtualSize) throws Exception { // TODO a bit ugly here BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties"))); - out.write("filename=" + templateName + ".ova"); + out.write("filename=" + templateName + ".ova"); out.newLine(); - out.write("description="); + out.write("description="); out.newLine(); - out.write("checksum="); + out.write("checksum="); out.newLine(); - out.write("hvm=false"); + out.write("hvm=false"); out.newLine(); - out.write("size=" + size); + out.write("size=" + size); out.newLine(); - out.write("ova=true"); + out.write("ova=true"); out.newLine(); - out.write("id=" + templateId); + out.write("id=" + templateId); out.newLine(); - out.write("public=false"); + out.write("public=false"); out.newLine(); - out.write("ova.filename=" + templateName + ".ova"); + out.write("ova.filename=" + templateName + ".ova"); out.newLine(); out.write("uniquename=" + templateName); out.newLine(); - out.write("ova.virtualsize=" + virtualSize); + out.write("ova.virtualsize=" + virtualSize); out.newLine(); - out.write("virtualsize=" + virtualSize); + out.write("virtualsize=" + virtualSize); out.newLine(); - out.write("ova.size=" + size); + out.write("ova.size=" + size); out.newLine(); } finally { if(out != null) @@ -651,21 +651,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } - private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, + private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, long accountId, long volumeId, String secStorageUrl, String snapshotBackupUuid) throws Exception { - - restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName, + + restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName, secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), snapshotBackupUuid); return null; } - - private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, + + private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, String secStorageUrl, String secStorageDir, String backupName) throws Exception { - + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/" + String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/" + backupName + "." + ImageFormat.OVA.getFileExtension(); - + String srcFileName = getOVFFilePath(srcOVAFileName); if(srcFileName == null) { Script command = new Script("tar", 0, s_logger); @@ -680,21 +680,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { throw new Exception(msg); } } - + srcFileName = getOVFFilePath(srcOVAFileName); if(srcFileName == null) { - String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; + String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; s_logger.error(msg); throw new Exception(msg); } - + VirtualMachineMO clonedVm = null; try { hyperHost.importVmFromOVF(srcFileName, newVolumeName, primaryDsMo, "thin"); clonedVm = hyperHost.findVmOnHyperHost(newVolumeName); if(clonedVm == null) throw new Exception("Unable to create container VM for volume creation"); - + clonedVm.moveAllVmDiskFiles(primaryDsMo, "", false); clonedVm.detachAllDisks(); } finally { @@ -704,24 +704,24 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } } - - private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId, - String volumePath, String snapshotUuid, String secStorageUrl, + + private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId, + String volumePath, String snapshotUuid, String secStorageUrl, String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception { - + String backupUuid = UUID.randomUUID().toString(); - exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, + exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName); return backupUuid; } - - private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath, + + private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath, String secStorageUrl, String secStorageDir, String exportName, String workerVmName) throws Exception { - + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); String exportPath = secondaryMountPoint + "/" + secStorageDir; - + synchronized(exportPath.intern()) { if(!new File(exportPath).exists()) { Script command = new Script(false, "mkdir", _timeout, s_logger); @@ -734,16 +734,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { VirtualMachineMO clonedVm = null; try { - + Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false); if(volumeDeviceInfo == null) { String msg = "Unable to find related disk device for volume. volume path: " + volumePath; s_logger.error(msg); throw new Exception(msg); } - + // 4 MB is the minimum requirement for VM memory in VMware - vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), + vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName); if(clonedVm == null) { @@ -751,7 +751,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.error(msg); throw new Exception(msg); } - + clonedVm.exportVm(exportPath, exportName, true, true); } finally { if(clonedVm != null) { @@ -760,7 +760,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } } - + private String deleteSnapshotOnSecondaryStorge(long accountId, long volumeId, String secStorageUrl, String backupUuid) throws Exception { String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); @@ -769,18 +769,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { if(file.exists()) { if(file.delete()) return null; - + } else { return "Backup file does not exist. backupUuid: " + backupUuid; } - + return "Failed to delete snapshot backup file, backupUuid: " + backupUuid; } - - private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd, - String vmName, long volumeId, String poolId, String volumePath, + + private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd, + String vmName, long volumeId, String poolId, String volumePath, String secStorageUrl, String workerVmName) throws Exception { - + String volumeFolder = String.valueOf(volumeId) + "/"; VirtualMachineMO workerVm=null; VirtualMachineMO vmMo=null; @@ -804,21 +804,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { vmConfig.setName(workerVmName); vmConfig.setMemoryMB((long) 4); vmConfig.setNumCPUs(1); - vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString()); + vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); - scsiController.setSharedBus(VirtualSCSISharing.noSharing); + scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); - scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); - vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec }); - + scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); + vmConfig.getDeviceChange().add(scsiControllerSpec); + hyperHost.createVm(vmConfig); workerVm = hyperHost.findVmOnHyperHost(workerVmName); if (workerVm == null) { @@ -826,7 +826,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.error(msg); throw new Exception(msg); } - + //attach volume to worker VM String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath); workerVm.attachDisk(new String[] { datastoreVolumePath }, morDs); @@ -835,7 +835,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { vmMo.createSnapshot(exportName, "Temporary snapshot for copy-volume command", false, false); - exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName, + exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName, hostService.getWorkerName(hyperHost.getContext(), cmd, 1)); return new Pair(volumeFolder, exportName); @@ -849,16 +849,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } - private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId, + private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId, DatastoreMO dsMo, String secStorageUrl, String exportName) throws Exception { String volumeFolder = String.valueOf(volumeId) + "/"; String newVolume = UUID.randomUUID().toString().replaceAll("-", ""); restoreVolumeFromSecStorage(hyperHost, dsMo, newVolume, secStorageUrl, "volumes/" + volumeFolder, exportName); - + return new Pair(volumeFolder, newVolume); } - + private String getOVFFilePath(String srcOVAFileName) { File file = new File(srcOVAFileName); assert(_storage != null); @@ -873,11 +873,11 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } return null; } - + private static String getTemplateRelativeDirInSecStorage(long accountId, long templateId) { return "template/tmpl/" + accountId + "/" + templateId; } - + private static String getSnapshotRelativeDirInSecStorage(long accountId, long volumeId) { return "snapshots/" + accountId + "/" + volumeId; } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java index 053ed6eaf46..11a75d8217f 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.vmware.resource; @@ -19,22 +19,22 @@ package com.cloud.hypervisor.vmware.resource; import org.apache.log4j.Logger; import com.cloud.hypervisor.vmware.manager.VmwareManager; +import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentLocator; -import com.vmware.apputils.version.ExtendedAppUtil; public class VmwareContextFactory { - + private static final Logger s_logger = Logger.getLogger(VmwareContextFactory.class); - + private static volatile int s_seq = 1; private static VmwareManager s_vmwareMgr; - + static { // skip certificate check System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); - + ComponentLocator locator = ComponentLocator.getLocator("management-server"); s_vmwareMgr = locator.getManager(VmwareManager.class); } @@ -45,17 +45,17 @@ public class VmwareContextFactory { assert(vCenterPassword != null); String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService"; - String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; + //String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; if(s_logger.isDebugEnabled()) s_logger.debug("initialize VmwareContext. url: " + serviceUrl + ", username: " + vCenterUserName + ", password: " + StringUtils.getMaskedPasswordForDisplay(vCenterPassword)); - - ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params); - - appUtil.connect(); - VmwareContext context = new VmwareContext(appUtil, vCenterAddress); + + VmwareClient vimClient = new VmwareClient(vCenterAddress + "-" + s_seq++); + vimClient.connect(serviceUrl, vCenterUserName, vCenterPassword); + + VmwareContext context = new VmwareContext(vimClient, vCenterAddress); context.registerStockObject(VmwareManager.CONTEXT_STOCK_NAME, s_vmwareMgr); - + context.registerStockObject("serviceconsole", s_vmwareMgr.getServiceConsolePortGroupName()); context.registerStockObject("manageportgroup", s_vmwareMgr.getManagementPortGroupName()); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 96c4348cbda..e527c2e5b39 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.vmware.resource; @@ -24,6 +24,7 @@ import java.net.URI; import java.nio.channels.SocketChannel; import java.rmi.RemoteException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -237,7 +238,9 @@ import com.vmware.vim25.PerfMetricSeries; import com.vmware.vim25.PerfQuerySpec; import com.vmware.vim25.PerfSampleInfo; import com.vmware.vim25.RuntimeFault; +import com.vmware.vim25.RuntimeFaultFaultMsg; import com.vmware.vim25.ToolsUnavailable; +import com.vmware.vim25.ToolsUnavailableFaultMsg; import com.vmware.vim25.VimPortType; import com.vmware.vim25.VirtualDevice; import com.vmware.vim25.VirtualDeviceConfigSpec; @@ -259,8 +262,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected String _name; protected final long _ops_timeout = 900000; // 15 minutes time out to time - protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown - + protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown + // out an operation protected final int _retry = 24; protected final int _sleep = 10000; @@ -281,14 +284,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected String _guestNetworkVSwitchName; protected VirtualSwitchType _vSwitchType = VirtualSwitchType.StandardVirtualSwitch; protected boolean _nexusVSwitch = false; - + protected float _cpuOverprovisioningFactor = 1; protected boolean _reserveCpu = false; - + protected float _memOverprovisioningFactor = 1; protected boolean _reserveMem = false; protected boolean _recycleHungWorker = false; - protected DiskControllerType _rootDiskController = DiskControllerType.ide; + protected DiskControllerType _rootDiskController = DiskControllerType.ide; protected ManagedObjectReference _morHyperHost; protected VmwareContext _serviceContext; @@ -304,9 +307,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected static HashMap s_statesTable; static { s_statesTable = new HashMap(); - s_statesTable.put(VirtualMachinePowerState.poweredOn, State.Running); - s_statesTable.put(VirtualMachinePowerState.poweredOff, State.Stopped); - s_statesTable.put(VirtualMachinePowerState.suspended, State.Stopped); + s_statesTable.put(VirtualMachinePowerState.POWERED_ON, State.Running); + s_statesTable.put(VirtualMachinePowerState.POWERED_OFF, State.Stopped); + s_statesTable.put(VirtualMachinePowerState.SUSPENDED, State.Stopped); } public VmwareResource() { @@ -317,7 +320,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa public Answer executeRequest(Command cmd) { if(s_logger.isTraceEnabled()) s_logger.trace("Begin executeRequest(), cmd: " + cmd.getClass().getSimpleName()); - + Answer answer = null; NDC.push(_hostName != null ? _hostName : _guid + "(" + ComponentLocator.class.getPackage().getImplementationVersion() + ")"); try { @@ -464,14 +467,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa synchronized (this) { try { - JmxUtil.registerMBean("VMware " + _morHyperHost.get_value(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); + JmxUtil.registerMBean("VMware " + _morHyperHost.getValue(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); _cmdMBeans.add(mbean); if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); _cmdMBeans.remove(0); - JmxUtil.unregisterMBean("VMware " + _morHyperHost.get_value(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); + JmxUtil.unregisterMBean("VMware " + _morHyperHost.getValue(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); } } catch (Exception e) { if(s_logger.isTraceEnabled()) @@ -485,10 +488,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if(s_logger.isTraceEnabled()) s_logger.trace("End executeRequest(), cmd: " + cmd.getClass().getSimpleName()); - + return answer; } - + protected Answer execute(CheckNetworkCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckNetworkCommand " + _gson.toJson(cmd)); @@ -497,7 +500,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // TODO setup portgroup for private network needs to be done here now return new CheckNetworkAnswer(cmd, true , "Network Setup check by names is done"); } - + protected Answer execute(NetworkUsageCommand cmd) { if ( cmd.isForVpc() ) { return VPCNetworkUsage(cmd); @@ -549,7 +552,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (!resultPair.first()) { throw new Exception(" vpc network usage plugin call failed "); } - + if (option.equals("get") || option.equals("vpn")) { String result = resultPair.second(); if (result == null || result.isEmpty()) { @@ -568,7 +571,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } catch (Throwable e) { - s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); @@ -583,7 +586,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String args = ""; String[] results = new String[cmd.getRules().length]; int i = 0; - + boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { args += rule.revoked() ? " -D " : " -A "; @@ -616,7 +619,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new SetPortForwardingRulesAnswer(cmd, results, endResult); } - + protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { String controlIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; @@ -672,9 +675,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa for (int i=0; i < results.length; i++) { results[i] = "Failed"; } - + return new SetFirewallRulesAnswer(cmd, false, results); - } + } } catch (Throwable e) { s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to " @@ -684,11 +687,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); - } + } return new SetFirewallRulesAnswer(cmd, true, results); - } - + } + protected Answer execute(SetStaticNatRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); @@ -704,11 +707,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); - + if (rule.getProtocol() != null) { args += " -P " + rule.getProtocol().toLowerCase(); } - + args += " -d " + rule.getStringSrcPortRange(); args += " -G "; @@ -742,7 +745,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); - + assert(controlIp != null); LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); @@ -794,7 +797,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa args += " -s " + sb.toString(); } - + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + " /etc/haproxy/haproxy.cfg.new"); if (!result.first()) { @@ -1271,12 +1274,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; - deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); - deviceConfigSpecArray[0].setDevice(nic); - deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add); + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); + deviceConfigSpec.setDevice(nic); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when running PlugNicCommand"); } @@ -1319,12 +1322,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new UnPlugNicAnswer(cmd, true, "success"); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; - deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); - deviceConfigSpecArray[0].setDevice(nic); - deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.remove); + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); + deviceConfigSpec.setDevice(nic); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when running unplugNicCommand"); } @@ -1444,7 +1447,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa args += " -c "; args += "eth" + publicNicInfo.first(); - + args += " -g "; args += vlanGateway; @@ -1461,7 +1464,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } if (removeVif) { - + String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); int nicMasks = Integer.parseInt(nicMasksStr); nicMasks &= ~(1 << publicNicInfo.first().intValue()); @@ -1486,7 +1489,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { // TODO : probably need to set traffic shaping Pair networkInfo = null; - + if (!_nexusVSwitch) { networkInfo = HypervisorHostHelper.prepareNetwork(this._publicNetworkVSwitchName, "cloud.public", vmMo.getRunningHost(), vlanId, null, null, this._ops_timeout, true); @@ -1514,33 +1517,33 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; - deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); - deviceConfigSpecArray[0].setDevice(device); - deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.edit); - - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); + deviceConfigSpec.setDevice(device); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); + + vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when plugPublicNic"); } } catch(Exception e) { - + // restore allocation mask in case of exceptions String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); int nicMasks = Integer.parseInt(nicMasksStr); nicMasks &= ~(1 << nicIndex); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); - + throw e; } } - + private int allocPublicNicIndex(VirtualMachineMO vmMo) throws Exception { String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); if(nicMasksStr == null || nicMasksStr.isEmpty()) { throw new Exception("Could not find NIC allocation info"); } - + int nicMasks = Integer.parseInt(nicMasksStr); VirtualDevice[] nicDevices = vmMo.getNicDevices(); for(int i = 3; i < nicDevices.length; i++) { @@ -1550,7 +1553,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return i; } } - + throw new Exception("Could not allocate a free public NIC"); } @@ -1606,7 +1609,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected Answer execute(SavePasswordCommand cmd) { if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } @@ -1620,7 +1623,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + controlIp + ", /root/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } - + args += " -p " + password; @@ -1655,11 +1658,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String args = " " + cmd.getVmMac(); args += " " + cmd.getVmIpAddress(); args += " " + cmd.getVmName(); - + if (cmd.getDefaultRouter() != null) { args += " " + cmd.getDefaultRouter(); } - + if (cmd.getDefaultDns() != null) { args += " " + cmd.getDefaultDns(); } @@ -1667,7 +1670,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (cmd.getStaticRoutes() != null) { args += " " + cmd.getStaticRoutes(); } - + if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); } @@ -1696,7 +1699,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new Answer(cmd); } - + protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd)); @@ -1759,7 +1762,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } return new CheckRouterAnswer(cmd, result.second(), true); } - + protected Answer execute(GetDomRVersionCmd cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource GetDomRVersionCmd: " + _gson.toJson(cmd)); @@ -1793,7 +1796,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); } - + protected Answer execute(BumpUpPriorityCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource BumpUpPriorityCommand: " + _gson.toJson(cmd)); @@ -1834,7 +1837,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); - + String vmIpAddress = cmd.getVmIpAddress(); List vmData = cmd.getVmData(); String[] vmDataArgs = new String[vmData.size() * 2 + 4]; @@ -1960,7 +1963,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); - + State state = State.Stopped; VmwareContext context = getServiceContext(); try { @@ -1974,7 +1977,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.valueOf(vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER)); if(s_logger.isDebugEnabled()) s_logger.debug("VM " + vmName + " will be started with NIC device type: " + nicDeviceType); - + VmwareHypervisorHost hyperHost = getHyperHost(context); VolumeTO[] disks = validateDisks(vmSpec.getDisks()); assert (disks.length > 0); @@ -2020,7 +2023,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } assert (vmSpec.getSpeed() != null) && (rootDiskDataStoreDetails != null); - if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), + if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), vmSpec.getLimitCpuUse(), ramMb, getReserveMemMB(ramMb), translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmName); @@ -2052,10 +2055,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); - VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), + VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), ramMb, getReserveMemMB(ramMb), translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse()); - + VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; int ideControllerKey = vmMo.getIDEDeviceControllerKey(); @@ -2072,7 +2075,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); - + ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; @@ -2081,17 +2084,17 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); - Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), + Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), true, true, i, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } i++; } else { @@ -2107,11 +2110,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } else { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); @@ -2120,13 +2123,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); + + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } i++; @@ -2178,11 +2181,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); } deviceConfigSpecArray[i].setDevice(device); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); - + i++; } } @@ -2206,32 +2209,32 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), i, i + 1, true, true); } - + deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(nic); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); - + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); + if(s_logger.isDebugEnabled()) s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i])); - + // this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3 if(nicCount < 3) nicMask |= (1 << nicCount); - + i++; nicCount++; } - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + vmConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray)); // pass boot arguments through machine.id & perform customized options to VMX - + Map vmDetailOptions = validateVmDetails(vmSpec.getDetails()); OptionValue[] extraOptions = new OptionValue[2 + vmDetailOptions.size()]; extraOptions[0] = new OptionValue(); extraOptions[0].setKey("machine.id"); extraOptions[0].setValue(vmSpec.getBootArgs()); - + extraOptions[1] = new OptionValue(); extraOptions[1].setKey("devices.hotplug"); extraOptions[1].setValue("true"); @@ -2243,16 +2246,16 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa extraOptions[j].setValue(entry.getValue()); j++; } - + String keyboardLayout = null; if(vmSpec.getDetails() != null) keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD); - vmConfigSpec.setExtraConfig(configureVnc(extraOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout)); + vmConfigSpec.getExtraConfig().addAll(Arrays.asList(configureVnc(extraOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout))); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure VM before start. vmName: " + vmName); } - + vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask)); if (!vmMo.powerOn()) { @@ -2280,10 +2283,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } } - + private Map validateVmDetails(Map vmDetails) { Map validatedDetails = new HashMap(); - + if(vmDetails != null && vmDetails.size() > 0) { for(Map.Entry entry : vmDetails.entrySet()) { if("machine.id".equalsIgnoreCase(entry.getKey())) @@ -2309,18 +2312,18 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if(this._reserveCpu) { return (int)(cpuMHz / this._cpuOverprovisioningFactor); } - + return 0; } - + private int getReserveMemMB(int memMB) { if(this._reserveMem) { return (int)(memMB / this._memOverprovisioningFactor); } - + return 0; } - + private NicTO[] sortNicsByDeviceId(NicTO[] nics) { List listForSort = new ArrayList(); @@ -2343,7 +2346,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return listForSort.toArray(new NicTO[0]); } - + private VolumeTO[] sortVolumesByDeviceId(VolumeTO[] volumes) { List listForSort = new ArrayList(); @@ -2407,38 +2410,38 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } private Pair prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo) throws Exception { - + Pair switchName = getTargetSwitch(nicTo); String namePrefix = getNetworkNamePrefix(nicTo); Pair networkInfo = null; s_logger.info("Prepare network on vSwitch: " + switchName + " with name prefix: " + namePrefix); - + if(!_nexusVSwitch) { - networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), - nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, + networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), + nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, !namePrefix.startsWith("cloud.private")); } else { - networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), + networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout); } - + return networkInfo; } - + // return Pair private Pair getTargetSwitch(NicTO nicTo) throws Exception { if(nicTo.getName() != null && !nicTo.getName().isEmpty()) { String[] tokens = nicTo.getName().split(","); - + if(tokens.length == 2) { return new Pair(tokens[0], tokens[1]); } else { return new Pair(nicTo.getName(), Vlan.UNTAGGED); } } - + if (nicTo.getType() == Networks.TrafficType.Guest) { return new Pair(this._guestNetworkVSwitchName, Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { @@ -2453,7 +2456,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } } - + private String getNetworkNamePrefix(NicTO nicTo) throws Exception { if (nicTo.getType() == Networks.TrafficType.Guest) { return "cloud.guest"; @@ -2606,7 +2609,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ReadyCommand: " + _gson.toJson(cmd)); } - + try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); @@ -2628,7 +2631,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); - + HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), 0, 0, 0, "host", 0, 0, 0, 0); Answer answer = new GetHostStatsAnswer(cmd, hostStats); try { @@ -2735,9 +2738,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa try { vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, "0"); - + if (getVmState(vmMo) != State.Stopped) { - + // before we stop VM, remove all possible snapshots on the VM to let // disk chain be collapsed s_logger.info("Remove all snapshot before stopping VM " + cmd.getVmName()); @@ -2815,7 +2818,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa try { vmMo.rebootGuest(); return new RebootAnswer(cmd, "reboot succeeded", true); - } catch(ToolsUnavailable e) { + } catch(ToolsUnavailableFaultMsg e) { s_logger.warn("VMware tools is not installed at guest OS, we will perform hard reset for reboot"); } catch(Exception e) { s_logger.warn("We are not able to perform gracefull guest reboot due to " + VmwareHelper.getExceptionMessage(e)); @@ -2919,7 +2922,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); - + ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; @@ -2997,11 +3000,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } private VmwareHypervisorHost getTargetHyperHost(DatacenterMO dcMo, String destIp) throws Exception { - + VmwareManager mgr = dcMo.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - ObjectContent[] ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); - if (ocs != null && ocs.length > 0) { + + List ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); + if (ocs != null && ocs.size() > 0) { for (ObjectContent oc : ocs) { HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj()); VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo)); @@ -3034,7 +3037,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ManagedObjectReference morDatastore = null; morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if(morDatastore == null) - morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), + morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid().replace("-", "")); assert (morDatastore != null); @@ -3065,7 +3068,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa try { // We will leave datastore cleanup management to vCenter. Since for cluster VMFS datastore, it will always // be mounted by vCenter. - + // VmwareHypervisorHost hyperHost = this.getHyperHost(getServiceContext()); // hyperHost.unmountDatastore(pool.getUuid()); Answer answer = new Answer(cmd, true, "success"); @@ -3439,7 +3442,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName()); } } - + Pair portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (s_logger.isTraceEnabled()) { @@ -3486,7 +3489,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if(result.first()) return new Answer(cmd); } catch (Exception e) { - s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new Answer(cmd,false,"PingTestCommand failed"); @@ -3547,11 +3550,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa /* * DestroyCommand content example - * + * * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType": * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } } - * + * * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem", * "poolId":0,"deviceId":0 } } @@ -3574,7 +3577,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO clusterMo = new ClusterMO(context, morCluster); - + if (cmd.getVolume().getType() == Volume.Type.ROOT) { String vmName = cmd.getVmName(); if (vmName != null) { @@ -3586,13 +3589,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa HostMO hostMo = vmMo.getRunningHost(); List networks = vmMo.getNetworksWithDetails(); - + // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.destroy(); - + for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { @@ -3600,12 +3603,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } } - } - + } + if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); - + // root volume may be created via linked-clone, delete the delta disk as well if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-delta.vmdk"); @@ -3622,7 +3625,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (vmMo != null) { if (s_logger.isInfoEnabled()) s_logger.info("Destroy template volume " + cmd.getVolume().getPath()); - + vmMo.destroy(); return new Answer(cmd, true, "Success"); } @@ -3645,7 +3648,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name"); } dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); - + if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-flat.vmdk"); } @@ -3656,7 +3659,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); } dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); - + if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-flat.vmdk"); } @@ -3683,7 +3686,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa * NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms = * networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) { * s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); } - * + * * hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) { * s_logger.warn("Unable to cleanup network due to exception, skip for next time"); } */ @@ -3767,7 +3770,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.warn("Template host in vSphere is not in connected state, request template reload"); return new CreateAnswer(cmd, "Template host in vSphere is not in connected state, request template reload", true); } - + ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); @@ -3796,7 +3799,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); - + dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); @@ -3861,21 +3864,21 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmConfig.setName(vmName); vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB vmConfig.setNumCPUs(1); - vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString()); + vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); - scsiController.setSharedBus(VirtualSCSISharing.noSharing); + scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); - scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec }); + vmConfig.getDeviceChange().add(scsiControllerSpec ); hyperHost.createVm(vmConfig); vmMo = hyperHost.findVmOnHyperHost(vmName); return vmMo; @@ -3902,25 +3905,25 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - + if(hyperHost.isHyperHostConnected()) { mgr.gcLeftOverVMs(context); - + if(_recycleHungWorker) { s_logger.info("Scan hung worker VM to recycle"); - + // GC worker that has been running for too long ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost( new String[] {"name", "config.template", "runtime.powerState", "runtime.bootTime"}); if(ocs != null) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { String name = null; boolean template = false; - VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; + VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; GregorianCalendar bootTime = null; - + for(DynamicProperty prop : props) { if(prop.getName().equals("name")) name = prop.getVal().toString(); @@ -3928,22 +3931,22 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa template = (Boolean)prop.getVal(); else if(prop.getName().equals("runtime.powerState")) powerState = (VirtualMachinePowerState)prop.getVal(); - else if(prop.getName().equals("runtime.bootTime")) + else if(prop.getName().equals("runtime.bootTime")) bootTime = (GregorianCalendar)prop.getVal(); } - + if(!template && name.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { boolean recycle = false; - + // recycle stopped worker VM and VM that has been running for too long (hard-coded 10 hours for now) - if(powerState == VirtualMachinePowerState.poweredOff) + if(powerState == VirtualMachinePowerState.POWERED_OFF) recycle = true; else if(bootTime != null && (new Date().getTime() - bootTime.getTimeInMillis() > 10*3600*1000)) recycle = true; - + if(recycle) { s_logger.info("Recycle pending worker VM: " + name); - + VirtualMachineMO vmMo = new VirtualMachineMO(hyperHost.getContext(), oc.getObj()); vmMo.powerOff(); vmMo.destroy(); @@ -3984,17 +3987,17 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.info("Host " + hyperHost.getHyperHostName() + " is not in connected state"); return null; } - + AboutInfo aboutInfo = ((HostMO)hyperHost).getHostAboutInfo(); hostApiVersion = aboutInfo.getApiVersion(); - + } catch (Exception e) { String msg = "VmwareResource intialize() failed due to : " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); invalidateServiceContext(); return null; } - + StartupRoutingCommand cmd = new StartupRoutingCommand(); fillHostInfo(cmd); @@ -4040,7 +4043,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa DatastoreSummary dsSummary = dsMo.getSummary(); String address = hostMo.getHostName(); - StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().get_value(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); + StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().getValue(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setName(poolUuid); cmd.setPoolInfo(pInfo); @@ -4078,7 +4081,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa fillHostHardwareInfo(serviceContext, cmd); fillHostNetworkInfo(serviceContext, cmd); fillHostDetailsInfo(serviceContext, details); - } catch (RuntimeFault e) { + } catch (RuntimeFaultFaultMsg e) { s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e); throw new CloudRuntimeException("RuntimeFault while retrieving host info"); } catch (RemoteException e) { @@ -4100,7 +4103,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); } - private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException, Exception { + private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException, Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary(); @@ -4116,14 +4119,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa cmd.setMemory(summary.getMemoryBytes()); } - private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException { + private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException { try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - + assert(hyperHost instanceof HostMO); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - + VmwareHypervisorHostNetworkSummary summary = hyperHost.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (summary == null) { throw new Exception("No ESX(i) host found"); @@ -4152,7 +4155,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig(); - if (dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) { + if (dasConfig != null && dasConfig.isEnabled() != null && dasConfig.isEnabled().booleanValue()) { details.put("NativeHA", "true"); } } @@ -4223,7 +4226,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report but we detected that it might be migrated to other host by vCenter"); } - + if(oldState != State.Starting && oldState != State.Migrating) { s_logger.debug("VM " + vm + " is now missing from host report and VM is not at starting/migrating state, remove it from host VM-sync map, oldState: " + oldState); _vms.remove(vm); @@ -4270,22 +4273,22 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return hyperHost.findVmOnPeerHyperHost(vmName) != null; } - protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, + protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception { - + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(!mgr.beginExclusiveOperation(600)) throw new Exception("Unable to begin exclusive operation, lock time out"); - + try { int maxVncPorts = 64; int vncPort = 0; Random random = new Random(); - + HostMO vmOwnerHost = vmMo.getRunningHost(); - + ManagedObjectReference morParent = vmOwnerHost.getParentMor(); HashMap portInfo; if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { @@ -4294,7 +4297,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } else { portInfo = vmOwnerHost.getVmVncPortsOnHost(); } - + // allocate first at 5900 - 5964 range Collection existingPorts = portInfo.values(); int val = random.nextInt(maxVncPorts); @@ -4304,10 +4307,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vncPort = 5900 + val; break; } - + val = (++val) % maxVncPorts; } while (val != startVal); - + if(vncPort == 0) { s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); @@ -4320,19 +4323,19 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vncPort = additionalRange.first() + val; break; } - + val = (++val) % maxVncPorts; } while (val != startVal); } - + if (vncPort == 0) { throw new Exception("Unable to find an available VNC port on host"); } - + if (s_logger.isInfoEnabled()) { s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); } - + return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); } finally { try { @@ -4356,9 +4359,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } if (cpuArchitecture.equalsIgnoreCase("x86_64")) { - return VirtualMachineGuestOsIdentifier.otherGuest64; + return VirtualMachineGuestOsIdentifier.OTHER_GUEST_64; } - return VirtualMachineGuestOsIdentifier.otherGuest; + return VirtualMachineGuestOsIdentifier.OTHER_GUEST; } private void prepareNetworkForVmTargetHost(HostMO hostMo, VirtualMachineMO vmMo) throws Exception { @@ -4377,7 +4380,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String[] tokens = networkName.split("\\."); if (tokens.length == 3) { Integer networkRateMbps = null; - if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) { + if (shapingPolicy != null && shapingPolicy.isEnabled() != null && shapingPolicy.isEnabled().booleanValue()) { networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024)); } String vlanId = null; @@ -4393,7 +4396,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String[] tokens = networkName.split("\\."); if (tokens.length == 3) { Integer networkRateMbps = null; - if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) { + if (shapingPolicy != null && shapingPolicy.isEnabled() != null && shapingPolicy.isEnabled().booleanValue()) { networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024)); } String vlanId = null; @@ -4409,7 +4412,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String[] tokens = networkName.split("\\."); if (tokens.length >= 3) { Integer networkRateMbps = null; - if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) { + if (shapingPolicy != null && shapingPolicy.isEnabled() != null && shapingPolicy.isEnabled().booleanValue()) { networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024)); } @@ -4427,7 +4430,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } } - + private HashMap getVmStates() throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", "runtime.powerState", "config.template" }); @@ -4435,12 +4438,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa HashMap newStates = new HashMap(); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); + List objProps = oc.getPropSet(); if (objProps != null) { boolean isTemplate = false; String name = null; - VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; + VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("config.template")) { if (objProp.getVal().toString().equalsIgnoreCase("true")) { @@ -4467,14 +4470,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa private HashMap getVmStats(List vmNames) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); HashMap vmResponseMap = new HashMap(); - ManagedObjectReference perfMgr = getServiceContext().getServiceConnection().getServiceContent().getPerfManager(); - VimPortType service = getServiceContext().getServiceConnection().getService(); + ManagedObjectReference perfMgr = getServiceContext().getServiceContent().getPerfManager(); + VimPortType service = getServiceContext().getService(); PerfCounterInfo rxPerfCounterInfo = null; PerfCounterInfo txPerfCounterInfo = null; - PerfCounterInfo[] cInfo = (PerfCounterInfo[]) getServiceContext().getServiceUtil().getDynamicProperty(perfMgr, "perfCounter"); + PerfCounterInfo[] cInfo = (PerfCounterInfo[]) getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); for(int i=0; i 0) { for (ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); + List objProps = oc.getPropSet(); if (objProps != null) { String name = null; String numberCPUs = null; @@ -4511,13 +4514,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa assert(vmMor!=null); ArrayList vmNetworkMetrics = new ArrayList(); - // get all the metrics from the available sample period - PerfMetricId[] perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null); + // get all the metrics from the available sample period + List perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null); if(perfMetrics != null) { - for(int index=0; index < perfMetrics.length; ++index) { - if ( ((rxPerfCounterInfo != null) && (perfMetrics[index].getCounterId() == rxPerfCounterInfo.getKey())) || - ((txPerfCounterInfo != null) && (perfMetrics[index].getCounterId() == txPerfCounterInfo.getKey())) ) { - vmNetworkMetrics.add(perfMetrics[index]); + for(int index=0; index < perfMetrics.size(); ++index) { + if ( ((rxPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == rxPerfCounterInfo.getKey())) || + ((txPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == txPerfCounterInfo.getKey())) ) { + vmNetworkMetrics.add(perfMetrics.get(index)); } } } @@ -4530,23 +4533,26 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa PerfQuerySpec qSpec = new PerfQuerySpec(); qSpec.setEntity(vmMor); PerfMetricId[] availableMetricIds = (PerfMetricId[]) vmNetworkMetrics.toArray(new PerfMetricId[0]); - qSpec.setMetricId(availableMetricIds); - PerfQuerySpec[] qSpecs = new PerfQuerySpec[] {qSpec}; - PerfEntityMetricBase[] values = service.queryPerf(perfMgr, qSpecs); + qSpec.getMetricId().addAll(Arrays.asList(availableMetricIds)); + List qSpecs = new ArrayList(); + qSpecs.add(qSpec); + List values = service.queryPerf(perfMgr, qSpecs); - for(int i=0; i infos = ((PerfEntityMetric)values.get(i)).getSampleInfo(); + int endMs = infos.get(infos.size()-1).getTimestamp().getSecond() * 1000 + infos.get(infos.size()-1).getTimestamp().getMillisecond(); + int beginMs = infos.get(0).getTimestamp().getSecond() * 1000 + infos.get(0).getTimestamp().getMillisecond(); + sampleDuration = (endMs - beginMs) /1000; + List vals = ((PerfEntityMetric)values.get(i)).getValue(); + for(int vi = 0; ((vals!= null) && (vi < vals.size())); ++vi){ + if(vals.get(vi) instanceof PerfMetricIntSeries) { + PerfMetricIntSeries val = (PerfMetricIntSeries)vals.get(vi); + List perfValues = val.getValue(); + if (vals.get(vi).getId().getCounterId() == rxPerfCounterInfo.getKey()) { + networkReadKBs = sampleDuration * perfValues.get(3); //get the average RX rate multiplied by sampled duration } - if (vals[vi].getId().getCounterId() == txPerfCounterInfo.getKey()) { - networkWriteKBs = sampleDuration * perfValues[3];//get the average TX rate multiplied by sampled duration + if (vals.get(vi).getId().getCounterId() == txPerfCounterInfo.getKey()) { + networkWriteKBs = sampleDuration * perfValues.get(3);//get the average TX rate multiplied by sampled duration } } } @@ -4556,8 +4562,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } } - return vmResponseMap; - } + return vmResponseMap; + } protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { String args = null; @@ -4590,7 +4596,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return result.second(); } catch (Throwable e) { - s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } @@ -4681,7 +4687,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ComputeResourceSummary hardwareSummary = hyperHost.getHyperHostHardwareSummary(); if(hardwareSummary == null) return null; - + HostStatsEntry entry = new HostStatsEntry(); entry.setEntityType("host"); @@ -4692,19 +4698,19 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return entry; } - + private static String getRouterSshControlIp(NetworkElementCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); - + if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { if(s_logger.isDebugEnabled()) s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); - + return routerGuestIp; } - + if(s_logger.isDebugEnabled()) s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); return routerIp; @@ -4724,15 +4730,15 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa _dcId = (String) params.get("zone"); _pod = (String) params.get("pod"); _cluster = (String) params.get("cluster"); - + _guid = (String) params.get("guid"); String[] tokens = _guid.split("@"); _vCenterAddress = tokens[1]; _morHyperHost = new ManagedObjectReference(); String[] hostTokens = tokens[0].split(":"); _morHyperHost.setType(hostTokens[0]); - _morHyperHost.set_value(hostTokens[1]); - + _morHyperHost.setValue(hostTokens[1]); + VmwareContext context = getServiceContext(); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); @@ -4770,14 +4776,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if(_privateNetworkVSwitchName == null) { _privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name"); - } + } if(_publicNetworkVSwitchName == null) { _publicNetworkVSwitchName = (String) params.get("public.network.vswitch.name"); } if(_guestNetworkVSwitchName == null) { _guestNetworkVSwitchName = (String) params.get("guest.network.vswitch.name"); } - + String value = (String) params.get("cpu.overprovisioning.factor"); if(value != null) _cpuOverprovisioningFactor = Float.parseFloat(value); @@ -4785,7 +4791,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa value = (String) params.get("vmware.reserve.cpu"); if(value != null && value.equalsIgnoreCase("true")) _reserveCpu = true; - + value = (String) params.get("vmware.recycle.hung.wokervm"); if(value != null && value.equalsIgnoreCase("true")) _recycleHungWorker = true; @@ -4797,7 +4803,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa value = (String) params.get("vmware.reserve.mem"); if(value != null && value.equalsIgnoreCase("true")) _reserveMem = true; - + value = (String)params.get("vmware.root.disk.controller"); if(value != null && value.equalsIgnoreCase("scsi")) _rootDiskController = DiskControllerType.scsi; @@ -4848,7 +4854,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa _serviceContext = VmwareContextFactory.create(_vCenterAddress, _username, _password); VmwareHypervisorHost hyperHost = getHyperHost(_serviceContext, cmd); assert(hyperHost instanceof HostMO); - + HostFirewallSystemMO firewallMo = ((HostMO)hyperHost).getHostFirewallSystemMO(); boolean bRefresh = false; if(firewallMo != null) { @@ -4864,7 +4870,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } } - + if(bRefresh) firewallMo.refreshFirewall(); } diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java index fc298c895c8..646ef633fc7 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.storage.resource; @@ -20,45 +20,44 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.apputils.version.ExtendedAppUtil; public class VmwareSecondaryStorageContextFactory { private static volatile int s_seq = 1; - + private static Map s_contextMap = new HashMap(); - + public static void initFactoryEnvironment() { System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); } - + public static VmwareContext create(String vCenterAddress, String vCenterUserName, String vCenterPassword) throws Exception { assert(vCenterAddress != null); assert(vCenterUserName != null); assert(vCenterPassword != null); - + VmwareContext context = null; - + synchronized(s_contextMap) { context = s_contextMap.get(vCenterAddress); if(context == null) { String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService"; - String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; - ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params); - - appUtil.connect(); - context = new VmwareContext(appUtil, vCenterAddress); + //String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; + VmwareClient vimClient = new VmwareClient(vCenterAddress + "-" + s_seq++); + vimClient.connect(serviceUrl, vCenterUserName, vCenterPassword); + context = new VmwareContext(vimClient, vCenterAddress); context.registerStockObject("username", vCenterUserName); context.registerStockObject("password", vCenterPassword); - + s_contextMap.put(vCenterAddress, context); } } - + assert(context != null); return context; } - + public static void invalidate(VmwareContext context) { synchronized(s_contextMap) { for(Iterator> entryIter = s_contextMap.entrySet().iterator(); entryIter.hasNext();) { @@ -68,7 +67,7 @@ public class VmwareSecondaryStorageContextFactory { } } } - + context.close(); } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java index 2abed160dfc..566e750c3fe 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java +++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java @@ -11,7 +11,7 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.storage.resource; @@ -85,11 +85,11 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe if(cmd.getContextParam("execid") != null) { answer.setContextParam("execid", cmd.getContextParam("execid")); } - + if(cmd.getContextParam("checkpoint") != null) { answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint")); } - + if(cmd.getContextParam("checkpoint2") != null) { answer.setContextParam("checkpoint2", cmd.getContextParam("checkpoint2")); } @@ -219,23 +219,23 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe } morHyperHost.setType(hostTokens[0]); - morHyperHost.set_value(hostTokens[1]); + morHyperHost.setValue(hostTokens[1]); if(morHyperHost.getType().equalsIgnoreCase("HostSystem")) { HostMO hostMo = new HostMO(context, morHyperHost); try { - + ManagedObjectReference mor = hostMo.getHyperHostCluster(); ClusterMO clusterMo = new ClusterMO(hostMo.getContext(), mor); List> hostsInCluster = clusterMo.getClusterHosts(); for(Pair hostPair : hostsInCluster) { HostMO hostIteratorMo = new HostMO(hostMo.getContext(), hostPair.first()); - + VmwareHypervisorHostNetworkSummary netSummary = hostIteratorMo.getHyperHostNetworkSummary( hostIteratorMo.getHostType() == VmwareHostType.ESXi ? cmd.getContextParam("manageportgroup") : cmd.getContextParam("serviceconsole")); _resource.ensureOutgoingRuleForAddress(netSummary.getHostIp()); - + s_logger.info("Setup firewall rule for host: " + netSummary.getHostIp()); } } catch(Throwable e) { @@ -253,7 +253,7 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) { assert(cmd.getContextParam("worker") != null); assert(workerSequence < 2); - + if(workerSequence == 0) return cmd.getContextParam("worker"); return cmd.getContextParam("worker2"); @@ -276,7 +276,7 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe assert(hostTokens.length == 2); morHyperHost.setType(hostTokens[0]); - morHyperHost.set_value(hostTokens[1]); + morHyperHost.setValue(hostTokens[1]); if(morHyperHost.getType().equalsIgnoreCase("HostSystem")) { HostMO hostMo = new HostMO(context, morHyperHost); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java index ff7e00436ea..0ac93e4cd6a 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java @@ -25,55 +25,55 @@ import com.vmware.vim25.ManagedObjectReference; public class BaseMO { private static final Logger s_logger = Logger.getLogger(BaseMO.class); - + protected VmwareContext _context; protected ManagedObjectReference _mor; private String _name; - + public BaseMO(VmwareContext context, ManagedObjectReference mor) { assert(context != null); - + _context = context; _mor = mor; } - + public BaseMO(VmwareContext context, String morType, String morValue) { assert(context != null); assert(morType != null); assert(morValue != null); - + _context = context; _mor = new ManagedObjectReference(); _mor.setType(morType); - _mor.set_value(morValue); + _mor.setValue(morValue); } - + public VmwareContext getContext() { return _context; } - + public ManagedObjectReference getMor() { assert(_mor != null); return _mor; } - + public ManagedObjectReference getParentMor() throws Exception { - return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "parent"); + return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "parent"); } public String getName() throws Exception { if(_name == null) - _name = (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); - + _name = (String)_context.getVimClient().getDynamicProperty(_mor, "name"); + return _name; } - + public boolean destroy() throws Exception { - ManagedObjectReference morTask = _context.getService().destroy_Task(_mor); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + ManagedObjectReference morTask = _context.getService().destroyTask(_mor); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -81,16 +81,16 @@ public class BaseMO { } return false; } - + public void reload() throws Exception { _context.getService().reload(_mor); } - + public boolean rename(String newName) throws Exception { - ManagedObjectReference morTask = _context.getService().rename_Task(_mor, newName); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + ManagedObjectReference morTask = _context.getService().renameTask(_mor, newName); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -98,11 +98,11 @@ public class BaseMO { } return false; } - + public void setCustomFieldValue(String fieldName, String value) throws Exception { - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager()); - + int key = getCustomFieldKey(fieldName); if(key == 0) { try { @@ -114,36 +114,36 @@ public class BaseMO { key = getCustomFieldKey(fieldName); } } - + if(key == 0) throw new Exception("Unable to setup custom field facility"); - + cfmMo.setField(getMor(), key, value); } - + public String getCustomFieldValue(String fieldName) throws Exception { int key = getCustomFieldKey(fieldName); if(key == 0) return null; - - CustomFieldStringValue cfValue = (CustomFieldStringValue)_context.getServiceUtil().getDynamicProperty(getMor(), + + CustomFieldStringValue cfValue = (CustomFieldStringValue)_context.getVimClient().getDynamicProperty(getMor(), String.format("value[%d]", key)); if(cfValue != null) return cfValue.getValue(); - + return null; } - + public int getCustomFieldKey(String fieldName) throws Exception { return getCustomFieldKey(getMor().getType(), fieldName); } - + public int getCustomFieldKey(String morType, String fieldName) throws Exception { assert(morType != null); - - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager()); - + return cfmMo.getCustomFieldKey(morType, fieldName); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java index 2ce6695befb..10265545bf4 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java @@ -26,7 +26,6 @@ import org.apache.log4j.Logger; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.Pair; import com.google.gson.Gson; -import com.vmware.apputils.vim25.ServiceUtil; import com.vmware.vim25.ArrayOfHostIpRouteEntry; import com.vmware.vim25.ClusterComputeResourceSummary; import com.vmware.vim25.ClusterConfigInfoEx; @@ -47,24 +46,25 @@ import com.vmware.vim25.ObjectSpec; import com.vmware.vim25.OptionValue; import com.vmware.vim25.PropertyFilterSpec; import com.vmware.vim25.PropertySpec; -import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.TraversalSpec; import com.vmware.vim25.VirtualMachineConfigSpec; +import edu.emory.mathcs.backport.java.util.Arrays; + // // interface. This has changed as ClusterMO no longer works as a special host anymore. Need to refactor accordingly // public class ClusterMO extends BaseMO implements VmwareHypervisorHost { private static final Logger s_logger = Logger.getLogger(ClusterMO.class); - + public ClusterMO(VmwareContext context, ManagedObjectReference morCluster) { super(context, morCluster); } - + public ClusterMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + @Override public String getHyperHostName() throws Exception { return getName(); @@ -73,40 +73,39 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { @Override public ClusterDasConfigInfo getDasConfig() throws Exception { // Note getDynamicProperty() with "configurationEx.dasConfig" does not work here because of that dasConfig is a property in subclass - ClusterConfigInfoEx configInfo = (ClusterConfigInfoEx)_context.getServiceUtil().getDynamicProperty(_mor, "configurationEx"); + ClusterConfigInfoEx configInfo = (ClusterConfigInfoEx)_context.getVimClient().getDynamicProperty(_mor, "configurationEx"); return configInfo.getDasConfig(); } - + @Override public ManagedObjectReference getHyperHostDatacenter() throws Exception { Pair dcPair = DatacenterMO.getOwnerDatacenter(getContext(), getMor()); assert(dcPair != null); return dcPair.first().getMor(); } - + @Override public ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception { - ServiceUtil serviceUtil = _context.getServiceUtil(); - return (ManagedObjectReference)serviceUtil.getDynamicProperty(getMor(), "resourcePool"); + return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(getMor(), "resourcePool"); } - + @Override public ManagedObjectReference getHyperHostCluster() throws Exception { return _mor; } - + @Override public VirtualMachineMO findVmOnHyperHost(String name) throws Exception { ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] { "name" }); return HypervisorHostHelper.findVmFromObjectContent(_context, ocs, name); } - + @Override public VirtualMachineMO findVmOnPeerHyperHost(String name) throws Exception { ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] { "name" }); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { for(DynamicProperty prop : props) { if(prop.getVal().toString().equals(name)) @@ -117,54 +116,54 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { } return null; } - + @Override public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths)); - + s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths)); + PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); - pSpec.setPathSet(propertyPaths); + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); TraversalSpec host2VmFolderTraversal = new TraversalSpec(); host2VmFolderTraversal.setType("HostSystem"); host2VmFolderTraversal.setPath("vm"); host2VmFolderTraversal.setName("host2VmFolderTraversal"); - + TraversalSpec cluster2HostFolderTraversal = new TraversalSpec(); cluster2HostFolderTraversal.setType("ClusterComputeResource"); cluster2HostFolderTraversal.setPath("host"); cluster2HostFolderTraversal.setName("cluster2HostFolderTraversal"); - cluster2HostFolderTraversal.setSelectSet(new SelectionSpec[] { host2VmFolderTraversal }); - + cluster2HostFolderTraversal.getSelectSet().add(host2VmFolderTraversal); + ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(getMor()); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { cluster2HostFolderTraversal }); - + oSpec.getSelectSet().add(cluster2HostFolderTraversal); + PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List properties = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr); + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; + return properties.toArray(new ObjectContent[properties.size()]); } @Override public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths)); - + s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths)); + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec cluster2DatastoreTraversal = new TraversalSpec(); cluster2DatastoreTraversal.setType("ClusterComputeResource"); cluster2DatastoreTraversal.setPath("datastore"); @@ -173,29 +172,30 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { cluster2DatastoreTraversal }); + oSpec.getSelectSet().add(cluster2DatastoreTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List properties = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; + return properties.toArray(new ObjectContent[properties.size()]); } - + private ObjectContent[] getHostPropertiesOnCluster(String[] propertyPaths) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - retrieveProperties() on Host properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths)); + s_logger.trace("vCenter API trace - retrieveProperties() on Host properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("HostSystem"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec cluster2HostTraversal = new TraversalSpec(); cluster2HostTraversal.setType("ClusterComputeResource"); cluster2HostTraversal.setPath("host"); @@ -204,63 +204,65 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { cluster2HostTraversal }); + oSpec.getSelectSet().add(cluster2HostTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List properties = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; + return properties.toArray(new ObjectContent[properties.size()]); } @Override public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.get_value() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec)); - + s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.getValue() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec)); + assert(vmSpec != null); DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); - - ManagedObjectReference morTask = _context.getService().createVM_Task( + + ManagedObjectReference morTask = _context.getService().createVMTask( dcMo.getVmFolder(), vmSpec, morPool, null); - String result = _context.getServiceUtil().waitForTask(morTask); - - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + + if(result) { _context.waitForTaskProgressDone(morTask); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createVM_Task() done(successfully)"); return true; } else { s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createVM_Task() done(failed)"); return false; } - + @Override public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.get_value() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName - + ", datastore: " + dsMo.getMor().get_value() + ", diskOption: " + diskOption); + s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + + ", datastore: " + dsMo.getMor().getValue() + ", diskOption: " + diskOption); ManagedObjectReference morRp = getHyperHostOwnerResourcePool(); assert(morRp != null); - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.get_value()); - + s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.getValue()); + HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, null); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - importVmFromOVF() done"); } @@ -268,83 +270,83 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { @Override public boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.get_value() + ", vmName: " + vmName + ", cpuCount: " + cpuCount - + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB - + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.get_value() + ", snapshotDirToParent: " + snapshotDirToParent); - + s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount + + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB + + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent); + boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, memoryMB, memoryReserveMB, guestOsIdentifier, morDs, snapshotDirToParent); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createBlankVm() done"); - + return result; } @Override - public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress, + public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress, int poolHostPort, String poolPath, String poolUuid) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); - + ManagedObjectReference morDs = null; ManagedObjectReference morDsFirst = null; - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host"); + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); if(hosts != null && hosts.length > 0) { for(ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); morDs = hostMo.mountDatastore(vmfsDatastore, poolHostAddress, poolHostPort, poolPath, poolUuid); if(morDsFirst == null) morDsFirst = morDs; - + // assume datastore is in scope of datacenter - assert(morDsFirst.get_value().equals(morDs.get_value())); + assert(morDsFirst.getValue().equals(morDs.getValue())); } } - + if(morDs == null) { String msg = "Failed to mount datastore in all hosts within the cluster"; s_logger.error(msg); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore() done(failed)"); throw new Exception(msg); } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore() done(successfully)"); - + return morDs; } - + @Override public void unmountDatastore(String poolUuid) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid); - - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host"); + s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid); + + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); if(hosts != null && hosts.length > 0) { for(ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); hostMo.unmountDatastore(poolUuid); } } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - unmountDatastore() done"); } - + @Override public ManagedObjectReference findDatastore(String poolUuid) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - findDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid); - - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + s_logger.trace("vCenter API trace - findDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid); + + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager()); int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID); assert(key != 0); @@ -352,16 +354,16 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"name", String.format("value[%d]", key)}); if(ocs != null) { for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().equals(poolUuid)) + if(oc.getPropSet().get(0).getVal().equals(poolUuid)) return oc.getObj(); - - if(oc.getPropSet().length > 1) { - DynamicProperty prop = oc.getPropSet(1); + + if(oc.getPropSet().size() > 1) { + DynamicProperty prop = oc.getPropSet().get(1); if(prop != null && prop.getVal() != null) { if(prop.getVal() instanceof CustomFieldStringValue) { String val = ((CustomFieldStringValue)prop.getVal()).getValue(); if(val.equalsIgnoreCase(poolUuid)) { - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findDatastore() done(successfully)"); return oc.getObj(); @@ -371,31 +373,31 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { } } } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findDatastore() done(failed)"); return null; } - + @Override public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - findDatastoreByExportPath(). target MOR: " + _mor.get_value() + ", exportPath: " + exportPath); - + s_logger.trace("vCenter API trace - findDatastoreByExportPath(). target MOR: " + _mor.getValue() + ", exportPath: " + exportPath); + ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"info"}); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet(0).getVal(); + DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet().get(0).getVal(); if(dsInfo != null && dsInfo instanceof NasDatastoreInfo) { NasDatastoreInfo info = (NasDatastoreInfo)dsInfo; if(info != null) { String vmwareUrl = info.getUrl(); if(vmwareUrl.charAt(vmwareUrl.length() - 1) == '/') vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1); - + URI uri = new URI(vmwareUrl); if(uri.getPath().equals("/" + exportPath)) { - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(successfully)"); return oc.getObj(); @@ -404,49 +406,49 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { } } } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(failed)"); return null; } - + @Override public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.get_value() + ", vm: " + vmMo.getName()); + s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.getValue() + ", vm: " + vmMo.getName()); - ClusterHostRecommendation[] candidates = recommendHostsForVm(vmMo); - if(candidates != null && candidates.length > 0) { + List candidates = recommendHostsForVm(vmMo); + if(candidates != null && candidates.size() > 0) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findMigrationTarget() done(successfully)"); - return candidates[0].getHost(); + return candidates.get(0).getHost(); } if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findMigrationTarget() done(failed)"); return null; } - + @Override public boolean isHyperHostConnected() throws Exception { ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"runtime"}); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)oc.getPropSet(0).getVal(); - // as long as we have one host connected, we assume the cluster is up - if(runtimeInfo.getConnectionState() == HostSystemConnectionState.connected) + HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)oc.getPropSet().get(0).getVal(); + // as long as we have one host connected, we assume the cluster is up + if(runtimeInfo.getConnectionState() == HostSystemConnectionState.CONNECTED) return true; } } return false; } - + @Override public String getHyperHostDefaultGateway() throws Exception { ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"config.network.routeTableInfo.ipRoute"}); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - ArrayOfHostIpRouteEntry entries = (ArrayOfHostIpRouteEntry)oc.getPropSet(0).getVal(); + ArrayOfHostIpRouteEntry entries = (ArrayOfHostIpRouteEntry)oc.getPropSet().get(0).getVal(); if(entries != null) { for(HostIpRouteEntry entry : entries.getHostIpRouteEntry()) { if(entry.getNetwork().equalsIgnoreCase("0.0.0.0")) @@ -455,28 +457,28 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { } } } - + throw new Exception("Could not find host default gateway, host is not properly configured?"); } - + @Override public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.get_value()); + s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.getValue()); VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); - - ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getServiceUtil().getDynamicProperty( + + ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getVimClient().getDynamicProperty( _mor, "summary"); - - // TODO, need to use traversal to optimize retrieve of + + // TODO, need to use traversal to optimize retrieve of int cpuNumInCpuThreads = 1; - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host"); + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); if(hosts != null && hosts.length > 0) { for(ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); HostHardwareSummary hardwareSummary = hostMo.getHostHardwareSummary(); - + if(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuThreads() > cpuNumInCpuThreads) cpuNumInCpuThreads = hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuThreads(); } @@ -484,74 +486,74 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { summary.setCpuCount(cpuNumInCpuThreads); summary.setCpuSpeed(vmwareSummary.getTotalCpu()); summary.setMemoryBytes(vmwareSummary.getTotalMemory()); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done"); return summary; } - + @Override public VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String esxServiceConsolePort) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.get_value() + ", mgmtPortgroup: " + esxServiceConsolePort); - - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host"); + s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + esxServiceConsolePort); + + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); if(hosts != null && hosts.length > 0) { VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts[0]).getHyperHostNetworkSummary(esxServiceConsolePort); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(successfully)"); return summary; } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(failed)"); return null; } - + @Override public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.get_value()); + s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.getValue()); ClusterComputeResourceSummary hardwareSummary = (ClusterComputeResourceSummary) - _context.getServiceUtil().getDynamicProperty(_mor, "summary"); + _context.getVimClient().getDynamicProperty(_mor, "summary"); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostHardwareSummary() done"); return hardwareSummary; } - public ClusterHostRecommendation[] recommendHostsForVm(VirtualMachineMO vmMo) throws Exception { - return _context.getService().recommendHostsForVm(_mor, vmMo.getMor(), + public List recommendHostsForVm(VirtualMachineMO vmMo) throws Exception { + return _context.getService().recommendHostsForVm(_mor, vmMo.getMor(), getHyperHostOwnerResourcePool()); } - + public List> getClusterHosts() throws Exception { List> hosts = new ArrayList>(); - + ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"name"}); if(ocs != null) { for(ObjectContent oc : ocs) { ManagedObjectReference morHost = oc.getObj(); - String name = (String)oc.getPropSet(0).getVal(); - + String name = (String)oc.getPropSet().get(0).getVal(); + hosts.add(new Pair(morHost, name)); } } return hosts; } - + public HashMap getVmVncPortsOnCluster() throws Exception { ObjectContent[] ocs = getVmPropertiesOnHyperHost( new String[] { "name", "config.extraConfig[\"RemoteDisplay.vnc.port\"]" } ); - + HashMap portInfo = new HashMap(); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); + List objProps = oc.getPropSet(); if(objProps != null) { String name = null; String value = null; @@ -561,16 +563,16 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { } else { OptionValue optValue = (OptionValue)objProp.getVal(); value = (String)optValue.getValue(); - } + } } - + if(name != null && value != null) { portInfo.put(name, Integer.parseInt(value)); } } } } - + return portInfo; } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java index 44de683bb05..08932c5e5ba 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java @@ -26,32 +26,32 @@ public class CustomFieldsManagerMO extends BaseMO { public CustomFieldsManagerMO(VmwareContext context, ManagedObjectReference mor) { super(context, mor); } - + public CustomFieldsManagerMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - - public CustomFieldDef addCustomerFieldDef(String fieldName, String morType, + + public CustomFieldDef addCustomerFieldDef(String fieldName, String morType, PrivilegePolicyDef fieldDefPolicy, PrivilegePolicyDef fieldPolicy) throws Exception { return _context.getService().addCustomFieldDef(getMor(), fieldName, morType, fieldDefPolicy, fieldPolicy); } - + public void removeCustomFieldDef(int key) throws Exception { _context.getService().removeCustomFieldDef(getMor(), key); } - + public void renameCustomFieldDef(int key, String name) throws Exception { _context.getService().renameCustomFieldDef(getMor(), key, name); } - + public void setField(ManagedObjectReference morEntity, int key, String value) throws Exception { _context.getService().setField(getMor(), morEntity, key, value); } - + public CustomFieldDef[] getFields() throws Exception { - return (CustomFieldDef[])_context.getServiceUtil().getDynamicProperty(getMor(), "field"); + return (CustomFieldDef[])_context.getVimClient().getDynamicProperty(getMor(), "field"); } - + public int getCustomFieldKey(String morType, String fieldName) throws Exception { CustomFieldDef[] fields = getFields(); if(fields != null) { @@ -62,12 +62,12 @@ public class CustomFieldsManagerMO extends BaseMO { } return 0; } - + public int ensureCustomFieldDef(String morType, String fieldName) throws Exception { int key = getCustomFieldKey(morType, fieldName); if(key > 0) return key; - + try { CustomFieldDef field = addCustomerFieldDef(fieldName, morType, null, null); return field.getKey(); @@ -75,10 +75,10 @@ public class CustomFieldsManagerMO extends BaseMO { // assuming that someone is adding it key = getCustomFieldKey(morType, fieldName); } - + if(key == 0) throw new Exception("Unable to setup custom field facility for " + morType + ":" + fieldName); - + return key; } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java index eb10e167732..4cb0a619401 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java @@ -22,7 +22,6 @@ import java.util.List; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.Pair; -import com.vmware.apputils.vim25.ServiceUtil; import com.vmware.vim25.CustomFieldStringValue; import com.vmware.vim25.DVPortgroupConfigInfo; import com.vmware.vim25.DistributedVirtualSwitchPortConnection; @@ -34,59 +33,58 @@ import com.vmware.vim25.PropertyFilterSpec; import com.vmware.vim25.PropertySpec; import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.TraversalSpec; -import com.vmware.vim25.VirtualDeviceBackingInfo; import com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo; -import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo; +import edu.emory.mathcs.backport.java.util.Arrays; public class DatacenterMO extends BaseMO { - + public DatacenterMO(VmwareContext context, ManagedObjectReference morDc) { super(context, morDc); } - + public DatacenterMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public DatacenterMO(VmwareContext context, String dcName) throws Exception { super(context, null); - - _mor = _context.getServiceUtil().getDecendentMoRef(_context.getRootFolder(), "Datacenter", dcName); + + _mor = _context.getVimClient().getDecendentMoRef(_context.getRootFolder(), "Datacenter", dcName); assert(_mor != null); } - - public String getName() throws Exception { - return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); + + @Override + public String getName() throws Exception { + return (String)_context.getVimClient().getDynamicProperty(_mor, "name"); } - - public void registerTemplate(ManagedObjectReference morHost, String datastoreName, + + public void registerTemplate(ManagedObjectReference morHost, String datastoreName, String templateName, String templateFileName) throws Exception { - - ServiceUtil serviceUtil = _context.getServiceUtil(); - - ManagedObjectReference morFolder = (ManagedObjectReference)serviceUtil.getDynamicProperty( + + + ManagedObjectReference morFolder = (ManagedObjectReference)_context.getVimClient().getDynamicProperty( _mor, "vmFolder"); assert(morFolder != null); - - ManagedObjectReference morTask = _context.getService().registerVM_Task( - morFolder, + + ManagedObjectReference morTask = _context.getService().registerVMTask( + morFolder, String.format("[%s] %s/%s", datastoreName, templateName, templateFileName), - templateName, true, + templateName, true, null, morHost); - - String result = serviceUtil.waitForTask(morTask); - if (!result.equalsIgnoreCase("Sucess")) { + + boolean result = _context.getVimClient().waitForTask(morTask); + if (!result) { throw new Exception("Unable to register template due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } else { _context.waitForTaskProgressDone(morTask); } } - + public VirtualMachineMO findVm(String vmName) throws Exception { - ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" }); - if(ocs != null && ocs.length > 0) { + List ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" }); + if(ocs != null && ocs.size() > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { for(DynamicProperty prop : props) { if(prop.getVal().toString().equals(vmName)) @@ -97,19 +95,19 @@ public class DatacenterMO extends BaseMO { } return null; } - + public List findVmByNameAndLabel(String vmLabel) throws Exception { - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager()); int key = cfmMo.getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_UUID); assert(key != 0); - + List list = new ArrayList(); - - ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name", String.format("value[%d]", key)}); - if(ocs != null && ocs.length > 0) { + + List ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name", String.format("value[%d]", key)}); + if(ocs != null && ocs.size() > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { for(DynamicProperty prop : props) { if(prop.getVal() != null) { @@ -135,209 +133,217 @@ public class DatacenterMO extends BaseMO { public List> getAllVmsOnDatacenter() throws Exception { List> vms = new ArrayList>(); - - ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" }); + + List ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" }); if(ocs != null) { for(ObjectContent oc : ocs) { - String vmName = oc.getPropSet(0).getVal().toString(); + String vmName = oc.getPropSet().get(0).getVal().toString(); vms.add(new Pair(oc.getObj(), vmName)); } } - + return vms; - } - + } + public ManagedObjectReference findDatastore(String name) throws Exception { assert(name != null); - - ObjectContent[] ocs = getDatastorePropertiesOnDatacenter(new String[] { "name" }); + + List ocs = getDatastorePropertiesOnDatacenter(new String[] { "name" }); if(ocs != null) { for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().toString().equals(name)) { + if(oc.getPropSet().get(0).getVal().toString().equals(name)) { return oc.getObj(); } } } return null; } - + public ManagedObjectReference findHost(String name) throws Exception { - ObjectContent[] ocs= getHostPropertiesOnDatacenterHostFolder(new String[] { "name" }); - + List ocs= getHostPropertiesOnDatacenterHostFolder(new String[] { "name" }); + if(ocs != null) { for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().toString().equals(name)) { + if(oc.getPropSet().get(0).getVal().toString().equals(name)) { return oc.getObj(); } } } return null; } - + public ManagedObjectReference getVmFolder() throws Exception { - return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "vmFolder"); + return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "vmFolder"); } - - public ObjectContent[] getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception { + + public List getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("HostSystem"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec computeResource2HostTraversal = new TraversalSpec(); computeResource2HostTraversal.setType("ComputeResource"); computeResource2HostTraversal.setPath("host"); computeResource2HostTraversal.setName("computeResource2HostTraversal"); - + SelectionSpec recurseFolders = new SelectionSpec(); recurseFolders.setName("folder2childEntity"); - + TraversalSpec folder2childEntity = new TraversalSpec(); folder2childEntity.setType("Folder"); folder2childEntity.setPath("childEntity"); folder2childEntity.setName(recurseFolders.getName()); - folder2childEntity.setSelectSet(new SelectionSpec[] { recurseFolders, computeResource2HostTraversal }); - + folder2childEntity.getSelectSet().add(recurseFolders); + folder2childEntity.getSelectSet().add(computeResource2HostTraversal); + TraversalSpec dc2HostFolderTraversal = new TraversalSpec(); dc2HostFolderTraversal.setType("Datacenter"); dc2HostFolderTraversal.setPath("hostFolder"); dc2HostFolderTraversal.setName("dc2HostFolderTraversal"); - dc2HostFolderTraversal.setSelectSet(new SelectionSpec[] { folder2childEntity } ); - + dc2HostFolderTraversal.getSelectSet().add(folder2childEntity); + ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { dc2HostFolderTraversal }); + oSpec.getSelectSet().add(dc2HostFolderTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - return _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr); + } - - public ObjectContent[] getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception { - + + public List getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception { + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec dc2DatastoreTraversal = new TraversalSpec(); dc2DatastoreTraversal.setType("Datacenter"); dc2DatastoreTraversal.setPath("datastore"); dc2DatastoreTraversal.setName("dc2DatastoreTraversal"); - + ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { dc2DatastoreTraversal }); + oSpec.getSelectSet().add(dc2DatastoreTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - return _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr); + } - - public ObjectContent[] getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception { + + public List getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec dc2VmFolderTraversal = new TraversalSpec(); dc2VmFolderTraversal.setType("Datacenter"); dc2VmFolderTraversal.setPath("vmFolder"); dc2VmFolderTraversal.setName("dc2VmFolderTraversal"); - + + SelectionSpec recurseFolders = new SelectionSpec(); recurseFolders.setName("folder2childEntity"); - + TraversalSpec folder2childEntity = new TraversalSpec(); folder2childEntity.setType("Folder"); folder2childEntity.setPath("childEntity"); folder2childEntity.setName(recurseFolders.getName()); - folder2childEntity.setSelectSet(new SelectionSpec[] { recurseFolders }); - dc2VmFolderTraversal.setSelectSet(new SelectionSpec[] { folder2childEntity } ); + folder2childEntity.getSelectSet().add(recurseFolders); + dc2VmFolderTraversal.getSelectSet().add(folder2childEntity); ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { dc2VmFolderTraversal }); + oSpec.getSelectSet().add(dc2VmFolderTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - return _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr); } - - public static Pair getOwnerDatacenter(VmwareContext context, + + public static Pair getOwnerDatacenter(VmwareContext context, ManagedObjectReference morEntity) throws Exception { - + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datacenter"); - pSpec.setPathSet(new String[] { "name" }); - + pSpec.getPathSet().add("name"); + TraversalSpec entityParentTraversal = new TraversalSpec(); entityParentTraversal.setType("ManagedEntity"); entityParentTraversal.setPath("parent"); entityParentTraversal.setName("entityParentTraversal"); - entityParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "entityParentTraversal") }); + SelectionSpec selSpec = new SelectionSpec(); + selSpec.setName("entityParentTraversal"); + entityParentTraversal.getSelectSet().add(selSpec); ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(morEntity); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { entityParentTraversal }); + oSpec.getSelectSet().add(entityParentTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] ocs = context.getService().retrieveProperties( - context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - - assert(ocs != null); - assert(ocs[0].getObj() != null); - assert(ocs[0].getPropSet(0) != null); - assert(ocs[0].getPropSet(0).getVal() != null); - - String dcName = ocs[0].getPropSet(0).getVal().toString(); - return new Pair(new DatacenterMO(context, ocs[0].getObj()), dcName); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List ocs = context.getService().retrieveProperties( + context.getPropertyCollector(), pfSpecArr); + + assert(ocs != null && ocs.size() > 0); + assert(ocs.get(0).getObj() != null); + assert(ocs.get(0).getPropSet().get(0) != null); + assert(ocs.get(0).getPropSet().get(0).getVal() != null); + + String dcName = ocs.get(0).getPropSet().get(0).getVal().toString(); + return new Pair(new DatacenterMO(context, ocs.get(0).getObj()), dcName); } - + public ManagedObjectReference getDvPortGroupMor(String dvPortGroupName) throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("DistributedVirtualPortgroup"); - pSpec.setPathSet(new String[] {"name"}); - + pSpec.getPathSet().add("name"); + TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec(); datacenter2DvPortGroupTraversal.setType("Datacenter"); datacenter2DvPortGroupTraversal.setPath("network"); datacenter2DvPortGroupTraversal.setName("datacenter2DvPortgroupTraversal"); - + ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { datacenter2DvPortGroupTraversal }); + oSpec.getSelectSet().add(datacenter2DvPortGroupTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); + if(ocs != null) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { for(DynamicProperty prop : props) { if(prop.getVal().equals(dvPortGroupName)) @@ -347,22 +353,23 @@ public class DatacenterMO extends BaseMO { } } return null; - } + } public boolean hasDvPortGroup(String dvPortGroupName) throws Exception { ManagedObjectReference morNetwork = getDvPortGroupMor(dvPortGroupName); if(morNetwork != null) return true; - return false; + return false; } - + public DVPortgroupConfigInfo getDvPortGroupSpec(String dvPortGroupName) throws Exception { DVPortgroupConfigInfo configSpec = null; String nameProperty = null; PropertySpec pSpec = new PropertySpec(); pSpec.setType("DistributedVirtualPortgroup"); - pSpec.setPathSet(new String[] {"name", "config"}); - + pSpec.getPathSet().add("name"); + pSpec.getPathSet().add("config"); + TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec(); datacenter2DvPortGroupTraversal.setType("Datacenter"); datacenter2DvPortGroupTraversal.setPath("network"); @@ -371,21 +378,22 @@ public class DatacenterMO extends BaseMO { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { datacenter2DvPortGroupTraversal }); + oSpec.getSelectSet().add(datacenter2DvPortGroupTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); + if(ocs != null) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { - assert(props.length == 2); + assert(props.size() == 2); for(DynamicProperty prop : props) { if(prop.getName().equals("config")) { configSpec = (DVPortgroupConfigInfo) prop.getVal(); @@ -395,7 +403,7 @@ public class DatacenterMO extends BaseMO { } } if(nameProperty.equalsIgnoreCase(dvPortGroupName)) { - return configSpec; + return configSpec; } } } @@ -408,7 +416,8 @@ public class DatacenterMO extends BaseMO { ManagedObjectReference dvSwitchMor = null; PropertySpec pSpec = new PropertySpec(); pSpec.setType("DistributedVirtualPortgroup"); - pSpec.setPathSet(new String[] { "key", "config.distributedVirtualSwitch" }); + pSpec.getPathSet().add("key"); + pSpec.getPathSet().add("config.distributedVirtualSwitch"); TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec(); datacenter2DvPortGroupTraversal.setType("Datacenter"); @@ -418,21 +427,22 @@ public class DatacenterMO extends BaseMO { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { datacenter2DvPortGroupTraversal }); + oSpec.getSelectSet().add(datacenter2DvPortGroupTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); if (ocs != null) { for (ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if (props != null) { - assert (props.length == 2); + assert (props.size() == 2); for (DynamicProperty prop : props) { if (prop.getName().equals("key")) { dvPortGroupKey = (String) prop.getVal(); @@ -441,7 +451,7 @@ public class DatacenterMO extends BaseMO { dvSwitchMor = (ManagedObjectReference) prop.getVal(); } } - if ((dvPortGroupKey != null) && dvPortGroupKey.equals(dvPortGroupMor.get_value())) { + if ((dvPortGroupKey != null) && dvPortGroupKey.equals(dvPortGroupMor.getValue())) { return dvSwitchMor; } } @@ -452,7 +462,7 @@ public class DatacenterMO extends BaseMO { public String getDvSwitchUuid(ManagedObjectReference dvSwitchMor) throws Exception { assert (dvSwitchMor != null); - return (String) _context.getServiceUtil().getDynamicProperty(dvSwitchMor, "uuid"); + return (String) _context.getVimClient().getDynamicProperty(dvSwitchMor, "uuid"); } public VirtualEthernetCardDistributedVirtualPortBackingInfo getDvPortBackingInfo(Pair networkInfo) @@ -464,7 +474,7 @@ public class DatacenterMO extends BaseMO { ManagedObjectReference dvsMor = getDvSwitchMor(networkInfo.first()); String dvSwitchUuid = getDvSwitchUuid(dvsMor); dvPortConnection.setSwitchUuid(dvSwitchUuid); - dvPortConnection.setPortgroupKey(networkInfo.first().get_value()); + dvPortConnection.setPortgroupKey(networkInfo.first().getValue()); dvPortBacking.setPort(dvPortConnection); System.out.println("Plugging NIC device into network " + networkInfo.second() + " backed by dvSwitch: " + dvSwitchUuid); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java index 57e83b9799b..c79605d08ab 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java @@ -36,95 +36,98 @@ import com.vmware.vim25.TraversalSpec; public class DatastoreMO extends BaseMO { private static final Logger s_logger = Logger.getLogger(DatastoreMO.class); - - private String _name; - private Pair _ownerDc; - + + private String _name; + private Pair _ownerDc; + public DatastoreMO(VmwareContext context, ManagedObjectReference morDatastore) { super(context, morDatastore); } - + public DatastoreMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } public String getName() throws Exception { - if(_name == null) - _name = (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); - + if(_name == null) + _name = (String)_context.getVimClient().getDynamicProperty(_mor, "name"); + return _name; } - + public DatastoreSummary getSummary() throws Exception { - return (DatastoreSummary)_context.getServiceUtil().getDynamicProperty(_mor, "summary"); + return (DatastoreSummary)_context.getVimClient().getDynamicProperty(_mor, "summary"); } - + public HostDatastoreBrowserMO getHostDatastoreBrowserMO() throws Exception { - return new HostDatastoreBrowserMO(_context, - (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "browser")); + return new HostDatastoreBrowserMO(_context, + (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "browser")); } - + public String getInventoryPath() throws Exception { Pair dcInfo = getOwnerDatacenter(); return dcInfo.second() + "/" + getName(); } - + public Pair getOwnerDatacenter() throws Exception { if(_ownerDc != null) return _ownerDc; - + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datacenter"); - pSpec.setPathSet(new String[] { "name" }); - + pSpec.getPathSet().add("name"); + TraversalSpec folderParentTraversal = new TraversalSpec(); folderParentTraversal.setType("Folder"); folderParentTraversal.setPath("parent"); folderParentTraversal.setName("folderParentTraversal"); - folderParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "folderParentTraversal") }); - + SelectionSpec sSpec = new SelectionSpec(); + sSpec.setName("folderParentTraversal"); + folderParentTraversal.getSelectSet().add(sSpec); + TraversalSpec dsParentTraversal = new TraversalSpec(); dsParentTraversal.setType("Datastore"); dsParentTraversal.setPath("parent"); dsParentTraversal.setName("dsParentTraversal"); - dsParentTraversal.setSelectSet(new SelectionSpec[] { folderParentTraversal }); + dsParentTraversal.getSelectSet().add(folderParentTraversal); ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(getMor()); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { dsParentTraversal }); + oSpec.getSelectSet().add(dsParentTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - - assert(ocs != null); - assert(ocs[0].getObj() != null); - assert(ocs[0].getPropSet() != null); - String dcName = ocs[0].getPropSet()[0].getVal().toString(); - _ownerDc = new Pair(new DatacenterMO(_context, ocs[0].getObj()), dcName); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); + + assert(ocs != null && ocs.size() > 0); + assert(ocs.get(0).getObj() != null); + assert(ocs.get(0).getPropSet() != null); + String dcName = ocs.get(0).getPropSet().get(0).getVal().toString(); + _ownerDc = new Pair(new DatacenterMO(_context, ocs.get(0).getObj()), dcName); return _ownerDc; } - + public void makeDirectory(String path, ManagedObjectReference morDc) throws Exception { String datastoreName = getName(); ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager(); - + String fullPath = path; - if(!DatastoreFile.isFullDatastorePath(fullPath)) + if(!DatastoreFile.isFullDatastorePath(fullPath)) fullPath = String.format("[%s] %s", datastoreName, path); - + _context.getService().makeDirectory(morFileManager, fullPath, morDc, true); } - + public boolean deleteFile(String path, ManagedObjectReference morDc, boolean testExistence) throws Exception { String datastoreName = getName(); ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager(); - + String fullPath = path; if(!DatastoreFile.isFullDatastorePath(fullPath)) fullPath = String.format("[%s] %s", datastoreName, path); @@ -136,12 +139,11 @@ public class DatastoreMO extends BaseMO { s_logger.info("Unable to test file existence due to exception " + e.getClass().getName() + ", skip deleting of it"); return true; } - - ManagedObjectReference morTask = _context.getService().deleteDatastoreFile_Task(morFileManager, - fullPath, morDc); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + + ManagedObjectReference morTask = _context.getService().deleteDatastoreFileTask(morFileManager, fullPath, morDc); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -149,29 +151,29 @@ public class DatastoreMO extends BaseMO { } return false; } - + public boolean copyDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, - ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc, + ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc, boolean forceOverwrite) throws Exception { - + String srcDsName = getName(); DatastoreMO destDsMo = new DatastoreMO(_context, morDestDs); String destDsName = destDsMo.getName(); - + ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager(); String srcFullPath = srcFilePath; if(!DatastoreFile.isFullDatastorePath(srcFullPath)) srcFullPath = String.format("[%s] %s", srcDsName, srcFilePath); - + String destFullPath = destFilePath; if(!DatastoreFile.isFullDatastorePath(destFullPath)) destFullPath = String.format("[%s] %s", destDsName, destFilePath); - - ManagedObjectReference morTask = _context.getService().copyDatastoreFile_Task(morFileManager, + + ManagedObjectReference morTask = _context.getService().copyDatastoreFileTask(morFileManager, srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -179,29 +181,29 @@ public class DatastoreMO extends BaseMO { } return false; } - + public boolean moveDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, - ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc, + ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc, boolean forceOverwrite) throws Exception { - + String srcDsName = getName(); DatastoreMO destDsMo = new DatastoreMO(_context, morDestDs); String destDsName = destDsMo.getName(); - + ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager(); String srcFullPath = srcFilePath; if(!DatastoreFile.isFullDatastorePath(srcFullPath)) srcFullPath = String.format("[%s] %s", srcDsName, srcFilePath); - + String destFullPath = destFilePath; if(!DatastoreFile.isFullDatastorePath(destFullPath)) destFullPath = String.format("[%s] %s", destDsName, destFilePath); - - ManagedObjectReference morTask = _context.getService().moveDatastoreFile_Task(morFileManager, + + ManagedObjectReference morTask = _context.getService().moveDatastoreFileTask(morFileManager, srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -209,23 +211,23 @@ public class DatastoreMO extends BaseMO { } return false; } - + public String[] getVmdkFileChain(String rootVmdkDatastoreFullPath) throws Exception { Pair dcPair = getOwnerDatacenter(); - + List files = new ArrayList(); files.add(rootVmdkDatastoreFullPath); - + String currentVmdkFullPath = rootVmdkDatastoreFullPath; while(true) { String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), currentVmdkFullPath); byte[] content = getContext().getResourceContent(url); if(content == null || content.length == 0) break; - + VmdkFileDescriptor descriptor = new VmdkFileDescriptor(); descriptor.parse(content); - + String parentFileName = descriptor.getParentFileName(); if(parentFileName == null) break; @@ -239,8 +241,8 @@ public class DatastoreMO extends BaseMO { dir = dir.substring(0, dir.lastIndexOf('/')); else dir = ""; - - currentVmdkFullPath = new DatastoreFile(dsFile.getDatastoreName(), dir, + + currentVmdkFullPath = new DatastoreFile(dsFile.getDatastoreName(), dir, parentFileName.substring(parentFileName.lastIndexOf('/') + 1)).getPath(); files.add(currentVmdkFullPath); } else { @@ -248,7 +250,7 @@ public class DatastoreMO extends BaseMO { files.add(currentVmdkFullPath); } } - + return files.toArray(new String[0]); } @@ -257,59 +259,59 @@ public class DatastoreMO extends BaseMO { String fullPath = path; if(!DatastoreFile.isFullDatastorePath(fullPath)) fullPath = String.format("[%s] %s", getName(), fullPath); - + Pair dcPair = getOwnerDatacenter(); String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), fullPath); - + // TODO, VMware currently does not have a formal API to list Datastore directory content, // folloing hacking may have performance hit if datastore has a large number of files return _context.listDatastoreDirContent(url); } - + public boolean fileExists(String fileFullPath) throws Exception { DatastoreFile file = new DatastoreFile(fileFullPath); DatastoreFile dirFile = new DatastoreFile(file.getDatastoreName(), file.getDir()); - + HostDatastoreBrowserMO browserMo = getHostDatastoreBrowserMO(); - + s_logger.info("Search file " + file.getFileName() + " on " + dirFile.getPath()); HostDatastoreBrowserSearchResults results = browserMo.searchDatastore(dirFile.getPath(), file.getFileName(), true); if(results != null) { - FileInfo[] info = results.getFile(); - if(info != null && info.length > 0) { + List info = results.getFile(); + if(info != null && info.size() > 0) { s_logger.info("File " + fileFullPath + " exists on datastore"); return true; } } - + s_logger.info("File " + fileFullPath + " does not exist on datastore"); return false; -/* +/* String[] fileNames = listDirContent(dirFile.getPath()); - + String fileName = file.getFileName(); for(String name : fileNames) { if(name.equalsIgnoreCase(fileName)) return true; - } - + } + return false; -*/ +*/ } - + public boolean folderExists(String folderParentDatastorePath, String folderName) throws Exception { HostDatastoreBrowserMO browserMo = getHostDatastoreBrowserMO(); - + HostDatastoreBrowserSearchResults results = browserMo.searchDatastore(folderParentDatastorePath, folderName, true); if(results != null) { - FileInfo[] info = results.getFile(); - if(info != null && info.length > 0) { + List info = results.getFile(); + if(info != null && info.size() > 0) { s_logger.info("Folder " + folderName + " exists on datastore"); return true; } } - + s_logger.info("Folder " + folderName + " does not exist on datastore"); return false; } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java index ec0a1810701..59e754c951d 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java @@ -24,39 +24,39 @@ import com.vmware.vim25.HostDatastoreBrowserSearchSpec; import com.vmware.vim25.ManagedObjectReference; public class HostDatastoreBrowserMO extends BaseMO { - + private static final Logger s_logger = Logger.getLogger(HostDatastoreBrowserMO.class); - + public HostDatastoreBrowserMO(VmwareContext context, ManagedObjectReference morHostDatastoreBrowser) { super(context, morHostDatastoreBrowser); } - + public HostDatastoreBrowserMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public void DeleteFile(String datastoreFullPath) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - deleteFile(). target mor: " + _mor.get_value() + ", file datastore path: " + datastoreFullPath); - + s_logger.trace("vCenter API trace - deleteFile(). target mor: " + _mor.getValue() + ", file datastore path: " + datastoreFullPath); + _context.getService().deleteFile(_mor, datastoreFullPath); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - deleteFile() done"); } - + public HostDatastoreBrowserSearchResults searchDatastore(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - searchDatastore(). target mor: " + _mor.get_value() + ", file datastore path: " + datastorePath); + s_logger.trace("vCenter API trace - searchDatastore(). target mor: " + _mor.getValue() + ", file datastore path: " + datastorePath); try { - ManagedObjectReference morTask = _context.getService().searchDatastore_Task(_mor, datastorePath, searchSpec); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + ManagedObjectReference morTask = _context.getService().searchDatastoreTask(_mor, datastorePath, searchSpec); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); - - return (HostDatastoreBrowserSearchResults)_context.getServiceUtil().getDynamicProperty(morTask, "info.result"); + + return (HostDatastoreBrowserSearchResults)_context.getVimClient().getDynamicProperty(morTask, "info.result"); } else { s_logger.error("VMware searchDaastore_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } @@ -64,30 +64,30 @@ public class HostDatastoreBrowserMO extends BaseMO { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - searchDatastore() done"); } - + return null; } - + public HostDatastoreBrowserSearchResults searchDatastore(String datastorePath, String fileName, boolean caseInsensitive) throws Exception { HostDatastoreBrowserSearchSpec spec = new HostDatastoreBrowserSearchSpec(); spec.setSearchCaseInsensitive(caseInsensitive); - spec.setMatchPattern(new String[] { fileName }); + spec.getMatchPattern().add(fileName); return searchDatastore(datastorePath, spec); } - + public HostDatastoreBrowserSearchResults searchDatastoreSubFolders(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - searchDatastoreSubFolders(). target mor: " + _mor.get_value() + ", file datastore path: " + datastorePath); + s_logger.trace("vCenter API trace - searchDatastoreSubFolders(). target mor: " + _mor.getValue() + ", file datastore path: " + datastorePath); try { - ManagedObjectReference morTask = _context.getService().searchDatastoreSubFolders_Task(_mor, datastorePath, searchSpec); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + ManagedObjectReference morTask = _context.getService().searchDatastoreSubFoldersTask(_mor, datastorePath, searchSpec); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); - - return (HostDatastoreBrowserSearchResults)_context.getServiceUtil().getDynamicProperty(morTask, "info.result"); + + return (HostDatastoreBrowserSearchResults)_context.getVimClient().getDynamicProperty(morTask, "info.result"); } else { s_logger.error("VMware searchDaastoreSubFolders_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } @@ -95,14 +95,14 @@ public class HostDatastoreBrowserMO extends BaseMO { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - searchDatastore() done"); } - + return null; } - + public HostDatastoreBrowserSearchResults searchDatastoreSubFolders(String datastorePath, String folderName, boolean caseInsensitive) throws Exception { HostDatastoreBrowserSearchSpec spec = new HostDatastoreBrowserSearchSpec(); spec.setSearchCaseInsensitive(caseInsensitive); - spec.setMatchPattern(new String[] { folderName }); + spec.getMatchPattern().add(folderName); return searchDatastore(datastorePath, spec); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java index d94102bb2fb..7d967a9b532 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java @@ -17,6 +17,9 @@ package com.cloud.hypervisor.vmware.mo; import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.CustomFieldStringValue; @@ -37,27 +40,27 @@ public class HostDatastoreSystemMO extends BaseMO { public HostDatastoreSystemMO(VmwareContext context, ManagedObjectReference morHostDatastore) { super(context, morHostDatastore); } - + public HostDatastoreSystemMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public ManagedObjectReference findDatastore(String name) throws Exception { // added cloud.com specific name convention, we will use custom field "cloud.uuid" as datastore name as well - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, _context.getServiceContent().getCustomFieldsManager()); int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID); assert(key != 0); - ObjectContent[] ocs = getDatastorePropertiesOnHostDatastoreSystem( + List ocs = getDatastorePropertiesOnHostDatastoreSystem( new String[] { "name", String.format("value[%d]", key) }); if(ocs != null) { for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().equals(name)) + if(oc.getPropSet().get(0).getVal().equals(name)) return oc.getObj(); - - if(oc.getPropSet().length > 1) { - DynamicProperty prop = oc.getPropSet(1); + + if(oc.getPropSet().size() > 1) { + DynamicProperty prop = oc.getPropSet().get(1); if(prop != null && prop.getVal() != null) { if(prop.getVal() instanceof CustomFieldStringValue) { String val = ((CustomFieldStringValue)prop.getVal()).getValue(); @@ -70,11 +73,11 @@ public class HostDatastoreSystemMO extends BaseMO { } return null; } - + // storeUrl in nfs://host/exportpath format public ManagedObjectReference findDatastoreByUrl(String storeUrl) throws Exception { assert(storeUrl != null); - + ManagedObjectReference[] datastores = getDatastores(); if(datastores != null && datastores.length > 0) { for(ManagedObjectReference morDatastore : datastores) { @@ -87,7 +90,7 @@ public class HostDatastoreSystemMO extends BaseMO { } } } - + return null; } @@ -95,30 +98,30 @@ public class HostDatastoreSystemMO extends BaseMO { // we should be able to find the datastore by name public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception { assert(exportPath != null); - + ManagedObjectReference[] datastores = getDatastores(); if(datastores != null && datastores.length > 0) { for(ManagedObjectReference morDatastore : datastores) { DatastoreMO dsMo = new DatastoreMO(_context, morDatastore); - if(dsMo.getInventoryPath().equals(exportPath)) + if(dsMo.getInventoryPath().equals(exportPath)) return morDatastore; - + NasDatastoreInfo info = getNasDatastoreInfo(morDatastore); if(info != null) { String vmwareUrl = info.getUrl(); if(vmwareUrl.charAt(vmwareUrl.length() - 1) == '/') vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1); - + URI uri = new URI(vmwareUrl); if(uri.getPath().equals("/" + exportPath)) return morDatastore; } } } - + return null; } - + public boolean deleteDatastore(String name) throws Exception { ManagedObjectReference morDatastore = findDatastore(name); if(morDatastore != null) { @@ -127,59 +130,60 @@ public class HostDatastoreSystemMO extends BaseMO { } return false; } - - public ManagedObjectReference createNfsDatastore(String host, int port, + + public ManagedObjectReference createNfsDatastore(String host, int port, String exportPath, String uuid) throws Exception { - + HostNasVolumeSpec spec = new HostNasVolumeSpec(); spec.setRemoteHost(host); spec.setRemotePath(exportPath); spec.setType("nfs"); spec.setLocalPath(uuid); - + // readOnly/readWrite spec.setAccessMode("readWrite"); return _context.getService().createNasDatastore(_mor, spec); } - + public ManagedObjectReference[] getDatastores() throws Exception { - return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty( + return (ManagedObjectReference[])_context.getVimClient().getDynamicProperty( _mor, "datastore"); } - + public DatastoreInfo getDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { - return (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); + return (DatastoreInfo)_context.getVimClient().getDynamicProperty(morDatastore, "info"); } - + public NasDatastoreInfo getNasDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { - DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); + DatastoreInfo info = (DatastoreInfo)_context.getVimClient().getDynamicProperty(morDatastore, "info"); if(info instanceof NasDatastoreInfo) return (NasDatastoreInfo)info; return null; } - - public ObjectContent[] getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception { - + + public List getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception { + PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec hostDsSys2DatastoreTraversal = new TraversalSpec(); hostDsSys2DatastoreTraversal.setType("HostDatastoreSystem"); hostDsSys2DatastoreTraversal.setPath("datastore"); hostDsSys2DatastoreTraversal.setName("hostDsSys2DatastoreTraversal"); - + ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { hostDsSys2DatastoreTraversal }); + oSpec.getSelectSet().add(hostDsSys2DatastoreTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + return _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + _context.getPropertyCollector(), pfSpecArr); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java index 2d2b35390ce..df159261c43 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java @@ -29,27 +29,27 @@ public class HostFirewallSystemMO extends BaseMO { public HostFirewallSystemMO(VmwareContext context, ManagedObjectReference morFirewallSystem) { super(context, morFirewallSystem); } - + public HostFirewallSystemMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public HostFirewallInfo getFirewallInfo() throws Exception { - return (HostFirewallInfo)_context.getServiceUtil().getDynamicProperty(_mor, "firewallInfo"); + return (HostFirewallInfo)_context.getVimClient().getDynamicProperty(_mor, "firewallInfo"); } - + public void updateDefaultPolicy(HostFirewallDefaultPolicy policy) throws Exception { _context.getService().updateDefaultPolicy(_mor, policy); } - + public void enableRuleset(String rulesetName) throws Exception { _context.getService().enableRuleset(_mor, rulesetName); } - + public void disableRuleset(String rulesetName) throws Exception { _context.getService().disableRuleset(_mor, rulesetName); } - + public void refreshFirewall() throws Exception { _context.getService().refreshFirewall(_mor); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java index a765b42fd78..c164cc22f23 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java @@ -27,8 +27,8 @@ import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.utils.Pair; import com.google.gson.Gson; -import com.vmware.apputils.vim25.ServiceUtil; import com.vmware.vim25.AboutInfo; +import com.vmware.vim25.AlreadyExistsFaultMsg; import com.vmware.vim25.ClusterDasConfigInfo; import com.vmware.vim25.ComputeResourceSummary; import com.vmware.vim25.DatastoreSummary; @@ -55,63 +55,64 @@ import com.vmware.vim25.ObjectSpec; import com.vmware.vim25.OptionValue; import com.vmware.vim25.PropertyFilterSpec; import com.vmware.vim25.PropertySpec; -import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.TraversalSpec; import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualNicManagerNetConfig; import com.vmware.vim25.NasDatastoreInfo; +import edu.emory.mathcs.backport.java.util.Arrays; + public class HostMO extends BaseMO implements VmwareHypervisorHost { private static final Logger s_logger = Logger.getLogger(HostMO.class); Map _vmCache = new HashMap(); - + public HostMO (VmwareContext context, ManagedObjectReference morHost) { super(context, morHost); } - + public HostMO (VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public HostHardwareSummary getHostHardwareSummary() throws Exception { HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor); HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware(); return hardwareSummary; } - + public HostConfigManager getHostConfigManager() throws Exception { - return (HostConfigManager)_context.getServiceUtil().getDynamicProperty(_mor, "configManager"); + return (HostConfigManager)_context.getVimClient().getDynamicProperty(_mor, "configManager"); } - + public VirtualNicManagerNetConfig[] getHostVirtualNicManagerNetConfig() throws Exception { - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor, + VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); - return netConfigs; + return netConfigs; } - + public HostIpRouteEntry[] getHostIpRouteEntries() throws Exception { - HostIpRouteEntry[] entries = (HostIpRouteEntry[])_context.getServiceUtil().getDynamicProperty(_mor, + HostIpRouteEntry[] entries = (HostIpRouteEntry[])_context.getVimClient().getDynamicProperty(_mor, "config.network.routeTableInfo.ipRoute"); - return entries; + return entries; } - + public HostListSummaryQuickStats getHostQuickStats() throws Exception { - return (HostListSummaryQuickStats)_context.getServiceUtil().getDynamicProperty(_mor, "summary.quickStats"); + return (HostListSummaryQuickStats)_context.getVimClient().getDynamicProperty(_mor, "summary.quickStats"); } - + public HostHyperThreadScheduleInfo getHostHyperThreadInfo() throws Exception { - return (HostHyperThreadScheduleInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.hyperThread"); + return (HostHyperThreadScheduleInfo)_context.getVimClient().getDynamicProperty(_mor, "config.hyperThread"); } - + public HostNetworkInfo getHostNetworkInfo() throws Exception { - return (HostNetworkInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.network"); + return (HostNetworkInfo)_context.getVimClient().getDynamicProperty(_mor, "config.network"); } - + public HostPortGroupSpec getHostPortGroupSpec(String portGroupName) throws Exception { - + HostNetworkInfo hostNetInfo = getHostNetworkInfo(); - - HostPortGroup[] portGroups = hostNetInfo.getPortgroup(); + + List portGroups = hostNetInfo.getPortgroup(); if(portGroups != null) { for(HostPortGroup portGroup : portGroups) { HostPortGroupSpec spec = portGroup.getSpec(); @@ -119,15 +120,15 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return spec; } } - + return null; } - + @Override public String getHyperHostName() throws Exception { return getName(); } - + @Override public ClusterDasConfigInfo getDasConfig() throws Exception { ManagedObjectReference morParent = getParentMor(); @@ -135,10 +136,10 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ClusterMO clusterMo = new ClusterMO(_context, morParent); return clusterMo.getDasConfig(); } - + return null; } - + @Override public String getHyperHostDefaultGateway() throws Exception { HostIpRouteEntry[] entries = getHostIpRouteEntries(); @@ -146,20 +147,20 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { if(entry.getNetwork().equalsIgnoreCase("0.0.0.0")) return entry.getGateway(); } - + throw new Exception("Could not find host default gateway, host is not properly configured?"); } - + public HostDatastoreSystemMO getHostDatastoreSystemMO() throws Exception { return new HostDatastoreSystemMO(_context, - (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty( + (ManagedObjectReference)_context.getVimClient().getDynamicProperty( _mor, "configManager.datastoreSystem") ); } - + public HostDatastoreBrowserMO getHostDatastoreBrowserMO() throws Exception { return new HostDatastoreBrowserMO(_context, - (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty( + (ManagedObjectReference)_context.getVimClient().getDynamicProperty( _mor, "datastoreBrowser") ); } @@ -168,7 +169,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { "name"} ); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); + List objProps = oc.getPropSet(); if(objProps != null) { for(DynamicProperty objProp : objProps) { if(objProp.getVal().toString().equals(datastoreName)) @@ -179,22 +180,22 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } return null; } - + public HostNetworkSystemMO getHostNetworkSystemMO() throws Exception { HostConfigManager configMgr = getHostConfigManager(); return new HostNetworkSystemMO(_context, configMgr.getNetworkSystem()); } - + public HostFirewallSystemMO getHostFirewallSystemMO() throws Exception { HostConfigManager configMgr = getHostConfigManager(); ManagedObjectReference morFirewall = configMgr.getFirewallSystem(); - + // only ESX hosts have firewall manager if(morFirewall != null) return new HostFirewallSystemMO(_context, morFirewall); return null; } - + @Override public ManagedObjectReference getHyperHostDatacenter() throws Exception { Pair dcPair = DatacenterMO.getOwnerDatacenter(getContext(), getMor()); @@ -204,43 +205,40 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { @Override public ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception { - ServiceUtil serviceUtil = _context.getServiceUtil(); - ManagedObjectReference morComputerResource = (ManagedObjectReference)serviceUtil.getDynamicProperty(_mor, "parent"); - return (ManagedObjectReference)serviceUtil.getDynamicProperty(morComputerResource, "resourcePool"); + ManagedObjectReference morComputerResource = (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "parent"); + return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(morComputerResource, "resourcePool"); } @Override public ManagedObjectReference getHyperHostCluster() throws Exception { - ServiceUtil serviceUtil = _context.getServiceUtil(); - ManagedObjectReference morParent = (ManagedObjectReference)serviceUtil.getDynamicProperty(_mor, "parent"); - + ManagedObjectReference morParent = (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "parent"); + if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { return morParent; } - + assert(false); throw new Exception("Standalone host is not supported"); } - + public ManagedObjectReference[] getHostLocalDatastore() throws Exception { - ServiceUtil serviceUtil = _context.getServiceUtil(); - ManagedObjectReference[] datastores = (ManagedObjectReference[])serviceUtil.getDynamicProperty( + ManagedObjectReference[] datastores = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty( _mor, "datastore"); List l = new ArrayList(); if(datastores != null) { for(ManagedObjectReference mor : datastores) { - DatastoreSummary summary = (DatastoreSummary)serviceUtil.getDynamicProperty(mor, "summary"); - if(summary.getType().equalsIgnoreCase("VMFS") && !summary.getMultipleHostAccess()) + DatastoreSummary summary = (DatastoreSummary)_context.getVimClient().getDynamicProperty(mor, "summary"); + if(summary.getType().equalsIgnoreCase("VMFS") && !summary.isMultipleHostAccess()) l.add(mor); } } return l.toArray(new ManagedObjectReference[1]); } - + public HostVirtualSwitch getHostVirtualSwitchByName(String name) throws Exception { - HostVirtualSwitch[] switches = (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty( + HostVirtualSwitch[] switches = (HostVirtualSwitch[])_context.getVimClient().getDynamicProperty( _mor, "config.network.vswitch"); - + if(switches != null) { for(HostVirtualSwitch vswitch : switches) { if(vswitch.getName().equals(name)) @@ -249,44 +247,44 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } return null; } - + public HostVirtualSwitch[] getHostVirtualSwitch() throws Exception { - return (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty(_mor, "config.network.vswitch"); + return (HostVirtualSwitch[])_context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); } - + public AboutInfo getHostAboutInfo() throws Exception { - return (AboutInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.product"); + return (AboutInfo)_context.getVimClient().getDynamicProperty(_mor, "config.product"); } - + public VmwareHostType getHostType() throws Exception { AboutInfo aboutInfo = getHostAboutInfo(); if("VMware ESXi".equals(aboutInfo.getName())) return VmwareHostType.ESXi; else if("VMware ESX".equals(aboutInfo.getName())) return VmwareHostType.ESX; - + throw new Exception("Unrecognized VMware host type " + aboutInfo.getName()); } - + // default virtual switch is which management network residents on public HostVirtualSwitch getHostDefaultVirtualSwitch() throws Exception { String managementPortGroup = getPortGroupNameByNicType(HostVirtualNicType.management); if(managementPortGroup != null) return getPortGroupVirtualSwitch(managementPortGroup); - + return null; } - + public HostVirtualSwitch getPortGroupVirtualSwitch(String portGroupName) throws Exception { String vSwitchName = getPortGroupVirtualSwitchName(portGroupName); if(vSwitchName != null) return getVirtualSwitchByName(vSwitchName); - + return null; } - + public HostVirtualSwitch getVirtualSwitchByName(String vSwitchName) throws Exception { - + HostVirtualSwitch[] vSwitchs = getHostVirtualSwitch(); if(vSwitchs != null) { for(HostVirtualSwitch vSwitch: vSwitchs) { @@ -294,13 +292,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return vSwitch; } } - + return null; } - + public String getPortGroupVirtualSwitchName(String portGroupName) throws Exception { HostNetworkInfo hostNetInfo = getHostNetworkInfo(); - HostPortGroup[] portGroups = hostNetInfo.getPortgroup(); + List portGroups = hostNetInfo.getPortgroup(); if(portGroups != null) { for(HostPortGroup portGroup : portGroups) { HostPortGroupSpec spec = portGroup.getSpec(); @@ -308,13 +306,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return spec.getVswitchName(); } } - + return null; } - + public HostPortGroupSpec getPortGroupSpec(String portGroupName) throws Exception { HostNetworkInfo hostNetInfo = getHostNetworkInfo(); - HostPortGroup[] portGroups = hostNetInfo.getPortgroup(); + List portGroups = hostNetInfo.getPortgroup(); if(portGroups != null) { for(HostPortGroup portGroup : portGroups) { HostPortGroupSpec spec = portGroup.getSpec(); @@ -322,20 +320,20 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return spec; } } - + return null; } - + public String getPortGroupNameByNicType(HostVirtualNicType nicType) throws Exception { assert(nicType != null); - - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor, + + VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); - + if(netConfigs != null) { for(VirtualNicManagerNetConfig netConfig : netConfigs) { if(netConfig.getNicType().equals(nicType.toString())) { - HostVirtualNic[] nics = netConfig.getCandidateVnic(); + List nics = netConfig.getCandidateVnic(); if(nics != null) { for(HostVirtualNic nic : nics) { return nic.getPortgroup(); @@ -344,36 +342,36 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } } } - + if(nicType == HostVirtualNicType.management) { // ESX management network is configured in service console HostNetworkInfo netInfo = getHostNetworkInfo(); assert(netInfo != null); - HostVirtualNic[] nics = netInfo.getConsoleVnic(); + List nics = netInfo.getConsoleVnic(); if(nics != null) { for(HostVirtualNic nic : nics) { return nic.getPortgroup(); } } } - + return null; } - + public boolean hasPortGroup(HostVirtualSwitch vSwitch, String portGroupName) throws Exception { ManagedObjectReference morNetwork = getNetworkMor(portGroupName); if(morNetwork != null) return true; return false; } - + public void createPortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, HostNetworkSecurityPolicy secPolicy, HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception { assert(portGroupName != null); HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO(); assert(hostNetMo != null); - + HostPortGroupSpec spec = new HostPortGroupSpec(); - + spec.setName(portGroupName); if(vlanId != null) spec.setVlanId(vlanId.intValue()); @@ -385,14 +383,14 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { spec.setVswitchName(vSwitch.getName()); hostNetMo.addPortGroup(spec); } - + public void updatePortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, HostNetworkSecurityPolicy secPolicy, HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception { assert(portGroupName != null); HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO(); assert(hostNetMo != null); - + HostPortGroupSpec spec = new HostPortGroupSpec(); - + spec.setName(portGroupName); if(vlanId != null) spec.setVlanId(vlanId.intValue()); @@ -404,19 +402,19 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { spec.setVswitchName(vSwitch.getName()); hostNetMo.updatePortGroup(portGroupName, spec); } - + public void deletePortGroup(String portGroupName) throws Exception { assert(portGroupName != null); HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO(); assert(hostNetMo != null); - hostNetMo.removePortGroup(portGroupName); + hostNetMo.removePortGroup(portGroupName); } - + public ManagedObjectReference getNetworkMor(String portGroupName) throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("Network"); - pSpec.setPathSet(new String[] {"summary.name"}); - + pSpec.getPathSet().add("summary.name"); + TraversalSpec host2NetworkTraversal = new TraversalSpec(); host2NetworkTraversal.setType("HostSystem"); host2NetworkTraversal.setPath("network"); @@ -425,19 +423,20 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { host2NetworkTraversal }); + oSpec.getSelectSet().add(host2NetworkTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); + if(ocs != null) { for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { for(DynamicProperty prop : props) { if(prop.getVal().equals(portGroupName)) @@ -448,62 +447,62 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } return null; } - + public ManagedObjectReference[] getVmMorsOnNetwork(String portGroupName) throws Exception { ManagedObjectReference morNetwork = getNetworkMor(portGroupName); if(morNetwork != null) - return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(morNetwork, "vm"); + return (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(morNetwork, "vm"); return null; } - + public String getHostName() throws Exception { - return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); + return (String)_context.getVimClient().getDynamicProperty(_mor, "name"); } @Override public synchronized VirtualMachineMO findVmOnHyperHost(String name) throws Exception { if(s_logger.isDebugEnabled()) s_logger.debug("find VM " + name + " on host"); - + VirtualMachineMO vmMo = _vmCache.get(name); if(vmMo != null) { if(s_logger.isDebugEnabled()) s_logger.debug("VM " + name + " found in host cache"); return vmMo; } - + loadVmCache(); return _vmCache.get(name); } - + private void loadVmCache() throws Exception { if(s_logger.isDebugEnabled()) s_logger.debug("load VM cache on host"); - + _vmCache.clear(); - + ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] { "name" }); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - String vmName = oc.getPropSet()[0].getVal().toString(); - + String vmName = oc.getPropSet().get(0).getVal().toString(); + if(s_logger.isTraceEnabled()) s_logger.trace("put " + vmName + " into host cache"); - + _vmCache.put(vmName, new VirtualMachineMO(_context, oc.getObj())); } } } - + @Override public VirtualMachineMO findVmOnPeerHyperHost(String name) throws Exception { ManagedObjectReference morParent = getParentMor(); - + if(morParent.getType().equals("ClusterComputeResource")) { ClusterMO clusterMo = new ClusterMO(_context, morParent); return clusterMo.findVmOnHyperHost(name); } else { - // we don't support standalone host, all hosts have to be managed by + // we don't support standalone host, all hosts have to be managed by // a cluster within vCenter assert(false); return null; @@ -515,30 +514,30 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { assert(vmSpec != null); DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); - - ManagedObjectReference morTask = _context.getService().createVM_Task( + + ManagedObjectReference morTask = _context.getService().createVMTask( dcMo.getVmFolder(), vmSpec, morPool, _mor); - String result = _context.getServiceUtil().waitForTask(morTask); - - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } - + return false; } - + public HashMap getVmVncPortsOnHost() throws Exception { ObjectContent[] ocs = getVmPropertiesOnHyperHost( new String[] { "name", "config.extraConfig[\"RemoteDisplay.vnc.port\"]" } ); - + HashMap portInfo = new HashMap(); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); + List objProps = oc.getPropSet(); if(objProps != null) { String name = null; String value = null; @@ -548,27 +547,28 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } else { OptionValue optValue = (OptionValue)objProp.getVal(); value = (String)optValue.getValue(); - } + } } - + if(name != null && value != null) { portInfo.put(name, Integer.parseInt(value)); } } } } - + return portInfo; } - - public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception { + + @Override + public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths)); - + s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths)); + PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec host2VmTraversal = new TraversalSpec(); host2VmTraversal.setType("HostSystem"); host2VmTraversal.setPath("vm"); @@ -577,30 +577,31 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { host2VmTraversal }); + oSpec.getSelectSet().add(host2VmTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List properties = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; + return properties.toArray(new ObjectContent[properties.size()]); } @Override public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths)); + s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths)); PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); - pSpec.setPathSet(propertyPaths); - + pSpec.getPathSet().addAll(Arrays.asList(propertyPaths)); + TraversalSpec host2DatastoreTraversal = new TraversalSpec(); host2DatastoreTraversal.setType("HostSystem"); host2DatastoreTraversal.setPath("datastore"); @@ -609,87 +610,88 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { host2DatastoreTraversal }); + oSpec.getSelectSet().add(host2DatastoreTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List properties = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; + return properties.toArray(new ObjectContent[properties.size()]); } - + public List> getDatastoreMountsOnHost() throws Exception { List> mounts = new ArrayList>(); - + ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { - String.format("host[\"%s\"].mountInfo.path", _mor.get_value()) }); + String.format("host[\"%s\"].mountInfo.path", _mor.getValue()) }); if(ocs != null) { for(ObjectContent oc : ocs) { Pair mount = new Pair( - oc.getObj(), oc.getPropSet(0).getVal().toString()); + oc.getObj(), oc.getPropSet().get(0).getVal().toString()); mounts.add(mount); } } return mounts; } - + public List> getLocalDatastoreOnHost() throws Exception { List> dsList = new ArrayList>(); - + ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { "name", "summary" }); if(ocs != null) { for(ObjectContent oc : ocs) { DatastoreSummary dsSummary = (DatastoreSummary)VmwareHelper.getPropValue(oc, "summary"); - if(dsSummary.getMultipleHostAccess() == false && dsSummary.isAccessible() && dsSummary.getType().equalsIgnoreCase("vmfs")) { + if(dsSummary.isMultipleHostAccess() == false && dsSummary.isAccessible() && dsSummary.getType().equalsIgnoreCase("vmfs")) { ManagedObjectReference morDs = oc.getObj(); String name = (String)VmwareHelper.getPropValue(oc, "name"); - + dsList.add(new Pair(morDs, name)); } } } return dsList; } - + public void importVmFromOVF(String ovfFilePath, String vmName, String datastoreName, String diskOption) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.get_value() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ",datastoreName: " + datastoreName + ", diskOption: " + diskOption); - + DatastoreMO dsMo = getHostDatastoreMO(datastoreName); if(dsMo == null) throw new Exception("Invalid datastore name: " + datastoreName); - + importVmFromOVF(ovfFilePath, vmName, dsMo, diskOption); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - importVmFromOVF() done"); } - + @Override public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception { ManagedObjectReference morRp = getHyperHostOwnerResourcePool(); assert(morRp != null); - + HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, _mor); } - + @Override public boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.get_value() + ", vmName: " + vmName + ", cpuCount: " + cpuCount - + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB - + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.get_value() + ", snapshotDirToParent: " + snapshotDirToParent); - + s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount + + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB + + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent); + boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, memoryMB, memoryReserveMB, guestOsIdentifier, morDs, snapshotDirToParent); @@ -732,13 +734,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } @Override - public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress, + public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress, int poolHostPort, String poolPath, String poolUuid) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); - + HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); ManagedObjectReference morDatastore = hostDatastoreSystemMo.findDatastore(poolUuid); if(morDatastore == null) { @@ -749,9 +751,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { poolHostPort, poolPath, poolUuid); - } catch (com.vmware.vim25.AlreadyExists e) { + } catch (AlreadyExistsFaultMsg e) { s_logger.info("Creation of NFS datastore on vCenter failed since datastore already exists." + - " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + + " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); // Retrieve the morDatastore and return it. @@ -759,16 +761,16 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { poolHostPort, poolPath, poolUuid, hostDatastoreSystemMo)); } catch (Exception e) { s_logger.info("Creation of NFS datastore on vCenter failed. " + - " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + + " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid + ". Exception mesg: " + e.getMessage()); throw new Exception("Creation of NFS datastore on vCenter failed."); } if(morDatastore == null) { - String msg = "Unable to create NFS datastore. host: " + poolHostAddress + ", port: " + String msg = "Unable to create NFS datastore. host: " + poolHostAddress + ", port: " + poolHostPort + ", path: " + poolPath + ", uuid: " + poolUuid; s_logger.error(msg); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore() done(failed)"); throw new Exception(msg); @@ -776,32 +778,32 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } else { morDatastore = _context.getDatastoreMorByPath(poolPath); if(morDatastore == null) { - String msg = "Unable to create VMFS datastore. host: " + poolHostAddress + ", port: " + String msg = "Unable to create VMFS datastore. host: " + poolHostAddress + ", port: " + poolHostPort + ", path: " + poolPath + ", uuid: " + poolUuid; s_logger.error(msg); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore() done(failed)"); throw new Exception(msg); } - + DatastoreMO dsMo = new DatastoreMO(_context, morDatastore); dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid); } } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore() done(successfully)"); - + return morDatastore; } - + @Override public void unmountDatastore(String poolUuid) throws Exception { - + if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid); - + s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid); + HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); if(!hostDatastoreSystemMo.deleteDatastore(poolUuid)) { String msg = "Unable to unmount datastore. uuid: " + poolUuid; @@ -811,35 +813,35 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { s_logger.trace("vCenter API trace - unmountDatastore() done(failed)"); throw new Exception(msg); } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - unmountDatastore() done"); } - + @Override public ManagedObjectReference findDatastore(String poolUuid) throws Exception { HostDatastoreSystemMO hostDsMo = getHostDatastoreSystemMO(); return hostDsMo.findDatastore(poolUuid); } - + @Override public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception { HostDatastoreSystemMO datastoreSystemMo = getHostDatastoreSystemMO(); return datastoreSystemMo.findDatastoreByExportPath(exportPath); } - + @Override public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception { return _mor; } - + @Override public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.get_value()); - + s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.getValue()); + VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); - + HostHardwareSummary hardwareSummary = getHostHardwareSummary(); // TODO: not sure how hyper-thread is counted in VMware resource pool summary.setCpuCount(hardwareSummary.getNumCpuCores()); @@ -850,19 +852,19 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done"); return summary; } - + @Override public VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String managementPortGroup) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.get_value() + ", mgmtPortgroup: " + managementPortGroup); - + s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + managementPortGroup); + VmwareHypervisorHostNetworkSummary summary = new VmwareHypervisorHostNetworkSummary(); - + if(this.getHostType() == VmwareHostType.ESXi) { - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor, + VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); assert(netConfigs != null); - + for(int i = 0; i < netConfigs.length; i++) { if(netConfigs[i].getNicType().equals("management")) { for(HostVirtualNic nic : netConfigs[i].getCandidateVnic()) { @@ -870,7 +872,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { summary.setHostIp(nic.getSpec().getIp().getIpAddress()); summary.setHostNetmask(nic.getSpec().getIp().getSubnetMask()); summary.setHostMacAddress(nic.getSpec().getMac()); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostNetworkSummary() done(successfully)"); return summary; @@ -880,16 +882,16 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } } else { // try with ESX path - HostVirtualNic[] hostVNics = (HostVirtualNic[])_context.getServiceUtil().getDynamicProperty(_mor, + HostVirtualNic[] hostVNics = (HostVirtualNic[])_context.getVimClient().getDynamicProperty(_mor, "config.network.consoleVnic"); - + if(hostVNics != null) { for(HostVirtualNic vnic : hostVNics) { if(vnic.getPortgroup().equals(managementPortGroup)) { summary.setHostIp(vnic.getSpec().getIp().getIpAddress()); summary.setHostNetmask(vnic.getSpec().getIp().getSubnetMask()); summary.setHostMacAddress(vnic.getSpec().getMac()); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostNetworkSummary() done(successfully)"); return summary; @@ -902,29 +904,29 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { s_logger.trace("vCenter API trace - getHyperHostNetworkSummary() done(failed)"); throw new Exception("Uanble to find management port group " + managementPortGroup); } - + @Override public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.get_value()); + s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.getValue()); // // This is to adopt the model when using Cluster as a big host while ComputeResourceSummary is used // directly from VMware resource pool // - // When we break cluster hosts into individual hosts used in our resource allocator, + // When we break cluster hosts into individual hosts used in our resource allocator, // we will have to populate ComputeResourceSummary by ourselves here // HostHardwareSummary hardwareSummary = getHostHardwareSummary(); - + ComputeResourceSummary resourceSummary = new ComputeResourceSummary(); - + // TODO: not sure how hyper-threading is counted in VMware resourceSummary.setNumCpuCores(hardwareSummary.getNumCpuCores()); - + // Note: memory here is in Byte unit resourceSummary.setTotalMemory(hardwareSummary.getMemorySize()); - + // Total CPU is based on (# of cores) x Mhz int totalCpu = hardwareSummary.getCpuMhz() * hardwareSummary.getNumCpuCores(); resourceSummary.setTotalCpu(totalCpu); @@ -932,21 +934,21 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { HostListSummaryQuickStats stats = getHostQuickStats(); if(stats.getOverallCpuUsage() == null || stats.getOverallMemoryUsage() == null) throw new Exception("Unable to get valid overal CPU/Memory usage data, host may be disconnected"); - + resourceSummary.setEffectiveCpu(totalCpu - stats.getOverallCpuUsage()); - + // Note effective memory is in MB unit resourceSummary.setEffectiveMemory(hardwareSummary.getMemorySize()/(1024*1024) - stats.getOverallMemoryUsage()); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostHardwareSummary() done"); - + return resourceSummary; } - + @Override public boolean isHyperHostConnected() throws Exception { - HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)_context.getServiceUtil().getDynamicProperty(_mor, "runtime"); - return runtimeInfo.getConnectionState() == HostSystemConnectionState.connected; + HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)_context.getVimClient().getDynamicProperty(_mor, "runtime"); + return runtimeInfo.getConnectionState() == HostSystemConnectionState.CONNECTED; } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java index 90d690c1101..1198b3365d7 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java @@ -20,6 +20,7 @@ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; +import java.util.List; import org.apache.log4j.Logger; @@ -33,108 +34,108 @@ import com.vmware.vim25.OvfFileItem; public class HttpNfcLeaseMO extends BaseMO { private static final Logger s_logger = Logger.getLogger(HttpNfcLeaseMO.class); - + public HttpNfcLeaseMO(VmwareContext context, ManagedObjectReference morHttpNfcLease) { super(context, morHttpNfcLease); } - + public HttpNfcLeaseMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } public HttpNfcLeaseState getState() throws Exception { - return (HttpNfcLeaseState)_context.getServiceUtil().getDynamicProperty(_mor, "state"); + return (HttpNfcLeaseState)_context.getVimClient().getDynamicProperty(_mor, "state"); } - + public HttpNfcLeaseState waitState(HttpNfcLeaseState[] states) throws Exception { assert(states != null); assert(states.length > 0); - + HttpNfcLeaseState state; while(true) { state = getState(); - if(state == HttpNfcLeaseState.ready || state == HttpNfcLeaseState.error) + if(state == HttpNfcLeaseState.READY || state == HttpNfcLeaseState.ERROR) return state; } } - + public HttpNfcLeaseInfo getLeaseInfo() throws Exception { - return (HttpNfcLeaseInfo)_context.getServiceUtil().getDynamicProperty(_mor, "info"); + return (HttpNfcLeaseInfo)_context.getVimClient().getDynamicProperty(_mor, "info"); } - - public HttpNfcLeaseManifestEntry[] getLeaseManifest() throws Exception { + + public List getLeaseManifest() throws Exception { return _context.getService().httpNfcLeaseGetManifest(_mor); } - + public void completeLease() throws Exception { _context.getService().httpNfcLeaseComplete(_mor); } - + public void abortLease() throws Exception { _context.getService().httpNfcLeaseAbort(_mor, null); } - + public void updateLeaseProgress(int percent) throws Exception { // make sure percentage is in right range if(percent < 0) percent = 0; else if(percent > 100) percent = 100; - + _context.getService().httpNfcLeaseProgress(_mor, percent); } - + public ProgressReporter createProgressReporter() { return new ProgressReporter(); } - - public static long calcTotalBytes(OvfCreateImportSpecResult ovfImportResult) { - OvfFileItem[] fileItemArr = ovfImportResult.getFileItem(); - long totalBytes = 0; - if (fileItemArr != null) { - for (OvfFileItem fi : fileItemArr) { - totalBytes += fi.getSize(); - } - } - return totalBytes; - } - - public static String readOvfContent(String ovfFilePath) throws IOException { - StringBuffer strContent = new StringBuffer(); - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath))); - String lineStr; - while ((lineStr = in.readLine()) != null) { - strContent.append(lineStr); - } - in.close(); - return strContent.toString(); + public static long calcTotalBytes(OvfCreateImportSpecResult ovfImportResult) { + List fileItemArr = ovfImportResult.getFileItem(); + long totalBytes = 0; + if (fileItemArr != null) { + for (OvfFileItem fi : fileItemArr) { + totalBytes += fi.getSize(); + } + } + return totalBytes; } - + + public static String readOvfContent(String ovfFilePath) throws IOException { + StringBuffer strContent = new StringBuffer(); + BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath))); + String lineStr; + while ((lineStr = in.readLine()) != null) { + strContent.append(lineStr); + } + + in.close(); + return strContent.toString(); + } + public class ProgressReporter extends Thread { volatile int _percent; volatile boolean _done; - + public ProgressReporter() { _percent = 0; _done = false; - + setDaemon(true); start(); } - + public void reportProgress(int percent) { _percent = percent; } - + public void close() { if(s_logger.isInfoEnabled()) s_logger.info("close ProgressReporter, interrupt reporter runner to let it quit"); - + _done = true; interrupt(); } - + @Override public void run() { while(!_done) { @@ -149,7 +150,7 @@ public class HttpNfcLeaseMO extends BaseMO { s_logger.warn("Unexpected exception ", e); } } - + if(s_logger.isInfoEnabled()) s_logger.info("ProgressReporter stopped"); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java index 50f95413bd2..abc391fa035 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java @@ -69,16 +69,16 @@ public class HypervisorHostHelper { private static final Logger s_logger = Logger.getLogger(HypervisorHostHelper.class); private static final int DEFAULT_LOCK_TIMEOUT_SECONDS = 600; private static final String s_policyNamePrefix = "cloud.policy."; - + // make vmware-base loosely coupled with cloud-specific stuff, duplicate VLAN.UNTAGGED constant here private static final String UNTAGGED_VLAN_NAME = "untagged"; - - public static VirtualMachineMO findVmFromObjectContent(VmwareContext context, + + public static VirtualMachineMO findVmFromObjectContent(VmwareContext context, ObjectContent[] ocs, String name) { - + if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DynamicProperty prop = oc.getPropSet(0); + DynamicProperty prop = oc.getPropSet().get(0); assert(prop != null); if(prop.getVal().toString().equals(name)) return new VirtualMachineMO(context, oc.getObj()); @@ -86,20 +86,20 @@ public class HypervisorHostHelper { } return null; } - + public static ManagedObjectReference findDatastoreWithBackwardsCompatibility(VmwareHypervisorHost hyperHost, String uuidName) throws Exception { ManagedObjectReference morDs = hyperHost.findDatastore(uuidName.replace("-", "")); if(morDs == null) morDs = hyperHost.findDatastore(uuidName); - + return morDs; } - + public static DatastoreMO getHyperHostDatastoreMO(VmwareHypervisorHost hyperHost, String datastoreName) throws Exception { ObjectContent[] ocs = hyperHost.getDatastorePropertiesOnHyperHost(new String[] { "name"} ); if(ocs != null && ocs.length > 0) { for(ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); + List objProps = oc.getPropSet(); if(objProps != null) { for(DynamicProperty objProp : objProps) { if(objProp.getVal().toString().equals(datastoreName)) @@ -110,7 +110,7 @@ public class HypervisorHostHelper { } return null; } - + public static String getPublicNetworkNamePrefix(String vlanId) { if (UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) { return "cloud.public.untagged"; @@ -118,24 +118,24 @@ public class HypervisorHostHelper { return "cloud.public." + vlanId; } } - + public static String composeCloudNetworkName(String prefix, String vlanId, Integer networkRateMbps, String vSwitchName) { StringBuffer sb = new StringBuffer(prefix); if(vlanId == null || UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) sb.append(".untagged"); else sb.append(".").append(vlanId); - + if(networkRateMbps != null && networkRateMbps.intValue() > 0) sb.append(".").append(String.valueOf(networkRateMbps)); else sb.append(".0"); sb.append(".").append(VersioningContants.PORTGROUP_NAMING_VERSION); sb.append("-").append(vSwitchName); - + return sb.toString(); } - + public static Map getValidatedVsmCredentials(VmwareContext context) throws Exception { Map vsmCredentials = context.getStockObject("vsmcredentials"); String msg; @@ -415,7 +415,7 @@ public class HypervisorHostHelper { boolean createGCTag = false; String networkName; Integer vid = null; - + if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) { createGCTag = true; vid = Integer.parseInt(vlanId); @@ -466,8 +466,8 @@ public class HypervisorHostHelper { bWaitPortGroupReady = true; updatePortProfile(context, ethPortProfileName, networkName, vid, networkRateMbps, peakBandwidth, burstSize); } - // Wait for dvPortGroup on vCenter - if(bWaitPortGroupReady) + // Wait for dvPortGroup on vCenter + if(bWaitPortGroupReady) morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs); else morNetwork = dataCenterMo.getDvPortGroupMor(networkName); @@ -476,7 +476,7 @@ public class HypervisorHostHelper { s_logger.error(msg); throw new Exception(msg); } - + if(createGCTag) { NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork); networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true"); @@ -511,39 +511,39 @@ public class HypervisorHostHelper { currentTrafficShapingPolicy = spec.getDefaultPortConfig().getInShapingPolicy(); // TODO(sateesh): Extract and compare vendor specific configuration specification as well. // DistributedVirtualSwitchKeyedOpaqueBlob[] vendorSpecificConfig = spec.getVendorSpecificConfig(); - + assert(currentTrafficShapingPolicy != null); - + LongPolicy averageBandwidth = currentTrafficShapingPolicy.getAverageBandwidth(); LongPolicy burstSize = currentTrafficShapingPolicy.getBurstSize(); LongPolicy peakBandwidth = currentTrafficShapingPolicy.getPeakBandwidth(); BoolPolicy isEnabled = currentTrafficShapingPolicy.getEnabled(); - - if(!isEnabled.getValue()) + + if(!isEnabled.isValue()) return false; - + if(averageBandwidth != null && !averageBandwidth.equals(shapingPolicy.getAverageBandwidth())) { if(s_logger.isInfoEnabled()) { s_logger.info("Average bandwidth setting in shaping policy doesn't match with existing setting."); - } + } return false; } else if(burstSize != null && !burstSize.equals(shapingPolicy.getBurstSize())) { if(s_logger.isInfoEnabled()) { s_logger.info("Burst size setting in shaping policy doesn't match with existing setting."); - } + } return false; } else if(peakBandwidth != null && !peakBandwidth.equals(shapingPolicy.getPeakBandwidth())) { if(s_logger.isInfoEnabled()) { s_logger.info("Peak bandwidth setting in shaping policy doesn't match with existing setting."); - } + } return false; } - + return true; } public static Pair prepareNetwork(String vSwitchName, String namePrefix, - HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, + HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, boolean syncPeerHosts) throws Exception { HostVirtualSwitch vSwitch; @@ -558,12 +558,12 @@ public class HypervisorHostHelper { boolean createGCTag = false; String networkName; Integer vid = null; - + if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) { createGCTag = true; vid = Integer.parseInt(vlanId); } - + networkName = composeCloudNetworkName(namePrefix, vlanId, networkRateMbps, vSwitchName); HostNetworkSecurityPolicy secPolicy = null; if (namePrefix.equalsIgnoreCase("cloud.private")) { @@ -577,11 +577,11 @@ public class HypervisorHostHelper { shapingPolicy = new HostNetworkTrafficShapingPolicy(); shapingPolicy.setEnabled(true); shapingPolicy.setAverageBandwidth((long)networkRateMbps.intValue()*1024L*1024L); - - // + + // // TODO : people may have different opinion on how to set the following // - + // give 50% premium to peek shapingPolicy.setPeakBandwidth((long)(shapingPolicy.getAverageBandwidth()*1.5)); @@ -602,7 +602,7 @@ public class HypervisorHostHelper { } ManagedObjectReference morNetwork; - if(bWaitPortGroupReady) + if(bWaitPortGroupReady) morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs); else morNetwork = hostMo.getNetworkMor(networkName); @@ -611,24 +611,24 @@ public class HypervisorHostHelper { s_logger.error(msg); throw new Exception(msg); } - + if(createGCTag) { NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork); networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true"); } - + if(syncPeerHosts) { ManagedObjectReference morParent = hostMo.getParentMor(); if(morParent != null && morParent.getType().equals("ClusterComputeResource")) { // to be conservative, lock cluster - GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.get_value()); + GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.getValue()); try { if(lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) { try { - ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getServiceUtil().getDynamicProperty(morParent, "host"); + ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host"); if(hosts != null) { for(ManagedObjectReference otherHost: hosts) { - if(!otherHost.get_value().equals(hostMo.getMor().get_value())) { + if(!otherHost.getValue().equals(hostMo.getMor().getValue())) { HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost); try { if(s_logger.isDebugEnabled()) @@ -655,7 +655,7 @@ public class HypervisorHostHelper { s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName); return new Pair(morNetwork, networkName); } - + private static boolean isSpecMatch(HostPortGroupSpec spec, Integer vlanId, HostNetworkTrafficShapingPolicy shapingPolicy) { // check VLAN configuration if(vlanId != null) { @@ -670,17 +670,17 @@ public class HypervisorHostHelper { HostNetworkTrafficShapingPolicy policyInSpec = null; if(spec.getPolicy() != null) policyInSpec = spec.getPolicy().getShapingPolicy(); - + if(policyInSpec != null && shapingPolicy == null || policyInSpec == null && shapingPolicy != null) return false; - + if(policyInSpec == null && shapingPolicy == null) return true; - + // so far policyInSpec and shapingPolicy should both not be null - if(policyInSpec.getEnabled() == null || !policyInSpec.getEnabled().booleanValue()) + if(policyInSpec.isEnabled() == null || !policyInSpec.isEnabled().booleanValue()) return false; - + if(policyInSpec.getAverageBandwidth() == null || policyInSpec.getAverageBandwidth().longValue() != shapingPolicy.getAverageBandwidth().longValue()) return false; @@ -689,10 +689,10 @@ public class HypervisorHostHelper { if(policyInSpec.getBurstSize() == null || policyInSpec.getBurstSize().longValue() != shapingPolicy.getBurstSize().longValue()) return false; - + return true; } - + public static ManagedObjectReference waitForNetworkReady(HostMO hostMo, String networkName, long timeOutMs) throws Exception { @@ -713,14 +713,14 @@ public class HypervisorHostHelper { return morNetwork; } - - public static boolean createBlankVm(VmwareHypervisorHost host, String vmName, - int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, + + public static boolean createBlankVm(VmwareHypervisorHost host, String vmName, + int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception { - + if(s_logger.isInfoEnabled()) s_logger.info("Create blank VM. cpuCount: " + cpuCount + ", cpuSpeed(MHz): " + cpuSpeedMHz + ", mem(Mb): " + memoryMB); - + // VM config basics VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); vmConfig.setName(vmName); @@ -728,62 +728,63 @@ public class HypervisorHostHelper { // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); - scsiController.setSharedBus(VirtualSCSISharing.noSharing); + scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); - scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); DatastoreMO dsMo = new DatastoreMO(host.getContext(), morDs); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); - + VirtualMachineVideoCard videoCard = new VirtualMachineVideoCard(); videoCard.setControllerKey(100); videoCard.setUseAutoDetect(true); - + VirtualDeviceConfigSpec videoDeviceSpec = new VirtualDeviceConfigSpec(); videoDeviceSpec.setDevice(videoCard); - videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.add); - - vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec, videoDeviceSpec }); + videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); + + vmConfig.getDeviceChange().add(scsiControllerSpec); + vmConfig.getDeviceChange().add(videoDeviceSpec); if(host.createVm(vmConfig)) { VirtualMachineMO vmMo = host.findVmOnHyperHost(vmName); assert(vmMo != null); - + int ideControllerKey = -1; while(ideControllerKey < 0) { ideControllerKey = vmMo.tryGetIDEDeviceControllerKey(); if(ideControllerKey >= 0) break; - + s_logger.info("Waiting for IDE controller be ready in VM: " + vmName); Thread.sleep(1000); } - + if(snapshotDirToParent) { String snapshotDir = String.format("/vmfs/volumes/%s/", dsMo.getName()); - + s_logger.info("Switch snapshot working directory to " + snapshotDir + " for " + vmName); vmMo.setSnapshotDirectory(snapshotDir); - + // Don't have a good way to test if the VM is really ready for use through normal API after configuration file manipulation, // delay 3 seconds Thread.sleep(3000); } - + s_logger.info("Blank VM: " + vmName + " is ready for use"); return true; } return false; } - + public static String resolveHostNameInUrl(DatacenterMO dcMo, String url) { - + s_logger.info("Resolving host name in url through vCenter, url: " + url); - + URI uri; try { uri = new URI(url); @@ -791,13 +792,13 @@ public class HypervisorHostHelper { s_logger.warn("URISyntaxException on url " + url); return url; } - + String host = uri.getHost(); if(NetUtils.isValidIp(host)) { s_logger.info("host name in url is already in IP address, url: " + url); return url; } - + try { ManagedObjectReference morHost = dcMo.findHost(host); if(morHost != null) { @@ -807,18 +808,18 @@ public class HypervisorHostHelper { managementPortGroupName = (String)dcMo.getContext().getStockObject("manageportgroup"); else managementPortGroupName = (String)dcMo.getContext().getStockObject("serviceconsole"); - + VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(managementPortGroupName); if(summary == null) { s_logger.warn("Unable to resolve host name in url through vSphere, url: " + url); return url; } - + String hostIp = summary.getHostIp(); - + try { URI resolvedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostIp, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); - + s_logger.info("url " + url + " is resolved to " + resolvedUri.toString() + " through vCenter"); return resolvedUri.toString(); } catch (URISyntaxException e) { @@ -829,77 +830,77 @@ public class HypervisorHostHelper { } catch(Exception e) { s_logger.warn("Unexpected exception ", e); } - + return url; } - - public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, + + public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception { - + assert(morRp != null); - - OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams(); - importSpecParams.setHostSystem(morHost); - importSpecParams.setLocale("US"); - importSpecParams.setEntityName(vmName); + + OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams(); + importSpecParams.setHostSystem(morHost); + importSpecParams.setLocale("US"); + importSpecParams.setEntityName(vmName); importSpecParams.setDeploymentOption(""); importSpecParams.setDiskProvisioning(diskOption); // diskOption: thin, thick, etc - importSpecParams.setPropertyMapping(null); - + //importSpecParams.setPropertyMapping(null); + String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath); VmwareContext context = host.getContext(); OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec( - context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, + context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams); - + if(ovfImportResult == null) { - String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption; s_logger.error(msg); throw new Exception(msg); } - + DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter()); - ManagedObjectReference morLease = context.getService().importVApp(morRp, + ManagedObjectReference morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost); if(morLease == null) { - String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption; s_logger.error(msg); throw new Exception(msg); } final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease); HttpNfcLeaseState state = leaseMo.waitState( - new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error }); + new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR }); try { - if(state == HttpNfcLeaseState.ready) { + if(state == HttpNfcLeaseState.READY) { final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult); - File ovfFile = new File(ovfFilePath); - + File ovfFile = new File(ovfFilePath); + HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo(); - HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl(); + List deviceUrls = httpNfcLeaseInfo.getDeviceUrl(); long bytesAlreadyWritten = 0; - + final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter(); try { for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) { - String deviceKey = deviceUrl.getImportKey(); + String deviceKey = deviceUrl.getImportKey(); for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) { - if (deviceKey.equals(ovfFileItem.getDeviceId())) { + if (deviceKey.equals(ovfFileItem.getDeviceId())) { String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath(); String urlToPost = deviceUrl.getUrl(); urlToPost = resolveHostNameInUrl(dcMo, urlToPost); - - context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, + + context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate () { public void action(Long param) { progressReporter.reportProgress((int)(param * 100 / totalBytes)); } - }); - + }); + bytesAlreadyWritten += ovfFileItem.getSize(); - } - } + } + } } } finally { progressReporter.close(); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java index dadd7d12a01..b8e3ab42b5b 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java @@ -23,17 +23,17 @@ public class NetworkMO extends BaseMO { public NetworkMO(VmwareContext context, ManagedObjectReference morCluster) { super(context, morCluster); } - + public NetworkMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public void destroyNetwork() throws Exception { - _context.getService().destroyNetwork(_mor); + _context.getService().destroyNetwork(_mor); } - + public ManagedObjectReference[] getVMsOnNetwork() throws Exception { - ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "vm"); + ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "vm"); return vms; } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java index 5d57bd1fb09..6c2b7bb2ab7 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java @@ -16,7 +16,13 @@ // under the License. package com.cloud.hypervisor.vmware.mo; +import java.util.ArrayList; import java.util.Calendar; +import java.util.List; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.ManagedObjectReference; @@ -28,58 +34,91 @@ import com.vmware.vim25.PerfMetricId; import com.vmware.vim25.PerfProviderSummary; import com.vmware.vim25.PerfQuerySpec; +import edu.emory.mathcs.backport.java.util.Arrays; + public class PerfManagerMO extends BaseMO { public PerfManagerMO(VmwareContext context, ManagedObjectReference mor) { super(context, mor); } - + public PerfManagerMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public void createPerfInterval(PerfInterval interval) throws Exception { _context.getService().createPerfInterval(_mor, interval); } - - public PerfMetricId[] queryAvailablePerfMetric(ManagedObjectReference morEntity, Calendar beginTime, + + /** + * Converts Calendar object into XMLGregorianCalendar + * + * @param calendar Object to be converted + * @return XMLGregorianCalendar + */ + private XMLGregorianCalendar calendarToXMLGregorianCalendar(Calendar calendar) throws DatatypeConfigurationException { + + DatatypeFactory dtf = DatatypeFactory.newInstance(); + XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar(); + xgc.setYear(calendar.get(Calendar.YEAR)); + xgc.setMonth(calendar.get(Calendar.MONTH) + 1); + xgc.setDay(calendar.get(Calendar.DAY_OF_MONTH)); + xgc.setHour(calendar.get(Calendar.HOUR_OF_DAY)); + xgc.setMinute(calendar.get(Calendar.MINUTE)); + xgc.setSecond(calendar.get(Calendar.SECOND)); + xgc.setMillisecond(calendar.get(Calendar.MILLISECOND)); + + // Calendar ZONE_OFFSET and DST_OFFSET fields are in milliseconds. + int offsetInMinutes = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000); + xgc.setTimezone(offsetInMinutes); + return xgc; + } + + public List queryAvailablePerfMetric(ManagedObjectReference morEntity, Calendar beginTime, Calendar endTime, Integer intervalId) throws Exception { - - return _context.getService().queryAvailablePerfMetric(_mor, morEntity, beginTime, endTime, intervalId); + + return _context.getService().queryAvailablePerfMetric(_mor, morEntity, calendarToXMLGregorianCalendar(beginTime), + calendarToXMLGregorianCalendar(endTime), intervalId); } public PerfCompositeMetric queryPerfComposite(PerfQuerySpec spec) throws Exception { return _context.getService().queryPerfComposite(_mor, spec); } - - public PerfCounterInfo[] queryPerfCounter(int[] counterId) throws Exception { - return _context.getService().queryPerfCounter(_mor, counterId); - } - - public PerfCounterInfo[] queryPerfCounterByLevel(int level) throws Exception { - return _context.getService().queryPerfCounterByLevel(_mor, level); - } - - public PerfProviderSummary queryPerfProviderSummary(ManagedObjectReference morEntity) throws Exception { - return _context.getService().queryPerfProviderSummary(_mor, morEntity); + + public List queryPerfCounter(int[] counterId) throws Exception { + List counterArr = new ArrayList(); + if ( counterId != null){ + for (int i = 0; i < counterId.length; i++ ){ + counterArr.add(counterId[i]); + } + } + return _context.getService().queryPerfCounter(_mor, counterArr); } - public PerfEntityMetricBase[] queryPerf(PerfQuerySpec[] specs) throws Exception { - return _context.getService().queryPerf(_mor, specs); + public List queryPerfCounterByLevel(int level) throws Exception { + return _context.getService().queryPerfCounterByLevel(_mor, level); } - + + public PerfProviderSummary queryPerfProviderSummary(ManagedObjectReference morEntity) throws Exception { + return _context.getService().queryPerfProviderSummary(_mor, morEntity); + } + + public List queryPerf(PerfQuerySpec[] specs) throws Exception { + return _context.getService().queryPerf(_mor, Arrays.asList(specs)); + } + public void removePerfInterval(int samplePeriod) throws Exception { _context.getService().removePerfInterval(_mor, samplePeriod); } - + public void updatePerfInterval(PerfInterval interval) throws Exception { _context.getService().updatePerfInterval(_mor, interval); } - + public PerfCounterInfo[] getCounterInfo() throws Exception { - return (PerfCounterInfo[])_context.getServiceUtil().getDynamicProperty(_mor, "perfCounter"); + return (PerfCounterInfo[])_context.getVimClient().getDynamicProperty(_mor, "perfCounter"); } - + public PerfInterval[] getIntervalInfo() throws Exception { - return (PerfInterval[])_context.getServiceUtil().getDynamicProperty(_mor, "historicalInterval"); + return (PerfInterval[])_context.getVimClient().getDynamicProperty(_mor, "historicalInterval"); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java index 3b0b153dc7f..694734bf09a 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java @@ -27,48 +27,48 @@ public class TaskMO extends BaseMO { public TaskMO(VmwareContext context, ManagedObjectReference morTask) { super(context, morTask); } - + public TaskMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public TaskInfo getTaskInfo() throws Exception { - return (TaskInfo)getContext().getServiceUtil().getDynamicProperty(_mor, "info"); + return (TaskInfo)getContext().getVimClient().getDynamicProperty(_mor, "info"); } - + public void setTaskDescription(LocalizableMessage description) throws Exception { _context.getService().setTaskDescription(_mor, description); } - + public void setTaskState(TaskInfoState state, Object result, LocalizedMethodFault fault) throws Exception { _context.getService().setTaskState(_mor, state, result, fault); } - + public void updateProgress(int percentDone) throws Exception { _context.getService().updateProgress(_mor, percentDone); } - + public void cancelTask() throws Exception { _context.getService().cancelTask(_mor); } - + public static String getTaskFailureInfo(VmwareContext context, ManagedObjectReference morTask) { StringBuffer sb = new StringBuffer(); - + try { - TaskInfo info = (TaskInfo)context.getServiceUtil().getDynamicProperty(morTask, "info"); + TaskInfo info = (TaskInfo)context.getVimClient().getDynamicProperty(morTask, "info"); if(info != null) { LocalizedMethodFault fault = info.getError(); if(fault != null) { sb.append(fault.getLocalizedMessage()).append(" "); - + if(fault.getFault() != null) sb.append(fault.getFault().getClass().getName()); } } } catch(Exception e) { } - + return sb.toString(); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java index aab82100421..e21d06adf62 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java @@ -25,132 +25,132 @@ import com.vmware.vim25.VirtualDiskSpec; public class VirtualDiskManagerMO extends BaseMO { private static final Logger s_logger = Logger.getLogger(VirtualDiskManagerMO.class); - + public VirtualDiskManagerMO(VmwareContext context, ManagedObjectReference morDiskMgr) { super(context, morDiskMgr); } - + public VirtualDiskManagerMO(VmwareContext context, String morType, String morValue) { super(context, morType, morValue); } - + public void copyVirtualDisk(String srcName, ManagedObjectReference morSrcDc, - String destName, ManagedObjectReference morDestDc, VirtualDiskSpec diskSpec, + String destName, ManagedObjectReference morDestDc, VirtualDiskSpec diskSpec, boolean force) throws Exception { - - ManagedObjectReference morTask = _context.getService().copyVirtualDisk_Task(_mor, srcName, morSrcDc, destName, morDestDc, diskSpec, force); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) - throw new Exception("Unable to copy virtual disk " + srcName + " to " + destName - + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - - _context.waitForTaskProgressDone(morTask); - } - - public void createVirtualDisk(String name, ManagedObjectReference morDc, VirtualDiskSpec diskSpec) throws Exception { - ManagedObjectReference morTask = _context.getService().createVirtualDisk_Task(_mor, name, morDc, diskSpec); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) - throw new Exception("Unable to create virtual disk " + name + + ManagedObjectReference morTask = _context.getService().copyVirtualDiskTask(_mor, srcName, morSrcDc, destName, morDestDc, diskSpec, force); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) + throw new Exception("Unable to copy virtual disk " + srcName + " to " + destName + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + + public void createVirtualDisk(String name, ManagedObjectReference morDc, VirtualDiskSpec diskSpec) throws Exception { + ManagedObjectReference morTask = _context.getService().createVirtualDiskTask(_mor, name, morDc, diskSpec); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) + throw new Exception("Unable to create virtual disk " + name + + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + + _context.waitForTaskProgressDone(morTask); + } + public void defragmentVirtualDisk(String name, ManagedObjectReference morDc) throws Exception { - ManagedObjectReference morTask = _context.getService().defragmentVirtualDisk_Task(_mor, name, morDc); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().defragmentVirtualDiskTask(_mor, name, morDc); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to defragment virtual disk " + name + " due to " + result); _context.waitForTaskProgressDone(morTask); } - + public void deleteVirtualDisk(String name, ManagedObjectReference morDc) throws Exception { - ManagedObjectReference morTask = _context.getService().deleteVirtualDisk_Task(_mor, name, morDc); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().deleteVirtualDiskTask(_mor, name, morDc); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to delete virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public void eagerZeroVirtualDisk(String name, ManagedObjectReference morDc) throws Exception { - ManagedObjectReference morTask = _context.getService().eagerZeroVirtualDisk_Task(_mor, name, morDc); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().eagerZeroVirtualDiskTask(_mor, name, morDc); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to eager zero virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public void extendVirtualDisk(String name, ManagedObjectReference morDc, long newCapacityKb, boolean eagerZero) throws Exception { - ManagedObjectReference morTask = _context.getService().extendVirtualDisk_Task(_mor, name, morDc, newCapacityKb, eagerZero); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().extendVirtualDiskTask(_mor, name, morDc, newCapacityKb, eagerZero); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to extend virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public void inflateVirtualDisk(String name, ManagedObjectReference morDc) throws Exception { - ManagedObjectReference morTask = _context.getService().inflateVirtualDisk_Task(_mor, name, morDc); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().inflateVirtualDiskTask(_mor, name, morDc); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to inflate virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public void shrinkVirtualDisk(String name, ManagedObjectReference morDc, boolean copy) throws Exception { - ManagedObjectReference morTask = _context.getService().shrinkVirtualDisk_Task(_mor, name, morDc, copy); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().shrinkVirtualDiskTask(_mor, name, morDc, copy); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to shrink virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public void zeroFillVirtualDisk(String name, ManagedObjectReference morDc) throws Exception { - ManagedObjectReference morTask = _context.getService().zeroFillVirtualDisk_Task(_mor, name, morDc); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) + ManagedObjectReference morTask = _context.getService().zeroFillVirtualDiskTask(_mor, name, morDc); + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) throw new Exception("Unable to zero fill virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public void moveVirtualDisk(String srcName, ManagedObjectReference morSrcDc, String destName, ManagedObjectReference morDestDc, boolean force) throws Exception { - - ManagedObjectReference morTask = _context.getService().moveVirtualDisk_Task(_mor, srcName, morSrcDc, + + ManagedObjectReference morTask = _context.getService().moveVirtualDiskTask(_mor, srcName, morSrcDc, destName, morDestDc, force); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) - throw new Exception("Unable to move virtual disk " + srcName + " to " + destName + + boolean result = _context.getVimClient().waitForTask(morTask); + if(!result) + throw new Exception("Unable to move virtual disk " + srcName + " to " + destName + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); _context.waitForTaskProgressDone(morTask); } - + public int queryVirtualDiskFragmentation(String name, ManagedObjectReference morDc) throws Exception { return _context.getService().queryVirtualDiskFragmentation(_mor, name, morDc); } - + public HostDiskDimensionsChs queryVirtualDiskGeometry(String name, ManagedObjectReference morDc) throws Exception { return _context.getService().queryVirtualDiskGeometry(_mor, name, morDc); } - + public String queryVirtualDiskUuid(String name, ManagedObjectReference morDc) throws Exception { return _context.getService().queryVirtualDiskUuid(_mor, name, morDc); } - + public void setVirtualDiskUuid(String name, ManagedObjectReference morDc, String uuid) throws Exception { _context.getService().setVirtualDiskUuid(_mor, name, morDc, uuid); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index 0dc41a1f597..76072cd614a 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -97,6 +97,8 @@ import com.vmware.vim25.VirtualPCIController; import com.vmware.vim25.VirtualSCSIController; import com.vmware.vim25.VirtualSCSISharing; +import edu.emory.mathcs.backport.java.util.Arrays; + public class VirtualMachineMO extends BaseMO { private static final Logger s_logger = Logger.getLogger(VirtualMachineMO.class); @@ -117,7 +119,7 @@ public class VirtualMachineMO extends BaseMO { PropertySpec pSpec = new PropertySpec(); pSpec.setType("Datastore"); - pSpec.setPathSet(new String[] { "name" }); + pSpec.getPathSet().add("name"); TraversalSpec vmDatastoreTraversal = new TraversalSpec(); vmDatastoreTraversal.setType("VirtualMachine"); @@ -127,19 +129,21 @@ public class VirtualMachineMO extends BaseMO { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { vmDatastoreTraversal }); + oSpec.getSelectSet().add(vmDatastoreTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); if(ocs != null) { for(ObjectContent oc : ocs) { - DynamicProperty prop = oc.getPropSet(0); + DynamicProperty prop = oc.getPropSet().get(0); if(prop.getVal().toString().equals(dsName)) { return new Pair(new DatastoreMO(_context, oc.getObj()), dsName); } @@ -155,11 +159,11 @@ public class VirtualMachineMO extends BaseMO { } public String getVmName() throws Exception { - return (String)getContext().getServiceUtil().getDynamicProperty(_mor, "name"); + return (String)getContext().getVimClient().getDynamicProperty(_mor, "name"); } public GuestInfo getVmGuestInfo() throws Exception { - return (GuestInfo)getContext().getServiceUtil().getDynamicProperty(_mor, "guest"); + return (GuestInfo)getContext().getVimClient().getDynamicProperty(_mor, "guest"); } public boolean isVMwareToolsRunning() throws Exception { @@ -172,13 +176,13 @@ public class VirtualMachineMO extends BaseMO { } public boolean powerOn() throws Exception { - if(getPowerState() == VirtualMachinePowerState.poweredOn) + if(getPowerState() == VirtualMachinePowerState.POWERED_ON) return true; - ManagedObjectReference morTask = _context.getService().powerOnVM_Task(_mor, null); + ManagedObjectReference morTask = _context.getService().powerOnVMTask(_mor, null); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -189,7 +193,7 @@ public class VirtualMachineMO extends BaseMO { } public boolean powerOff() throws Exception { - if(getPowerState() == VirtualMachinePowerState.poweredOff) + if(getPowerState() == VirtualMachinePowerState.POWERED_OFF) return true; return powerOffNoCheck(); @@ -197,7 +201,7 @@ public class VirtualMachineMO extends BaseMO { public boolean safePowerOff(int shutdownWaitMs) throws Exception { - if(getPowerState() == VirtualMachinePowerState.poweredOff) + if(getPowerState() == VirtualMachinePowerState.POWERED_OFF) return true; if(isVMwareToolsRunning()) { @@ -208,14 +212,14 @@ public class VirtualMachineMO extends BaseMO { shutdown(); long startTick = System.currentTimeMillis(); - while(getPowerState() != VirtualMachinePowerState.poweredOff && System.currentTimeMillis() - startTick < shutdownWaitMs) { + while(getPowerState() != VirtualMachinePowerState.POWERED_OFF && System.currentTimeMillis() - startTick < shutdownWaitMs) { try { Thread.sleep(1000); } catch(InterruptedException e) { } } - if(getPowerState() != VirtualMachinePowerState.poweredOff) { + if(getPowerState() != VirtualMachinePowerState.POWERED_OFF) { s_logger.info("can not gracefully shutdown VM within " + (shutdownWaitMs/1000) + " seconds, we will perform force power off on VM " + vmName); return powerOffNoCheck(); } @@ -230,17 +234,17 @@ public class VirtualMachineMO extends BaseMO { } private boolean powerOffNoCheck() throws Exception { - ManagedObjectReference morTask = _context.getService().powerOffVM_Task(_mor); + ManagedObjectReference morTask = _context.getService().powerOffVMTask(_mor); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); // It seems that even if a power-off task is returned done, VM state may still not be marked, // wait up to 5 seconds to make sure to avoid race conditioning for immediate following on operations // that relies on a powered-off VM long startTick = System.currentTimeMillis(); - while(getPowerState() != VirtualMachinePowerState.poweredOff && System.currentTimeMillis() - startTick < 5000) { + while(getPowerState() != VirtualMachinePowerState.POWERED_OFF && System.currentTimeMillis() - startTick < 5000) { try { Thread.sleep(1000); } catch(InterruptedException e) { @@ -248,7 +252,7 @@ public class VirtualMachineMO extends BaseMO { } return true; } else { - if(getPowerState() == VirtualMachinePowerState.poweredOff) { + if(getPowerState() == VirtualMachinePowerState.POWERED_OFF) { // to help deal with possible race-condition s_logger.info("Current power-off task failed. However, VM has been switched to the state we are expecting for"); return true; @@ -262,7 +266,7 @@ public class VirtualMachineMO extends BaseMO { public VirtualMachinePowerState getPowerState() throws Exception { - VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; + VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; // This is really ugly, there is a case that when windows guest VM is doing sysprep, the temporary // rebooting process may let us pick up a "poweredOff" state during VMsync process, this can trigger @@ -272,8 +276,8 @@ public class VirtualMachineMO extends BaseMO { // In the future, VMsync should not kick off CloudStack action (this is not a HA case) based on VM // state report, until then we can remove this hacking fix for(int i = 0; i < 3; i++) { - powerState = (VirtualMachinePowerState)getContext().getServiceUtil().getDynamicProperty(_mor, "runtime.powerState"); - if(powerState == VirtualMachinePowerState.poweredOff) { + powerState = (VirtualMachinePowerState)getContext().getVimClient().getDynamicProperty(_mor, "runtime.powerState"); + if(powerState == VirtualMachinePowerState.POWERED_OFF) { try { Thread.sleep(1000); } catch(InterruptedException e) { @@ -287,10 +291,10 @@ public class VirtualMachineMO extends BaseMO { } public boolean reset() throws Exception { - ManagedObjectReference morTask = _context.getService().resetVM_Task(_mor); + ManagedObjectReference morTask = _context.getService().resetVMTask(_mor); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -317,11 +321,11 @@ public class VirtualMachineMO extends BaseMO { } public boolean migrate(ManagedObjectReference morRp, ManagedObjectReference morTargetHost) throws Exception { - ManagedObjectReference morTask = _context.getService().migrateVM_Task(_mor, - morRp, morTargetHost, VirtualMachineMovePriority.defaultPriority, null); + ManagedObjectReference morTask = _context.getService().migrateVMTask(_mor, + morRp, morTargetHost, VirtualMachineMovePriority.DEFAULT_PRIORITY, null); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -335,11 +339,11 @@ public class VirtualMachineMO extends BaseMO { VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); relocateSpec.setHost(morTargetHost); - ManagedObjectReference morTask = _context.getService().relocateVM_Task(_mor, + ManagedObjectReference morTask = _context.getService().relocateVMTask(_mor, relocateSpec, null); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -350,17 +354,17 @@ public class VirtualMachineMO extends BaseMO { } public VirtualMachineSnapshotInfo getSnapshotInfo() throws Exception { - return (VirtualMachineSnapshotInfo)_context.getServiceUtil().getDynamicProperty(_mor, "snapshot"); + return (VirtualMachineSnapshotInfo)_context.getVimClient().getDynamicProperty(_mor, "snapshot"); } public boolean createSnapshot(String snapshotName, String snapshotDescription, boolean dumpMemory, boolean quiesce) throws Exception { - ManagedObjectReference morTask = _context.getService().createSnapshot_Task(_mor, snapshotName, + ManagedObjectReference morTask = _context.getService().createSnapshotTask(_mor, snapshotName, snapshotDescription, dumpMemory, quiesce); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); ManagedObjectReference morSnapshot = null; @@ -393,9 +397,9 @@ public class VirtualMachineMO extends BaseMO { return false; } - ManagedObjectReference morTask = _context.getService().removeSnapshot_Task(morSnapshot, removeChildren); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + ManagedObjectReference morTask = _context.getService().removeSnapshotTask(morSnapshot, removeChildren, true); + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -409,11 +413,11 @@ public class VirtualMachineMO extends BaseMO { VirtualMachineSnapshotInfo snapshotInfo = getSnapshotInfo(); if(snapshotInfo != null && snapshotInfo.getRootSnapshotList() != null) { - VirtualMachineSnapshotTree[] tree = snapshotInfo.getRootSnapshotList(); + List tree = snapshotInfo.getRootSnapshotList(); for(VirtualMachineSnapshotTree treeNode : tree) { - ManagedObjectReference morTask = _context.getService().removeSnapshot_Task(treeNode.getSnapshot(), true); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + ManagedObjectReference morTask = _context.getService().removeSnapshotTask(treeNode.getSnapshot(), true, true); + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); } else { s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -474,29 +478,31 @@ public class VirtualMachineMO extends BaseMO { public String getSnapshotDescriptorDatastorePath() throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); - pSpec.setPathSet(new String[] { "name", "config.files" }); + pSpec.getPathSet().add("name"); + pSpec.getPathSet().add("config.files"); ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.FALSE); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); assert(ocs != null); String vmName = null; VirtualMachineFileInfo fileInfo = null; - assert(ocs.length == 1); + assert(ocs.size() == 1); for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); + List props = oc.getPropSet(); if(props != null) { - assert(props.length == 2); + assert(props.size() == 2); for(DynamicProperty prop : props) { if(prop.getName().equals("name")) { @@ -535,10 +541,10 @@ public class VirtualMachineMO extends BaseMO { relocSpec.setDatastore(morDs); relocSpec.setPool(morResourcePool); - ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec); + ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -560,18 +566,19 @@ public class VirtualMachineMO extends BaseMO { VirtualDisk[] independentDisks = getAllIndependentDiskDevice(); VirtualMachineRelocateSpec rSpec = new VirtualMachineRelocateSpec(); if(independentDisks.length > 0) { - VirtualMachineRelocateSpecDiskLocator[] diskLocator = new VirtualMachineRelocateSpecDiskLocator[independentDisks.length]; - for(int i = 0; i < diskLocator.length; i++) { - diskLocator[i] = new VirtualMachineRelocateSpecDiskLocator(); - diskLocator[i].setDatastore(morDs); - diskLocator[i].setDiskId(independentDisks[i].getKey()); - diskLocator[i].setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._moveAllDiskBackingsAndDisallowSharing); + List diskLocator = new ArrayList(independentDisks.length); + for(int i = 0; i < independentDisks.length; i++) { + VirtualMachineRelocateSpecDiskLocator loc = new VirtualMachineRelocateSpecDiskLocator(); + loc.setDatastore(morDs); + loc.setDiskId(independentDisks[i].getKey()); + loc.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING.toString()); + diskLocator.add(loc); } - rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._createNewChildDiskBacking); - rSpec.setDisk(diskLocator); + rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.toString()); + rSpec.getDisk().addAll(diskLocator); } else { - rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._createNewChildDiskBacking); + rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.toString()); } rSpec.setPool(morResourcePool); @@ -581,10 +588,10 @@ public class VirtualMachineMO extends BaseMO { cloneSpec.setLocation(rSpec); cloneSpec.setSnapshot(morBaseSnapshot); - ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec); + ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -595,34 +602,34 @@ public class VirtualMachineMO extends BaseMO { } public VirtualMachineRuntimeInfo getRuntimeInfo() throws Exception { - return (VirtualMachineRuntimeInfo)_context.getServiceUtil().getDynamicProperty( + return (VirtualMachineRuntimeInfo)_context.getVimClient().getDynamicProperty( _mor, "runtime"); } public VirtualMachineConfigInfo getConfigInfo() throws Exception { - return (VirtualMachineConfigInfo)_context.getServiceUtil().getDynamicProperty( + return (VirtualMachineConfigInfo)_context.getVimClient().getDynamicProperty( _mor, "config"); } public VirtualMachineConfigSummary getConfigSummary() throws Exception { - return (VirtualMachineConfigSummary)_context.getServiceUtil().getDynamicProperty( + return (VirtualMachineConfigSummary)_context.getVimClient().getDynamicProperty( _mor, "summary.config"); } public VirtualMachineFileInfo getFileInfo() throws Exception { - return (VirtualMachineFileInfo)_context.getServiceUtil().getDynamicProperty( + return (VirtualMachineFileInfo)_context.getVimClient().getDynamicProperty( _mor, "config.files"); } public ManagedObjectReference getParentMor() throws Exception { - return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty( + return (ManagedObjectReference)_context.getVimClient().getDynamicProperty( _mor, "parent"); } public String[] getNetworks() throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setType("Network"); - pSpec.setPathSet(new String[] {"name"}); + pSpec.getPathSet().add("name"); TraversalSpec vm2NetworkTraversal = new TraversalSpec(); vm2NetworkTraversal.setType("VirtualMachine"); @@ -632,20 +639,21 @@ public class VirtualMachineMO extends BaseMO { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal }); + oSpec.getSelectSet().add(vm2NetworkTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); List networks = new ArrayList(); - if(ocs != null && ocs.length > 0) { + if(ocs != null && ocs.size() > 0) { for(ObjectContent oc : ocs) { - networks.add(oc.getPropSet(0).getVal().toString()); + networks.add(oc.getPropSet().get(0).getVal().toString()); } } return networks.toArray(new String[0]); @@ -663,7 +671,9 @@ public class VirtualMachineMO extends BaseMO { PropertySpec pSpec = new PropertySpec(); pSpec.setType("Network"); - pSpec.setPathSet(new String[] {"name", "vm", String.format("value[%d]", gcTagKey)}); + pSpec.getPathSet().add("name"); + pSpec.getPathSet().add("vm"); + pSpec.getPathSet().add(String.format("value[%d]", gcTagKey)); TraversalSpec vm2NetworkTraversal = new TraversalSpec(); vm2NetworkTraversal.setType("VirtualMachine"); @@ -673,17 +683,19 @@ public class VirtualMachineMO extends BaseMO { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(_mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal }); + oSpec.getSelectSet().add(vm2NetworkTraversal); PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); - ObjectContent[] ocs = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); + List ocs = _context.getService().retrieveProperties( + _context.getPropertyCollector(), pfSpecArr); - if(ocs != null && ocs.length > 0) { + + if(ocs != null && ocs.size() > 0) { for(ObjectContent oc : ocs) { ArrayOfManagedObjectReference morVms = null; String gcTagValue = null; @@ -702,7 +714,7 @@ public class VirtualMachineMO extends BaseMO { } NetworkDetails details = new NetworkDetails(name, oc.getObj(), - (morVms != null ? morVms.getManagedObjectReference() : null), + (morVms != null ? morVms.getManagedObjectReference().toArray(new ManagedObjectReference[morVms.getManagedObjectReference().size()]) : null), gcTagValue); networks.add(details); @@ -755,11 +767,11 @@ public class VirtualMachineMO extends BaseMO { public boolean setVncConfigInfo(boolean enableVnc, String vncPassword, int vncPort, String keyboard) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); OptionValue[] vncOptions = VmwareHelper.composeVncOptions(null, enableVnc, vncPassword, vncPort, keyboard); - vmConfigSpec.setExtraConfig(vncOptions); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, vmConfigSpec); + vmConfigSpec.getExtraConfig().addAll(Arrays.asList(vncOptions)); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, vmConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -769,10 +781,10 @@ public class VirtualMachineMO extends BaseMO { } public boolean configureVm(VirtualMachineConfigSpec vmConfigSpec) throws Exception { - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, vmConfigSpec); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, vmConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -796,12 +808,12 @@ public class VirtualMachineMO extends BaseMO { deviceConfigSpec.setFileOperation(deviceTernary.third()); deviceConfigSpecArray[i++] = deviceConfigSpec; } - configSpec.setDeviceChange(deviceConfigSpecArray); + configSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray)); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, configSpec); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, configSpec); - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if(result) { _context.waitForTaskProgressDone(morTask); return true; } else { @@ -815,7 +827,7 @@ public class VirtualMachineMO extends BaseMO { VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(hostNetworkName); VirtualMachineConfigInfo configInfo = getConfigInfo(); - OptionValue[] values = configInfo.getExtraConfig(); + List values = configInfo.getExtraConfig(); if(values != null) { for(OptionValue option : values) { @@ -832,7 +844,7 @@ public class VirtualMachineMO extends BaseMO { // vmdkDatastorePath: [datastore name] vmdkFilePath public void createDisk(String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, int controllerKey) throws Exception { - createDisk(vmdkDatastorePath, VirtualDiskType.thin, VirtualDiskMode.persistent, null, sizeInMb, morDs, controllerKey); + createDisk(vmdkDatastorePath, VirtualDiskType.THIN, VirtualDiskMode.PERSISTENT, null, sizeInMb, morDs, controllerKey); } // vmdkDatastorePath: [datastore name] vmdkFilePath @@ -840,9 +852,9 @@ public class VirtualMachineMO extends BaseMO { String rdmDeviceName, int sizeInMb, ManagedObjectReference morDs, int controllerKey) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - createDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + vmdkDatastorePath + s_logger.trace("vCenter API trace - createDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath + ", sizeInMb: " + sizeInMb + ", diskType: " + diskType + ", diskMode: " + diskMode + ", rdmDeviceName: " + rdmDeviceName - + ", datastore: " + morDs.get_value() + ", controllerKey: " + controllerKey); + + ", datastore: " + morDs.getValue() + ", controllerKey: " + controllerKey); assert(vmdkDatastorePath != null); assert(morDs != null); @@ -852,18 +864,18 @@ public class VirtualMachineMO extends BaseMO { } VirtualDisk newDisk = new VirtualDisk(); - if(diskType == VirtualDiskType.thin || diskType == VirtualDiskType.preallocated - || diskType == VirtualDiskType.eagerZeroedThick) { + if(diskType == VirtualDiskType.THIN || diskType == VirtualDiskType.PREALLOCATED + || diskType == VirtualDiskType.EAGER_ZEROED_THICK) { VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); - backingInfo.setDiskMode(diskMode.persistent.toString()); - if(diskType == VirtualDiskType.thin) { + backingInfo.setDiskMode(diskMode.PERSISTENT.toString()); + if(diskType == VirtualDiskType.THIN) { backingInfo.setThinProvisioned(true); } else { backingInfo.setThinProvisioned(false); } - if(diskType == VirtualDiskType.eagerZeroedThick) { + if(diskType == VirtualDiskType.EAGER_ZEROED_THICK) { backingInfo.setEagerlyScrub(true); } else { backingInfo.setEagerlyScrub(false); @@ -872,17 +884,17 @@ public class VirtualMachineMO extends BaseMO { backingInfo.setDatastore(morDs); backingInfo.setFileName(vmdkDatastorePath); newDisk.setBacking(backingInfo); - } else if(diskType == VirtualDiskType.rdm || diskType == VirtualDiskType.rdmp) { + } else if(diskType == VirtualDiskType.RDM || diskType == VirtualDiskType.RDMP) { VirtualDiskRawDiskMappingVer1BackingInfo backingInfo = new VirtualDiskRawDiskMappingVer1BackingInfo(); - if(diskType == VirtualDiskType.rdm) { + if(diskType == VirtualDiskType.RDM) { backingInfo.setCompatibilityMode("virtualMode"); } else { backingInfo.setCompatibilityMode("physicalMode"); } backingInfo.setDeviceName(rdmDeviceName); - if(diskType == VirtualDiskType.rdm) { - backingInfo.setDiskMode(diskMode.persistent.toString()); + if(diskType == VirtualDiskType.RDM) { + backingInfo.setDiskMode(diskMode.PERSISTENT.toString()); } backingInfo.setDatastore(morDs); @@ -898,20 +910,20 @@ public class VirtualMachineMO extends BaseMO { newDisk.setCapacityInKB(sizeInMb*1024); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(newDisk); - deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create); - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.CREATE); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - deviceConfigSpecArray[0] = deviceConfigSpec; - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + //deviceConfigSpecArray[0] = deviceConfigSpec; + reConfigSpec.getDeviceChange().add(deviceConfigSpec); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createDisk() done(failed)"); throw new Exception("Unable to create disk " + vmdkDatastorePath + " due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -926,25 +938,25 @@ public class VirtualMachineMO extends BaseMO { public void attachDisk(String[] vmdkDatastorePathChain, ManagedObjectReference morDs) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " - + new Gson().toJson(vmdkDatastorePathChain) + ", datastore: " + morDs.get_value()); + s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + + new Gson().toJson(vmdkDatastorePathChain) + ", datastore: " + morDs.getValue()); VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, getScsiDeviceControllerKey(), vmdkDatastorePathChain, morDs, -1, 1); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(newDisk); - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - deviceConfigSpecArray[0] = deviceConfigSpec; - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + //deviceConfigSpecArray[0] = deviceConfigSpec; + reConfigSpec.getDeviceChange().add(deviceConfigSpec); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - attachDisk() done(failed)"); throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -959,25 +971,25 @@ public class VirtualMachineMO extends BaseMO { public void attachDisk(Pair[] vmdkDatastorePathChain, int controllerKey) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + new Gson().toJson(vmdkDatastorePathChain)); VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, controllerKey, vmdkDatastorePathChain, -1, 1); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(newDisk); - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - deviceConfigSpecArray[0] = deviceConfigSpec; - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + //deviceConfigSpecArray[0] = deviceConfigSpec; + reConfigSpec.getDeviceChange().add(deviceConfigSpec); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - attachDisk() done(failed)"); throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -993,7 +1005,7 @@ public class VirtualMachineMO extends BaseMO { public List> detachDisk(String vmdkDatastorePath, boolean deleteBackingFile) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath + ", deleteBacking: " + deleteBackingFile); // Note: if VM has been taken snapshot, original backing file will be renamed, therefore, when we try to find the matching @@ -1008,22 +1020,22 @@ public class VirtualMachineMO extends BaseMO { List> chain = getDiskDatastorePathChain(deviceInfo.first(), true); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(deviceInfo.first()); if(deleteBackingFile) { - deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.destroy); + deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.DESTROY); } - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.remove); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); - deviceConfigSpecArray[0] = deviceConfigSpec; - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + //deviceConfigSpecArray[0] = deviceConfigSpec; + reConfigSpec.getDeviceChange().add(deviceConfigSpec); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachDisk() done (failed)"); @@ -1059,7 +1071,7 @@ public class VirtualMachineMO extends BaseMO { public void detachAllDisks() throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachAllDisk(). target MOR: " + _mor.get_value()); + s_logger.trace("vCenter API trace - detachAllDisk(). target MOR: " + _mor.getValue()); VirtualDisk[] disks = getAllDiskDevice(); if(disks.length > 0) { @@ -1069,14 +1081,14 @@ public class VirtualMachineMO extends BaseMO { for(int i = 0; i < disks.length; i++) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(disks[i]); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.remove); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.REMOVE); } - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + reConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray)); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachAllDisk() done(failed)"); throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -1094,8 +1106,8 @@ public class VirtualMachineMO extends BaseMO { boolean connect, boolean connectAtBoot) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " - + isoDatastorePath + ", datastore: " + morDs.get_value() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot); + s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.getValue() + ", isoDatastorePath: " + + isoDatastorePath + ", datastore: " + morDs.getValue() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot); assert(isoDatastorePath != null); assert(morDs != null); @@ -1123,23 +1135,23 @@ public class VirtualMachineMO extends BaseMO { cdRom.setBacking(backingInfo); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(cdRom); if(newCdRom) { - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.edit); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); } - deviceConfigSpecArray[0] = deviceConfigSpec; - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + //deviceConfigSpecArray[0] = deviceConfigSpec; + reConfigSpec.getDeviceChange().add(deviceConfigSpec); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso() done(failed)"); throw new Exception("Failed to attach ISO due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -1153,7 +1165,7 @@ public class VirtualMachineMO extends BaseMO { public void detachIso(String isoDatastorePath) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " + s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.getValue() + ", isoDatastorePath: " + isoDatastorePath); VirtualDevice device = getIsoDevice(); @@ -1168,19 +1180,19 @@ public class VirtualMachineMO extends BaseMO { device.setBacking(backingInfo); VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(device); - deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.edit); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); - deviceConfigSpecArray[0] = deviceConfigSpec; - reConfigSpec.setDeviceChange(deviceConfigSpecArray); + //deviceConfigSpecArray[0] = deviceConfigSpec; + reConfigSpec.getDeviceChange().add(deviceConfigSpec); - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec); - String result = _context.getServiceUtil().waitForTask(morTask); + ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec); + boolean result = _context.getVimClient().waitForTask(morTask); - if(!result.equals("sucess")) { + if(!result) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso() done(failed)"); throw new Exception("Failed to detachIso due to " + TaskMO.getTaskFailureInfo(_context, morTask)); @@ -1194,7 +1206,7 @@ public class VirtualMachineMO extends BaseMO { public Pair getVmdkFileInfo(String vmdkDatastorePath) throws Exception { if(s_logger.isTraceEnabled()) - s_logger.trace("vCenter API trace - getVmdkFileInfo(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: " + s_logger.trace("vCenter API trace - getVmdkFileInfo(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath); Pair dcPair = getOwnerDatacenter(); @@ -1222,7 +1234,7 @@ public class VirtualMachineMO extends BaseMO { DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter()); - if(runtimeInfo.getPowerState() != VirtualMachinePowerState.poweredOff) { + if(runtimeInfo.getPowerState() != VirtualMachinePowerState.POWERED_OFF) { String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName; s_logger.error(msg); throw new Exception(msg); @@ -1235,10 +1247,10 @@ public class VirtualMachineMO extends BaseMO { } HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(_context, morLease); - HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error }); + HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR }); try { - if(state == HttpNfcLeaseState.ready) { + if(state == HttpNfcLeaseState.READY) { final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter(); boolean success = false; @@ -1248,12 +1260,12 @@ public class VirtualMachineMO extends BaseMO { final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024; long totalBytesDownloaded = 0; - HttpNfcLeaseDeviceUrl[] deviceUrls = leaseInfo.getDeviceUrl(); + List deviceUrls = leaseInfo.getDeviceUrl(); if(deviceUrls != null) { - OvfFile[] ovfFiles = new OvfFile[deviceUrls.length]; - for (int i = 0; i < deviceUrls.length; i++) { - String deviceId = deviceUrls[i].getKey(); - String deviceUrlStr = deviceUrls[i].getUrl(); + OvfFile[] ovfFiles = new OvfFile[deviceUrls.size()]; + for (int i = 0; i < deviceUrls.size(); i++) { + String deviceId = deviceUrls.get(i).getKey(); + String deviceUrlStr = deviceUrls.get(i).getUrl(); String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1); String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk")); String diskUrlStr = deviceUrlStr.replace("*", hostName); @@ -1285,7 +1297,7 @@ public class VirtualMachineMO extends BaseMO { // write OVF descriptor file OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams(); - ovfDescParams.setOvfFiles(ovfFiles); + ovfDescParams.getOvfFiles().addAll(Arrays.asList(ovfFiles)); OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams); String ovfPath = exportDir + File.separator + exportName + ".ovf"; fileNames.add(ovfPath); @@ -1513,14 +1525,14 @@ public class VirtualMachineMO extends BaseMO { boolean bSuccess = false; try { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; - deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); VirtualDevice device = VmwareHelper.prepareDiskDevice(clonedVmMo, -1, disks, morDs, -1, 1); - deviceConfigSpecArray[0].setDevice(device); - deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add); - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + deviceConfigSpec.setDevice(device); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); + vmConfigSpec.getDeviceChange().add(deviceConfigSpec); clonedVmMo.configureVm(vmConfigSpec); bSuccess = true; } finally { @@ -1533,12 +1545,12 @@ public class VirtualMachineMO extends BaseMO { public void plugDevice(VirtualDevice device) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; - deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); - deviceConfigSpecArray[0].setDevice(device); - deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add); + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); + deviceConfigSpec.setDevice(device); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!configureVm(vmConfigSpec)) { throw new Exception("Failed to add devices"); } @@ -1546,12 +1558,12 @@ public class VirtualMachineMO extends BaseMO { public void tearDownDevice(VirtualDevice device) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; - deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec(); - deviceConfigSpecArray[0].setDevice(device); - deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.remove); + //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); + deviceConfigSpec.setDevice(device); + deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!configureVm(vmConfigSpec)) { throw new Exception("Failed to detach devices"); } @@ -1566,10 +1578,10 @@ public class VirtualMachineMO extends BaseMO { for(int i = 0; i < devices.length; i++) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(devices[i]); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.remove); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.REMOVE); } - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + vmConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray)); if(!configureVm(vmConfigSpec)) { throw new Exception("Failed to detach devices"); } @@ -1651,7 +1663,7 @@ public class VirtualMachineMO extends BaseMO { } public int getScsiDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { @@ -1667,7 +1679,7 @@ public class VirtualMachineMO extends BaseMO { } public int getScsiDeviceControllerKeyNoException() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { @@ -1688,14 +1700,14 @@ public class VirtualMachineMO extends BaseMO { // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); - scsiController.setSharedBus(VirtualSCSISharing.noSharing); + scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); - scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); - vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec }); + vmConfig.getDeviceChange().add(scsiControllerSpec); if(configureVm(vmConfig)) { throw new Exception("Unable to add Scsi controller"); } @@ -1704,7 +1716,7 @@ public class VirtualMachineMO extends BaseMO { // return pair of VirtualDisk and disk device bus name(ide0:0, etc) public Pair getDiskDevice(String vmdkDatastorePath, boolean matchExactly) throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil().getDynamicProperty(_mor, "config.hardware.device"); + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); s_logger.info("Look for disk device info from volume : " + vmdkDatastorePath); DatastoreFile dsSrcFile = new DatastoreFile(vmdkDatastorePath); @@ -1842,7 +1854,7 @@ public class VirtualMachineMO extends BaseMO { public VirtualDisk[] getAllDiskDevice() throws Exception { List deviceList = new ArrayList(); - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil().getDynamicProperty(_mor, "config.hardware.device"); + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualDisk) { @@ -1882,7 +1894,7 @@ public class VirtualMachineMO extends BaseMO { } public int tryGetIDEDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { @@ -1897,7 +1909,7 @@ public class VirtualMachineMO extends BaseMO { } public int getIDEDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { @@ -1918,7 +1930,7 @@ public class VirtualMachineMO extends BaseMO { } public VirtualDevice getIsoDevice() throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { for(VirtualDevice device : devices) { @@ -1931,7 +1943,7 @@ public class VirtualMachineMO extends BaseMO { } public int getPCIDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null && devices.length > 0) { @@ -1952,7 +1964,7 @@ public class VirtualMachineMO extends BaseMO { } public int getNextDeviceNumber(int controllerKey) throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); int deviceNumber = -1; @@ -1969,7 +1981,7 @@ public class VirtualMachineMO extends BaseMO { } public VirtualDevice[] getNicDevices() throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); List nics = new ArrayList(); @@ -1985,7 +1997,7 @@ public class VirtualMachineMO extends BaseMO { } public Pair getNicDeviceIndex(String networkNamePrefix) throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); List nics = new ArrayList(); @@ -2035,9 +2047,9 @@ public class VirtualMachineMO extends BaseMO { DistributedVirtualSwitchPortConnection dvsPort = (DistributedVirtualSwitchPortConnection) dvpBackingInfo.getPort(); String dvPortGroupKey = dvsPort.getPortgroupKey(); ManagedObjectReference dvPortGroupMor = new ManagedObjectReference(); - dvPortGroupMor.set_value(dvPortGroupKey); + dvPortGroupMor.setValue(dvPortGroupKey); dvPortGroupMor.setType("DistributedVirtualPortgroup"); - return (String) _context.getServiceUtil().getDynamicProperty(dvPortGroupMor, "name"); + return (String) _context.getVimClient().getDynamicProperty(dvPortGroupMor, "name"); } public VirtualDevice[] getMatchedDevices(Class[] deviceClasses) throws Exception { @@ -2045,7 +2057,7 @@ public class VirtualMachineMO extends BaseMO { List returnList = new ArrayList(); - VirtualDevice[] devices = (VirtualDevice[])_context.getServiceUtil(). + VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null) { @@ -2086,14 +2098,14 @@ public class VirtualMachineMO extends BaseMO { _context.getService().unregisterVM(_mor); - ManagedObjectReference morTask = _context.getService().registerVM_Task( + ManagedObjectReference morTask = _context.getService().registerVMTask( morFolder, vmFileInfo.getVmPathName(), vmName, false, morPool, hostMo.getMor()); - String result = _context.getServiceUtil().waitForTask(morTask); - if (!result.equalsIgnoreCase("Sucess")) { + boolean result = _context.getVimClient().waitForTask(morTask); + if (!result) { throw new Exception("Unable to register template due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } else { _context.waitForTaskProgressDone(morTask); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java new file mode 100644 index 00000000000..3fbe5c8c34d --- /dev/null +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -0,0 +1,509 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.hypervisor.vmware.util; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; +import javax.net.ssl.HttpsURLConnection; +import javax.xml.ws.BindingProvider; + +import com.vmware.vim25.DynamicProperty; +import com.vmware.vim25.InvalidCollectorVersionFaultMsg; +import com.vmware.vim25.InvalidPropertyFaultMsg; +import com.vmware.vim25.LocalizedMethodFault; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.ObjectSpec; +import com.vmware.vim25.ObjectUpdate; +import com.vmware.vim25.ObjectUpdateKind; +import com.vmware.vim25.PropertyChange; +import com.vmware.vim25.PropertyChangeOp; +import com.vmware.vim25.PropertyFilterSpec; +import com.vmware.vim25.PropertyFilterUpdate; +import com.vmware.vim25.PropertySpec; +import com.vmware.vim25.RuntimeFaultFaultMsg; +import com.vmware.vim25.SelectionSpec; +import com.vmware.vim25.ServiceContent; +import com.vmware.vim25.TaskInfoState; +import com.vmware.vim25.TraversalSpec; +import com.vmware.vim25.UpdateSet; +import com.vmware.vim25.VimPortType; +import com.vmware.vim25.VimService; +import com.vmware.vim25.ObjectContent; + +/** + * A wrapper class to handle Vmware vsphere connection and disconnection. + * + * @author minc + * + */ +public class VmwareClient { + + private ManagedObjectReference SVC_INST_REF = new ManagedObjectReference(); + private ManagedObjectReference propCollectorRef; + private ManagedObjectReference rootRef; + private VimService vimService; + private VimPortType vimPort; + private ServiceContent serviceContent; + private final String SVC_INST_NAME = "ServiceInstance"; + + private boolean isConnected = false; + + public VmwareClient(String name) { + + } + + /** + * Establishes session with the virtual center server. + * + * @throws Exception + * the exception + */ + public void connect(String url, String userName, String password) throws Exception { + + HostnameVerifier hv = new HostnameVerifier() { + @Override + public boolean verify(String urlHostName, SSLSession session) { + return true; + } + }; + HttpsURLConnection.setDefaultHostnameVerifier(hv); + + SVC_INST_REF.setType(SVC_INST_NAME); + SVC_INST_REF.setValue(SVC_INST_NAME); + + vimService = new VimService(); + vimPort = vimService.getVimPort(); + Map ctxt = ((BindingProvider) vimPort).getRequestContext(); + + ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); + ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); + + serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); + vimPort.login(serviceContent.getSessionManager(), userName, password, null); + isConnected = true; + + propCollectorRef = serviceContent.getPropertyCollector(); + rootRef = serviceContent.getRootFolder(); + } + + /** + * Disconnects the user session. + * + * @throws Exception + */ + public void disconnect() throws Exception { + if (isConnected) { + vimPort.logout(serviceContent.getSessionManager()); + } + isConnected = false; + } + + /** + * @return Service instance + */ + public VimPortType getService() { + return vimPort; + } + + /** + * @return Service instance content + */ + public ServiceContent getServiceContent() { + return serviceContent; + } + + /** + * @return Service property collector + */ + public ManagedObjectReference getPropCol() { + return propCollectorRef; + } + + /** + * @return Root folder + */ + public ManagedObjectReference getRootFolder() { + return rootRef; + } + + /** + * Get the property value of a managed object. + * + * @param mor + * managed object reference + * @param propertyName + * property name. + * @return property value. + * @throws Exception + * in case of error. + */ + public Object getDynamicProperty(ManagedObjectReference mor, String propertyName) throws Exception { + List props = new ArrayList(); + props.add(propertyName); + List objContent = this.getObjectProperties(mor, props); + + Object propertyValue = null; + if (objContent != null && objContent.size() > 0) { + List dynamicProperty = objContent.get(0).getPropSet(); + if (dynamicProperty != null && dynamicProperty.size() > 0) { + DynamicProperty dp = dynamicProperty.get(0); + propertyValue = dp.getVal(); + /* + * If object is ArrayOfXXX object, then get the XXX[] by + * invoking getXXX() on the object. + * For Ex: + * ArrayOfManagedObjectReference.getManagedObjectReference() + * returns ManagedObjectReference[] array. + */ + Class dpCls = propertyValue.getClass(); + String dynamicPropertyName = dpCls.getName(); + if (dynamicPropertyName.startsWith("ArrayOf")) { + String methodName = "get" + + dynamicPropertyName + .substring(dynamicPropertyName.indexOf("ArrayOf") + "ArrayOf".length(), dynamicPropertyName.length()); + + Method getMorMethod = dpCls.getDeclaredMethod(methodName, null); + propertyValue = getMorMethod.invoke(propertyValue, (Object[]) null); + } + } + } + return propertyValue; + } + + private List getObjectProperties(ManagedObjectReference mObj, List props) throws Exception { + PropertySpec pSpec = new PropertySpec(); + pSpec.setAll(false); + pSpec.setType(mObj.getType()); + pSpec.getPathSet().addAll(props); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(mObj); + oSpec.setSkip(false); + PropertyFilterSpec spec = new PropertyFilterSpec(); + spec.getPropSet().add(pSpec); + spec.getObjectSet().add(oSpec); + List specArr = new ArrayList(); + specArr.add(spec); + + return vimPort.retrieveProperties(propCollectorRef, specArr); + } + + /** + * This method returns a boolean value specifying whether the Task is + * succeeded or failed. + * + * @param task + * ManagedObjectReference representing the Task. + * + * @return boolean value representing the Task result. + * @throws InvalidCollectorVersionFaultMsg + * @throws RuntimeFaultFaultMsg + * @throws InvalidPropertyFaultMsg + */ + public boolean waitForTask(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { + + boolean retVal = false; + + // info has a property - state for state of the task + Object[] result = waitForValues(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { + TaskInfoState.SUCCESS, TaskInfoState.ERROR } }); + + if (result[0].equals(TaskInfoState.SUCCESS)) { + retVal = true; + } + if (result[1] instanceof LocalizedMethodFault) { + throw new RuntimeException(((LocalizedMethodFault) result[1]).getLocalizedMessage()); + } + return retVal; + } + + /** + * Handle Updates for a single object. waits till expected values of + * properties to check are reached Destroys the ObjectFilter when done. + * + * @param objmor + * MOR of the Object to wait for + * @param filterProps + * Properties list to filter + * @param endWaitProps + * Properties list to check for expected values these be + * properties of a property in the filter properties list + * @param expectedVals + * values for properties to end the wait + * @return true indicating expected values were met, and false otherwise + * @throws RuntimeFaultFaultMsg + * @throws InvalidPropertyFaultMsg + * @throws InvalidCollectorVersionFaultMsg + */ + private Object[] waitForValues(ManagedObjectReference objmor, String[] filterProps, String[] endWaitProps, Object[][] expectedVals) + throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { + // version string is initially null + String version = ""; + Object[] endVals = new Object[endWaitProps.length]; + Object[] filterVals = new Object[filterProps.length]; + + PropertyFilterSpec spec = new PropertyFilterSpec(); + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(objmor); + oSpec.setSkip(Boolean.FALSE); + spec.getObjectSet().add(oSpec); + + PropertySpec pSpec = new PropertySpec(); + pSpec.getPathSet().addAll(Arrays.asList(filterProps)); + pSpec.setType(objmor.getType()); + spec.getPropSet().add(pSpec); + + ManagedObjectReference filterSpecRef = vimPort.createFilter(propCollectorRef, spec, true); + + boolean reached = false; + + UpdateSet updateset = null; + List filtupary = null; + List objupary = null; + List propchgary = null; + while (!reached) { + updateset = vimPort.waitForUpdates(propCollectorRef, version); + if (updateset == null || updateset.getFilterSet() == null) { + continue; + } + version = updateset.getVersion(); + + // Make this code more general purpose when PropCol changes later. + filtupary = updateset.getFilterSet(); + + for (PropertyFilterUpdate filtup : filtupary) { + objupary = filtup.getObjectSet(); + for (ObjectUpdate objup : objupary) { + // TODO: Handle all "kind"s of updates. + if (objup.getKind() == ObjectUpdateKind.MODIFY || objup.getKind() == ObjectUpdateKind.ENTER + || objup.getKind() == ObjectUpdateKind.LEAVE) { + propchgary = objup.getChangeSet(); + for (PropertyChange propchg : propchgary) { + updateValues(endWaitProps, endVals, propchg); + updateValues(filterProps, filterVals, propchg); + } + } + } + } + + Object expctdval = null; + // Check if the expected values have been reached and exit the loop + // if done. + // Also exit the WaitForUpdates loop if this is the case. + for (int chgi = 0; chgi < endVals.length && !reached; chgi++) { + for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++) { + expctdval = expectedVals[chgi][vali]; + + reached = expctdval.equals(endVals[chgi]) || reached; + } + } + } + + // Destroy the filter when we are done. + vimPort.destroyPropertyFilter(filterSpecRef); + return filterVals; + } + + private void updateValues(String[] props, Object[] vals, PropertyChange propchg) { + for (int findi = 0; findi < props.length; findi++) { + if (propchg.getName().lastIndexOf(props[findi]) >= 0) { + if (propchg.getOp() == PropertyChangeOp.REMOVE) { + vals[findi] = ""; + } else { + vals[findi] = propchg.getVal(); + } + } + } + } + + private SelectionSpec getSelectionSpec(String name) { + SelectionSpec genericSpec = new SelectionSpec(); + genericSpec.setName(name); + return genericSpec; + } + + /* + * @return An array of SelectionSpec covering VM, Host, Resource pool, + * Cluster Compute Resource and Datastore. + */ + private List buildFullTraversal() { + // Terminal traversal specs + + // RP -> VM + TraversalSpec rpToVm = new TraversalSpec(); + rpToVm.setName("rpToVm"); + rpToVm.setType("ResourcePool"); + rpToVm.setPath("vm"); + rpToVm.setSkip(Boolean.FALSE); + + // vApp -> VM + TraversalSpec vAppToVM = new TraversalSpec(); + vAppToVM.setName("vAppToVM"); + vAppToVM.setType("VirtualApp"); + vAppToVM.setPath("vm"); + + // HostSystem -> VM + TraversalSpec hToVm = new TraversalSpec(); + hToVm.setType("HostSystem"); + hToVm.setPath("vm"); + hToVm.setName("hToVm"); + hToVm.getSelectSet().add(getSelectionSpec("VisitFolders")); + hToVm.setSkip(Boolean.FALSE); + + // DC -> DS + TraversalSpec dcToDs = new TraversalSpec(); + dcToDs.setType("Datacenter"); + dcToDs.setPath("datastore"); + dcToDs.setName("dcToDs"); + dcToDs.setSkip(Boolean.FALSE); + + // Recurse through all ResourcePools + TraversalSpec rpToRp = new TraversalSpec(); + rpToRp.setType("ResourcePool"); + rpToRp.setPath("resourcePool"); + rpToRp.setSkip(Boolean.FALSE); + rpToRp.setName("rpToRp"); + rpToRp.getSelectSet().add(getSelectionSpec("rpToRp")); + + TraversalSpec crToRp = new TraversalSpec(); + crToRp.setType("ComputeResource"); + crToRp.setPath("resourcePool"); + crToRp.setSkip(Boolean.FALSE); + crToRp.setName("crToRp"); + crToRp.getSelectSet().add(getSelectionSpec("rpToRp")); + + TraversalSpec crToH = new TraversalSpec(); + crToH.setSkip(Boolean.FALSE); + crToH.setType("ComputeResource"); + crToH.setPath("host"); + crToH.setName("crToH"); + + TraversalSpec dcToHf = new TraversalSpec(); + dcToHf.setSkip(Boolean.FALSE); + dcToHf.setType("Datacenter"); + dcToHf.setPath("hostFolder"); + dcToHf.setName("dcToHf"); + dcToHf.getSelectSet().add(getSelectionSpec("VisitFolders")); + + TraversalSpec vAppToRp = new TraversalSpec(); + vAppToRp.setName("vAppToRp"); + vAppToRp.setType("VirtualApp"); + vAppToRp.setPath("resourcePool"); + vAppToRp.getSelectSet().add(getSelectionSpec("rpToRp")); + + TraversalSpec dcToVmf = new TraversalSpec(); + dcToVmf.setType("Datacenter"); + dcToVmf.setSkip(Boolean.FALSE); + dcToVmf.setPath("vmFolder"); + dcToVmf.setName("dcToVmf"); + dcToVmf.getSelectSet().add(getSelectionSpec("VisitFolders")); + + // For Folder -> Folder recursion + TraversalSpec visitFolders = new TraversalSpec(); + visitFolders.setType("Folder"); + visitFolders.setPath("childEntity"); + visitFolders.setSkip(Boolean.FALSE); + visitFolders.setName("VisitFolders"); + List sspecarrvf = new ArrayList(); + sspecarrvf.add(getSelectionSpec("crToRp")); + sspecarrvf.add(getSelectionSpec("crToH")); + sspecarrvf.add(getSelectionSpec("dcToVmf")); + sspecarrvf.add(getSelectionSpec("dcToHf")); + sspecarrvf.add(getSelectionSpec("vAppToRp")); + sspecarrvf.add(getSelectionSpec("vAppToVM")); + sspecarrvf.add(getSelectionSpec("dcToDs")); + sspecarrvf.add(getSelectionSpec("hToVm")); + sspecarrvf.add(getSelectionSpec("rpToVm")); + sspecarrvf.add(getSelectionSpec("VisitFolders")); + + visitFolders.getSelectSet().addAll(sspecarrvf); + + List resultspec = new ArrayList(); + resultspec.add(visitFolders); + resultspec.add(crToRp); + resultspec.add(crToH); + resultspec.add(dcToVmf); + resultspec.add(dcToHf); + resultspec.add(vAppToRp); + resultspec.add(vAppToVM); + resultspec.add(dcToDs); + resultspec.add(hToVm); + resultspec.add(rpToVm); + resultspec.add(rpToRp); + + return resultspec; + } + + + /** + * Get the ManagedObjectReference for an item under the + * specified root folder that has the type and name specified. + * + * @param root a root folder if available, or null for default + * @param type type of the managed object + * @param name name to match + * + * @return First ManagedObjectReference of the type / name pair found + */ + public ManagedObjectReference getDecendentMoRef(ManagedObjectReference root, String type, String name) throws Exception { + if (name == null || name.length() == 0) { + return null; + } + + // Create PropertySpecs + PropertySpec pSpec = new PropertySpec(); + pSpec.setType(type); + pSpec.setAll(false); + pSpec.getPathSet().add(name); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(root); + oSpec.setSkip(false); + oSpec.getSelectSet().addAll(buildFullTraversal()); + + PropertyFilterSpec spec = new PropertyFilterSpec(); + spec.getPropSet().add(pSpec); + spec.getObjectSet().add(oSpec); + List specArr = new ArrayList(); + specArr.add(spec); + + List ocary = vimPort.retrieveProperties(propCollectorRef, specArr); + + if (ocary == null || ocary.size() == 0) { + return null; + } + + for (ObjectContent oc : ocary) { + ManagedObjectReference mor = oc.getObj(); + List propary = oc.getPropSet(); + if (type == null || type.equals(mor.getType())) { + if (propary.size() > 0) { + String propval = (String) propary.get(0).getVal(); + if (propval != null && name.equals(propval)) + return mor; + } + } + } + return null; + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java index 6dd6475ae11..7f9aacb538d 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java @@ -26,7 +26,6 @@ import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; -import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; @@ -44,15 +43,11 @@ import org.apache.log4j.Logger; import com.cloud.hypervisor.vmware.mo.DatacenterMO; import com.cloud.hypervisor.vmware.mo.DatastoreFile; import com.cloud.utils.ActionDelegate; -import com.vmware.apputils.version.ExtendedAppUtil; -import com.vmware.apputils.vim25.ServiceConnection; -import com.vmware.apputils.vim25.ServiceUtil; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ObjectContent; import com.vmware.vim25.ObjectSpec; import com.vmware.vim25.PropertyFilterSpec; import com.vmware.vim25.PropertySpec; -import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.ServiceContent; import com.vmware.vim25.TaskInfo; import com.vmware.vim25.TraversalSpec; @@ -63,30 +58,30 @@ public class VmwareContext { private static int MAX_CONNECT_RETRY = 5; private static int CONNECT_RETRY_INTERVAL = 1000; - - private ExtendedAppUtil _appUtil; + + private VmwareClient _vimClient; private String _serverAddress; - + private Map _stockMap = new HashMap(); private int _CHUNKSIZE = 1*1024*1024; // 1M - + static { try { - javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; - javax.net.ssl.TrustManager tm = new TrustAllManager(); - trustAllCerts[0] = tm; - javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, null); + javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; + javax.net.ssl.TrustManager tm = new TrustAllManager(); + trustAllCerts[0] = tm; + javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { s_logger.error("Unexpected exception ", e); } } - - public VmwareContext(ExtendedAppUtil appUtil, String address) { - assert(appUtil != null) : "Invalid parameter in constructing VmwareContext object"; - - _appUtil = appUtil; + + public VmwareContext(VmwareClient client, String address) { + assert(client != null) : "Invalid parameter in constructing VmwareContext object"; + + _vimClient = client; _serverAddress = address; } @@ -95,132 +90,136 @@ public class VmwareContext { _stockMap.put(name, obj); } } - + public void uregisterStockObject(String name) { synchronized(_stockMap) { _stockMap.remove(name); } } - + @SuppressWarnings("unchecked") public T getStockObject(String name) { synchronized(_stockMap) { return (T)_stockMap.get(name); } } - + public String getServerAddress() { return _serverAddress; } - + + /* public ServiceConnection getServiceConnection() { - return _appUtil.getServiceConnection3(); + return _vimClient.getServiceConnection3(); } - + */ + public VimPortType getService() { - return getServiceConnection().getService(); + return _vimClient.getService(); } - + public ServiceContent getServiceContent() { - return getServiceConnection().getServiceContent(); + return _vimClient.getServiceContent(); } - + + /* public ServiceUtil getServiceUtil() { - return _appUtil.getServiceUtil3(); + return _vimClient.getServiceUtil3(); } - + */ + + public ManagedObjectReference getPropertyCollector(){ + return _vimClient.getPropCol(); + } + public ManagedObjectReference getRootFolder() { - return getServiceContent().getRootFolder(); + return _vimClient.getRootFolder(); } - + + public VmwareClient getVimClient(){ + return _vimClient; + } + + public ManagedObjectReference getHostMorByPath(String inventoryPath) throws Exception { assert(inventoryPath != null); - + String[] tokens; if(inventoryPath.startsWith("/")) tokens = inventoryPath.substring(1).split("/"); else tokens = inventoryPath.split("/"); - + ManagedObjectReference mor = getRootFolder(); for(int i=0; i < tokens.length;i++) { String token = tokens[i]; - ObjectContent[] ocs; + List ocs; + PropertySpec pSpec = null; + ObjectSpec oSpec = null; if(mor.getType().equalsIgnoreCase("Datacenter")) { - PropertySpec pSpec = new PropertySpec(); + pSpec = new PropertySpec(); + pSpec.setAll(false); pSpec.setType("ManagedEntity"); - pSpec.setPathSet(new String[] { "name" }); - + pSpec.getPathSet().add("name"); + TraversalSpec dcHostFolderTraversal = new TraversalSpec(); dcHostFolderTraversal.setType("Datacenter"); dcHostFolderTraversal.setPath("hostFolder"); dcHostFolderTraversal.setName("dcHostFolderTraversal"); - ObjectSpec oSpec = new ObjectSpec(); + oSpec = new ObjectSpec(); oSpec.setObj(mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { dcHostFolderTraversal }); + oSpec.getSelectSet().add(dcHostFolderTraversal); - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - ocs = getService().retrieveProperties( - getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - } else if(mor.getType().equalsIgnoreCase("Folder")) { - PropertySpec pSpec = new PropertySpec(); + pSpec = new PropertySpec(); + pSpec.setAll(false); pSpec.setType("ManagedEntity"); - pSpec.setPathSet(new String[] { "name" }); - + pSpec.getPathSet().add("name"); + TraversalSpec folderChildrenTraversal = new TraversalSpec(); folderChildrenTraversal.setType("Folder"); folderChildrenTraversal.setPath("childEntity"); folderChildrenTraversal.setName("folderChildrenTraversal"); - ObjectSpec oSpec = new ObjectSpec(); + oSpec = new ObjectSpec(); oSpec.setObj(mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { folderChildrenTraversal }); + oSpec.getSelectSet().add(folderChildrenTraversal); + - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ocs = getService().retrieveProperties( - getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); } else if(mor.getType().equalsIgnoreCase("ClusterComputeResource")) { - PropertySpec pSpec = new PropertySpec(); + pSpec = new PropertySpec(); pSpec.setType("ManagedEntity"); - pSpec.setPathSet(new String[] { "name" }); - + pSpec.getPathSet().add("name"); + TraversalSpec clusterHostTraversal = new TraversalSpec(); clusterHostTraversal.setType("ClusterComputeResource"); clusterHostTraversal.setPath("host"); clusterHostTraversal.setName("folderChildrenTraversal"); - ObjectSpec oSpec = new ObjectSpec(); + oSpec = new ObjectSpec(); oSpec.setObj(mor); oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { clusterHostTraversal }); + oSpec.getSelectSet().add(clusterHostTraversal); - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ocs = getService().retrieveProperties( - getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); } else { s_logger.error("Invalid inventory path, path element can only be datacenter and folder"); return null; } - - if(ocs != null && ocs.length > 0) { + + PropertyFilterSpec pfSpec = new PropertyFilterSpec(); + pfSpec.getPropSet().add(pSpec); + pfSpec.getObjectSet().add(oSpec); + List pfSpecArr = new ArrayList(); + pfSpecArr.add(pfSpec); + ocs = getService().retrieveProperties(getPropertyCollector(), pfSpecArr); + + if(ocs != null && ocs.size() > 0) { boolean found = false; for(ObjectContent oc : ocs) { - String name = oc.getPropSet()[0].getVal().toString(); + String name = oc.getPropSet().get(0).getVal().toString(); if(name.equalsIgnoreCase(token) || name.equalsIgnoreCase("host")) { mor = oc.getObj(); found = true; @@ -244,44 +243,44 @@ public class VmwareContext { // path in format of / public ManagedObjectReference getDatastoreMorByPath(String inventoryPath) throws Exception { assert(inventoryPath != null); - + String[] tokens; if(inventoryPath.startsWith("/")) tokens = inventoryPath.substring(1).split("/"); else tokens = inventoryPath.split("/"); - + if(tokens == null || tokens.length != 2) { s_logger.error("Invalid datastore inventory path. path: " + inventoryPath); return null; } - + DatacenterMO dcMo = new DatacenterMO(this, tokens[0]); if(dcMo.getMor() == null) { s_logger.error("Unable to locate the datacenter specified in path: " + inventoryPath); return null; } - + return dcMo.findDatastore(tokens[1]); } - + public void waitForTaskProgressDone(ManagedObjectReference morTask) throws Exception { while(true) { - TaskInfo tinfo = (TaskInfo)getServiceUtil().getDynamicProperty(morTask, "info"); + TaskInfo tinfo = (TaskInfo)_vimClient.getDynamicProperty(morTask, "info"); Integer progress = tinfo.getProgress(); if(progress == null) break; - + if(progress.intValue() >= 100) break; - + Thread.sleep(1000); } } - + public void getFile(String urlString, String localFileFullName) throws Exception { HttpURLConnection conn = getHTTPConnection(urlString); - + InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(new File(localFileFullName)); byte[] buf = new byte[_CHUNKSIZE]; @@ -290,19 +289,19 @@ public class VmwareContext { out.write(buf, 0, len); } in.close(); - out.close(); + out.close(); } - + public void uploadFile(String urlString, String localFileFullName) throws Exception { uploadFile(urlString, new File(localFileFullName)); } - + public void uploadFile(String urlString, File localFile) throws Exception { HttpURLConnection conn = getHTTPConnection(urlString, "PUT"); OutputStream out = null; InputStream in = null; BufferedReader br = null; - + try { out = conn.getOutputStream(); in = new FileInputStream(localFile); @@ -312,7 +311,7 @@ public class VmwareContext { out.write(buf, 0, len); } out.flush(); - + br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { @@ -322,41 +321,41 @@ public class VmwareContext { } finally { if(in != null) in.close(); - + if(out != null) out.close(); - + if(br != null) br.close(); } } - - public void uploadVmdkFile(String httpMethod, String urlString, String localFileName, + + public void uploadVmdkFile(String httpMethod, String urlString, String localFileName, long totalBytesUpdated, ActionDelegate progressUpdater) throws Exception { - + HttpURLConnection conn = getRawHTTPConnection(urlString); - + conn.setDoOutput(true); conn.setUseCaches(false); - - conn.setChunkedStreamingMode(_CHUNKSIZE); - conn.setRequestMethod(httpMethod); - conn.setRequestProperty("Connection", "Keep-Alive"); - conn.setRequestProperty("Content-Type", "application/x-vnd.vmware-streamVmdk"); + + conn.setChunkedStreamingMode(_CHUNKSIZE); + conn.setRequestMethod(httpMethod); + conn.setRequestProperty("Connection", "Keep-Alive"); + conn.setRequestProperty("Content-Type", "application/x-vnd.vmware-streamVmdk"); conn.setRequestProperty("Content-Length", Long.toString(new File(localFileName).length())); connectWithRetry(conn); - + BufferedOutputStream bos = null; BufferedInputStream is = null; try { - bos = new BufferedOutputStream(conn.getOutputStream()); - is = new BufferedInputStream(new FileInputStream(localFileName)); - int bufferSize = _CHUNKSIZE; - byte[] buffer = new byte[bufferSize]; - while (true) { - int bytesRead = is.read(buffer, 0, bufferSize); - if (bytesRead == -1) { - break; + bos = new BufferedOutputStream(conn.getOutputStream()); + is = new BufferedInputStream(new FileInputStream(localFileName)); + int bufferSize = _CHUNKSIZE; + byte[] buffer = new byte[bufferSize]; + while (true) { + int bytesRead = is.read(buffer, 0, bufferSize); + if (bytesRead == -1) { + break; } bos.write(buffer, 0, bytesRead); totalBytesUpdated += bytesRead; @@ -370,54 +369,54 @@ public class VmwareContext { is.close(); if(bos != null) bos.close(); - + conn.disconnect(); } } - - public long downloadVmdkFile(String urlString, String localFileName, + + public long downloadVmdkFile(String urlString, String localFileName, long totalBytesDownloaded, ActionDelegate progressUpdater) throws Exception { HttpURLConnection conn = getRawHTTPConnection(urlString); - + String cookieString = getServiceCookie(); conn.setRequestProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE, cookieString); conn.setDoInput(true); - conn.setDoOutput(true); + conn.setDoOutput(true); conn.setAllowUserInteraction(true); connectWithRetry(conn); - long bytesWritten = 0; - InputStream in = null; - OutputStream out = null; + long bytesWritten = 0; + InputStream in = null; + OutputStream out = null; try { - in = conn.getInputStream(); - out = new FileOutputStream(new File(localFileName)); - - byte[] buf = new byte[_CHUNKSIZE]; - int len = 0; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); + in = conn.getInputStream(); + out = new FileOutputStream(new File(localFileName)); + + byte[] buf = new byte[_CHUNKSIZE]; + int len = 0; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); bytesWritten += len; totalBytesDownloaded += len; - + if(progressUpdater != null) progressUpdater.action(new Long(totalBytesDownloaded)); - } + } } finally { if(in != null) in.close(); if(out != null) out.close(); - + conn.disconnect(); } - return bytesWritten; + return bytesWritten; } - + public byte[] getResourceContent(String urlString) throws Exception { HttpURLConnection conn = getHTTPConnection(urlString); InputStream in = conn.getInputStream(); - + ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[_CHUNKSIZE]; int len = 0; @@ -425,10 +424,10 @@ public class VmwareContext { out.write(buf, 0, len); } in.close(); - out.close(); + out.close(); return out.toByteArray(); } - + public void uploadResourceContent(String urlString, byte[] content) throws Exception { // vSphere does not support POST HttpURLConnection conn = getHTTPConnection(urlString, "PUT"); @@ -436,7 +435,7 @@ public class VmwareContext { OutputStream out = conn.getOutputStream(); out.write(content); out.flush(); - + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { @@ -446,15 +445,15 @@ public class VmwareContext { out.close(); in.close(); } - + /* * Sample content returned by query a datastore directory - * + * * Url for the query * https://vsphere-1.lab.vmops.com/folder/Fedora-clone-test?dcPath=cupertino&dsName=NFS+datastore * * Returned conent from vSphere - * + * @@ -485,7 +484,7 @@ public class VmwareContext { - */ + */ public String[] listDatastoreDirContent(String urlString) throws Exception { List fileList = new ArrayList(); String content = new String(getResourceContent(urlString)); @@ -497,7 +496,7 @@ public class VmwareContext { int beginPos = content.lastIndexOf('>', parsePos -1); if(beginPos < 0) beginPos = 0; - + fileList.add((content.substring(beginPos + 1, parsePos))); parsePos += marker.length(); } else { @@ -511,11 +510,11 @@ public class VmwareContext { DatastoreFile dsFile = new DatastoreFile(fullPath); return composeDatastoreBrowseUrl(dcName, dsFile.getDatastoreName(), dsFile.getRelativePath()); } - + public String composeDatastoreBrowseUrl(String dcName, String datastoreName, String relativePath) { assert(relativePath != null); assert(datastoreName != null); - + StringBuffer sb = new StringBuffer(); sb.append("https://"); sb.append(_serverAddress); @@ -525,23 +524,24 @@ public class VmwareContext { sb.append(URLEncoder.encode(datastoreName)); return sb.toString(); } - + public HttpURLConnection getHTTPConnection(String urlString) throws Exception { return getHTTPConnection(urlString, "GET"); } - + public HttpURLConnection getHTTPConnection(String urlString, String httpMethod) throws Exception { String cookieString = getServiceCookie(); HostnameVerifier hv = new HostnameVerifier() { - public boolean verify(String urlHostName, SSLSession session) { + @Override + public boolean verify(String urlHostName, SSLSession session) { return true; } }; - - HttpsURLConnection.setDefaultHostnameVerifier(hv); - URL url = new URL(urlString); + + HttpsURLConnection.setDefaultHostnameVerifier(hv); + URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - + conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); @@ -550,16 +550,17 @@ public class VmwareContext { connectWithRetry(conn); return conn; } - + public HttpURLConnection getRawHTTPConnection(String urlString) throws Exception { HostnameVerifier hv = new HostnameVerifier() { - public boolean verify(String urlHostName, SSLSession session) { + @Override + public boolean verify(String urlHostName, SSLSession session) { return true; } }; - - HttpsURLConnection.setDefaultHostnameVerifier(hv); - URL url = new URL(urlString); + + HttpsURLConnection.setDefaultHostnameVerifier(hv); + URL url = new URL(urlString); return (HttpURLConnection)url.openConnection(); } @@ -571,7 +572,7 @@ public class VmwareContext { String cookieString = (String)msgContext.getProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE); return cookieString; } - + private static void connectWithRetry(HttpURLConnection conn) throws Exception { boolean connected = false; for(int i = 0; i < MAX_CONNECT_RETRY && !connected; i++) { @@ -581,45 +582,48 @@ public class VmwareContext { s_logger.info("Connected, conn: " + conn.toString() + ", retry: " + i); } catch (Exception e) { s_logger.warn("Unable to connect, conn: " + conn.toString() + ", message: " + e.toString() + ", retry: " + i); - + try { Thread.sleep(CONNECT_RETRY_INTERVAL); } catch(InterruptedException ex) { } } } - + if(!connected) throw new Exception("Unable to connect to " + conn.toString()); } - + public void close() { try { - _appUtil.disConnect(); + _vimClient.disconnect(); } catch(Exception e) { s_logger.warn("Unexpected exception: ", e); } } public static class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } - + public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { return true; } - + public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { return true; } - - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } - - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) + + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } From 1ce4d62ace9ffd5976eda30652ada78a89fdae80 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 5 Feb 2013 21:44:38 -0800 Subject: [PATCH 03/17] Fix cast error from List to array. --- .../vmware/manager/VmwareManagerImpl.java | 12 ++--- .../vmware/resource/VmwareContextFactory.java | 17 +++++-- .../vmware/resource/VmwareResource.java | 14 +++--- .../cloud/hypervisor/vmware/mo/ClusterMO.java | 18 +++---- .../vmware/mo/CustomFieldsManagerMO.java | 8 ++-- .../vmware/mo/HostDatastoreSystemMO.java | 12 ++--- .../cloud/hypervisor/vmware/mo/HostMO.java | 48 +++++++++---------- .../vmware/mo/HypervisorHostHelper.java | 2 +- .../cloud/hypervisor/vmware/mo/NetworkMO.java | 7 +-- .../hypervisor/vmware/mo/PerfManagerMO.java | 8 ++-- .../vmware/mo/VirtualMachineMO.java | 10 ++-- .../hypervisor/vmware/util/VmwareClient.java | 3 +- .../vmware/mo/TestVmwareContextFactory.java | 14 +++--- .../hypervisor/vmware/mo/TestVmwareMO.java | 1 - .../test/com/cloud/vmware/TestVMWare.java | 1 - 15 files changed, 92 insertions(+), 83 deletions(-) diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java index 24c89d3624d..21cd914689d 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java @@ -390,20 +390,20 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw List returnedHostList = new ArrayList(); if(mor.getType().equals("ComputeResource")) { - ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getVimClient().getDynamicProperty(mor, "host"); - assert(hosts != null); + List hosts = (List)serviceContext.getVimClient().getDynamicProperty(mor, "host"); + assert(hosts != null && hosts.size() > 0); // For ESX host, we need to enable host firewall to allow VNC access - HostMO hostMo = new HostMO(serviceContext, hosts[0]); + HostMO hostMo = new HostMO(serviceContext, hosts.get(0)); prepareHost(hostMo, privateTrafficLabel); - returnedHostList.add(hosts[0]); + returnedHostList.add(hosts.get(0)); return returnedHostList; } else if(mor.getType().equals("ClusterComputeResource")) { - ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getVimClient().getDynamicProperty(mor, "host"); + List hosts = (List)serviceContext.getVimClient().getDynamicProperty(mor, "host"); assert(hosts != null); - if(hosts.length > _maxHostsPerCluster) { + if(hosts.size() > _maxHostsPerCluster) { String msg = "vCenter cluster size is too big (current configured cluster size: " + _maxHostsPerCluster + ")"; s_logger.error(msg); throw new DiscoveredWithErrorException(msg); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java index 20399cd737e..5db9da3c02d 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java @@ -16,16 +16,18 @@ // under the License. package com.cloud.hypervisor.vmware.resource; +import javax.annotation.PostConstruct; +import javax.inject.Inject; + import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.hypervisor.vmware.manager.VmwareManager; -import com.cloud.hypervisor.vmware.manager.VmwareManagerImpl; import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.StringUtils; -import com.cloud.utils.component.ComponentContext; - +@Component public class VmwareContextFactory { private static final Logger s_logger = Logger.getLogger(VmwareContextFactory.class); @@ -33,10 +35,17 @@ public class VmwareContextFactory { private static volatile int s_seq = 1; private static VmwareManager s_vmwareMgr; + @Inject VmwareManager _vmwareMgr; + static { // skip certificate check System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); - s_vmwareMgr = ComponentContext.inject(VmwareManagerImpl.class); + //s_vmwareMgr = ComponentContext.inject(VmwareManagerImpl.class); + } + + @PostConstruct + void init() { + s_vmwareMgr = _vmwareMgr; } public static VmwareContext create(String vCenterAddress, String vCenterUserName, String vCenterPassword) throws Exception { diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 397408af7ff..7b97d3d1d1b 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -4494,14 +4494,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa PerfCounterInfo rxPerfCounterInfo = null; PerfCounterInfo txPerfCounterInfo = null; - PerfCounterInfo[] cInfo = (PerfCounterInfo[]) getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); - for(int i=0; i cInfo = (List) getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); + for(PerfCounterInfo info : cInfo) { + if ("net".equalsIgnoreCase(info.getGroupInfo().getKey())) { + if ("transmitted".equalsIgnoreCase(info.getNameInfo().getKey())) { + txPerfCounterInfo = info; } - if ("received".equalsIgnoreCase(cInfo[i].getNameInfo().getKey())) { - rxPerfCounterInfo = cInfo[i]; + if ("received".equalsIgnoreCase(info.getNameInfo().getKey())) { + rxPerfCounterInfo = info; } } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java index 10265545bf4..d112c34fb9e 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java @@ -295,8 +295,8 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { ManagedObjectReference morDs = null; ManagedObjectReference morDsFirst = null; - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); - if(hosts != null && hosts.length > 0) { + List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + if(hosts != null && hosts.size() > 0) { for(ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); morDs = hostMo.mountDatastore(vmfsDatastore, poolHostAddress, poolHostPort, poolPath, poolUuid); @@ -328,8 +328,8 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid); - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); - if(hosts != null && hosts.length > 0) { + List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + if(hosts != null && hosts.size() > 0) { for(ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); hostMo.unmountDatastore(poolUuid); @@ -473,8 +473,8 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { // TODO, need to use traversal to optimize retrieve of int cpuNumInCpuThreads = 1; - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); - if(hosts != null && hosts.length > 0) { + List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + if(hosts != null && hosts.size() > 0) { for(ManagedObjectReference morHost : hosts) { HostMO hostMo = new HostMO(_context, morHost); HostHardwareSummary hardwareSummary = hostMo.getHostHardwareSummary(); @@ -498,9 +498,9 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + esxServiceConsolePort); - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host"); - if(hosts != null && hosts.length > 0) { - VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts[0]).getHyperHostNetworkSummary(esxServiceConsolePort); + List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host"); + if(hosts != null && hosts.size() > 0) { + VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts.get(0)).getHyperHostNetworkSummary(esxServiceConsolePort); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(successfully)"); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java index 08932c5e5ba..3082a7143b5 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.hypervisor.vmware.mo; +import java.util.List; + import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.CustomFieldDef; import com.vmware.vim25.ManagedObjectReference; @@ -48,12 +50,12 @@ public class CustomFieldsManagerMO extends BaseMO { _context.getService().setField(getMor(), morEntity, key, value); } - public CustomFieldDef[] getFields() throws Exception { - return (CustomFieldDef[])_context.getVimClient().getDynamicProperty(getMor(), "field"); + public List getFields() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(getMor(), "field"); } public int getCustomFieldKey(String morType, String fieldName) throws Exception { - CustomFieldDef[] fields = getFields(); + List fields = getFields(); if(fields != null) { for(CustomFieldDef field : fields) { if(field.getName().equals(fieldName) && field.getManagedObjectType().equals(morType)) diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java index 7d967a9b532..3dcd7249060 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java @@ -78,8 +78,8 @@ public class HostDatastoreSystemMO extends BaseMO { public ManagedObjectReference findDatastoreByUrl(String storeUrl) throws Exception { assert(storeUrl != null); - ManagedObjectReference[] datastores = getDatastores(); - if(datastores != null && datastores.length > 0) { + List datastores = getDatastores(); + if(datastores != null && datastores.size() > 0) { for(ManagedObjectReference morDatastore : datastores) { NasDatastoreInfo info = getNasDatastoreInfo(morDatastore); if(info != null) { @@ -99,8 +99,8 @@ public class HostDatastoreSystemMO extends BaseMO { public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception { assert(exportPath != null); - ManagedObjectReference[] datastores = getDatastores(); - if(datastores != null && datastores.length > 0) { + List datastores = getDatastores(); + if(datastores != null && datastores.size() > 0) { for(ManagedObjectReference morDatastore : datastores) { DatastoreMO dsMo = new DatastoreMO(_context, morDatastore); if(dsMo.getInventoryPath().equals(exportPath)) @@ -145,8 +145,8 @@ public class HostDatastoreSystemMO extends BaseMO { return _context.getService().createNasDatastore(_mor, spec); } - public ManagedObjectReference[] getDatastores() throws Exception { - return (ManagedObjectReference[])_context.getVimClient().getDynamicProperty( + public List getDatastores() throws Exception { + return (List)_context.getVimClient().getDynamicProperty( _mor, "datastore"); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java index c164cc22f23..d80680292a5 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java @@ -84,16 +84,14 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return (HostConfigManager)_context.getVimClient().getDynamicProperty(_mor, "configManager"); } - public VirtualNicManagerNetConfig[] getHostVirtualNicManagerNetConfig() throws Exception { - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getVimClient().getDynamicProperty(_mor, + public List getHostVirtualNicManagerNetConfig() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); - return netConfigs; } - public HostIpRouteEntry[] getHostIpRouteEntries() throws Exception { - HostIpRouteEntry[] entries = (HostIpRouteEntry[])_context.getVimClient().getDynamicProperty(_mor, + public List getHostIpRouteEntries() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.routeTableInfo.ipRoute"); - return entries; } public HostListSummaryQuickStats getHostQuickStats() throws Exception { @@ -142,7 +140,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { @Override public String getHyperHostDefaultGateway() throws Exception { - HostIpRouteEntry[] entries = getHostIpRouteEntries(); + List entries = getHostIpRouteEntries(); for(HostIpRouteEntry entry : entries) { if(entry.getNetwork().equalsIgnoreCase("0.0.0.0")) return entry.getGateway(); @@ -222,7 +220,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public ManagedObjectReference[] getHostLocalDatastore() throws Exception { - ManagedObjectReference[] datastores = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty( + List datastores = (List)_context.getVimClient().getDynamicProperty( _mor, "datastore"); List l = new ArrayList(); if(datastores != null) { @@ -236,7 +234,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } public HostVirtualSwitch getHostVirtualSwitchByName(String name) throws Exception { - HostVirtualSwitch[] switches = (HostVirtualSwitch[])_context.getVimClient().getDynamicProperty( + List switches = (List)_context.getVimClient().getDynamicProperty( _mor, "config.network.vswitch"); if(switches != null) { @@ -248,8 +246,8 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return null; } - public HostVirtualSwitch[] getHostVirtualSwitch() throws Exception { - return (HostVirtualSwitch[])_context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); + public List getHostVirtualSwitch() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch"); } public AboutInfo getHostAboutInfo() throws Exception { @@ -285,7 +283,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public HostVirtualSwitch getVirtualSwitchByName(String vSwitchName) throws Exception { - HostVirtualSwitch[] vSwitchs = getHostVirtualSwitch(); + List vSwitchs = getHostVirtualSwitch(); if(vSwitchs != null) { for(HostVirtualSwitch vSwitch: vSwitchs) { if(vSwitch.getName().equals(vSwitchName)) @@ -327,7 +325,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public String getPortGroupNameByNicType(HostVirtualNicType nicType) throws Exception { assert(nicType != null); - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getVimClient().getDynamicProperty(_mor, + List netConfigs = (List)_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); if(netConfigs != null) { @@ -448,10 +446,10 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return null; } - public ManagedObjectReference[] getVmMorsOnNetwork(String portGroupName) throws Exception { + public List getVmMorsOnNetwork(String portGroupName) throws Exception { ManagedObjectReference morNetwork = getNetworkMor(portGroupName); if(morNetwork != null) - return (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(morNetwork, "vm"); + return (List)_context.getVimClient().getDynamicProperty(morNetwork, "vm"); return null; } @@ -703,7 +701,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { public ManagedObjectReference getExistingDataStoreOnHost(boolean vmfsDatastore, String hostAddress, int hostPort, String path, String uuid, HostDatastoreSystemMO hostDatastoreSystemMo) { // First retrieve the list of Datastores on the host. - ManagedObjectReference[] morArray; + List morArray; try { morArray = hostDatastoreSystemMo.getDatastores(); } catch (Exception e) { @@ -711,17 +709,17 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { return null; } // Next, get all the NAS datastores from this array of datastores. - if (morArray.length > 0) { + if (morArray.size() > 0) { int i; - for (i = 0; i < morArray.length; i++) { + for (i = 0; i < morArray.size(); i++) { NasDatastoreInfo nasDS; try { - nasDS = hostDatastoreSystemMo.getNasDatastoreInfo(morArray[i]); + nasDS = hostDatastoreSystemMo.getNasDatastoreInfo(morArray.get(i)); if (nasDS != null) { //DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); if (nasDS.getNas().getRemoteHost().equalsIgnoreCase(hostAddress) && nasDS.getNas().getRemotePath().equalsIgnoreCase(path)) { - return morArray[i]; + return morArray.get(i); } } } catch (Exception e) { @@ -861,13 +859,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { VmwareHypervisorHostNetworkSummary summary = new VmwareHypervisorHostNetworkSummary(); if(this.getHostType() == VmwareHostType.ESXi) { - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getVimClient().getDynamicProperty(_mor, + List netConfigs = (List)_context.getVimClient().getDynamicProperty(_mor, "config.virtualNicManagerInfo.netConfig"); assert(netConfigs != null); - for(int i = 0; i < netConfigs.length; i++) { - if(netConfigs[i].getNicType().equals("management")) { - for(HostVirtualNic nic : netConfigs[i].getCandidateVnic()) { + for(VirtualNicManagerNetConfig netConfig : netConfigs) { + if(netConfig.getNicType().equals("management")) { + for(HostVirtualNic nic : netConfig.getCandidateVnic()) { if(nic.getPortgroup().equals(managementPortGroup)) { summary.setHostIp(nic.getSpec().getIp().getIpAddress()); summary.setHostNetmask(nic.getSpec().getIp().getSubnetMask()); @@ -882,7 +880,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } } else { // try with ESX path - HostVirtualNic[] hostVNics = (HostVirtualNic[])_context.getVimClient().getDynamicProperty(_mor, + List hostVNics = (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.consoleVnic"); if(hostVNics != null) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java index abc391fa035..e4a9485c32c 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java @@ -625,7 +625,7 @@ public class HypervisorHostHelper { try { if(lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) { try { - ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host"); + List hosts = (List)hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host"); if(hosts != null) { for(ManagedObjectReference otherHost: hosts) { if(!otherHost.getValue().equals(hostMo.getMor().getValue())) { diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java index b8e3ab42b5b..df82f155cf1 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.hypervisor.vmware.mo; +import java.util.List; + import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.ManagedObjectReference; @@ -32,8 +34,7 @@ public class NetworkMO extends BaseMO { _context.getService().destroyNetwork(_mor); } - public ManagedObjectReference[] getVMsOnNetwork() throws Exception { - ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "vm"); - return vms; + public List getVMsOnNetwork() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(_mor, "vm"); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java index 6c2b7bb2ab7..bb4fb56ebbc 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java @@ -114,11 +114,11 @@ public class PerfManagerMO extends BaseMO { _context.getService().updatePerfInterval(_mor, interval); } - public PerfCounterInfo[] getCounterInfo() throws Exception { - return (PerfCounterInfo[])_context.getVimClient().getDynamicProperty(_mor, "perfCounter"); + public List getCounterInfo() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(_mor, "perfCounter"); } - public PerfInterval[] getIntervalInfo() throws Exception { - return (PerfInterval[])_context.getVimClient().getDynamicProperty(_mor, "historicalInterval"); + public List getIntervalInfo() throws Exception { + return (List)_context.getVimClient().getDynamicProperty(_mor, "historicalInterval"); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index 76072cd614a..6f836c442b5 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -1716,13 +1716,13 @@ public class VirtualMachineMO extends BaseMO { // return pair of VirtualDisk and disk device bus name(ide0:0, etc) public Pair getDiskDevice(String vmdkDatastorePath, boolean matchExactly) throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); s_logger.info("Look for disk device info from volume : " + vmdkDatastorePath); DatastoreFile dsSrcFile = new DatastoreFile(vmdkDatastorePath); String srcBaseName = dsSrcFile.getFileBaseName(); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualDisk) { s_logger.info("Test against disk device, controller key: " + device.getControllerKey() + ", unit number: " + device.getUnitNumber()); @@ -1837,7 +1837,7 @@ public class VirtualMachineMO extends BaseMO { return pathList; } - private String getDeviceBusName(VirtualDevice[] allDevices, VirtualDevice theDevice) throws Exception { + private String getDeviceBusName(List allDevices, VirtualDevice theDevice) throws Exception { for(VirtualDevice device : allDevices) { if(device.getKey() == theDevice.getControllerKey().intValue()) { if(device instanceof VirtualIDEController) { @@ -1854,8 +1854,8 @@ public class VirtualMachineMO extends BaseMO { public VirtualDisk[] getAllDiskDevice() throws Exception { List deviceList = new ArrayList(); - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device"); + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualDisk) { deviceList.add((VirtualDisk)device); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java index 3fbe5c8c34d..2e0238d8acb 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -97,6 +97,7 @@ public class VmwareClient { ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); + ctxt.put("com.sun.xml.internal.ws.request.timeout", 60000); serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); vimPort.login(serviceContent.getSessionManager(), userName, password, null); @@ -177,7 +178,7 @@ public class VmwareClient { */ Class dpCls = propertyValue.getClass(); String dynamicPropertyName = dpCls.getName(); - if (dynamicPropertyName.startsWith("ArrayOf")) { + if (dynamicPropertyName.indexOf("ArrayOf") != -1) { String methodName = "get" + dynamicPropertyName .substring(dynamicPropertyName.indexOf("ArrayOf") + "ArrayOf".length(), dynamicPropertyName.length()); diff --git a/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareContextFactory.java b/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareContextFactory.java index a857986de72..81a62d2993a 100644 --- a/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareContextFactory.java +++ b/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareContextFactory.java @@ -16,12 +16,13 @@ // under the License. package com.cloud.hypervisor.vmware.mo; +import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.apputils.version.ExtendedAppUtil; + public class TestVmwareContextFactory { private static volatile int s_seq = 1; - + static { // skip certificate check System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); @@ -33,11 +34,10 @@ public class TestVmwareContextFactory { assert(vCenterPassword != null); String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService"; - String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; - ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params); - - appUtil.connect(); - VmwareContext context = new VmwareContext(appUtil, vCenterAddress); + VmwareClient vimClient = new VmwareClient(vCenterAddress + "-" + s_seq++); + vimClient.connect(serviceUrl, vCenterUserName, vCenterPassword); + + VmwareContext context = new VmwareContext(vimClient, vCenterAddress); return context; } } diff --git a/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareMO.java b/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareMO.java index 2417ddf99de..c9807f443f1 100644 --- a/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareMO.java +++ b/vmware-base/test/com/cloud/hypervisor/vmware/mo/TestVmwareMO.java @@ -22,7 +22,6 @@ import org.apache.log4j.Logger; import com.cloud.hypervisor.vmware.mo.SnapshotDescriptor.SnapshotInfo; import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.cloud.serializer.GsonHelper; import com.cloud.utils.Pair; import com.cloud.utils.testcase.Log4jEnabledTestCase; import com.google.gson.Gson; diff --git a/vmware-base/test/com/cloud/vmware/TestVMWare.java b/vmware-base/test/com/cloud/vmware/TestVMWare.java index 43c784ce2e6..b0ec68d69ae 100644 --- a/vmware-base/test/com/cloud/vmware/TestVMWare.java +++ b/vmware-base/test/com/cloud/vmware/TestVMWare.java @@ -37,7 +37,6 @@ import javax.net.ssl.SSLSession; import org.apache.log4j.xml.DOMConfigurator; import com.cloud.utils.PropertiesUtil; -import com.vmware.apputils.version.ExtendedAppUtil; import com.vmware.vim25.HostIpConfig; import com.vmware.vim25.HostVirtualNicSpec; import com.vmware.vim25.HostConfigManager; From 640fa6be760177d11bca2d03805462a9bdf41e8e Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 7 Feb 2013 12:23:57 -0800 Subject: [PATCH 04/17] Fix a bug in converting Enum type to String. --- .../manager/VmwareStorageManagerImpl.java | 4 ++-- .../vmware/resource/VmwareResource.java | 6 ++--- .../hypervisor/vmware/mo/HttpNfcLeaseMO.java | 22 ++++++++++++++++++- .../vmware/mo/VirtualMachineMO.java | 14 ++++++------ .../hypervisor/vmware/util/VmwareHelper.java | 10 ++++----- 5 files changed, 38 insertions(+), 18 deletions(-) diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java index 435db748680..fd3afe8e5c9 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java @@ -192,7 +192,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { workerVMName = hostService.getWorkerName(context, cmd, 0); // attach a volume to dummay wrapper VM for taking snapshot and exporting the VM for backup - if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString(), morDs, false)) { + if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier.OTHER_GUEST.value(), morDs, false)) { String msg = "Unable to create worker VM to execute BackupSnapshotCommand"; s_logger.error(msg); throw new Exception(msg); @@ -804,7 +804,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { vmConfig.setName(workerVmName); vmConfig.setMemoryMB((long) 4); vmConfig.setNumCPUs(1); - vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString()); + vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 51b463ef47c..21f17328c53 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -2094,7 +2094,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), vmSpec.getLimitCpuUse(), ramMb, getReserveMemMB(ramMb), - translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) { + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmName); } } @@ -2126,7 +2126,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), ramMb, getReserveMemMB(ramMb), - translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse()); + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), vmSpec.getLimitCpuUse()); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; @@ -3935,7 +3935,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmConfig.setName(vmName); vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB vmConfig.setNumCPUs(1); - vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString()); + vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java index 1198b3365d7..ca362809f3a 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java @@ -20,17 +20,23 @@ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; +import java.rmi.RemoteException; +import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; +import org.w3c.dom.Element; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.HttpNfcLeaseInfo; import com.vmware.vim25.HttpNfcLeaseManifestEntry; import com.vmware.vim25.HttpNfcLeaseState; import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.ObjectSpec; import com.vmware.vim25.OvfCreateImportSpecResult; import com.vmware.vim25.OvfFileItem; +import com.vmware.vim25.PropertyFilterSpec; +import com.vmware.vim25.PropertySpec; public class HttpNfcLeaseMO extends BaseMO { private static final Logger s_logger = Logger.getLogger(HttpNfcLeaseMO.class); @@ -44,7 +50,19 @@ public class HttpNfcLeaseMO extends BaseMO { } public HttpNfcLeaseState getState() throws Exception { - return (HttpNfcLeaseState)_context.getVimClient().getDynamicProperty(_mor, "state"); + Object stateProp = _context.getVimClient().getDynamicProperty(_mor, "state"); + // Due to some issue in JAX-WS De-serialization getting the information + // from the nodes + assert (stateProp.toString().contains("val: null")); + String stateVal = null; + Element stateElement = (Element) stateProp; + if (stateElement != null && stateElement.getFirstChild() != null) { + stateVal = stateElement.getFirstChild().getTextContent(); + } + if (stateVal != null) { + return HttpNfcLeaseState.fromValue(stateVal); + } + return HttpNfcLeaseState.ERROR; } public HttpNfcLeaseState waitState(HttpNfcLeaseState[] states) throws Exception { @@ -59,6 +77,8 @@ public class HttpNfcLeaseMO extends BaseMO { } } + + public HttpNfcLeaseInfo getLeaseInfo() throws Exception { return (HttpNfcLeaseInfo)_context.getVimClient().getDynamicProperty(_mor, "info"); } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index 6f836c442b5..2b07f9ad66d 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -571,14 +571,14 @@ public class VirtualMachineMO extends BaseMO { VirtualMachineRelocateSpecDiskLocator loc = new VirtualMachineRelocateSpecDiskLocator(); loc.setDatastore(morDs); loc.setDiskId(independentDisks[i].getKey()); - loc.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING.toString()); + loc.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING.value()); diskLocator.add(loc); } - rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.toString()); + rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.value()); rSpec.getDisk().addAll(diskLocator); } else { - rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.toString()); + rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.value()); } rSpec.setPool(morResourcePool); @@ -868,7 +868,7 @@ public class VirtualMachineMO extends BaseMO { || diskType == VirtualDiskType.EAGER_ZEROED_THICK) { VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); - backingInfo.setDiskMode(diskMode.PERSISTENT.toString()); + backingInfo.setDiskMode(diskMode.PERSISTENT.value()); if(diskType == VirtualDiskType.THIN) { backingInfo.setThinProvisioned(true); } else { @@ -894,7 +894,7 @@ public class VirtualMachineMO extends BaseMO { } backingInfo.setDeviceName(rdmDeviceName); if(diskType == VirtualDiskType.RDM) { - backingInfo.setDiskMode(diskMode.PERSISTENT.toString()); + backingInfo.setDiskMode(diskMode.PERSISTENT.value()); } backingInfo.setDatastore(morDs); @@ -1894,10 +1894,10 @@ public class VirtualMachineMO extends BaseMO { } public int tryGetIDEDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualIDEController) { return ((VirtualIDEController)device).getKey(); diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java index 8e6947fd072..32e36a63f3d 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java @@ -169,7 +169,7 @@ public class VmwareHelper { VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); - backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.value()); backingInfo.setThinProvisioned(true); backingInfo.setEagerlyScrub(false); backingInfo.setDatastore(morDs); @@ -273,7 +273,7 @@ public class VmwareHelper { VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); backingInfo.setDatastore(morDs); backingInfo.setFileName(vmdkDatastorePathChain[0]); - backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.value()); if(vmdkDatastorePathChain.length > 1) { String[] parentDisks = new String[vmdkDatastorePathChain.length - 1]; for(int i = 0; i < vmdkDatastorePathChain.length - 1; i++) @@ -313,7 +313,7 @@ public class VmwareHelper { VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); backingInfo.setDatastore(vmdkDatastorePathChain[0].second()); backingInfo.setFileName(vmdkDatastorePathChain[0].first()); - backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.value()); if(vmdkDatastorePathChain.length > 1) { Pair[] parentDisks = new Pair[vmdkDatastorePathChain.length - 1]; for(int i = 0; i < vmdkDatastorePathChain.length - 1; i++) @@ -346,7 +346,7 @@ public class VmwareHelper { VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); parentBacking.setDatastore(morDs); - parentBacking.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + parentBacking.setDiskMode(VirtualDiskMode.PERSISTENT.value()); if(parentDatastorePathList.length > 1) { String[] nextDatastorePathList = new String[parentDatastorePathList.length -1]; @@ -364,7 +364,7 @@ public class VmwareHelper { VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); parentBacking.setDatastore(parentDatastorePathList[0].second()); - parentBacking.setDiskMode(VirtualDiskMode.PERSISTENT.toString()); + parentBacking.setDiskMode(VirtualDiskMode.PERSISTENT.value()); if(parentDatastorePathList.length > 1) { Pair[] nextDatastorePathList = new Pair[parentDatastorePathList.length -1]; From 14ef9151a54201e2c12f68a353df0da4eac1df1d Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 7 Feb 2013 16:23:56 -0800 Subject: [PATCH 05/17] Fix ClassCastException. --- .../src/com/cloud/configuration/Config.java | 6 ++-- .../vmware/mo/VirtualMachineMO.java | 30 +++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index 7592b6bdfca..5002ca14722 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -258,8 +258,8 @@ public enum Config { VmwareAdditionalVncPortRangeSize("Advanced", ManagementServer.class, Integer.class, "vmware.additional.vnc.portrange.size", "1000", "Start port number of additional VNC port range", null), //VmwareGuestNicDeviceType("Advanced", ManagementServer.class, String.class, "vmware.guest.nic.device.type", "E1000", "Ethernet card type used in guest VM, valid values are E1000, PCNet32, Vmxnet2, Vmxnet3", null), VmwarePerClusterHostMax("Advanced", ManagementServer.class, Integer.class, "vmware.percluster.host.max", "8", "maxmium hosts per vCenter cluster(do not let it grow over 8)", "1-8"), - VmwareReserveCpu("Advanced", ManagementServer.class, Boolean.class, "vmware.reserve.cpu", "false", "Specify whether or not to reserve CPU based on CPU overprovisioning factor", null), - VmwareReserveMem("Advanced", ManagementServer.class, Boolean.class, "vmware.reserve.mem", "false", "Specify whether or not to reserve memory based on memory overprovisioning factor", null), + VmwareReserveCpu("Advanced", ManagementServer.class, Boolean.class, "vmware.reserve.cpu", "true", "Specify whether or not to reserve CPU based on CPU overprovisioning factor", null), + VmwareReserveMem("Advanced", ManagementServer.class, Boolean.class, "vmware.reserve.mem", "true", "Specify whether or not to reserve memory based on memory overprovisioning factor", null), VmwareRootDiskControllerType("Advanced", ManagementServer.class, String.class, "vmware.root.disk.controller", "ide", "Specify the default disk controller for root volumes, valid values are scsi, ide", null), VmwareSystemVmNicDeviceType("Advanced", ManagementServer.class, String.class, "vmware.systemvm.nic.device.type", "E1000", "Specify the default network device type for system VMs, valid values are E1000, PCNet32, Vmxnet2, Vmxnet3", null), VmwareRecycleHungWorker("Advanced", ManagementServer.class, Boolean.class, "vmware.recycle.hung.wokervm", "false", "Specify whether or not to recycle hung worker VMs", null), @@ -358,7 +358,7 @@ public enum Config { ConcurrentSnapshotsThresholdPerHost("Advanced", ManagementServer.class, Long.class, "concurrent.snapshots.threshold.perhost", null, "Limits number of snapshots that can be handled by the host concurrently; default is NULL - unlimited", null), NetworkIPv6SearchRetryMax("Network", ManagementServer.class, Integer.class, "network.ipv6.search.retry.max", "10000", "The maximum number of retrying times to search for an available IPv6 address in the table", null), - + ExternalBaremetalSystemUrl("Advanced", ManagementServer.class, String.class, "external.baremetal.system.url", null, "url of external baremetal system that CloudStack will talk to", null), ExternalBaremetalResourceClassName("Advanced", ManagementServer.class, String.class, "external,baremetal.resource.classname", null, "class name for handling external baremetal resource", null), EnableBaremetalSecurityGroupAgentEcho("Advanced", ManagementServer.class, Boolean.class, "enable.baremetal.securitygroup.agent.echo", "false", "After starting provision process, periodcially echo security agent installed in the template. Treat provisioning as success only if echo successfully", null), diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java index 2b07f9ad66d..0dfb2344e38 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -1663,10 +1663,10 @@ public class VirtualMachineMO extends BaseMO { } public int getScsiDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualLsiLogicController) { return device.getKey(); @@ -1679,10 +1679,10 @@ public class VirtualMachineMO extends BaseMO { } public int getScsiDeviceControllerKeyNoException() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualLsiLogicController) { return device.getKey(); @@ -1909,10 +1909,10 @@ public class VirtualMachineMO extends BaseMO { } public int getIDEDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualIDEController) { return ((VirtualIDEController)device).getKey(); @@ -1930,9 +1930,9 @@ public class VirtualMachineMO extends BaseMO { } public VirtualDevice getIsoDevice() throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualCdrom) { return device; @@ -1943,10 +1943,10 @@ public class VirtualMachineMO extends BaseMO { } public int getPCIDeviceControllerKey() throws Exception { - VirtualDevice[] devices = (VirtualDevice [])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device instanceof VirtualPCIController) { return ((VirtualPCIController)device).getKey(); @@ -1964,11 +1964,11 @@ public class VirtualMachineMO extends BaseMO { } public int getNextDeviceNumber(int controllerKey) throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); int deviceNumber = -1; - if(devices != null && devices.length > 0) { + if(devices != null && devices.size() > 0) { for(VirtualDevice device : devices) { if(device.getControllerKey() != null && device.getControllerKey().intValue() == controllerKey) { if(device.getUnitNumber() != null && device.getUnitNumber().intValue() > deviceNumber) { @@ -1981,7 +1981,7 @@ public class VirtualMachineMO extends BaseMO { } public VirtualDevice[] getNicDevices() throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); List nics = new ArrayList(); @@ -1997,7 +1997,7 @@ public class VirtualMachineMO extends BaseMO { } public Pair getNicDeviceIndex(String networkNamePrefix) throws Exception { - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); List nics = new ArrayList(); @@ -2057,7 +2057,7 @@ public class VirtualMachineMO extends BaseMO { List returnList = new ArrayList(); - VirtualDevice[] devices = (VirtualDevice[])_context.getVimClient(). + List devices = (List)_context.getVimClient(). getDynamicProperty(_mor, "config.hardware.device"); if(devices != null) { From c0442e2556a7b10cfb363a2d4d55b7fb9c381297 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 12 Feb 2013 16:56:02 -0800 Subject: [PATCH 06/17] Fix a bug in register template, cannot find template adapter. --- client/tomcatconf/componentContext.xml.in | 8 ++ .../tomcatconf/nonossComponentContext.xml.in | 8 ++ .../baremetal/BareMetalTemplateAdapter.java | 33 ++++---- ...er.java => HypervisorTemplateAdapter.java} | 75 +++++++++---------- 4 files changed, 69 insertions(+), 55 deletions(-) rename server/src/com/cloud/template/{HyervisorTemplateAdapter.java => HypervisorTemplateAdapter.java} (97%) diff --git a/client/tomcatconf/componentContext.xml.in b/client/tomcatconf/componentContext.xml.in index 43d31fb4b95..fc6c3e346c0 100644 --- a/client/tomcatconf/componentContext.xml.in +++ b/client/tomcatconf/componentContext.xml.in @@ -95,6 +95,14 @@ + + + + + + + + diff --git a/client/tomcatconf/nonossComponentContext.xml.in b/client/tomcatconf/nonossComponentContext.xml.in index 5532becba18..57f7ad5516f 100644 --- a/client/tomcatconf/nonossComponentContext.xml.in +++ b/client/tomcatconf/nonossComponentContext.xml.in @@ -104,6 +104,14 @@ + + + + + + + + diff --git a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java index 965c912a41e..33ab4684a63 100755 --- a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java +++ b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java @@ -48,17 +48,16 @@ import com.cloud.user.Account; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; -@Component @Local(value=TemplateAdapter.class) public class BareMetalTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter { private final static Logger s_logger = Logger.getLogger(BareMetalTemplateAdapter.class); @Inject HostDao _hostDao; @Inject ResourceManager _resourceMgr; - + @Override public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { TemplateProfile profile = super.prepare(cmd); - + if (profile.getZoneId() == null || profile.getZoneId() == -1) { List dcs = _dcDao.listAllIncludingRemoved(); for (DataCenterVO dc : dcs) { @@ -73,15 +72,15 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem throw new CloudRuntimeException("Please add PXE server before adding baremetal template in zone " + profile.getZoneId()); } } - + return profile; } - + @Override public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { throw new CloudRuntimeException("Baremetal doesn't support ISO template"); } - + private void templateCreateUsage(VMTemplateVO template, HostVO host) { if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) { UsageEventUtils.publishUsageEvent(EventTypes.EVENT_TEMPLATE_CREATE, template.getAccountId(), host.getDataCenterId(), @@ -89,12 +88,12 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem template.getClass().getName(), template.getUuid()); } } - + @Override public VMTemplateVO create(TemplateProfile profile) { VMTemplateVO template = persistTemplate(profile); Long zoneId = profile.getZoneId(); - + /* There is no secondary storage vm for baremetal, we use pxe server id. * Tempalte is not bound to pxeserver right now, and we assume the pxeserver * cannot be removed once it was added. so we use host id of first found pxe @@ -122,7 +121,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem _tmpltHostDao.persist(vmTemplateHost); templateCreateUsage(template, pxe); } - + _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template); return template; } @@ -130,7 +129,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem public TemplateProfile prepareDelete(DeleteIsoCmd cmd) { throw new CloudRuntimeException("Baremetal doesn't support ISO, how the delete get here???"); } - + @Override @DB public boolean delete(TemplateProfile profile) { VMTemplateVO template = (VMTemplateVO)profile.getTemplate(); @@ -138,7 +137,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem boolean success = true; String zoneName; boolean isAllZone; - + if (!template.isCrossZones() && profile.getZoneId() != null) { isAllZone = false; zoneName = profile.getZoneId().toString(); @@ -146,12 +145,12 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem zoneName = "all zones"; isAllZone = true; } - + s_logger.debug("Attempting to mark template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName); Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId()); String eventType = EventTypes.EVENT_TEMPLATE_DELETE; List templateHostVOs = _tmpltHostDao.listByTemplateId(templateId); - + for (VMTemplateHostVO vo : templateHostVOs) { VMTemplateHostVO lock = null; try { @@ -182,13 +181,13 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem } } } - + s_logger.debug("Successfully marked template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName); - + // If there are no more non-destroyed template host entries for this template, delete it if (success && (_tmpltHostDao.listByTemplateId(templateId).size() == 0)) { long accountId = template.getAccountId(); - + VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId); try { @@ -207,7 +206,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem } s_logger.debug("Removed template: " + template.getName() + " because all of its template host refs were marked as destroyed."); } - + return success; } } diff --git a/server/src/com/cloud/template/HyervisorTemplateAdapter.java b/server/src/com/cloud/template/HypervisorTemplateAdapter.java similarity index 97% rename from server/src/com/cloud/template/HyervisorTemplateAdapter.java rename to server/src/com/cloud/template/HypervisorTemplateAdapter.java index 089f6508d7e..b93d7e5ba42 100755 --- a/server/src/com/cloud/template/HyervisorTemplateAdapter.java +++ b/server/src/com/cloud/template/HypervisorTemplateAdapter.java @@ -63,18 +63,17 @@ import javax.ejb.Local; import java.net.*; import java.util.List; -@Component @Local(value=TemplateAdapter.class) -public class HyervisorTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter { - private final static Logger s_logger = Logger.getLogger(HyervisorTemplateAdapter.class); +public class HypervisorTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter { + private final static Logger s_logger = Logger.getLogger(HypervisorTemplateAdapter.class); @Inject DownloadMonitor _downloadMonitor; @Inject SecondaryStorageVmManager _ssvmMgr; @Inject AgentManager _agentMgr; - + private String validateUrl(String url) { try { URI uri = new URI(url); - if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") + if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { throw new IllegalArgumentException("Unsupported scheme for url: " + url); } @@ -95,34 +94,34 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); } - + return uri.toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } } - + @Override public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { TemplateProfile profile = super.prepare(cmd); String url = profile.getUrl(); - + if((!url.toLowerCase().endsWith("iso"))&&(!url.toLowerCase().endsWith("iso.zip"))&&(!url.toLowerCase().endsWith("iso.bz2")) &&(!url.toLowerCase().endsWith("iso.gz"))){ throw new InvalidParameterValueException("Please specify a valid iso"); } - + profile.setUrl(validateUrl(url)); return profile; } - + @Override public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { TemplateProfile profile = super.prepare(cmd); String url = profile.getUrl(); - + if((!url.toLowerCase().endsWith("vhd"))&&(!url.toLowerCase().endsWith("vhd.zip")) - &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz")) + &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz")) &&(!url.toLowerCase().endsWith("qcow2"))&&(!url.toLowerCase().endsWith("qcow2.zip")) &&(!url.toLowerCase().endsWith("qcow2.bz2"))&&(!url.toLowerCase().endsWith("qcow2.gz")) &&(!url.toLowerCase().endsWith("ova"))&&(!url.toLowerCase().endsWith("ova.zip")) @@ -130,40 +129,40 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem &&(!url.toLowerCase().endsWith("img"))&&(!url.toLowerCase().endsWith("raw"))){ throw new InvalidParameterValueException("Please specify a valid "+ cmd.getFormat().toLowerCase()); } - + if ((cmd.getFormat().equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith("vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith("vhd.gz") )) || (cmd.getFormat().equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith("qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz") )) || (cmd.getFormat().equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith("ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase().endsWith("ova.gz"))) || (cmd.getFormat().equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith("img") && !url.toLowerCase().endsWith("raw")))) { throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + cmd.getFormat().toLowerCase()); } - + profile.setUrl(validateUrl(url)); return profile; } - + @Override public VMTemplateVO create(TemplateProfile profile) { VMTemplateVO template = persistTemplate(profile); - + if (template == null) { throw new CloudRuntimeException("Unable to persist the template " + profile.getTemplate()); } - + _downloadMonitor.downloadTemplateToStorage(template, profile.getZoneId()); _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template); - + return template; } @Override @DB public boolean delete(TemplateProfile profile) { boolean success = true; - + VMTemplateVO template = (VMTemplateVO)profile.getTemplate(); Long zoneId = profile.getZoneId(); Long templateId = template.getId(); - + String zoneName; List secondaryStorageHosts; if (!template.isCrossZones() && zoneId != null) { @@ -174,9 +173,9 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem zoneName = "(all zones)"; secondaryStorageHosts = _ssvmMgr.listSecondaryStorageHostsInAllZones(); } - + s_logger.debug("Attempting to mark template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName); - + // Make sure the template is downloaded to all the necessary secondary storage hosts for (HostVO secondaryStorageHost : secondaryStorageHosts) { long hostId = secondaryStorageHost.getId(); @@ -189,16 +188,16 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem } } } - + Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId()); String eventType = ""; - + if (template.getFormat().equals(ImageFormat.ISO)){ eventType = EventTypes.EVENT_ISO_DELETE; } else { eventType = EventTypes.EVENT_TEMPLATE_DELETE; } - + // Iterate through all necessary secondary storage hosts and mark the template on each host as destroyed for (HostVO secondaryStorageHost : secondaryStorageHosts) { long hostId = secondaryStorageHost.getId(); @@ -229,7 +228,7 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem _tmpltHostDao.remove(templateHostVO.getId()); } VMTemplateZoneVO templateZone = _tmpltZoneDao.findByZoneTemplate(sZoneId, templateId); - + if (templateZone != null) { _tmpltZoneDao.remove(templateZone.getId()); } @@ -239,18 +238,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem } } } - + if (!success) { break; } } - + s_logger.debug("Successfully marked template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName); - + // If there are no more non-destroyed template host entries for this template, delete it if (success && (_tmpltHostDao.listByTemplateId(templateId).size() == 0)) { long accountId = template.getAccountId(); - + VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId); try { @@ -267,18 +266,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem _tmpltDao.releaseFromLockTable(lock.getId()); } } - + s_logger.debug("Removed template: " + template.getName() + " because all of its template host refs were marked as destroyed."); } - + return success; } - + public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) { TemplateProfile profile = super.prepareDelete(cmd); VMTemplateVO template = (VMTemplateVO)profile.getTemplate(); Long zoneId = profile.getZoneId(); - + if (template.getTemplateType() == TemplateType.SYSTEM) { throw new InvalidParameterValueException("The DomR template cannot be deleted."); } @@ -286,18 +285,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem if (zoneId != null && (_ssvmMgr.findSecondaryStorageHost(zoneId) == null)) { throw new InvalidParameterValueException("Failed to find a secondary storage host in the specified zone."); } - + return profile; } - + public TemplateProfile prepareDelete(DeleteIsoCmd cmd) { TemplateProfile profile = super.prepareDelete(cmd); Long zoneId = profile.getZoneId(); - + if (zoneId != null && (_ssvmMgr.findSecondaryStorageHost(zoneId) == null)) { throw new InvalidParameterValueException("Failed to find a secondary storage host in the specified zone."); } - + return profile; } } From c20ea048b4a01ddbbf80077b65f6e75d8f58e7bd Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 12 Feb 2013 16:57:20 -0800 Subject: [PATCH 07/17] Add new windows 8 guest os entries to DB. --- setup/db/db/schema-40to410.sql | 8 ++++++++ setup/db/templates.sql | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index bb9c815af05..a51ddb3fe8c 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -1299,3 +1299,11 @@ INSERT INTO `cloud`.`region` values ('1','Local','http://localhost:8080/client/a ALTER TABLE `cloud`.`account` ADD COLUMN `region_id` int unsigned NOT NULL DEFAULT '1'; ALTER TABLE `cloud`.`user` ADD COLUMN `region_id` int unsigned NOT NULL DEFAULT '1'; ALTER TABLE `cloud`.`domain` ADD COLUMN `region_id` int unsigned NOT NULL DEFAULT '1'; + + +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (208, UUID(), 6, 'Windows 8'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (209, UUID(), 6, 'Windows 8 (64 bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (210, UUID(), 6, 'Windows 8 Server (64 bit)'); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8', 208); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8 (64 bit)', 209); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8 Server (64 bit)', 210); diff --git a/setup/db/templates.sql b/setup/db/templates.sql index 9980b159630..34ec32d0ce7 100755 --- a/setup/db/templates.sql +++ b/setup/db/templates.sql @@ -219,6 +219,11 @@ INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (201 INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (202, UUID(), 5, 'Other SUSE Linux(32-bit)'); INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (203, UUID(), 5, 'Other SUSE Linux(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (208, UUID(), 6, 'Windows 8'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (209, UUID(), 6, 'Windows 8 (64 bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (210, UUID(), 6, 'Windows 8 Server (64 bit)'); + + INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.5 (32-bit)', 1); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.6 (32-bit)', 2); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.7 (32-bit)', 3); @@ -323,6 +328,10 @@ INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows NT 4', 64); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 3.1', 65); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8', 208); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8 (64 bit)', 209); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8 Server (64 bit)', 210); + INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5.0(32-bit)', 30); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5.1(32-bit)', 32); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5.2(32-bit)', 34); From 525fe14c25877aeb0c49a6ca8aa9d18f62ff97e2 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 20 Feb 2013 10:57:52 -0800 Subject: [PATCH 08/17] Trust all certificate in vcenter connect. --- .../hypervisor/vmware/util/VmwareClient.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java index ae5f47fca22..f29a8c0077a 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -58,6 +58,36 @@ import com.vmware.vim25.ObjectContent; */ public class VmwareClient { + private static class TrustAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { + return; + } + + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { + return; + } + } + + private static void trustAllHttpsCertificates() throws Exception { + // Create a trust manager that does not validate certificate chains: + javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; + javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); + trustAllCerts[0] = tm; + javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); + javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext(); + sslsc.setSessionTimeout(0); + sc.init(null, trustAllCerts, null); + javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } + private ManagedObjectReference SVC_INST_REF = new ManagedObjectReference(); private ManagedObjectReference propCollectorRef; private ManagedObjectReference rootRef; @@ -86,6 +116,7 @@ public class VmwareClient { return true; } }; + trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); SVC_INST_REF.setType(SVC_INST_NAME); From 0f3a3a9a6d84c97e53769cca3b76d07ad273c4c9 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 20 Feb 2013 10:58:18 -0800 Subject: [PATCH 09/17] Enable logging in systemvm. --- agent/src/com/cloud/agent/AgentShell.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java index 0e020935e90..7297ab285e5 100644 --- a/agent/src/com/cloud/agent/AgentShell.java +++ b/agent/src/com/cloud/agent/AgentShell.java @@ -48,6 +48,7 @@ import com.cloud.agent.dao.StorageComponent; import com.cloud.agent.dao.impl.PropertiesStorage; import com.cloud.host.Host; import com.cloud.resource.ServerResource; +import com.cloud.utils.LogUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.ProcessUtil; import com.cloud.utils.PropertiesUtil; @@ -611,6 +612,8 @@ public class AgentShell implements IAgentShell { public static void main(String[] args) { try { + LogUtils.initLog4j("log4j-cloud.xml"); + AgentShell shell = new AgentShell(); shell.init(args); shell.start(); From c9f0af42a6206ddf21f760469e21ab6dac5feddd Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 21 Feb 2013 10:22:14 -0800 Subject: [PATCH 10/17] Fix systemvm.iso path search issue. --- .../vmware/manager/VmwareManagerImpl.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java index 21cd914689d..64dbea18495 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java @@ -584,10 +584,15 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw private File getSystemVMPatchIsoFile() { // locate systemvm.iso - URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); - File file = new File(url.getFile()); - File isoFile = new File(file.getParent() + "/vms/systemvm.iso"); - if (!isoFile.exists()) { + //URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); + //File file = new File(url.getFile()); + //File isoFile = new File(file.getParent() + "/vms/systemvm.iso"); + URL url = this.getClass().getClassLoader().getResource("vms/systemvm.iso"); + File isoFile = null; + if (url != null) { + isoFile = new File(url.getPath()); + } + if (isoFile == null || !isoFile.exists()) { isoFile = new File("/usr/lib64/cloud/common/" + "/vms/systemvm.iso"); if (!isoFile.exists()) { isoFile = new File("/usr/lib/cloud/common/" + "/vms/systemvm.iso"); @@ -598,11 +603,14 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw @Override public File getSystemVMKeyFile() { - URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); - File file = new File(url.getFile()); - - File keyFile = new File(file.getParent(), "/scripts/vm/systemvm/id_rsa.cloud"); - if (!keyFile.exists()) { + // URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation(); + // File file = new File(url.getFile()); + URL url = this.getClass().getClassLoader().getResource("scripts/vm/systemvm/id_rsa.cloud"); + File keyFile = null; + if ( url != null ){ + keyFile = new File(url.getPath()); + } + if (keyFile == null || !keyFile.exists()) { keyFile = new File("/usr/lib64/cloud/common" + "/scripts/vm/systemvm/id_rsa.cloud"); if (!keyFile.exists()) { keyFile = new File("/usr/lib/cloud/common" + "/scripts/vm/systemvm/id_rsa.cloud"); From 8343931a326cc88fc2788f1242316cf9750cfb4a Mon Sep 17 00:00:00 2001 From: Min Chen Date: Fri, 22 Feb 2013 10:11:36 -0800 Subject: [PATCH 11/17] Fix how we can get VimPort cookie in SDK 5.1 due to ws implementation change from Axis to JAX-WS. --- .../hypervisor/vmware/util/VmwareContext.java | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java index 7f9aacb538d..091ce770836 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java @@ -37,6 +37,9 @@ import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; +import javax.xml.ws.BindingProvider; +import com.sun.xml.internal.ws.transport.http.client.CookieJar; +import com.sun.xml.internal.ws.client.BindingProviderProperties; import org.apache.log4j.Logger; @@ -378,8 +381,12 @@ public class VmwareContext { long totalBytesDownloaded, ActionDelegate progressUpdater) throws Exception { HttpURLConnection conn = getRawHTTPConnection(urlString); - String cookieString = getServiceCookie(); - conn.setRequestProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE, cookieString); + CookieJar cookie = getServiceCookie(); + if ( cookie == null ){ + s_logger.error("No cookie is found in vwware web service request context!"); + throw new Exception("No cookie is found in vmware web service request context!"); + } + cookie.applyRelevantCookies(conn); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); @@ -530,7 +537,11 @@ public class VmwareContext { } public HttpURLConnection getHTTPConnection(String urlString, String httpMethod) throws Exception { - String cookieString = getServiceCookie(); + CookieJar cookie = getServiceCookie(); + if ( cookie == null ){ + s_logger.error("No cookie is found in vmware web service request context!"); + throw new Exception("No cookie is found in vmware web service request context!"); + } HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { @@ -545,7 +556,7 @@ public class VmwareContext { conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); - conn.setRequestProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE, cookieString); + cookie.applyRelevantCookies(conn); conn.setRequestMethod(httpMethod); connectWithRetry(conn); return conn; @@ -564,13 +575,10 @@ public class VmwareContext { return (HttpURLConnection)url.openConnection(); } - private String getServiceCookie() throws Exception { - com.vmware.vim25.VimPortType service = getService(); - org.apache.axis.client.Stub st = (org.apache.axis.client.Stub)service; - org.apache.axis.client.Call callObj = st._getCall(); - org.apache.axis.MessageContext msgContext = callObj.getMessageContext(); - String cookieString = (String)msgContext.getProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE); - return cookieString; + private CookieJar getServiceCookie() throws Exception { + VimPortType port = getService(); + Map ctxt = ((BindingProvider) port).getRequestContext(); + return (CookieJar)ctxt.get(BindingProviderProperties.HTTP_COOKIE_JAR); } private static void connectWithRetry(HttpURLConnection conn) throws Exception { From a433a29e8ee32b45863de5b695acb8c791067995 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Fri, 22 Feb 2013 11:32:23 -0800 Subject: [PATCH 12/17] Add -XDignore.symbol.file=true javac option to avoid compilation check to acccess com.sun.xml.internal.ws.transport.http.client package. --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 149e6bf82d2..b1d0ea54e56 100644 --- a/pom.xml +++ b/pom.xml @@ -440,7 +440,8 @@ ${cs.jdk.version} true 128m - 512m + 512m + -XDignore.symbol.file=true From 610088fb2d56e0d9c43851910636135b542d1228 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 26 Feb 2013 13:29:02 -0800 Subject: [PATCH 13/17] Use value() instead of toString() to convert guestOsIdentifier. --- .../com/cloud/hypervisor/vmware/resource/VmwareResource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index c5b812bbbdf..580b4a82f23 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -2103,7 +2103,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa assert (vmSpec.getMinSpeed() != null) && (rootDiskDataStoreDetails != null); if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), vmSpec.getMinSpeed(), vmSpec.getLimitCpuUse(),(int)(vmSpec.getMaxRam()/(1024*1024)), ramMb, - translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) { + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmName); } } From 17488fac364c923de43fcd5d15a237f0978282ff Mon Sep 17 00:00:00 2001 From: Min Chen Date: Tue, 26 Feb 2013 15:32:59 -0800 Subject: [PATCH 14/17] Fix another toString() usage of GuestOsIdentifier enum. --- .../com/cloud/hypervisor/vmware/resource/VmwareResource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 11cb62c4456..1bc233cc70c 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -2138,7 +2138,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(),(int) (vmSpec.getMaxRam()/(1024*1024)), ramMb, - translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse()); + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), vmSpec.getLimitCpuUse()); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; From 7d2ebc9fc3587baf4f984c995e45195d989387a0 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Wed, 27 Feb 2013 13:46:43 -0800 Subject: [PATCH 15/17] Add some comments on some code source to give credit to vmware sample code. --- .../cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java | 2 +- .../src/com/cloud/hypervisor/vmware/util/VmwareClient.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java b/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java index 8bb2a4de902..6e22e174f58 100644 --- a/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java +++ b/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.storage.dao; +package com.cloud.vm.dao; import java.io.IOException; diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java index f29a8c0077a..21c649a48cb 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -53,7 +53,7 @@ import com.vmware.vim25.ObjectContent; /** * A wrapper class to handle Vmware vsphere connection and disconnection. * - * @author minc + * DISCLAIMER: This code is partly copied from sample codes that come along with Vmware web service 5.1 SDK. * */ public class VmwareClient { @@ -276,7 +276,7 @@ public class VmwareClient { * properties to check are reached Destroys the ObjectFilter when done. * * @param objmor - * MOR of the Object to wait for + * MOR of the Object to wait for * @param filterProps * Properties list to filter * @param endWaitProps From bcaac324aa995480830c60cbe77025b1f5c446fe Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 28 Feb 2013 11:00:03 -0800 Subject: [PATCH 16/17] Rebase with master, bring into Vmware vswitch change. --- .../cloud/hypervisor/vmware/mo/DatacenterMO.java | 4 ++-- .../vmware/mo/DistributedVirtualSwitchMO.java | 12 +++++++----- .../hypervisor/vmware/util/VmwareClient.java | 16 ++++++++++++++++ 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java index 7df0cf4bb9c..0a3e20ba8aa 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java @@ -484,8 +484,8 @@ public class DatacenterMO extends BaseMO { public ManagedObjectReference getDvSwitchMor(String dvSwitchName) throws Exception { ManagedObjectReference dvSwitchMor = null; ManagedObjectReference networkFolderMor = null; - networkFolderMor = _context.getServiceUtil().getMoRefProp(_mor, "networkFolder"); - dvSwitchMor = _context.getServiceUtil().getDecendentMoRef(networkFolderMor, "VmwareDistributedVirtualSwitch", dvSwitchName); + networkFolderMor = _context.getVimClient().getMoRefProp(_mor, "networkFolder"); + dvSwitchMor = _context.getVimClient().getDecendentMoRef(networkFolderMor, "VmwareDistributedVirtualSwitch", dvSwitchName); return dvSwitchMor; } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java index 494477e9be3..247be2a5fab 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java @@ -16,11 +16,13 @@ // under the License. package com.cloud.hypervisor.vmware.mo; +import java.util.ArrayList; +import java.util.List; + import org.apache.log4j.Logger; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.DVPortgroupConfigSpec; -import com.vmware.vim25.HostPortGroupSpec; import com.vmware.vim25.ManagedObjectReference; public class DistributedVirtualSwitchMO extends BaseMO { @@ -35,13 +37,13 @@ public class DistributedVirtualSwitchMO extends BaseMO { } public void createDVPortGroup(DVPortgroupConfigSpec dvPortGroupSpec) throws Exception { - DVPortgroupConfigSpec[] dvPortGroupSpecArray = new DVPortgroupConfigSpec[1]; - dvPortGroupSpecArray[0] = dvPortGroupSpec; - _context.getService().addDVPortgroup_Task(_mor, dvPortGroupSpecArray); + List dvPortGroupSpecArray = new ArrayList(); + dvPortGroupSpecArray.add(dvPortGroupSpec); + _context.getService().addDVPortgroupTask(_mor, dvPortGroupSpecArray); } public void updateDvPortGroup(ManagedObjectReference dvPortGroupMor, DVPortgroupConfigSpec dvPortGroupSpec) throws Exception { // TODO(sateesh): Update numPorts - _context.getService().reconfigureDVPortgroup_Task(dvPortGroupMor, dvPortGroupSpec); + _context.getService().reconfigureDVPortgroupTask(dvPortGroupMor, dvPortGroupSpec); } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java index 21c649a48cb..fc307f8050d 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -540,4 +540,20 @@ public class VmwareClient { } return null; } + + /** + * Get a MORef from the property returned. + * + * @param objMor Object to get a reference property from + * @param propName name of the property that is the MORef + * @return the ManagedObjectReference for that property. + */ + public ManagedObjectReference getMoRefProp(ManagedObjectReference objMor, String propName) throws Exception { + Object props = getDynamicProperty(objMor, propName); + ManagedObjectReference propmor = null; + if (!props.getClass().isArray()) { + propmor = (ManagedObjectReference)props; + } + return propmor; + } } From 737dac2e65a86d84e513e436fd6f487eda5352b4 Mon Sep 17 00:00:00 2001 From: Min Chen Date: Thu, 28 Feb 2013 15:42:56 -0800 Subject: [PATCH 17/17] Some cosmetic changes to VmwareClient private methods. --- .../hypervisor/vmware/util/VmwareClient.java | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java index fc307f8050d..344fbddc318 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java @@ -194,7 +194,7 @@ public class VmwareClient { public Object getDynamicProperty(ManagedObjectReference mor, String propertyName) throws Exception { List props = new ArrayList(); props.add(propertyName); - List objContent = this.getObjectProperties(mor, props); + List objContent = this.retrieveMoRefProperties(mor, props); Object propertyValue = null; if (objContent != null && objContent.size() > 0) { @@ -224,7 +224,7 @@ public class VmwareClient { return propertyValue; } - private List getObjectProperties(ManagedObjectReference mObj, List props) throws Exception { + private List retrieveMoRefProperties(ManagedObjectReference mObj, List props) throws Exception { PropertySpec pSpec = new PropertySpec(); pSpec.setAll(false); pSpec.setType(mObj.getType()); @@ -380,23 +380,21 @@ public class VmwareClient { * @return An array of SelectionSpec covering VM, Host, Resource pool, * Cluster Compute Resource and Datastore. */ - private List buildFullTraversal() { - // Terminal traversal specs - - // RP -> VM + private List constructCompleteTraversalSpec() { + // ResourcePools to VM: RP -> VM TraversalSpec rpToVm = new TraversalSpec(); rpToVm.setName("rpToVm"); rpToVm.setType("ResourcePool"); rpToVm.setPath("vm"); rpToVm.setSkip(Boolean.FALSE); - // vApp -> VM + // VirtualApp to VM: vApp -> VM TraversalSpec vAppToVM = new TraversalSpec(); vAppToVM.setName("vAppToVM"); vAppToVM.setType("VirtualApp"); vAppToVM.setPath("vm"); - // HostSystem -> VM + // Host to VM: HostSystem -> VM TraversalSpec hToVm = new TraversalSpec(); hToVm.setType("HostSystem"); hToVm.setPath("vm"); @@ -404,7 +402,7 @@ public class VmwareClient { hToVm.getSelectSet().add(getSelectionSpec("VisitFolders")); hToVm.setSkip(Boolean.FALSE); - // DC -> DS + // DataCenter to DataStore: DC -> DS TraversalSpec dcToDs = new TraversalSpec(); dcToDs.setType("Datacenter"); dcToDs.setPath("datastore"); @@ -513,7 +511,7 @@ public class VmwareClient { ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(root); oSpec.setSkip(false); - oSpec.getSelectSet().addAll(buildFullTraversal()); + oSpec.getSelectSet().addAll(constructCompleteTraversalSpec()); PropertyFilterSpec spec = new PropertyFilterSpec(); spec.getPropSet().add(pSpec); @@ -527,6 +525,7 @@ public class VmwareClient { return null; } + // filter through retrieved objects to get the first match. for (ObjectContent oc : ocary) { ManagedObjectReference mor = oc.getObj(); List propary = oc.getPropSet();