From bd4ad55535adc153cc6716fdd7d1cbdc3cf08586 Mon Sep 17 00:00:00 2001 From: David Nalley Date: Mon, 9 Apr 2012 14:21:43 -0400 Subject: [PATCH] fixing line endings for vmware-base --- .../cloud/hypervisor/vmware/mo/BaseMO.java | 266 +- .../cloud/hypervisor/vmware/mo/ClusterMO.java | 816 ++-- .../vmware/mo/CustomFieldsManagerMO.java | 136 +- .../hypervisor/vmware/mo/DatacenterMO.java | 508 +-- .../hypervisor/vmware/mo/DatastoreFile.java | 242 +- .../hypervisor/vmware/mo/DatastoreMO.java | 516 +-- .../vmware/mo/HostDatastoreSystemMO.java | 338 +- .../vmware/mo/HostFirewallSystemMO.java | 60 +- .../cloud/hypervisor/vmware/mo/HostMO.java | 1170 +++--- .../vmware/mo/HostNetworkSystemMO.java | 98 +- .../hypervisor/vmware/mo/HttpNfcLeaseMO.java | 282 +- .../vmware/mo/HypervisorHostHelper.java | 506 +-- .../cloud/hypervisor/vmware/mo/NetworkMO.java | 46 +- .../vmware/mo/PerfCounterInfoMapper.java | 156 +- .../hypervisor/vmware/mo/PerfManagerMO.java | 138 +- .../vmware/mo/SnapshotDescriptor.java | 510 +-- .../vmware/mo/VirtualDiskManagerMO.java | 282 +- .../vmware/mo/VirtualMachineMO.java | 3276 ++++++++--------- .../vmware/mo/VmdkFileDescriptor.java | 284 +- .../vmware/mo/VmwareHypervisorHost.java | 100 +- .../VmwareHypervisorHostNetworkSummary.java | 68 +- .../VmwareHypervisorHostResourceSummary.java | 68 +- .../hypervisor/vmware/util/VmwareContext.java | 1096 +++--- .../vmware/util/VmwareGuestOsMapper.java | 86 +- .../hypervisor/vmware/util/VmwareHelper.java | 866 ++--- 25 files changed, 5957 insertions(+), 5957 deletions(-) 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 55a83c5ac55..26c4e17ec67 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java @@ -10,136 +10,136 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.CustomFieldDef; -import com.vmware.vim25.CustomFieldStringValue; -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); - } - - 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"); - } - - public String getName() throws Exception { - if(_name == null) - _name = (String)_context.getServiceUtil().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")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware destroy_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - 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")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware rename_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - return false; - } - - public void setCustomFieldValue(String fieldName, String value) throws Exception { - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, - _context.getServiceContent().getCustomFieldsManager()); - - int key = getCustomFieldKey(fieldName); - if(key == 0) { - try { - CustomFieldDef field = cfmMo.addCustomerFieldDef(fieldName, getMor().getType(), null, null); - key = field.getKey(); - } catch (Exception e) { - // assuming the exception is caused by concurrent operation from other places - // so we retieve the key again - 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(), - 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, - _context.getServiceContent().getCustomFieldsManager()); - - return cfmMo.getCustomFieldKey(morType, fieldName); - } -} +package com.cloud.hypervisor.vmware.mo; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.CustomFieldDef; +import com.vmware.vim25.CustomFieldStringValue; +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); + } + + 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"); + } + + public String getName() throws Exception { + if(_name == null) + _name = (String)_context.getServiceUtil().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")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware destroy_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + 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")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware rename_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + return false; + } + + public void setCustomFieldValue(String fieldName, String value) throws Exception { + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + _context.getServiceContent().getCustomFieldsManager()); + + int key = getCustomFieldKey(fieldName); + if(key == 0) { + try { + CustomFieldDef field = cfmMo.addCustomerFieldDef(fieldName, getMor().getType(), null, null); + key = field.getKey(); + } catch (Exception e) { + // assuming the exception is caused by concurrent operation from other places + // so we retieve the key again + 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(), + 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, + _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 cec934b59a4..51801a2251e 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java @@ -10,94 +10,94 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.cloud.utils.Pair; +package com.cloud.hypervisor.vmware.mo; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +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; -import com.vmware.vim25.ClusterDasConfigInfo; -import com.vmware.vim25.ClusterHostRecommendation; -import com.vmware.vim25.ComputeResourceSummary; -import com.vmware.vim25.CustomFieldStringValue; -import com.vmware.vim25.DatastoreInfo; -import com.vmware.vim25.DynamicProperty; -import com.vmware.vim25.HostHardwareSummary; -import com.vmware.vim25.HostIpRouteEntry; -import com.vmware.vim25.HostRuntimeInfo; -import com.vmware.vim25.HostSystemConnectionState; -import com.vmware.vim25.ManagedObjectReference; -import com.vmware.vim25.NasDatastoreInfo; -import com.vmware.vim25.ObjectContent; -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; - -// -// 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(); - } - - @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"); - 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"); +import com.vmware.apputils.vim25.ServiceUtil; +import com.vmware.vim25.ArrayOfHostIpRouteEntry; +import com.vmware.vim25.ClusterComputeResourceSummary; +import com.vmware.vim25.ClusterConfigInfoEx; +import com.vmware.vim25.ClusterDasConfigInfo; +import com.vmware.vim25.ClusterHostRecommendation; +import com.vmware.vim25.ComputeResourceSummary; +import com.vmware.vim25.CustomFieldStringValue; +import com.vmware.vim25.DatastoreInfo; +import com.vmware.vim25.DynamicProperty; +import com.vmware.vim25.HostHardwareSummary; +import com.vmware.vim25.HostIpRouteEntry; +import com.vmware.vim25.HostRuntimeInfo; +import com.vmware.vim25.HostSystemConnectionState; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.NasDatastoreInfo; +import com.vmware.vim25.ObjectContent; +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; + +// +// 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(); + } + + @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"); + 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"); } @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 + + @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) { @@ -112,462 +112,462 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost { } } return null; - } - - @Override + } + + @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)); - - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("VirtualMachine"); - pSpec.setPathSet(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 }); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(getMor()); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { cluster2HostFolderTraversal }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("VirtualMachine"); + pSpec.setPathSet(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 }); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(getMor()); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; - } - - @Override + return properties; + } + + @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)); - - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Datastore"); - pSpec.setPathSet(propertyPaths); - - TraversalSpec cluster2DatastoreTraversal = new TraversalSpec(); - cluster2DatastoreTraversal.setType("ClusterComputeResource"); - cluster2DatastoreTraversal.setPath("datastore"); - cluster2DatastoreTraversal.setName("cluster2DatastoreTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { cluster2DatastoreTraversal }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Datastore"); + pSpec.setPathSet(propertyPaths); + + TraversalSpec cluster2DatastoreTraversal = new TraversalSpec(); + cluster2DatastoreTraversal.setType("ClusterComputeResource"); + cluster2DatastoreTraversal.setPath("datastore"); + cluster2DatastoreTraversal.setName("cluster2DatastoreTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; - } - - private ObjectContent[] getHostPropertiesOnCluster(String[] propertyPaths) throws Exception { + return properties; + } + + 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)); - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("HostSystem"); - pSpec.setPathSet(propertyPaths); - - TraversalSpec cluster2HostTraversal = new TraversalSpec(); - cluster2HostTraversal.setType("ClusterComputeResource"); - cluster2HostTraversal.setPath("host"); - cluster2HostTraversal.setName("cluster2HostTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { cluster2HostTraversal }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("HostSystem"); + pSpec.setPathSet(propertyPaths); + + TraversalSpec cluster2HostTraversal = new TraversalSpec(); + cluster2HostTraversal.setType("ClusterComputeResource"); + cluster2HostTraversal.setPath("host"); + cluster2HostTraversal.setName("cluster2HostTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; - } - - @Override + return properties; + } + + @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)); - assert(vmSpec != null); - DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); - ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); - - ManagedObjectReference morTask = _context.getService().createVM_Task( - dcMo.getVmFolder(), vmSpec, morPool, null); - String result = _context.getServiceUtil().waitForTask(morTask); - - if(result.equals("sucess")) { + assert(vmSpec != null); + DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); + ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); + + ManagedObjectReference morTask = _context.getService().createVM_Task( + dcMo.getVmFolder(), vmSpec, morPool, null); + String result = _context.getServiceUtil().waitForTask(morTask); + + if(result.equals("sucess")) { _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)); + 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 + 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); - ManagedObjectReference morRp = getHyperHostOwnerResourcePool(); - assert(morRp != null); + ManagedObjectReference morRp = getHyperHostOwnerResourcePool(); + assert(morRp != null); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.get_value()); - + HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, null); - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - importVmFromOVF() done"); - } - - @Override - public boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, + } + + @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); - - boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, + + 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, - int poolHostPort, String poolPath, String poolUuid) throws Exception { + return result; + } + + @Override + 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 + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); - - ManagedObjectReference morDs = null; - ManagedObjectReference morDsFirst = null; - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().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())); - } - } - - if(morDs == null) { - String msg = "Failed to mount datastore in all hosts within the cluster"; + + ManagedObjectReference morDs = null; + ManagedObjectReference morDsFirst = null; + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().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())); + } + } + + 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); + throw new Exception(msg); } - + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - mountDatastore() done(successfully)"); - return morDs; - } - - @Override + 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"); - if(hosts != null && hosts.length > 0) { - for(ManagedObjectReference morHost : hosts) { - HostMO hostMo = new HostMO(_context, morHost); - hostMo.unmountDatastore(poolUuid); - } + + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().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 { + } + + @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, - _context.getServiceContent().getCustomFieldsManager()); - int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID); - assert(key != 0); - - 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)) - return oc.getObj(); - - if(oc.getPropSet().length > 1) { - DynamicProperty prop = oc.getPropSet(1); - if(prop != null && prop.getVal() != null) { - if(prop.getVal() instanceof CustomFieldStringValue) { - String val = ((CustomFieldStringValue)prop.getVal()).getValue(); + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context, + _context.getServiceContent().getCustomFieldsManager()); + int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID); + assert(key != 0); + + 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)) + return oc.getObj(); + + if(oc.getPropSet().length > 1) { + DynamicProperty prop = oc.getPropSet(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(); - } - } - } - } - } + } + } + } + } + } } if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findDatastore() done(failed)"); - return null; - } - - @Override + 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); - - ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"info"}); - if(ocs != null && ocs.length > 0) { - for(ObjectContent oc : ocs) { - DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet(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); + + ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"info"}); + if(ocs != null && ocs.length > 0) { + for(ObjectContent oc : ocs) { + DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet(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(); - } - } - } - } - } - + } + } + } + } + } + if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(failed)"); - return null; - } - - @Override - public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception { + 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()); - ClusterHostRecommendation[] candidates = recommendHostsForVm(vmMo); + ClusterHostRecommendation[] candidates = recommendHostsForVm(vmMo); if(candidates != null && candidates.length > 0) { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - findMigrationTarget() done(successfully)"); return candidates[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) - return true; - } - } - return false; - } - - @Override + 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) + 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(); - if(entries != null) { - for(HostIpRouteEntry entry : entries.getHostIpRouteEntry()) { - 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?"); - } - - @Override - public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() 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(); + if(entries != null) { + for(HostIpRouteEntry entry : entries.getHostIpRouteEntry()) { + 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?"); + } + + @Override + public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.get_value()); - VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); - - ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getServiceUtil().getDynamicProperty( - _mor, "summary"); - - // TODO, need to use traversal to optimize retrieve of - int cpuNumInCpuThreads = 1; - ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().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(); - } - } - summary.setCpuCount(cpuNumInCpuThreads); - summary.setCpuSpeed(vmwareSummary.getTotalCpu()); + VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); + + ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getServiceUtil().getDynamicProperty( + _mor, "summary"); + + // TODO, need to use traversal to optimize retrieve of + int cpuNumInCpuThreads = 1; + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().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(); + } + } + 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 + 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"); + + ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().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; + return summary; } if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(failed)"); - return null; - } - - @Override - public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception { + return null; + } + + @Override + public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.get_value()); - ClusterComputeResourceSummary hardwareSummary = (ClusterComputeResourceSummary) - _context.getServiceUtil().getDynamicProperty(_mor, "summary"); + ClusterComputeResourceSummary hardwareSummary = (ClusterComputeResourceSummary) + _context.getServiceUtil().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(), - 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(); - - 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(); - if(objProps != null) { - String name = null; - String value = null; - for(DynamicProperty objProp : objProps) { - if(objProp.getName().equals("name")) { - name = (String)objProp.getVal(); - } else { - OptionValue optValue = (OptionValue)objProp.getVal(); - value = (String)optValue.getValue(); - } - } - - if(name != null && value != null) { - portInfo.put(name, Integer.parseInt(value)); - } - } - } - } - - return portInfo; - } -} - + return hardwareSummary; + } + + public ClusterHostRecommendation[] 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(); + + 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(); + if(objProps != null) { + String name = null; + String value = null; + for(DynamicProperty objProp : objProps) { + if(objProp.getName().equals("name")) { + name = (String)objProp.getVal(); + } 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 d2304b9a098..6dc5fdc0493 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java @@ -10,71 +10,71 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.CustomFieldDef; -import com.vmware.vim25.ManagedObjectReference; -import com.vmware.vim25.PrivilegePolicyDef; - -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, - 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"); - } - - public int getCustomFieldKey(String morType, String fieldName) throws Exception { - CustomFieldDef[] fields = getFields(); - if(fields != null) { - for(CustomFieldDef field : fields) { - if(field.getName().equals(fieldName) && field.getManagedObjectType().equals(morType)) - return field.getKey(); - } - } - 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(); - } catch(Exception e) { - // 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; - } -} +package com.cloud.hypervisor.vmware.mo; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.CustomFieldDef; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.PrivilegePolicyDef; + +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, + 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"); + } + + public int getCustomFieldKey(String morType, String fieldName) throws Exception { + CustomFieldDef[] fields = getFields(); + if(fields != null) { + for(CustomFieldDef field : fields) { + if(field.getName().equals(fieldName) && field.getManagedObjectType().equals(morType)) + return field.getKey(); + } + } + 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(); + } catch(Exception e) { + // 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 17535eb99b4..7c573509503 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java @@ -10,82 +10,82 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.cloud.utils.Pair; -import com.vmware.apputils.vim25.ServiceUtil; +package com.cloud.hypervisor.vmware.mo; + +import java.util.ArrayList; +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.DynamicProperty; -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.TraversalSpec; - -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); - assert(_mor != null); - } - - public String getName() throws Exception { - return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); - } - - public void registerTemplate(ManagedObjectReference morHost, String datastoreName, - String templateName, String templateFileName) throws Exception { - - ServiceUtil serviceUtil = _context.getServiceUtil(); - - ManagedObjectReference morFolder = (ManagedObjectReference)serviceUtil.getDynamicProperty( - _mor, "vmFolder"); - assert(morFolder != null); - - ManagedObjectReference morTask = _context.getService().registerVM_Task( - morFolder, - String.format("[%s] %s/%s", datastoreName, templateName, templateFileName), - templateName, true, - null, morHost); - - String result = serviceUtil.waitForTask(morTask); - if (!result.equalsIgnoreCase("Sucess")) { - 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) { - for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); - if(props != null) { - for(DynamicProperty prop : props) { - if(prop.getVal().toString().equals(vmName)) - return new VirtualMachineMO(_context, oc.getObj()); - } - } - } - } - return null; +import com.vmware.vim25.DynamicProperty; +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.TraversalSpec; + +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); + assert(_mor != null); + } + + public String getName() throws Exception { + return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); + } + + public void registerTemplate(ManagedObjectReference morHost, String datastoreName, + String templateName, String templateFileName) throws Exception { + + ServiceUtil serviceUtil = _context.getServiceUtil(); + + ManagedObjectReference morFolder = (ManagedObjectReference)serviceUtil.getDynamicProperty( + _mor, "vmFolder"); + assert(morFolder != null); + + ManagedObjectReference morTask = _context.getService().registerVM_Task( + morFolder, + String.format("[%s] %s/%s", datastoreName, templateName, templateFileName), + templateName, true, + null, morHost); + + String result = serviceUtil.waitForTask(morTask); + if (!result.equalsIgnoreCase("Sucess")) { + 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) { + for(ObjectContent oc : ocs) { + DynamicProperty[] props = oc.getPropSet(); + if(props != null) { + for(DynamicProperty prop : props) { + if(prop.getVal().toString().equals(vmName)) + return new VirtualMachineMO(_context, oc.getObj()); + } + } + } + } + return null; } public List findVmByNameAndLabel(String vmLabel) throws Exception { @@ -122,182 +122,182 @@ public class DatacenterMO extends BaseMO { } return list; } - - public List> getAllVmsOnDatacenter() throws Exception { - List> vms = new ArrayList>(); - - ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" }); - if(ocs != null) { - for(ObjectContent oc : ocs) { - String vmName = oc.getPropSet(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" }); - if(ocs != null) { - for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().toString().equals(name)) { - return oc.getObj(); - } - } - } - return null; - } - - public ManagedObjectReference findHost(String name) throws Exception { - ObjectContent[] ocs= getHostPropertiesOnDatacenterHostFolder(new String[] { "name" }); - - if(ocs != null) { - for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().toString().equals(name)) { - return oc.getObj(); - } - } - } - return null; - } - - public ManagedObjectReference getVmFolder() throws Exception { - return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "vmFolder"); - } - - public ObjectContent[] getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception { - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("HostSystem"); - pSpec.setPathSet(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 }); - - TraversalSpec dc2HostFolderTraversal = new TraversalSpec(); - dc2HostFolderTraversal.setType("Datacenter"); - dc2HostFolderTraversal.setPath("hostFolder"); - dc2HostFolderTraversal.setName("dc2HostFolderTraversal"); - dc2HostFolderTraversal.setSelectSet(new SelectionSpec[] { folder2childEntity } ); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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 }); - } - - public ObjectContent[] getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception { - - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Datastore"); - pSpec.setPathSet(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 }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - return _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - } - - public ObjectContent[] getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception { - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("VirtualMachine"); - pSpec.setPathSet(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 } ); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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 }); - } - - public static Pair getOwnerDatacenter(VmwareContext context, - ManagedObjectReference morEntity) throws Exception { - - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Datacenter"); - pSpec.setPathSet(new String[] { "name" }); - - TraversalSpec entityParentTraversal = new TraversalSpec(); - entityParentTraversal.setType("ManagedEntity"); - entityParentTraversal.setPath("parent"); - entityParentTraversal.setName("entityParentTraversal"); - entityParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "entityParentTraversal") }); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(morEntity); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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); - } -} + + public List> getAllVmsOnDatacenter() throws Exception { + List> vms = new ArrayList>(); + + ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" }); + if(ocs != null) { + for(ObjectContent oc : ocs) { + String vmName = oc.getPropSet(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" }); + if(ocs != null) { + for(ObjectContent oc : ocs) { + if(oc.getPropSet(0).getVal().toString().equals(name)) { + return oc.getObj(); + } + } + } + return null; + } + + public ManagedObjectReference findHost(String name) throws Exception { + ObjectContent[] ocs= getHostPropertiesOnDatacenterHostFolder(new String[] { "name" }); + + if(ocs != null) { + for(ObjectContent oc : ocs) { + if(oc.getPropSet(0).getVal().toString().equals(name)) { + return oc.getObj(); + } + } + } + return null; + } + + public ManagedObjectReference getVmFolder() throws Exception { + return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "vmFolder"); + } + + public ObjectContent[] getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception { + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("HostSystem"); + pSpec.setPathSet(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 }); + + TraversalSpec dc2HostFolderTraversal = new TraversalSpec(); + dc2HostFolderTraversal.setType("Datacenter"); + dc2HostFolderTraversal.setPath("hostFolder"); + dc2HostFolderTraversal.setName("dc2HostFolderTraversal"); + dc2HostFolderTraversal.setSelectSet(new SelectionSpec[] { folder2childEntity } ); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); + } + + public ObjectContent[] getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception { + + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Datastore"); + pSpec.setPathSet(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 }); + + PropertyFilterSpec pfSpec = new PropertyFilterSpec(); + pfSpec.setPropSet(new PropertySpec[] { pSpec }); + pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + + return _context.getService().retrieveProperties( + _context.getServiceContent().getPropertyCollector(), + new PropertyFilterSpec[] { pfSpec }); + } + + public ObjectContent[] getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception { + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("VirtualMachine"); + pSpec.setPathSet(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 } ); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); + } + + public static Pair getOwnerDatacenter(VmwareContext context, + ManagedObjectReference morEntity) throws Exception { + + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Datacenter"); + pSpec.setPathSet(new String[] { "name" }); + + TraversalSpec entityParentTraversal = new TraversalSpec(); + entityParentTraversal.setType("ManagedEntity"); + entityParentTraversal.setPath("parent"); + entityParentTraversal.setName("entityParentTraversal"); + entityParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "entityParentTraversal") }); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(morEntity); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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); + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreFile.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreFile.java index 018a2c2819f..295dfd4e104 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreFile.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreFile.java @@ -10,124 +10,124 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -public class DatastoreFile { - private String _path; - - public DatastoreFile(String path) { - assert(path != null); - _path = path; - } - - public DatastoreFile(String datastoreName, String pathWithoutDatastoreName) { - _path = String.format("[%s] %s", datastoreName, pathWithoutDatastoreName); - } - - public DatastoreFile(String datastoreName, String dir, String fileName) { - if(dir == null || dir.isEmpty()) - _path = String.format("[%s] %s", datastoreName, fileName); - else - _path = String.format("[%s] %s/%s", datastoreName, dir, fileName); - } - - public String getDatastoreName() { - return getDatastoreNameFromPath(_path); - } - - public String getPath() { - return _path; - } - - public String getRelativePath() { - int pos = _path.indexOf(']'); - if(pos < 0) - pos = 0; - else - pos++; - - return _path.substring(pos).trim(); - } - - public String getDir() { - int startPos = _path.indexOf("]"); - if(startPos < 0) - startPos = 0; - - int endPos = _path.lastIndexOf('/'); - if(endPos < 0) - endPos = 0; - - if(endPos > startPos) { - return _path.substring(startPos + 1, endPos).trim(); - } - - return ""; - } - - public String getFileName() { - int startPos = _path.indexOf("]"); - if(startPos < 0) - startPos = 0; - else - startPos++; - - int endPos = _path.lastIndexOf('/'); - if(endPos < 0) { - return _path.substring(startPos).trim(); - } else { - return _path.substring(endPos + 1); - } - } - - public String getFileBaseName() { - String name = getFileName(); - int endPos = name.lastIndexOf('.'); - if(endPos < 0) - return name; - return name.substring(0, endPos); - } - - public String getFileExtName() { - String name = getFileName(); - int endPos = name.lastIndexOf('.'); - if(endPos < 0) - return ""; - - return name.substring(endPos); - } - - public String getCompanionPath(String companionFileName) { - return getCompanionDatastorePath(_path, companionFileName); - } - - public static boolean isFullDatastorePath(String path) { - return path.matches("^\\[.*\\].*"); - } - - public static String getDatastoreNameFromPath(String path) { - if(isFullDatastorePath(path)) { - int endPos = path.indexOf("]"); - return path.substring(1, endPos).trim(); - } - return null; - } - - public static String getCompanionDatastorePath(String path, String companionFileName) { - if(isFullDatastorePath(path)) { - int endPos = path.indexOf("]"); - String dsName = path.substring(1, endPos); - String dsRelativePath = path.substring(endPos + 1).trim(); - - int fileNamePos = dsRelativePath.lastIndexOf('/'); - if(fileNamePos < 0) { - return String.format("[%s] %s", dsName, companionFileName); - } else { - return String.format("[%s] %s/%s", dsName, - dsRelativePath.substring(0, fileNamePos), - companionFileName); - } - } - return companionFileName; - } -} +package com.cloud.hypervisor.vmware.mo; + +public class DatastoreFile { + private String _path; + + public DatastoreFile(String path) { + assert(path != null); + _path = path; + } + + public DatastoreFile(String datastoreName, String pathWithoutDatastoreName) { + _path = String.format("[%s] %s", datastoreName, pathWithoutDatastoreName); + } + + public DatastoreFile(String datastoreName, String dir, String fileName) { + if(dir == null || dir.isEmpty()) + _path = String.format("[%s] %s", datastoreName, fileName); + else + _path = String.format("[%s] %s/%s", datastoreName, dir, fileName); + } + + public String getDatastoreName() { + return getDatastoreNameFromPath(_path); + } + + public String getPath() { + return _path; + } + + public String getRelativePath() { + int pos = _path.indexOf(']'); + if(pos < 0) + pos = 0; + else + pos++; + + return _path.substring(pos).trim(); + } + + public String getDir() { + int startPos = _path.indexOf("]"); + if(startPos < 0) + startPos = 0; + + int endPos = _path.lastIndexOf('/'); + if(endPos < 0) + endPos = 0; + + if(endPos > startPos) { + return _path.substring(startPos + 1, endPos).trim(); + } + + return ""; + } + + public String getFileName() { + int startPos = _path.indexOf("]"); + if(startPos < 0) + startPos = 0; + else + startPos++; + + int endPos = _path.lastIndexOf('/'); + if(endPos < 0) { + return _path.substring(startPos).trim(); + } else { + return _path.substring(endPos + 1); + } + } + + public String getFileBaseName() { + String name = getFileName(); + int endPos = name.lastIndexOf('.'); + if(endPos < 0) + return name; + return name.substring(0, endPos); + } + + public String getFileExtName() { + String name = getFileName(); + int endPos = name.lastIndexOf('.'); + if(endPos < 0) + return ""; + + return name.substring(endPos); + } + + public String getCompanionPath(String companionFileName) { + return getCompanionDatastorePath(_path, companionFileName); + } + + public static boolean isFullDatastorePath(String path) { + return path.matches("^\\[.*\\].*"); + } + + public static String getDatastoreNameFromPath(String path) { + if(isFullDatastorePath(path)) { + int endPos = path.indexOf("]"); + return path.substring(1, endPos).trim(); + } + return null; + } + + public static String getCompanionDatastorePath(String path, String companionFileName) { + if(isFullDatastorePath(path)) { + int endPos = path.indexOf("]"); + String dsName = path.substring(1, endPos); + String dsRelativePath = path.substring(endPos + 1).trim(); + + int fileNamePos = dsRelativePath.lastIndexOf('/'); + if(fileNamePos < 0) { + return String.format("[%s] %s", dsName, companionFileName); + } else { + return String.format("[%s] %s/%s", dsName, + dsRelativePath.substring(0, fileNamePos), + companionFileName); + } + } + return companionFileName; + } +} 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 cea137eb60c..b81fad16b4e 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java @@ -10,260 +10,260 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -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.cloud.utils.Pair; -import com.vmware.vim25.DatastoreSummary; +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.cloud.utils.Pair; +import com.vmware.vim25.DatastoreSummary; import com.vmware.vim25.FileInfo; import com.vmware.vim25.HostDatastoreBrowserSearchResults; -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.TraversalSpec; - -public class DatastoreMO extends BaseMO { - private static final Logger s_logger = Logger.getLogger(DatastoreMO.class); - - 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"); - - return _name; - } - - public DatastoreSummary getSummary() throws Exception { - return (DatastoreSummary)_context.getServiceUtil().getDynamicProperty(_mor, "summary"); +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.TraversalSpec; + +public class DatastoreMO extends BaseMO { + private static final Logger s_logger = Logger.getLogger(DatastoreMO.class); + + 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"); + + return _name; + } + + public DatastoreSummary getSummary() throws Exception { + return (DatastoreSummary)_context.getServiceUtil().getDynamicProperty(_mor, "summary"); } public HostDatastoreBrowserMO getHostDatastoreBrowserMO() throws Exception { return new HostDatastoreBrowserMO(_context, (ManagedObjectReference)_context.getServiceUtil().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" }); - - TraversalSpec folderParentTraversal = new TraversalSpec(); - folderParentTraversal.setType("Folder"); - folderParentTraversal.setPath("parent"); - folderParentTraversal.setName("folderParentTraversal"); - folderParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "folderParentTraversal") }); - - TraversalSpec dsParentTraversal = new TraversalSpec(); - dsParentTraversal.setType("Datastore"); - dsParentTraversal.setPath("parent"); - dsParentTraversal.setName("dsParentTraversal"); - dsParentTraversal.setSelectSet(new SelectionSpec[] { folderParentTraversal }); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(getMor()); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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); - 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)) - 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); - - try { - if(testExistence && !fileExists(fullPath)) - return true; - } catch(Exception e) { - 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")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware deleteDatastoreFile_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - return false; - } - - public boolean copyDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, - 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, - srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware copyDatastoreFile_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - return false; - } - - public boolean moveDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, - 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, - srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware moveDatgastoreFile_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - 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; - - if(parentFileName.startsWith("/")) { - // when parent file is not at the same directory as it is, assume it is at parent directory - // this is only valid in cloud.com primary storage deployment - DatastoreFile dsFile = new DatastoreFile(currentVmdkFullPath); - String dir = dsFile.getDir(); - if(dir != null && dir.lastIndexOf('/') > 0) - dir = dir.substring(0, dir.lastIndexOf('/')); - else - dir = ""; - - currentVmdkFullPath = new DatastoreFile(dsFile.getDatastoreName(), dir, - parentFileName.substring(parentFileName.lastIndexOf('/') + 1)).getPath(); - files.add(currentVmdkFullPath); - } else { - currentVmdkFullPath = DatastoreFile.getCompanionDatastorePath(currentVmdkFullPath, parentFileName); - files.add(currentVmdkFullPath); - } - } - - return files.toArray(new String[0]); - } + } + + 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" }); + + TraversalSpec folderParentTraversal = new TraversalSpec(); + folderParentTraversal.setType("Folder"); + folderParentTraversal.setPath("parent"); + folderParentTraversal.setName("folderParentTraversal"); + folderParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "folderParentTraversal") }); + + TraversalSpec dsParentTraversal = new TraversalSpec(); + dsParentTraversal.setType("Datastore"); + dsParentTraversal.setPath("parent"); + dsParentTraversal.setName("dsParentTraversal"); + dsParentTraversal.setSelectSet(new SelectionSpec[] { folderParentTraversal }); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(getMor()); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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); + 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)) + 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); + + try { + if(testExistence && !fileExists(fullPath)) + return true; + } catch(Exception e) { + 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")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware deleteDatastoreFile_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + return false; + } + + public boolean copyDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, + 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, + srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware copyDatastoreFile_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + return false; + } + + public boolean moveDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc, + 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, + srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware moveDatgastoreFile_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + 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; + + if(parentFileName.startsWith("/")) { + // when parent file is not at the same directory as it is, assume it is at parent directory + // this is only valid in cloud.com primary storage deployment + DatastoreFile dsFile = new DatastoreFile(currentVmdkFullPath); + String dir = dsFile.getDir(); + if(dir != null && dir.lastIndexOf('/') > 0) + dir = dir.substring(0, dir.lastIndexOf('/')); + else + dir = ""; + + currentVmdkFullPath = new DatastoreFile(dsFile.getDatastoreName(), dir, + parentFileName.substring(parentFileName.lastIndexOf('/') + 1)).getPath(); + files.add(currentVmdkFullPath); + } else { + currentVmdkFullPath = DatastoreFile.getCompanionDatastorePath(currentVmdkFullPath, parentFileName); + files.add(currentVmdkFullPath); + } + } + + return files.toArray(new String[0]); + } @Deprecated - public String[] listDirContent(String path) throws Exception { - 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); + public String[] listDirContent(String path) throws Exception { + 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(); @@ -279,19 +279,19 @@ public class DatastoreMO extends BaseMO { } 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; -*/ + +/* + 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 { @@ -309,4 +309,4 @@ public class DatastoreMO extends BaseMO { s_logger.info("Folder " + folderName + " does not exist on datastore"); return false; } -} +} 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 86f3f5a4aac..82903c314b6 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java @@ -10,172 +10,172 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.net.URI; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.CustomFieldStringValue; -import com.vmware.vim25.DatastoreInfo; -import com.vmware.vim25.DynamicProperty; -import com.vmware.vim25.HostNasVolumeSpec; -import com.vmware.vim25.ManagedObjectReference; -import com.vmware.vim25.NasDatastoreInfo; -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.TraversalSpec; - -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, - _context.getServiceContent().getCustomFieldsManager()); - int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID); - assert(key != 0); - - ObjectContent[] ocs = getDatastorePropertiesOnHostDatastoreSystem( - new String[] { "name", String.format("value[%d]", key) }); - if(ocs != null) { - for(ObjectContent oc : ocs) { - if(oc.getPropSet(0).getVal().equals(name)) - return oc.getObj(); - - if(oc.getPropSet().length > 1) { - DynamicProperty prop = oc.getPropSet(1); - if(prop != null && prop.getVal() != null) { - if(prop.getVal() instanceof CustomFieldStringValue) { - String val = ((CustomFieldStringValue)prop.getVal()).getValue(); - if(val.equalsIgnoreCase(name)) - return oc.getObj(); - } - } - } - } - } - 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) { - NasDatastoreInfo info = getNasDatastoreInfo(morDatastore); - if(info != null) { - URI uri = new URI(storeUrl); - String vmwareStyleUrl = "netfs://" + uri.getHost() + "/" + uri.getPath() + "/"; - if(info.getUrl().equals(vmwareStyleUrl)) - return morDatastore; - } - } - } - - return null; - } - - // TODO this is a hacking helper method, when we can pass down storage pool info along with volume - // 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)) - 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) { - _context.getService().removeDatastore(_mor, morDatastore); - return true; - } - return false; - } - - 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( - _mor, "datastore"); - } - - public DatastoreInfo getDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { - return (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); - } - - public NasDatastoreInfo getNasDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { - DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); - if(info instanceof NasDatastoreInfo) - return (NasDatastoreInfo)info; - return null; - } - - public ObjectContent[] getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception { - - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Datastore"); - pSpec.setPathSet(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 }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - return _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), - new PropertyFilterSpec[] { pfSpec }); - } -} +package com.cloud.hypervisor.vmware.mo; + +import java.net.URI; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.CustomFieldStringValue; +import com.vmware.vim25.DatastoreInfo; +import com.vmware.vim25.DynamicProperty; +import com.vmware.vim25.HostNasVolumeSpec; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.NasDatastoreInfo; +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.TraversalSpec; + +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, + _context.getServiceContent().getCustomFieldsManager()); + int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID); + assert(key != 0); + + ObjectContent[] ocs = getDatastorePropertiesOnHostDatastoreSystem( + new String[] { "name", String.format("value[%d]", key) }); + if(ocs != null) { + for(ObjectContent oc : ocs) { + if(oc.getPropSet(0).getVal().equals(name)) + return oc.getObj(); + + if(oc.getPropSet().length > 1) { + DynamicProperty prop = oc.getPropSet(1); + if(prop != null && prop.getVal() != null) { + if(prop.getVal() instanceof CustomFieldStringValue) { + String val = ((CustomFieldStringValue)prop.getVal()).getValue(); + if(val.equalsIgnoreCase(name)) + return oc.getObj(); + } + } + } + } + } + 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) { + NasDatastoreInfo info = getNasDatastoreInfo(morDatastore); + if(info != null) { + URI uri = new URI(storeUrl); + String vmwareStyleUrl = "netfs://" + uri.getHost() + "/" + uri.getPath() + "/"; + if(info.getUrl().equals(vmwareStyleUrl)) + return morDatastore; + } + } + } + + return null; + } + + // TODO this is a hacking helper method, when we can pass down storage pool info along with volume + // 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)) + 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) { + _context.getService().removeDatastore(_mor, morDatastore); + return true; + } + return false; + } + + 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( + _mor, "datastore"); + } + + public DatastoreInfo getDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { + return (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); + } + + public NasDatastoreInfo getNasDatastoreInfo(ManagedObjectReference morDatastore) throws Exception { + DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info"); + if(info instanceof NasDatastoreInfo) + return (NasDatastoreInfo)info; + return null; + } + + public ObjectContent[] getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception { + + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Datastore"); + pSpec.setPathSet(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 }); + + PropertyFilterSpec pfSpec = new PropertyFilterSpec(); + pfSpec.setPropSet(new PropertySpec[] { pSpec }); + pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); + + return _context.getService().retrieveProperties( + _context.getServiceContent().getPropertyCollector(), + new PropertyFilterSpec[] { pfSpec }); + } +} 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 c632a793bc5..c7a7dc4a60a 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java @@ -10,24 +10,24 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.vmware.util.VmwareContext; +package com.cloud.hypervisor.vmware.mo; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.vmware.util.VmwareContext; import com.vmware.vim25.HostFirewallDefaultPolicy; import com.vmware.vim25.HostFirewallInfo; -import com.vmware.vim25.ManagedObjectReference; - -public class HostFirewallSystemMO extends BaseMO { - private static final Logger s_logger = Logger.getLogger(HostFirewallSystemMO.class); - - public HostFirewallSystemMO(VmwareContext context, ManagedObjectReference morFirewallSystem) { - super(context, morFirewallSystem); - } - - public HostFirewallSystemMO(VmwareContext context, String morType, String morValue) { - super(context, morType, morValue); +import com.vmware.vim25.ManagedObjectReference; + +public class HostFirewallSystemMO extends BaseMO { + private static final Logger s_logger = Logger.getLogger(HostFirewallSystemMO.class); + + 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 { @@ -36,17 +36,17 @@ public class HostFirewallSystemMO extends BaseMO { 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); - } -} + } + + 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 470bc76dc5b..36221383bc3 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - +package com.cloud.hypervisor.vmware.mo; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -54,101 +54,101 @@ import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.TraversalSpec; import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualNicManagerNetConfig; - -public class HostMO extends BaseMO implements VmwareHypervisorHost { - private static final Logger s_logger = Logger.getLogger(HostMO.class); + +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"); - } - - public VirtualNicManagerNetConfig[] getHostVirtualNicManagerNetConfig() throws Exception { - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor, - "config.virtualNicManagerInfo.netConfig"); - return netConfigs; - } - - public HostIpRouteEntry[] getHostIpRouteEntries() throws Exception { - HostIpRouteEntry[] entries = (HostIpRouteEntry[])_context.getServiceUtil().getDynamicProperty(_mor, - "config.network.routeTableInfo.ipRoute"); - return entries; - } - - public HostListSummaryQuickStats getHostQuickStats() throws Exception { - return (HostListSummaryQuickStats)_context.getServiceUtil().getDynamicProperty(_mor, "summary.quickStats"); - } - - public HostHyperThreadScheduleInfo getHostHyperThreadInfo() throws Exception { - return (HostHyperThreadScheduleInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.hyperThread"); - } - - public HostNetworkInfo getHostNetworkInfo() throws Exception { - return (HostNetworkInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.network"); - } - + + 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"); + } + + public VirtualNicManagerNetConfig[] getHostVirtualNicManagerNetConfig() throws Exception { + VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor, + "config.virtualNicManagerInfo.netConfig"); + return netConfigs; + } + + public HostIpRouteEntry[] getHostIpRouteEntries() throws Exception { + HostIpRouteEntry[] entries = (HostIpRouteEntry[])_context.getServiceUtil().getDynamicProperty(_mor, + "config.network.routeTableInfo.ipRoute"); + return entries; + } + + public HostListSummaryQuickStats getHostQuickStats() throws Exception { + return (HostListSummaryQuickStats)_context.getServiceUtil().getDynamicProperty(_mor, "summary.quickStats"); + } + + public HostHyperThreadScheduleInfo getHostHyperThreadInfo() throws Exception { + return (HostHyperThreadScheduleInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.hyperThread"); + } + + public HostNetworkInfo getHostNetworkInfo() throws Exception { + return (HostNetworkInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.network"); + } + public HostPortGroupSpec getHostPortGroupSpec(String portGroupName) throws Exception { - - HostNetworkInfo hostNetInfo = getHostNetworkInfo(); - - HostPortGroup[] portGroups = hostNetInfo.getPortgroup(); - if(portGroups != null) { - for(HostPortGroup portGroup : portGroups) { - HostPortGroupSpec spec = portGroup.getSpec(); - if(spec.getName().equals(portGroupName)) - return spec; - } - } - - return null; - } - - @Override - public String getHyperHostName() throws Exception { - return getName(); - } - - @Override - public ClusterDasConfigInfo getDasConfig() throws Exception { - ManagedObjectReference morParent = getParentMor(); - if(morParent.getType().equals("ClusterComputeResource")) { - ClusterMO clusterMo = new ClusterMO(_context, morParent); - return clusterMo.getDasConfig(); - } - - return null; - } - - @Override - public String getHyperHostDefaultGateway() throws Exception { - HostIpRouteEntry[] entries = getHostIpRouteEntries(); - for(HostIpRouteEntry entry : entries) { - 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( - _mor, "configManager.datastoreSystem") - ); + + HostNetworkInfo hostNetInfo = getHostNetworkInfo(); + + HostPortGroup[] portGroups = hostNetInfo.getPortgroup(); + if(portGroups != null) { + for(HostPortGroup portGroup : portGroups) { + HostPortGroupSpec spec = portGroup.getSpec(); + if(spec.getName().equals(portGroupName)) + return spec; + } + } + + return null; + } + + @Override + public String getHyperHostName() throws Exception { + return getName(); + } + + @Override + public ClusterDasConfigInfo getDasConfig() throws Exception { + ManagedObjectReference morParent = getParentMor(); + if(morParent.getType().equals("ClusterComputeResource")) { + ClusterMO clusterMo = new ClusterMO(_context, morParent); + return clusterMo.getDasConfig(); + } + + return null; + } + + @Override + public String getHyperHostDefaultGateway() throws Exception { + HostIpRouteEntry[] entries = getHostIpRouteEntries(); + for(HostIpRouteEntry entry : entries) { + 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( + _mor, "configManager.datastoreSystem") + ); } public HostDatastoreBrowserMO getHostDatastoreBrowserMO() throws Exception { @@ -156,52 +156,52 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty( _mor, "datastoreBrowser") ); - } - - private DatastoreMO getHostDatastoreMO(String datastoreName) throws Exception { - ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { "name"} ); - if(ocs != null && ocs.length > 0) { - for(ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); - if(objProps != null) { - for(DynamicProperty objProp : objProps) { - if(objProp.getVal().toString().equals(datastoreName)) - return new DatastoreMO(_context, oc.getObj()); - } - } - } - } - 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()); - assert(dcPair != null); - return dcPair.first().getMor(); - } - - @Override - public ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception { - ServiceUtil serviceUtil = _context.getServiceUtil(); - ManagedObjectReference morComputerResource = (ManagedObjectReference)serviceUtil.getDynamicProperty(_mor, "parent"); - return (ManagedObjectReference)serviceUtil.getDynamicProperty(morComputerResource, "resourcePool"); - } + } + + private DatastoreMO getHostDatastoreMO(String datastoreName) throws Exception { + ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { "name"} ); + if(ocs != null && ocs.length > 0) { + for(ObjectContent oc : ocs) { + DynamicProperty[] objProps = oc.getPropSet(); + if(objProps != null) { + for(DynamicProperty objProp : objProps) { + if(objProp.getVal().toString().equals(datastoreName)) + return new DatastoreMO(_context, oc.getObj()); + } + } + } + } + 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()); + assert(dcPair != null); + return dcPair.first().getMor(); + } + + @Override + public ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception { + ServiceUtil serviceUtil = _context.getServiceUtil(); + ManagedObjectReference morComputerResource = (ManagedObjectReference)serviceUtil.getDynamicProperty(_mor, "parent"); + return (ManagedObjectReference)serviceUtil.getDynamicProperty(morComputerResource, "resourcePool"); + } @Override public ManagedObjectReference getHyperHostCluster() throws Exception { @@ -215,37 +215,37 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { assert(false); throw new Exception("Standalone host is not supported"); } - - public ManagedObjectReference[] getHostLocalDatastore() throws Exception { - ServiceUtil serviceUtil = _context.getServiceUtil(); - ManagedObjectReference[] datastores = (ManagedObjectReference[])serviceUtil.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()) - l.add(mor); - } - } - return l.toArray(new ManagedObjectReference[1]); - } - - public HostVirtualSwitch getHostVirtualSwitchByName(String name) throws Exception { - HostVirtualSwitch[] switches = (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty( - _mor, "config.network.vswitch"); - - if(switches != null) { - for(HostVirtualSwitch vswitch : switches) { - if(vswitch.getName().equals(name)) - return vswitch; - } - } - return null; - } - - public HostVirtualSwitch[] getHostVirtualSwitch() throws Exception { - return (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty(_mor, "config.network.vswitch"); + + public ManagedObjectReference[] getHostLocalDatastore() throws Exception { + ServiceUtil serviceUtil = _context.getServiceUtil(); + ManagedObjectReference[] datastores = (ManagedObjectReference[])serviceUtil.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()) + l.add(mor); + } + } + return l.toArray(new ManagedObjectReference[1]); + } + + public HostVirtualSwitch getHostVirtualSwitchByName(String name) throws Exception { + HostVirtualSwitch[] switches = (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty( + _mor, "config.network.vswitch"); + + if(switches != null) { + for(HostVirtualSwitch vswitch : switches) { + if(vswitch.getName().equals(name)) + return vswitch; + } + } + return null; + } + + public HostVirtualSwitch[] getHostVirtualSwitch() throws Exception { + return (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty(_mor, "config.network.vswitch"); } public AboutInfo getHostAboutInfo() throws Exception { @@ -262,13 +262,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { throw new Exception("Unrecognized VMware host type " + aboutInfo.getName()); } - // default virtual switch is which management network residents on - public HostVirtualSwitch getHostDefaultVirtualSwitch() throws Exception { + // 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; + return null; } public HostVirtualSwitch getPortGroupVirtualSwitch(String portGroupName) throws Exception { @@ -352,104 +352,104 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } 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, 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()); - HostNetworkPolicy policy = new HostNetworkPolicy(); - policy.setShapingPolicy(shapingPolicy); - spec.setPolicy(policy); - spec.setVswitchName(vSwitch.getName()); - hostNetMo.addPortGroup(spec); - } - - public void updatePortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, 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()); - HostNetworkPolicy policy = new HostNetworkPolicy(); - policy.setShapingPolicy(shapingPolicy); - spec.setPolicy(policy); - 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); - } - + } + + 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, 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()); + HostNetworkPolicy policy = new HostNetworkPolicy(); + policy.setShapingPolicy(shapingPolicy); + spec.setPolicy(policy); + spec.setVswitchName(vSwitch.getName()); + hostNetMo.addPortGroup(spec); + } + + public void updatePortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, 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()); + HostNetworkPolicy policy = new HostNetworkPolicy(); + policy.setShapingPolicy(shapingPolicy); + spec.setPolicy(policy); + 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); + } + public ManagedObjectReference getNetworkMor(String portGroupName) throws Exception { - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Network"); - pSpec.setPathSet(new String[] {"summary.name"}); - - TraversalSpec host2NetworkTraversal = new TraversalSpec(); - host2NetworkTraversal.setType("HostSystem"); - host2NetworkTraversal.setPath("network"); - host2NetworkTraversal.setName("host2NetworkTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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 }); - - if(ocs != null) { - for(ObjectContent oc : ocs) { - DynamicProperty[] props = oc.getPropSet(); - if(props != null) { - for(DynamicProperty prop : props) { - if(prop.getVal().equals(portGroupName)) - return oc.getObj(); - } - } - } - } - return null; - } - - public ManagedObjectReference[] getVmMorsOnNetwork(String portGroupName) throws Exception { - ManagedObjectReference morNetwork = getNetworkMor(portGroupName); - if(morNetwork != null) - return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(morNetwork, "vm"); - return null; - } - - public String getHostName() throws Exception { - return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); - } - + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Network"); + pSpec.setPathSet(new String[] {"summary.name"}); + + TraversalSpec host2NetworkTraversal = new TraversalSpec(); + host2NetworkTraversal.setType("HostSystem"); + host2NetworkTraversal.setPath("network"); + host2NetworkTraversal.setName("host2NetworkTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); + + if(ocs != null) { + for(ObjectContent oc : ocs) { + DynamicProperty[] props = oc.getPropSet(); + if(props != null) { + for(DynamicProperty prop : props) { + if(prop.getVal().equals(portGroupName)) + return oc.getObj(); + } + } + } + } + return null; + } + + public ManagedObjectReference[] getVmMorsOnNetwork(String portGroupName) throws Exception { + ManagedObjectReference morNetwork = getNetworkMor(portGroupName); + if(morNetwork != null) + return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(morNetwork, "vm"); + return null; + } + + public String getHostName() throws Exception { + return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name"); + } + @Override public synchronized VirtualMachineMO findVmOnHyperHost(String name) throws Exception { if(s_logger.isDebugEnabled()) @@ -484,412 +484,412 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { } } } - - @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); + + @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 // a cluster within vCenter assert(false); - return null; - } - } - - @Override - public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception { - assert(vmSpec != null); - DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); - ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); - - ManagedObjectReference morTask = _context.getService().createVM_Task( - dcMo.getVmFolder(), vmSpec, morPool, _mor); - String result = _context.getServiceUtil().waitForTask(morTask); - - if(result.equals("sucess")) { - _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(); - if(objProps != null) { - String name = null; - String value = null; - for(DynamicProperty objProp : objProps) { - if(objProp.getName().equals("name")) { - name = (String)objProp.getVal(); - } else { - OptionValue optValue = (OptionValue)objProp.getVal(); - value = (String)optValue.getValue(); - } - } - - if(name != null && value != null) { - portInfo.put(name, Integer.parseInt(value)); - } - } - } - } - - return portInfo; - } - + return null; + } + } + + @Override + public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception { + assert(vmSpec != null); + DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); + ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); + + ManagedObjectReference morTask = _context.getService().createVM_Task( + dcMo.getVmFolder(), vmSpec, morPool, _mor); + String result = _context.getServiceUtil().waitForTask(morTask); + + if(result.equals("sucess")) { + _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(); + if(objProps != null) { + String name = null; + String value = null; + for(DynamicProperty objProp : objProps) { + if(objProp.getName().equals("name")) { + name = (String)objProp.getVal(); + } 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 { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths)); - - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("VirtualMachine"); - pSpec.setPathSet(propertyPaths); - - TraversalSpec host2VmTraversal = new TraversalSpec(); - host2VmTraversal.setType("HostSystem"); - host2VmTraversal.setPath("vm"); - host2VmTraversal.setName("host2VmTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { host2VmTraversal }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("VirtualMachine"); + pSpec.setPathSet(propertyPaths); + + TraversalSpec host2VmTraversal = new TraversalSpec(); + host2VmTraversal.setType("HostSystem"); + host2VmTraversal.setPath("vm"); + host2VmTraversal.setName("host2VmTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; - } - - @Override - public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception { + return properties; + } + + @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)); - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Datastore"); - pSpec.setPathSet(propertyPaths); - - TraversalSpec host2DatastoreTraversal = new TraversalSpec(); - host2DatastoreTraversal.setType("HostSystem"); - host2DatastoreTraversal.setPath("datastore"); - host2DatastoreTraversal.setName("host2DatastoreTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { host2DatastoreTraversal }); - - PropertyFilterSpec pfSpec = new PropertyFilterSpec(); - pfSpec.setPropSet(new PropertySpec[] { pSpec }); - pfSpec.setObjectSet(new ObjectSpec[] { oSpec }); - - ObjectContent[] properties = _context.getService().retrieveProperties( - _context.getServiceContent().getPropertyCollector(), + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Datastore"); + pSpec.setPathSet(propertyPaths); + + TraversalSpec host2DatastoreTraversal = new TraversalSpec(); + host2DatastoreTraversal.setType("HostSystem"); + host2DatastoreTraversal.setPath("datastore"); + host2DatastoreTraversal.setName("host2DatastoreTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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 }); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - retrieveProperties() done"); - return properties; - } - - public List> getDatastoreMountsOnHost() throws Exception { - List> mounts = new ArrayList>(); - - ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { - String.format("host[\"%s\"].mountInfo.path", _mor.get_value()) }); - if(ocs != null) { - for(ObjectContent oc : ocs) { - Pair mount = new Pair( - oc.getObj(), oc.getPropSet(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")) { - 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 { + return properties; + } + + public List> getDatastoreMountsOnHost() throws Exception { + List> mounts = new ArrayList>(); + + ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { + String.format("host[\"%s\"].mountInfo.path", _mor.get_value()) }); + if(ocs != null) { + for(ObjectContent oc : ocs) { + Pair mount = new Pair( + oc.getObj(), oc.getPropSet(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")) { + 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 + ",datastoreName: " + datastoreName + ", diskOption: " + diskOption); - DatastoreMO dsMo = getHostDatastoreMO(datastoreName); - if(dsMo == null) - throw new Exception("Invalid datastore name: " + datastoreName); - + 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 { + } + + @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 { + 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); - - boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse, + + 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, + return result; + } + + @Override + 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 + ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid); - - HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); - ManagedObjectReference morDatastore = hostDatastoreSystemMo.findDatastore(poolUuid); - if(morDatastore == null) { - if(!vmfsDatastore) { - morDatastore = hostDatastoreSystemMo.createNfsDatastore( - poolHostAddress, - poolHostPort, - poolPath, - poolUuid); - if(morDatastore == null) { - String msg = "Unable to create NFS datastore. host: " + poolHostAddress + ", port: " - + poolHostPort + ", path: " + poolPath + ", uuid: " + poolUuid; + + HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); + ManagedObjectReference morDatastore = hostDatastoreSystemMo.findDatastore(poolUuid); + if(morDatastore == null) { + if(!vmfsDatastore) { + morDatastore = hostDatastoreSystemMo.createNfsDatastore( + poolHostAddress, + poolHostPort, + poolPath, + poolUuid); + if(morDatastore == null) { + 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); - } - } else { - morDatastore = _context.getDatastoreMorByPath(poolPath); - if(morDatastore == null) { - String msg = "Unable to create VMFS datastore. host: " + poolHostAddress + ", port: " - + poolHostPort + ", path: " + poolPath + ", uuid: " + poolUuid; + throw new Exception(msg); + } + } else { + morDatastore = _context.getDatastoreMorByPath(poolPath); + if(morDatastore == null) { + 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); - } + 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 + + 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); - - HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); - if(!hostDatastoreSystemMo.deleteDatastore(poolUuid)) { - String msg = "Unable to unmount datastore. uuid: " + poolUuid; + + HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO(); + if(!hostDatastoreSystemMo.deleteDatastore(poolUuid)) { + String msg = "Unable to unmount datastore. uuid: " + poolUuid; s_logger.error(msg); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - unmountDatastore() done(failed)"); - throw new Exception(msg); + 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 + } + + @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()); - - VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); - - HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor); - HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware(); - - // TODO: not sure how hyper-thread is counted in VMware resource pool - summary.setCpuCount(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); - summary.setMemoryBytes(hardwareSummary.getMemorySize()); - summary.setCpuSpeed(hardwareSummary.getCpuMhz()); + + VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); + + HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor); + HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware(); + + // TODO: not sure how hyper-thread is counted in VMware resource pool + summary.setCpuCount(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); + summary.setMemoryBytes(hardwareSummary.getMemorySize()); + summary.setCpuSpeed(hardwareSummary.getCpuMhz()); if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done"); - return summary; - } - - @Override - public VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String managementPortGroup) throws Exception { + 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); - - VmwareHypervisorHostNetworkSummary summary = new VmwareHypervisorHostNetworkSummary(); - - if(this.getHostType() == VmwareHostType.ESXi) { - VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor, - "config.virtualNicManagerInfo.netConfig"); - assert(netConfigs != null); - - for(int i = 0; i < netConfigs.length; i++) { + + VmwareHypervisorHostNetworkSummary summary = new VmwareHypervisorHostNetworkSummary(); + + if(this.getHostType() == VmwareHostType.ESXi) { + VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().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()) { - if(nic.getPortgroup().equals(managementPortGroup)) { - summary.setHostIp(nic.getSpec().getIp().getIpAddress()); - summary.setHostNetmask(nic.getSpec().getIp().getSubnetMask()); + if(nic.getPortgroup().equals(managementPortGroup)) { + 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; + return summary; } - } - } + } + } } - } else { - // try with ESX path - HostVirtualNic[] hostVNics = (HostVirtualNic[])_context.getServiceUtil().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()); + } else { + // try with ESX path + HostVirtualNic[] hostVNics = (HostVirtualNic[])_context.getServiceUtil().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; - } - } - } - } + return summary; + } + } + } + } if(s_logger.isTraceEnabled()) 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 { + 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()); - - // - // 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, - // 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 - short totalCores = (short)(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); - resourceSummary.setNumCpuCores(totalCores); - - // Note: memory here is in Byte unit - resourceSummary.setTotalMemory(hardwareSummary.getMemorySize()); - - // Total CPU is based on socket x core x Mhz - int totalCpu = hardwareSummary.getCpuMhz() * totalCores; - resourceSummary.setTotalCpu(totalCpu); - + + // + // 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, + // 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 + short totalCores = (short)(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); + resourceSummary.setNumCpuCores(totalCores); + + // Note: memory here is in Byte unit + resourceSummary.setTotalMemory(hardwareSummary.getMemorySize()); + + // Total CPU is based on socket x core x Mhz + int totalCpu = hardwareSummary.getCpuMhz() * totalCores; + resourceSummary.setTotalCpu(totalCpu); + 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.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; - } -} + return resourceSummary; + } + + @Override + public boolean isHyperHostConnected() throws Exception { + HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)_context.getServiceUtil().getDynamicProperty(_mor, "runtime"); + return runtimeInfo.getConnectionState() == HostSystemConnectionState.connected; + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java index 95439d02676..e80ba09d1c1 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostNetworkSystemMO.java @@ -10,52 +10,52 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.HostPortGroupSpec; -import com.vmware.vim25.HostVirtualSwitchSpec; -import com.vmware.vim25.ManagedObjectReference; - -public class HostNetworkSystemMO extends BaseMO { - private static final Logger s_logger = Logger.getLogger(HostNetworkSystemMO.class); - - public HostNetworkSystemMO(VmwareContext context, ManagedObjectReference morNetworkSystem) { - super(context, morNetworkSystem); - } - - public HostNetworkSystemMO(VmwareContext context, String morType, String morValue) { - super(context, morType, morValue); - } - - public void addPortGroup(HostPortGroupSpec spec) throws Exception { - _context.getService().addPortGroup(_mor, spec); - } - - public void updatePortGroup(String portGroupName, HostPortGroupSpec spec) throws Exception { - _context.getService().updatePortGroup(_mor, portGroupName, spec); - } - - public void removePortGroup(String portGroupName) throws Exception { - _context.getService().removePortGroup(_mor, portGroupName); - } - - public void addVirtualSwitch(String vSwitchName, HostVirtualSwitchSpec spec) throws Exception { - _context.getService().addVirtualSwitch(_mor, vSwitchName, spec); - } - - public void updateVirtualSwitch(String vSwitchName, HostVirtualSwitchSpec spec) throws Exception { - _context.getService().updateVirtualSwitch(_mor, vSwitchName, spec); - } - - public void removeVirtualSwitch(String vSwitchName) throws Exception { - _context.getService().removeVirtualSwitch(_mor, vSwitchName); - } - - public void refresh() throws Exception { - _context.getService().refreshNetworkSystem(_mor); - } -} - +package com.cloud.hypervisor.vmware.mo; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.HostPortGroupSpec; +import com.vmware.vim25.HostVirtualSwitchSpec; +import com.vmware.vim25.ManagedObjectReference; + +public class HostNetworkSystemMO extends BaseMO { + private static final Logger s_logger = Logger.getLogger(HostNetworkSystemMO.class); + + public HostNetworkSystemMO(VmwareContext context, ManagedObjectReference morNetworkSystem) { + super(context, morNetworkSystem); + } + + public HostNetworkSystemMO(VmwareContext context, String morType, String morValue) { + super(context, morType, morValue); + } + + public void addPortGroup(HostPortGroupSpec spec) throws Exception { + _context.getService().addPortGroup(_mor, spec); + } + + public void updatePortGroup(String portGroupName, HostPortGroupSpec spec) throws Exception { + _context.getService().updatePortGroup(_mor, portGroupName, spec); + } + + public void removePortGroup(String portGroupName) throws Exception { + _context.getService().removePortGroup(_mor, portGroupName); + } + + public void addVirtualSwitch(String vSwitchName, HostVirtualSwitchSpec spec) throws Exception { + _context.getService().addVirtualSwitch(_mor, vSwitchName, spec); + } + + public void updateVirtualSwitch(String vSwitchName, HostVirtualSwitchSpec spec) throws Exception { + _context.getService().updateVirtualSwitch(_mor, vSwitchName, spec); + } + + public void removeVirtualSwitch(String vSwitchName) throws Exception { + _context.getService().removeVirtualSwitch(_mor, vSwitchName); + } + + public void refresh() throws Exception { + _context.getService().refreshNetworkSystem(_mor); + } +} + 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 f2ca8eadd0a..5e6aacd97d8 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java @@ -10,144 +10,144 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; - -import org.apache.log4j.Logger; - -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.OvfCreateImportSpecResult; -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"); - } - - 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) - return state; - } - } - - public HttpNfcLeaseInfo getLeaseInfo() throws Exception { - return (HttpNfcLeaseInfo)_context.getServiceUtil().getDynamicProperty(_mor, "info"); - } - - public HttpNfcLeaseManifestEntry[] 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 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) { - try { - Thread.sleep(1000); // update progess every 1 second - updateLeaseProgress(_percent); - } catch(InterruptedException e) { - if(s_logger.isInfoEnabled()) - s_logger.info("ProgressReporter is interrupted, quiting"); - break; - } catch(Exception e) { - s_logger.warn("Unexpected exception ", e); - } - } - - if(s_logger.isInfoEnabled()) - s_logger.info("ProgressReporter stopped"); - } - } -} +package com.cloud.hypervisor.vmware.mo; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; + +import org.apache.log4j.Logger; + +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.OvfCreateImportSpecResult; +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"); + } + + 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) + return state; + } + } + + public HttpNfcLeaseInfo getLeaseInfo() throws Exception { + return (HttpNfcLeaseInfo)_context.getServiceUtil().getDynamicProperty(_mor, "info"); + } + + public HttpNfcLeaseManifestEntry[] 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 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) { + try { + Thread.sleep(1000); // update progess every 1 second + updateLeaseProgress(_percent); + } catch(InterruptedException e) { + if(s_logger.isInfoEnabled()) + s_logger.info("ProgressReporter is interrupted, quiting"); + break; + } catch(Exception e) { + 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 44c0dc49d18..b7a41a4cc86 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - +package com.cloud.hypervisor.vmware.mo; + import java.io.File; import java.net.URI; import java.net.URISyntaxException; @@ -43,42 +43,42 @@ import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualMachineFileInfo; import com.vmware.vim25.VirtualMachineVideoCard; import com.vmware.vim25.VirtualSCSISharing; - -public class HypervisorHostHelper { - private static final Logger s_logger = Logger.getLogger(HypervisorHostHelper.class); - private static final int DEFAULT_LOCK_TIMEOUT_SECONDS = 600; - - // 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, - ObjectContent[] ocs, String name) { - - if(ocs != null && ocs.length > 0) { - for(ObjectContent oc : ocs) { - DynamicProperty prop = oc.getPropSet(0); - assert(prop != null); - if(prop.getVal().toString().equals(name)) - return new VirtualMachineMO(context, oc.getObj()); - } - } - return null; - } - - 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(); - if(objProps != null) { - for(DynamicProperty objProp : objProps) { - if(objProp.getVal().toString().equals(datastoreName)) - return new DatastoreMO(hyperHost.getContext(), oc.getObj()); - } - } - } - } - return null; + +public class HypervisorHostHelper { + private static final Logger s_logger = Logger.getLogger(HypervisorHostHelper.class); + private static final int DEFAULT_LOCK_TIMEOUT_SECONDS = 600; + + // 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, + ObjectContent[] ocs, String name) { + + if(ocs != null && ocs.length > 0) { + for(ObjectContent oc : ocs) { + DynamicProperty prop = oc.getPropSet(0); + assert(prop != null); + if(prop.getVal().toString().equals(name)) + return new VirtualMachineMO(context, oc.getObj()); + } + } + return null; + } + + 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(); + if(objProps != null) { + for(DynamicProperty objProp : objProps) { + if(objProp.getVal().toString().equals(datastoreName)) + return new DatastoreMO(hyperHost.getContext(), oc.getObj()); + } + } + } + } + return null; } public static String getPublicNetworkNamePrefix(String vlanId) { @@ -88,7 +88,7 @@ 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)) @@ -104,7 +104,7 @@ public class HypervisorHostHelper { sb.append("-").append(vSwitchName); return sb.toString(); - } + } public static Pair prepareNetwork(String vSwitchName, String namePrefix, HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, @@ -250,222 +250,222 @@ public class HypervisorHostHelper { return true; } - - public static ManagedObjectReference waitForNetworkReady(HostMO hostMo, - String networkName, long timeOutMs) throws Exception { - - ManagedObjectReference morNetwork = null; - - // if portGroup is just created, getNetwork may fail to retrieve it, we - // need to retry - long startTick = System.currentTimeMillis(); - while (System.currentTimeMillis() - startTick <= timeOutMs) { - morNetwork = hostMo.getNetworkMor(networkName); - if (morNetwork != null) { - break; - } - - s_logger.info("Waiting for network " + networkName + " to be ready"); - Thread.sleep(1000); - } - - return morNetwork; - } - - 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); - VmwareHelper.setBasicVmConfig(vmConfig, cpuCount, cpuSpeedMHz, cpuReservedMHz, memoryMB, memoryReserveMB, guestOsIdentifier, limitCpuUse); - - // Scsi controller - VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); - scsiController.setSharedBus(VirtualSCSISharing.noSharing); - scsiController.setBusNumber(0); - scsiController.setKey(1); - VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); - scsiControllerSpec.setDevice(scsiController); - 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 }); - 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); - } catch (URISyntaxException e) { - 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) { + + public static ManagedObjectReference waitForNetworkReady(HostMO hostMo, + String networkName, long timeOutMs) throws Exception { + + ManagedObjectReference morNetwork = null; + + // if portGroup is just created, getNetwork may fail to retrieve it, we + // need to retry + long startTick = System.currentTimeMillis(); + while (System.currentTimeMillis() - startTick <= timeOutMs) { + morNetwork = hostMo.getNetworkMor(networkName); + if (morNetwork != null) { + break; + } + + s_logger.info("Waiting for network " + networkName + " to be ready"); + Thread.sleep(1000); + } + + return morNetwork; + } + + 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); + VmwareHelper.setBasicVmConfig(vmConfig, cpuCount, cpuSpeedMHz, cpuReservedMHz, memoryMB, memoryReserveMB, guestOsIdentifier, limitCpuUse); + + // Scsi controller + VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); + scsiController.setSharedBus(VirtualSCSISharing.noSharing); + scsiController.setBusNumber(0); + scsiController.setKey(1); + VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); + scsiControllerSpec.setDevice(scsiController); + 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 }); + 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); + } catch (URISyntaxException e) { + 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) { HostMO hostMo = new HostMO(dcMo.getContext(), morHost); String managementPortGroupName; if(hostMo.getHostType() == VmwareHostType.ESXi) 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) { - assert(false); - return url; - } - } - } 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, - ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception { - - assert(morRp != null); - - 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); - - String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath); - VmwareContext context = host.getContext(); - OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec( - context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, - dsMo.getMor(), importSpecParams); - - if(ovfImportResult == null) { - 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, - ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost); - if(morLease == null) { - 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 }); - try { - if(state == HttpNfcLeaseState.ready) { - final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult); - File ovfFile = new File(ovfFilePath); - - HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo(); - HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl(); - long bytesAlreadyWritten = 0; - - final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter(); - try { - for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) { - String deviceKey = deviceUrl.getImportKey(); - for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) { - 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, - bytesAlreadyWritten, new ActionDelegate () { - public void action(Long param) { - progressReporter.reportProgress((int)(param * 100 / totalBytes)); - } - }); - - bytesAlreadyWritten += ovfFileItem.getSize(); - } - } - } - } finally { - progressReporter.close(); - } - leaseMo.updateLeaseProgress(100); - } - } finally { - leaseMo.completeLease(); - } - } -} + + 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) { + assert(false); + return url; + } + } + } 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, + ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception { + + assert(morRp != null); + + 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); + + String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath); + VmwareContext context = host.getContext(); + OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec( + context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, + dsMo.getMor(), importSpecParams); + + if(ovfImportResult == null) { + 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, + ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost); + if(morLease == null) { + 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 }); + try { + if(state == HttpNfcLeaseState.ready) { + final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult); + File ovfFile = new File(ovfFilePath); + + HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo(); + HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl(); + long bytesAlreadyWritten = 0; + + final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter(); + try { + for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) { + String deviceKey = deviceUrl.getImportKey(); + for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) { + 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, + bytesAlreadyWritten, new ActionDelegate () { + public void action(Long param) { + progressReporter.reportProgress((int)(param * 100 / totalBytes)); + } + }); + + bytesAlreadyWritten += ovfFileItem.getSize(); + } + } + } + } finally { + progressReporter.close(); + } + leaseMo.updateLeaseProgress(100); + } + } finally { + leaseMo.completeLease(); + } + } +} 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 639a5179ec0..f31560172d2 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java @@ -10,26 +10,26 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.ManagedObjectReference; - -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); - } - - public ManagedObjectReference[] getVMsOnNetwork() throws Exception { - ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "vm"); - return vms; - } -} +package com.cloud.hypervisor.vmware.mo; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.ManagedObjectReference; + +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); + } + + public ManagedObjectReference[] getVMsOnNetwork() throws Exception { + ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "vm"); + return vms; + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfCounterInfoMapper.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfCounterInfoMapper.java index 2289562689f..1eb48027392 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfCounterInfoMapper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfCounterInfoMapper.java @@ -10,81 +10,81 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.vmware.vim25.PerfCounterInfo; -import com.vmware.vim25.PerfSummaryType; - -public class PerfCounterInfoMapper { - // map - Map>> _mapCounterInfos = - new HashMap>>(); - - public PerfCounterInfoMapper(PerfCounterInfo[] counterInfos) { - if(counterInfos != null) { - for(PerfCounterInfo counterInfo : counterInfos) { - List counterInfoList = getSafeCounterInfoList( - counterInfo.getGroupInfo().getKey(), counterInfo.getNameInfo().getKey()); - counterInfoList.add(counterInfo); - } - } - } - - public PerfCounterInfo[] lookup(String groupName, String counterName, PerfSummaryType rollupType) { - assert(groupName != null); - assert(counterName != null); - - Map> groupMap = _mapCounterInfos.get(groupName); - if(groupMap == null) - return null; - - List counterInfoList = groupMap.get(counterName); - if(counterInfoList == null) - return null; - - if(rollupType == null) { - return counterInfoList.toArray(new PerfCounterInfo[0]); - } - - for(PerfCounterInfo info : counterInfoList) { - if(info.getRollupType() == rollupType) - return new PerfCounterInfo[] { info }; - } - - return null; - } - - public PerfCounterInfo lookupOne(String groupName, String counterName, PerfSummaryType rollupType) { - PerfCounterInfo[] infos = lookup(groupName, counterName, rollupType); - if(infos != null && infos.length > 0) - return infos[0]; - - return null; - } - - private Map> getSafeGroupMap(String groupName) { - Map> groupMap = _mapCounterInfos.get(groupName); - if(groupMap == null) { - groupMap = new HashMap>(); - _mapCounterInfos.put(groupName, groupMap); - } - return groupMap; - } - - private List getSafeCounterInfoList(String groupName, String counterName) { - Map> groupMap = getSafeGroupMap(groupName); - assert(groupMap != null); - - List counterInfoList = groupMap.get(counterName); - if(counterInfoList == null) { - counterInfoList = new ArrayList(); - groupMap.put(counterName, counterInfoList); - } - return counterInfoList; - } -} +package com.cloud.hypervisor.vmware.mo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.vmware.vim25.PerfCounterInfo; +import com.vmware.vim25.PerfSummaryType; + +public class PerfCounterInfoMapper { + // map + Map>> _mapCounterInfos = + new HashMap>>(); + + public PerfCounterInfoMapper(PerfCounterInfo[] counterInfos) { + if(counterInfos != null) { + for(PerfCounterInfo counterInfo : counterInfos) { + List counterInfoList = getSafeCounterInfoList( + counterInfo.getGroupInfo().getKey(), counterInfo.getNameInfo().getKey()); + counterInfoList.add(counterInfo); + } + } + } + + public PerfCounterInfo[] lookup(String groupName, String counterName, PerfSummaryType rollupType) { + assert(groupName != null); + assert(counterName != null); + + Map> groupMap = _mapCounterInfos.get(groupName); + if(groupMap == null) + return null; + + List counterInfoList = groupMap.get(counterName); + if(counterInfoList == null) + return null; + + if(rollupType == null) { + return counterInfoList.toArray(new PerfCounterInfo[0]); + } + + for(PerfCounterInfo info : counterInfoList) { + if(info.getRollupType() == rollupType) + return new PerfCounterInfo[] { info }; + } + + return null; + } + + public PerfCounterInfo lookupOne(String groupName, String counterName, PerfSummaryType rollupType) { + PerfCounterInfo[] infos = lookup(groupName, counterName, rollupType); + if(infos != null && infos.length > 0) + return infos[0]; + + return null; + } + + private Map> getSafeGroupMap(String groupName) { + Map> groupMap = _mapCounterInfos.get(groupName); + if(groupMap == null) { + groupMap = new HashMap>(); + _mapCounterInfos.put(groupName, groupMap); + } + return groupMap; + } + + private List getSafeCounterInfoList(String groupName, String counterName) { + Map> groupMap = getSafeGroupMap(groupName); + assert(groupMap != null); + + List counterInfoList = groupMap.get(counterName); + if(counterInfoList == null) { + counterInfoList = new ArrayList(); + groupMap.put(counterName, counterInfoList); + } + return counterInfoList; + } +} 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 92009590459..990ab79dbb0 100644 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java @@ -10,72 +10,72 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.util.Calendar; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.ManagedObjectReference; -import com.vmware.vim25.PerfCompositeMetric; -import com.vmware.vim25.PerfCounterInfo; -import com.vmware.vim25.PerfEntityMetricBase; -import com.vmware.vim25.PerfInterval; -import com.vmware.vim25.PerfMetricId; -import com.vmware.vim25.PerfProviderSummary; -import com.vmware.vim25.PerfQuerySpec; - -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, - Calendar endTime, Integer intervalId) throws Exception { - - return _context.getService().queryAvailablePerfMetric(_mor, morEntity, beginTime, 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 PerfEntityMetricBase[] queryPerf(PerfQuerySpec[] specs) throws Exception { - return _context.getService().queryPerf(_mor, 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"); - } - - public PerfInterval[] getIntervalInfo() throws Exception { - return (PerfInterval[])_context.getServiceUtil().getDynamicProperty(_mor, "historicalInterval"); - } -} +package com.cloud.hypervisor.vmware.mo; + +import java.util.Calendar; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.PerfCompositeMetric; +import com.vmware.vim25.PerfCounterInfo; +import com.vmware.vim25.PerfEntityMetricBase; +import com.vmware.vim25.PerfInterval; +import com.vmware.vim25.PerfMetricId; +import com.vmware.vim25.PerfProviderSummary; +import com.vmware.vim25.PerfQuerySpec; + +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, + Calendar endTime, Integer intervalId) throws Exception { + + return _context.getService().queryAvailablePerfMetric(_mor, morEntity, beginTime, 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 PerfEntityMetricBase[] queryPerf(PerfQuerySpec[] specs) throws Exception { + return _context.getService().queryPerf(_mor, 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"); + } + + public PerfInterval[] getIntervalInfo() throws Exception { + return (PerfInterval[])_context.getServiceUtil().getDynamicProperty(_mor, "historicalInterval"); + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/SnapshotDescriptor.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/SnapshotDescriptor.java index bfebc4a2dce..ff5c1c26efa 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/SnapshotDescriptor.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/SnapshotDescriptor.java @@ -10,261 +10,261 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.ArrayList; -import java.util.Properties; - -import org.apache.log4j.Logger; - -public class SnapshotDescriptor { - private static final Logger s_logger = Logger.getLogger(SnapshotDescriptor.class); - - private Properties _properties = new Properties(); - - public SnapshotDescriptor() { - } - - public void parse(byte[] vmsdFileContent) throws IOException { - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmsdFileContent))); - String line; - while((line = in.readLine()) != null) { - // TODO, remember to remove this log, temporarily added for debugging purpose - s_logger.info("Parse snapshot file content: " + line); - - String[] tokens = line.split("="); - if(tokens.length == 2) { - String name = tokens[0].trim(); - String value = tokens[1].trim(); - if(value.charAt(0) == '\"') - value = value.substring(1, value.length() -1); - - _properties.put(name, value); - } - } - } finally { - if(in != null) - in.close(); - } - } - - public void removeDiskReferenceFromSnapshot(String diskFileName) { - String numSnapshotsStr = _properties.getProperty("snapshot.numSnapshots"); - if(numSnapshotsStr != null) { - int numSnaphosts = Integer.parseInt(numSnapshotsStr); - for(int i = 0; i < numSnaphosts; i++) { - String numDisksStr = _properties.getProperty(String.format("snapshot%d.numDisks", i)); - int numDisks = Integer.parseInt(numDisksStr); - - boolean diskFound = false; - for(int j = 0; j < numDisks; j++) { - String keyName = String.format("snapshot%d.disk%d.fileName", i, j); - String fileName = _properties.getProperty(keyName); - if(!diskFound) { - if(fileName.equalsIgnoreCase(diskFileName)) { - diskFound = true; - _properties.remove(keyName); - } - } else { - _properties.setProperty(String.format("snapshot%d.disk%d.fileName", i, j - 1), fileName); - } - } - - if(diskFound) - _properties.setProperty(String.format("snapshot%d.numDisks", i), String.valueOf(numDisks-1)); - } - } - } - - public byte[] getVmsdContent() { - BufferedWriter out = null; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - try { - out = new BufferedWriter(new OutputStreamWriter(bos, "UTF-8")); - - out.write(".encoding = \"UTF-8\""); out.newLine(); - out.write(String.format("snapshot.lastUID = \"%s\"", _properties.getProperty("snapshot.lastUID"))); out.newLine(); - String numSnapshotsStr = _properties.getProperty("snapshot.numSnapshots"); - if(numSnapshotsStr == null || numSnapshotsStr.isEmpty()) - numSnapshotsStr = "0"; - out.write(String.format("snapshot.numSnapshots = \"%s\"", numSnapshotsStr)); out.newLine(); - - String value = _properties.getProperty("snapshot.current"); - if(value != null) { - out.write(String.format("snapshot.current = \"%s\"", value)); - out.newLine(); - } - - String key; - for(int i = 0; i < Integer.parseInt(numSnapshotsStr); i++) { - key = String.format("snapshot%d.uid", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.filename", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.displayName", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.description", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.createTimeHigh", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.createTimeLow", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.numDisks", i); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - int numDisks = Integer.parseInt(value); - for(int j = 0; j < numDisks; j++) { - key = String.format("snapshot%d.disk%d.fileName", i, j); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - - key = String.format("snapshot%d.disk%d.node", i, j); - value = _properties.getProperty(key); - out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); - } - } - } catch(IOException e) { - assert(false); - s_logger.error("Unexpected exception ", e); - } finally { - if(out != null) { - try { - out.close(); - } catch (IOException e) { - } - } - } - - return bos.toByteArray(); - } - - private int getSnapshotId(String seqStr) { - if(seqStr != null) { - int seq = Integer.parseInt(seqStr); - String numSnapshotStr = _properties.getProperty("snapshot.numSnapshots"); - assert(numSnapshotStr != null); - for(int i = 0; i < Integer.parseInt(numSnapshotStr); i++) { - String value = _properties.getProperty(String.format("snapshot%d.uid", i)); - if(value != null && Integer.parseInt(value) == seq) - return i; - } - } - - return 0; - } - - public SnapshotInfo[] getCurrentDiskChain() { - ArrayList l = new ArrayList(); - String current = _properties.getProperty("snapshot.current"); - int id; - while(current != null) { - id = getSnapshotId(current); - String numDisksStr = _properties.getProperty(String.format("snapshot%d.numDisks", id)); +package com.cloud.hypervisor.vmware.mo; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.util.ArrayList; +import java.util.Properties; + +import org.apache.log4j.Logger; + +public class SnapshotDescriptor { + private static final Logger s_logger = Logger.getLogger(SnapshotDescriptor.class); + + private Properties _properties = new Properties(); + + public SnapshotDescriptor() { + } + + public void parse(byte[] vmsdFileContent) throws IOException { + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmsdFileContent))); + String line; + while((line = in.readLine()) != null) { + // TODO, remember to remove this log, temporarily added for debugging purpose + s_logger.info("Parse snapshot file content: " + line); + + String[] tokens = line.split("="); + if(tokens.length == 2) { + String name = tokens[0].trim(); + String value = tokens[1].trim(); + if(value.charAt(0) == '\"') + value = value.substring(1, value.length() -1); + + _properties.put(name, value); + } + } + } finally { + if(in != null) + in.close(); + } + } + + public void removeDiskReferenceFromSnapshot(String diskFileName) { + String numSnapshotsStr = _properties.getProperty("snapshot.numSnapshots"); + if(numSnapshotsStr != null) { + int numSnaphosts = Integer.parseInt(numSnapshotsStr); + for(int i = 0; i < numSnaphosts; i++) { + String numDisksStr = _properties.getProperty(String.format("snapshot%d.numDisks", i)); + int numDisks = Integer.parseInt(numDisksStr); + + boolean diskFound = false; + for(int j = 0; j < numDisks; j++) { + String keyName = String.format("snapshot%d.disk%d.fileName", i, j); + String fileName = _properties.getProperty(keyName); + if(!diskFound) { + if(fileName.equalsIgnoreCase(diskFileName)) { + diskFound = true; + _properties.remove(keyName); + } + } else { + _properties.setProperty(String.format("snapshot%d.disk%d.fileName", i, j - 1), fileName); + } + } + + if(diskFound) + _properties.setProperty(String.format("snapshot%d.numDisks", i), String.valueOf(numDisks-1)); + } + } + } + + public byte[] getVmsdContent() { + BufferedWriter out = null; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + try { + out = new BufferedWriter(new OutputStreamWriter(bos, "UTF-8")); + + out.write(".encoding = \"UTF-8\""); out.newLine(); + out.write(String.format("snapshot.lastUID = \"%s\"", _properties.getProperty("snapshot.lastUID"))); out.newLine(); + String numSnapshotsStr = _properties.getProperty("snapshot.numSnapshots"); + if(numSnapshotsStr == null || numSnapshotsStr.isEmpty()) + numSnapshotsStr = "0"; + out.write(String.format("snapshot.numSnapshots = \"%s\"", numSnapshotsStr)); out.newLine(); + + String value = _properties.getProperty("snapshot.current"); + if(value != null) { + out.write(String.format("snapshot.current = \"%s\"", value)); + out.newLine(); + } + + String key; + for(int i = 0; i < Integer.parseInt(numSnapshotsStr); i++) { + key = String.format("snapshot%d.uid", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.filename", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.displayName", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.description", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.createTimeHigh", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.createTimeLow", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.numDisks", i); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + int numDisks = Integer.parseInt(value); + for(int j = 0; j < numDisks; j++) { + key = String.format("snapshot%d.disk%d.fileName", i, j); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + + key = String.format("snapshot%d.disk%d.node", i, j); + value = _properties.getProperty(key); + out.write(String.format("%s = \"%s\"", key, value)); out.newLine(); + } + } + } catch(IOException e) { + assert(false); + s_logger.error("Unexpected exception ", e); + } finally { + if(out != null) { + try { + out.close(); + } catch (IOException e) { + } + } + } + + return bos.toByteArray(); + } + + private int getSnapshotId(String seqStr) { + if(seqStr != null) { + int seq = Integer.parseInt(seqStr); + String numSnapshotStr = _properties.getProperty("snapshot.numSnapshots"); + assert(numSnapshotStr != null); + for(int i = 0; i < Integer.parseInt(numSnapshotStr); i++) { + String value = _properties.getProperty(String.format("snapshot%d.uid", i)); + if(value != null && Integer.parseInt(value) == seq) + return i; + } + } + + return 0; + } + + public SnapshotInfo[] getCurrentDiskChain() { + ArrayList l = new ArrayList(); + String current = _properties.getProperty("snapshot.current"); + int id; + while(current != null) { + id = getSnapshotId(current); + String numDisksStr = _properties.getProperty(String.format("snapshot%d.numDisks", id)); int numDisks = 0; if(numDisksStr != null && !numDisksStr.isEmpty()) { - numDisks = Integer.parseInt(numDisksStr); - DiskInfo[] disks = new DiskInfo[numDisks]; - for(int i = 0; i < numDisks; i++) { - disks[i] = new DiskInfo( - _properties.getProperty(String.format("snapshot%d.disk%d.fileName", id, i)), - _properties.getProperty(String.format("snapshot%d.disk%d.node", id, i)) - ); - } - - SnapshotInfo info = new SnapshotInfo(); - info.setId(id); - info.setNumOfDisks(numDisks); - info.setDisks(disks); - info.setDisplayName(_properties.getProperty(String.format("snapshot%d.displayName", id))); + numDisks = Integer.parseInt(numDisksStr); + DiskInfo[] disks = new DiskInfo[numDisks]; + for(int i = 0; i < numDisks; i++) { + disks[i] = new DiskInfo( + _properties.getProperty(String.format("snapshot%d.disk%d.fileName", id, i)), + _properties.getProperty(String.format("snapshot%d.disk%d.node", id, i)) + ); + } + + SnapshotInfo info = new SnapshotInfo(); + info.setId(id); + info.setNumOfDisks(numDisks); + info.setDisks(disks); + info.setDisplayName(_properties.getProperty(String.format("snapshot%d.displayName", id))); l.add(info); - } - - current = _properties.getProperty(String.format("snapshot%d.parent", id)); - } - - return l.toArray(new SnapshotInfo[0]); - } - - public static class SnapshotInfo { - private int _id; - private String _displayName; - private int _numOfDisks; - private DiskInfo[] _disks; - - public SnapshotInfo() { - } - - public void setId(int id) { - _id = id; - } - - public int getId() { - return _id; - } - - public void setDisplayName(String name) { - _displayName = name; - } - - public String getDisplayName() { - return _displayName; - } - - public void setNumOfDisks(int numOfDisks) { - _numOfDisks = numOfDisks; - } - - public int getNumOfDisks() { - return _numOfDisks; - } - - public void setDisks(DiskInfo[] disks) { - _disks = disks; - } - - public DiskInfo[] getDisks() { - return _disks; - } - } - - public static class DiskInfo { - private String _diskFileName; - private String _deviceName; - - public DiskInfo(String diskFileName, String deviceName) { - _diskFileName = diskFileName; - _deviceName = deviceName; - } - - public String getDiskFileName() { - return _diskFileName; - } - - public String getDeviceName() { - return _deviceName; - } - } -} + } + + current = _properties.getProperty(String.format("snapshot%d.parent", id)); + } + + return l.toArray(new SnapshotInfo[0]); + } + + public static class SnapshotInfo { + private int _id; + private String _displayName; + private int _numOfDisks; + private DiskInfo[] _disks; + + public SnapshotInfo() { + } + + public void setId(int id) { + _id = id; + } + + public int getId() { + return _id; + } + + public void setDisplayName(String name) { + _displayName = name; + } + + public String getDisplayName() { + return _displayName; + } + + public void setNumOfDisks(int numOfDisks) { + _numOfDisks = numOfDisks; + } + + public int getNumOfDisks() { + return _numOfDisks; + } + + public void setDisks(DiskInfo[] disks) { + _disks = disks; + } + + public DiskInfo[] getDisks() { + return _disks; + } + } + + public static class DiskInfo { + private String _diskFileName; + private String _deviceName; + + public DiskInfo(String diskFileName, String deviceName) { + _diskFileName = diskFileName; + _deviceName = deviceName; + } + + public String getDiskFileName() { + return _diskFileName; + } + + public String getDeviceName() { + return _deviceName; + } + } +} 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 1b457dcca31..6e89733cb52 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java @@ -10,144 +10,144 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.HostDiskDimensionsChs; -import com.vmware.vim25.ManagedObjectReference; -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, - 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 - + " 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")) - 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")) - 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")) - 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")) - 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")) - 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")) - 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")) - 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, - destName, morDestDc, force); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(!result.equals("sucess")) - 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); - } -} +package com.cloud.hypervisor.vmware.mo; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.HostDiskDimensionsChs; +import com.vmware.vim25.ManagedObjectReference; +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, + 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 + + " 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")) + 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")) + 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")) + 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")) + 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")) + 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")) + 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")) + 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, + destName, morDestDc, force); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(!result.equals("sucess")) + 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 c9f15270d2f..9ad279f935a 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - +package com.cloud.hypervisor.vmware.mo; + import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; @@ -90,111 +90,111 @@ import com.vmware.vim25.VirtualMachineSnapshotTree; import com.vmware.vim25.VirtualPCIController; import com.vmware.vim25.VirtualSCSIController; import com.vmware.vim25.VirtualSCSISharing; - -public class VirtualMachineMO extends BaseMO { - private static final Logger s_logger = Logger.getLogger(VirtualMachineMO.class); - - 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"); - vmDatastoreTraversal.setName("vmDatastoreTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { vmDatastoreTraversal }); - - 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 }); - - if(ocs != null) { - for(ObjectContent oc : ocs) { - DynamicProperty prop = oc.getPropSet(0); - if(prop.getVal().toString().equals(dsName)) { - return new Pair(new DatastoreMO(_context, oc.getObj()), dsName); - } - } - } - - 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) { - if("guestToolsRunning".equalsIgnoreCase(guestInfo.getToolsRunningStatus())) - return true; - } - return false; - } - + +public class VirtualMachineMO extends BaseMO { + private static final Logger s_logger = Logger.getLogger(VirtualMachineMO.class); + + 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"); + vmDatastoreTraversal.setName("vmDatastoreTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { vmDatastoreTraversal }); + + 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 }); + + if(ocs != null) { + for(ObjectContent oc : ocs) { + DynamicProperty prop = oc.getPropSet(0); + if(prop.getVal().toString().equals(dsName)) { + return new Pair(new DatastoreMO(_context, oc.getObj()), dsName); + } + } + } + + 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) { + if("guestToolsRunning".equalsIgnoreCase(guestInfo.getToolsRunningStatus())) + return true; + } + 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); - return true; - } else { - s_logger.error("VMware powerOnVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - - return false; - } - + + ManagedObjectReference morTask = _context.getService().powerOnVM_Task(_mor, null); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } 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(); + + return powerOffNoCheck(); } public boolean safePowerOff(int shutdownWaitMs) throws Exception { if(getPowerState() == VirtualMachinePowerState.poweredOff) return true; - - if(isVMwareToolsRunning()) { + + if(isVMwareToolsRunning()) { try { String vmName = this.getName(); @@ -213,14 +213,14 @@ public class VirtualMachineMO extends BaseMO { 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)); - } - } - - return powerOffNoCheck(); + + return true; + } catch(Exception e) { + s_logger.warn("Failed to do guest-os graceful shutdown due to " + VmwareHelper.getExceptionMessage(e)); + } + } + + return powerOffNoCheck(); } private boolean powerOffNoCheck() throws Exception { @@ -278,83 +278,83 @@ public class VirtualMachineMO extends BaseMO { } 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); - return true; - } else { - s_logger.error("VMware resetVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - return false; - } - - public void shutdown() throws Exception { - _context.getService().shutdownGuest(_mor); - } + } + + 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); + return true; + } else { + s_logger.error("VMware resetVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + 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 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); - return true; - } 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, - relocateSpec, null); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { - _context.waitForTaskProgressDone(morTask); - return true; - } 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, - boolean dumpMemory, boolean quiesce) throws Exception { - - ManagedObjectReference morTask = _context.getService().createSnapshot_Task(_mor, snapshotName, - snapshotDescription, dumpMemory, quiesce); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { + } + + 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); + return true; + } 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, + relocateSpec, null); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } 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, + boolean dumpMemory, boolean quiesce) throws Exception { + + ManagedObjectReference morTask = _context.getService().createSnapshot_Task(_mor, snapshotName, + snapshotDescription, dumpMemory, quiesce); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { _context.waitForTaskProgressDone(morTask); ManagedObjectReference morSnapshot = null; @@ -372,31 +372,31 @@ public class VirtualMachineMO extends BaseMO { 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")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - - return false; + 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")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + + return false; } public boolean removeAllSnapshots() throws Exception { @@ -417,746 +417,746 @@ public class VirtualMachineMO extends BaseMO { } return true; - } - - 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 - 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 / - 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(), - 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(); - } - } - } - } - assert(vmName != null); - assert(fileInfo != null); - - // .vmsd file exists at the same directory of .vmx file - 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); - } - return null; - } - - 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); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { - _context.waitForTaskProgressDone(morTask); - return true; - } 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, - 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) { - 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); - } - - 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); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { - _context.waitForTaskProgressDone(morTask); - return true; - } 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"); - } - - public String[] getNetworks() throws Exception { - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("Network"); - pSpec.setPathSet(new String[] {"name"}); - - TraversalSpec vm2NetworkTraversal = new TraversalSpec(); - vm2NetworkTraversal.setType("VirtualMachine"); - vm2NetworkTraversal.setPath("network"); - vm2NetworkTraversal.setName("vm2NetworkTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal }); - - 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 }); - - List networks = new ArrayList(); - if(ocs != null && ocs.length > 0) { - for(ObjectContent oc : ocs) { - networks.add(oc.getPropSet(0).getVal().toString()); - } - } - return networks.toArray(new String[0]); - } - - public List getNetworksWithDetails() throws Exception { - List networks = new ArrayList(); - - int gcTagKey = getCustomFieldKey("Network", CustomFieldConstants.CLOUD_GC); - - 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"); - vm2NetworkTraversal.setName("vm2NetworkTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(_mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal }); - - 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 }); - - if(ocs != null && ocs.length > 0) { - for(ObjectContent oc : ocs) { - ArrayOfManagedObjectReference morVms = null; - String gcTagValue = null; - String name = null; - - for(DynamicProperty prop : oc.getPropSet()) { - if(prop.getName().equals("name")) - name = prop.getVal().toString(); - else if(prop.getName().equals("vm")) - morVms = (ArrayOfManagedObjectReference)prop.getVal(); - else if(prop.getName().startsWith("value[")) { - CustomFieldStringValue val = (CustomFieldStringValue)prop.getVal(); - if(val != null) - gcTagValue = val.getValue(); - } - } - - NetworkDetails details = new NetworkDetails(name, oc.getObj(), - (morVms != null ? morVms.getManagedObjectReference() : null), - gcTagValue); - - networks.add(details); - } - } - - return networks; - } - - /** - * 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("\\[|\\]|/"); - assert(vmxPathTokens.length == 4); - pathInfo[1] = vmxPathTokens[1].trim(); // vSphere vm name - pathInfo[2] = dcInfo.second(); // vSphere datacenter name - 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("/"); - sb.append(URLEncoder.encode(vmxPathTokens[3].trim())); - sb.append("?dcPath="); - 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); - return true; - } else { - s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - 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); - return true; - } else { - s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - 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; - for(Ternary deviceTernary: devices) { - VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); - deviceConfigSpec.setDevice(deviceTernary.first()); - deviceConfigSpec.setOperation(deviceTernary.second()); - deviceConfigSpec.setFileOperation(deviceTernary.third()); - deviceConfigSpecArray[i++] = deviceConfigSpec; - } - configSpec.setDeviceChange(deviceConfigSpecArray); - - ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, configSpec); - - String result = _context.getServiceUtil().waitForTask(morTask); - if(result.equals("sucess")) { - _context.waitForTaskProgressDone(morTask); - return true; - } else { - s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - 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")) { - String value = (String)option.getValue(); - if(value != null) { - return new Pair(summary.getHostIp(), Integer.parseInt(value)); - } - } - } - } - 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 { + } + + 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 + 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 / + 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(), + 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(); + } + } + } + } + assert(vmName != null); + assert(fileInfo != null); + + // .vmsd file exists at the same directory of .vmx file + 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); + } + return null; + } + + 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); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } 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, + 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) { + 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); + } + + 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); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } 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"); + } + + public String[] getNetworks() throws Exception { + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("Network"); + pSpec.setPathSet(new String[] {"name"}); + + TraversalSpec vm2NetworkTraversal = new TraversalSpec(); + vm2NetworkTraversal.setType("VirtualMachine"); + vm2NetworkTraversal.setPath("network"); + vm2NetworkTraversal.setName("vm2NetworkTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal }); + + 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 }); + + List networks = new ArrayList(); + if(ocs != null && ocs.length > 0) { + for(ObjectContent oc : ocs) { + networks.add(oc.getPropSet(0).getVal().toString()); + } + } + return networks.toArray(new String[0]); + } + + public List getNetworksWithDetails() throws Exception { + List networks = new ArrayList(); + + int gcTagKey = getCustomFieldKey("Network", CustomFieldConstants.CLOUD_GC); + + 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"); + vm2NetworkTraversal.setName("vm2NetworkTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(_mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal }); + + 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 }); + + if(ocs != null && ocs.length > 0) { + for(ObjectContent oc : ocs) { + ArrayOfManagedObjectReference morVms = null; + String gcTagValue = null; + String name = null; + + for(DynamicProperty prop : oc.getPropSet()) { + if(prop.getName().equals("name")) + name = prop.getVal().toString(); + else if(prop.getName().equals("vm")) + morVms = (ArrayOfManagedObjectReference)prop.getVal(); + else if(prop.getName().startsWith("value[")) { + CustomFieldStringValue val = (CustomFieldStringValue)prop.getVal(); + if(val != null) + gcTagValue = val.getValue(); + } + } + + NetworkDetails details = new NetworkDetails(name, oc.getObj(), + (morVms != null ? morVms.getManagedObjectReference() : null), + gcTagValue); + + networks.add(details); + } + } + + return networks; + } + + /** + * 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("\\[|\\]|/"); + assert(vmxPathTokens.length == 4); + pathInfo[1] = vmxPathTokens[1].trim(); // vSphere vm name + pathInfo[2] = dcInfo.second(); // vSphere datacenter name + 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("/"); + sb.append(URLEncoder.encode(vmxPathTokens[3].trim())); + sb.append("?dcPath="); + 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); + return true; + } else { + s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + 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); + return true; + } else { + s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + 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; + for(Ternary deviceTernary: devices) { + VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); + deviceConfigSpec.setDevice(deviceTernary.first()); + deviceConfigSpec.setOperation(deviceTernary.second()); + deviceConfigSpec.setFileOperation(deviceTernary.third()); + deviceConfigSpecArray[i++] = deviceConfigSpec; + } + configSpec.setDeviceChange(deviceConfigSpecArray); + + ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, configSpec); + + String result = _context.getServiceUtil().waitForTask(morTask); + if(result.equals("sucess")) { + _context.waitForTaskProgressDone(morTask); + return true; + } else { + s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + 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")) { + String value = (String)option.getValue(); + if(value != null) { + return new Pair(summary.getHostIp(), Integer.parseInt(value)); + } + } + } + } + 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 + ", 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) { - backingInfo.setThinProvisioned(true); - } 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(); - if(diskType == VirtualDiskType.rdm) { - backingInfo.setCompatibilityMode("virtualMode"); - } else { - backingInfo.setCompatibilityMode("physicalMode"); - } - backingInfo.setDeviceName(rdmDeviceName); - 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(); - 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")) { + + 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) { + backingInfo.setThinProvisioned(true); + } 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(); + if(diskType == VirtualDiskType.rdm) { + backingInfo.setCompatibilityMode("virtualMode"); + } else { + backingInfo.setCompatibilityMode("physicalMode"); + } + backingInfo.setDeviceName(rdmDeviceName); + 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(); + 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)); - } - + 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: " + new Gson().toJson(vmdkDatastorePathChain) + ", datastore: " + morDs.get_value()); - - VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, getScsiDeviceControllerKey(), - vmdkDatastorePathChain, morDs, -1, 1); - 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); - + + VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, getScsiDeviceControllerKey(), + vmdkDatastorePathChain, morDs, -1, 1); + 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)"); - throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); - } - + 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)"); - } - - // vmdkDatastorePath: [datastore name] vmdkFilePath + } + + // 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: " + 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); + + // 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); if(deviceInfo == null) { if(s_logger.isTraceEnabled()) 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(); - 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); - + throw new Exception("No such disk device: " + vmdkDatastorePath); + } + + List> chain = getDiskDatastorePathChain(deviceInfo.first(), true); + + 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); - - // VMware does not update snapshot references to the detached disk, we have to work around it - SnapshotDescriptor snapshotDescriptor = null; - try { - snapshotDescriptor = getSnapshotDescriptor(); - } 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()); + + throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask)); + } + _context.waitForTaskProgressDone(morTask); + + // VMware does not update snapshot references to the detached disk, we have to work around it + SnapshotDescriptor snapshotDescriptor = null; + try { + snapshotDescriptor = getSnapshotDescriptor(); + } 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; - } - + 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(); - 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")) { + + VirtualDisk[] disks = getAllDiskDevice(); + if(disks.length > 0) { + 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); + 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 { + } + + // 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: " + isoDatastorePath + ", datastore: " + morDs.get_value() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot); - - assert(isoDatastorePath != null); - assert(morDs != null); - - boolean newCdRom = false; - VirtualCdrom cdRom = (VirtualCdrom )getIsoDevice(); - if(cdRom == null) { - newCdRom = true; - cdRom = new VirtualCdrom(); - cdRom.setControllerKey(getIDEDeviceControllerKey()); - - int deviceNumber = getNextIDEDeviceNumber(); - 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(); - 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")) { + + assert(isoDatastorePath != null); + assert(morDs != null); + + boolean newCdRom = false; + VirtualCdrom cdRom = (VirtualCdrom )getIsoDevice(); + if(cdRom == null) { + newCdRom = true; + cdRom = new VirtualCdrom(); + cdRom.setControllerKey(getIDEDeviceControllerKey()); + + int deviceNumber = getNextIDEDeviceNumber(); + 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(); + 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)); - } - + 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 { + } + + public void detachIso(String isoDatastorePath) throws Exception { if(s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: " + isoDatastorePath); - VirtualDevice device = getIsoDevice(); - if(device == null) { + VirtualDevice device = getIsoDevice(); + if(device == null) { if(s_logger.isTraceEnabled()) 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(); - 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); - + throw new Exception("Unable to find a CDROM device"); + } + + VirtualCdromRemotePassthroughBackingInfo backingInfo = new VirtualCdromRemotePassthroughBackingInfo(); + backingInfo.setDeviceName(""); + device.setBacking(backingInfo); + + 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)); - } + 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: " + vmdkDatastorePath); - - Pair dcPair = getOwnerDatacenter(); - - String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), vmdkDatastorePath); - byte[] content = getContext().getResourceContent(url); - VmdkFileDescriptor descriptor = new VmdkFileDescriptor(); + + 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); @@ -1164,106 +1164,106 @@ public class VirtualMachineMO extends BaseMO { s_logger.trace("vCenter API trace - getVmdkFileInfo() done"); s_logger.trace("VMDK file descriptor: " + new Gson().toJson(result.first())); } - 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(); + 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(); boolean success = false; List fileNames = new ArrayList(); - try { - HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo(); - final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024; - long totalBytesDownloaded = 0; - - HttpNfcLeaseDeviceUrl[] deviceUrls = leaseInfo.getDeviceUrl(); + try { + 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(); - 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, - new ActionDelegate () { - @Override - public void action(Long param) { - if(s_logger.isTraceEnabled()) { - s_logger.trace("Download progress " + param + "/" + totalBytes); - } - progressReporter.reportProgress((int)(param * 100 / totalBytes)); - } - }); - totalBytesDownloaded += lengthOfDiskFile; - - OvfFile ovfFile = new 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); - String ovfPath = exportDir + File.separator + exportName + ".ovf"; - fileNames.add(ovfPath); - - FileWriter out = new FileWriter(ovfPath); - out.write(ovfCreateDescriptorResult.getOvfDescriptor()); - out.close(); - - // tar files into OVA + 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, + new ActionDelegate () { + @Override + public void action(Long param) { + if(s_logger.isTraceEnabled()) { + s_logger.trace("Download progress " + param + "/" + totalBytes); + } + progressReporter.reportProgress((int)(param * 100 / totalBytes)); + } + }); + totalBytesDownloaded += lengthOfDiskFile; + + OvfFile ovfFile = new 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); + String ovfPath = exportDir + File.separator + exportName + ".ovf"; + fileNames.add(ovfPath); + + FileWriter out = new FileWriter(ovfPath); + 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"); - command.add(exportName + ".ovf"); // OVF file should be the first file in OVA archive - for(String name: fileNames) { - command.add((new File(name).getName())); - } + + Script command = new Script(false, "tar", 0, s_logger); + command.setWorkDir(exportDir); + command.add("-cf", exportName + ".ova"); + command.add(exportName + ".ovf"); // OVF file should be the first file in OVA archive + for(String name: fileNames) { + command.add((new File(name).getName())); + } s_logger.info("Package OVA with commmand: " + command.toString()); command.execute(); @@ -1275,10 +1275,10 @@ public class VirtualMachineMO extends BaseMO { s_logger.error(exportDir + File.separator + exportName + ".ova is not created as expected"); } } - } - } catch(Throwable e) { - s_logger.error("Unexpected exception ", e); - } finally { + } + } catch(Throwable e) { + s_logger.error("Unexpected exception ", e); + } finally { progressReporter.close(); if(leaveOvaFileOnly) { @@ -1289,193 +1289,193 @@ public class VirtualMachineMO extends BaseMO { if(!success) throw new Exception("Unable to finish the whole process to package as a OVA file"); - } - } - } finally { - leaseMo.updateLeaseProgress(100); - leaseMo.completeLease(); - } - } - + } + } + } finally { + leaseMo.updateLeaseProgress(100); + leaseMo.completeLease(); + } + } + // snapshot directory in format of: /vmfs/volumes// - @Deprecated - public void setSnapshotDirectory(String snapshotDir) throws Exception { - VirtualMachineFileInfo fileInfo = getFileInfo(); - 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)); - String line; - while((line = in.readLine()) != null) { - if(line.startsWith("workingDir")) { - replaced = true; - out.write(String.format("workingDir=\"%s\"", snapshotDir)); - out.newLine(); - } else { - out.write(line); - out.newLine(); - } - } - - if(!replaced) { - out.newLine(); - out.write(String.format("workingDir=\"%s\"", snapshotDir)); - out.newLine(); - } - } finally { - if(in != null) { - in.close(); - } - if(out != null) { - out.close(); - } - } - _context.uploadResourceContent(vmxUrl, bos.toByteArray()); - - // It seems that I don't need to do re-registration. VMware has bug in writing the correct snapshot's VMDK path to - // its disk backing info anyway. - // redoRegistration(); - } - - // destName does not contain extension name - 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>(); - - 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; - String destFileName; - String destParentFileName; - for(SnapshotDescriptor.DiskInfo disk : disks) { - if(deviceName == null || deviceName.equals(disk.getDeviceName())) { - String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, - mounts, disk.getDiskFileName()); - Pair srcDsInfo = getOwnerDatastore(srcVmdkFullDsPath); - - Pair vmdkInfo = getVmdkFileInfo(srcVmdkFullDsPath); - String srcVmdkBaseFilePath = DatastoreFile.getCompanionDatastorePath( - srcVmdkFullDsPath, vmdkInfo.first().getBaseFileName()); - - destFileName = destName + (snapshotInfo.length - i - 1)+ ".vmdk"; - if(vmdkInfo.first().getParentFileName() != null) { - destBaseFileName = destName + (snapshotInfo.length - i - 1)+ "-delta.vmdk"; - destParentFileName = destName + (snapshotInfo.length - i - 2)+ ".vmdk"; - } else { - 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(), - morDestDs, destDsDirectory + "/" + destBaseFileName, dcMo.getMor(), true); - - byte[] newVmdkContent = VmdkFileDescriptor.changeVmdkContentBaseInfo( - vmdkInfo.second(), destBaseFileName, destParentFileName); - 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) - ); - } - } - } - } - - byte[] vdiskInfo = VmwareHelper.composeDiskInfo(backupInfo, snapshotInfo.length, includeBase); - 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(); - if(disks != null) { - for(SnapshotDescriptor.DiskInfo disk: disks) { - String deviceNameInDisk = disk.getDeviceName(); - if(diskDevice == null || diskDevice.equalsIgnoreCase(deviceNameInDisk)) { - String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, - mounts, disk.getDiskFileName()); - diskDsFullPaths.add(vmdkFullDsPath); - } - } - } - } - return diskDsFullPaths.toArray(new String[0]); - } - - 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, - String[] disks, ManagedObjectReference morDs) throws Exception { - assert(disks != null); - assert(disks.length >= 1); - - HostMO hostMo = getRunningHost(); - VirtualMachineConfigInfo vmConfigInfo = getConfigInfo(); - + @Deprecated + public void setSnapshotDirectory(String snapshotDir) throws Exception { + VirtualMachineFileInfo fileInfo = getFileInfo(); + 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)); + String line; + while((line = in.readLine()) != null) { + if(line.startsWith("workingDir")) { + replaced = true; + out.write(String.format("workingDir=\"%s\"", snapshotDir)); + out.newLine(); + } else { + out.write(line); + out.newLine(); + } + } + + if(!replaced) { + out.newLine(); + out.write(String.format("workingDir=\"%s\"", snapshotDir)); + out.newLine(); + } + } finally { + if(in != null) { + in.close(); + } + if(out != null) { + out.close(); + } + } + _context.uploadResourceContent(vmxUrl, bos.toByteArray()); + + // It seems that I don't need to do re-registration. VMware has bug in writing the correct snapshot's VMDK path to + // its disk backing info anyway. + // redoRegistration(); + } + + // destName does not contain extension name + 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>(); + + 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; + String destFileName; + String destParentFileName; + for(SnapshotDescriptor.DiskInfo disk : disks) { + if(deviceName == null || deviceName.equals(disk.getDeviceName())) { + String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, + mounts, disk.getDiskFileName()); + Pair srcDsInfo = getOwnerDatastore(srcVmdkFullDsPath); + + Pair vmdkInfo = getVmdkFileInfo(srcVmdkFullDsPath); + String srcVmdkBaseFilePath = DatastoreFile.getCompanionDatastorePath( + srcVmdkFullDsPath, vmdkInfo.first().getBaseFileName()); + + destFileName = destName + (snapshotInfo.length - i - 1)+ ".vmdk"; + if(vmdkInfo.first().getParentFileName() != null) { + destBaseFileName = destName + (snapshotInfo.length - i - 1)+ "-delta.vmdk"; + destParentFileName = destName + (snapshotInfo.length - i - 2)+ ".vmdk"; + } else { + 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(), + morDestDs, destDsDirectory + "/" + destBaseFileName, dcMo.getMor(), true); + + byte[] newVmdkContent = VmdkFileDescriptor.changeVmdkContentBaseInfo( + vmdkInfo.second(), destBaseFileName, destParentFileName); + 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) + ); + } + } + } + } + + byte[] vdiskInfo = VmwareHelper.composeDiskInfo(backupInfo, snapshotInfo.length, includeBase); + 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(); + if(disks != null) { + for(SnapshotDescriptor.DiskInfo disk: disks) { + String deviceNameInDisk = disk.getDeviceName(); + if(diskDevice == null || diskDevice.equalsIgnoreCase(deviceNameInDisk)) { + String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, + mounts, disk.getDiskFileName()); + diskDsFullPaths.add(vmdkFullDsPath); + } + } + } + } + return diskDsFullPaths.toArray(new String[0]); + } + + 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, + 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"); + 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); + 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); clonedVmMo.configureVm(vmConfigSpec); bSuccess = true; } finally { @@ -1483,143 +1483,143 @@ public class VirtualMachineMO extends BaseMO { clonedVmMo.detachAllDisks(); clonedVmMo.destroy(); } - } - } - - 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(); - if(disks != null) { - for(VirtualDevice disk : disks) { - 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(), - 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(), - destFile.getPath(), dcMo.getMor(), true); - } - } - } - } - } + } + } + + 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(); + if(disks != null) { + for(VirtualDevice disk : disks) { + 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(), + 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(), + destFile.getPath(), dcMo.getMor(), true); + } + } + } + } + } // this method relies on un-offical VMware API @Deprecated - public void moveAllVmDiskFiles(DatastoreMO destDsMo, String destDsDir, boolean followDiskChain) throws Exception { - VirtualDevice[] disks = getAllDiskDevice(); - DatacenterMO dcMo = getOwnerDatacenter().first(); - if(disks != null) { - for(VirtualDevice disk : disks) { - 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(), - 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(), - 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) { - return device.getKey(); - } - } - } - - assert(false); - throw new Exception("SCSI Controller Not Found"); - } + public void moveAllVmDiskFiles(DatastoreMO destDsMo, String destDsDir, boolean followDiskChain) throws Exception { + VirtualDevice[] disks = getAllDiskDevice(); + DatacenterMO dcMo = getOwnerDatacenter().first(); + if(disks != null) { + for(VirtualDevice disk : disks) { + 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(), + 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(), + 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) { + return device.getKey(); + } + } + } + + assert(false); + throw new Exception("SCSI Controller Not Found"); + } public int getScsiDeviceControllerKeyNoException() throws Exception { VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil(). @@ -1656,387 +1656,387 @@ 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; + + // 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(); - if(!(backingInfo instanceof VirtualDiskFlatVer2BackingInfo)) { - throw new Exception("Unsupported VirtualDeviceBackingInfo"); - } - - List> pathList = new ArrayList>(); - VirtualDiskFlatVer2BackingInfo diskBackingInfo = (VirtualDiskFlatVer2BackingInfo)backingInfo; - - if(!followChain) { - 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 - byte[] content = null; - try { - String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), diskBackingInfo.getFileName()); - content = getContext().getResourceContent(url); - 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 - // that its corresponding disk backing info is not updated correctly. therefore, we will try search - // 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("/"); - parentFileName = parentFileName.substring(fileNameStartPos + 1); - parentDiskBackingInfo.setFileName(vmxDirFile.getCompanionPath(parentFileName)); - } else { - parentDiskBackingInfo.setFileName(snapshotDirFile.getCompanionPath(parentFileName)); - } - 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()) { - if(device instanceof VirtualIDEController) { - return String.format("ide%d:%d", ((VirtualIDEController)device).getBusNumber(), theDevice.getUnitNumber()); - } else if(device instanceof VirtualSCSIController) { - return String.format("scsi%d:%d", ((VirtualSCSIController)device).getBusNumber(), theDevice.getUnitNumber()); - } else { - throw new Exception("Device controller is not supported yet"); - } - } - } - 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"); - if(devices != null && devices.length > 0) { - for(VirtualDevice device : devices) { - if(device instanceof VirtualDisk) { - deviceList.add((VirtualDisk)device); - } - } - } - - return deviceList.toArray(new VirtualDisk[0]); - } - - public VirtualDisk[] getAllIndependentDiskDevice() throws Exception { - List independentDisks = new ArrayList(); - VirtualDisk[] allDisks = getAllDiskDevice(); - if(allDisks.length > 0) { - for(VirtualDisk disk : allDisks) { - String diskMode = ""; - if(disk.getBacking() instanceof VirtualDiskFlatVer1BackingInfo) { - diskMode = ((VirtualDiskFlatVer1BackingInfo)disk.getBacking()).getDiskMode(); - } else if(disk.getBacking() instanceof VirtualDiskFlatVer2BackingInfo) { - diskMode = ((VirtualDiskFlatVer2BackingInfo)disk.getBacking()).getDiskMode(); - } else if(disk.getBacking() instanceof VirtualDiskRawDiskMappingVer1BackingInfo) { - diskMode = ((VirtualDiskRawDiskMappingVer1BackingInfo)disk.getBacking()).getDiskMode(); - } else if(disk.getBacking() instanceof VirtualDiskSparseVer1BackingInfo) { - diskMode = ((VirtualDiskSparseVer1BackingInfo)disk.getBacking()).getDiskMode(); - } 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) { - return ((VirtualIDEController)device).getKey(); - } - } - } - - 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) { - return ((VirtualIDEController)device).getKey(); - } - } - } - - 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"); - if(devices != null && devices.length > 0) { - for(VirtualDevice device : devices) { - if(device instanceof VirtualCdrom) { - return device; - } - } - } - 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) { - return ((VirtualPCIController)device).getKey(); - } - } - } - - 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) { - if(device.getControllerKey() != null && device.getControllerKey().intValue() == controllerKey) { - if(device.getUnitNumber() != null && device.getUnitNumber().intValue() > deviceNumber) { - deviceNumber = device.getUnitNumber().intValue(); - } - } - } - } - 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) { - if(device instanceof VirtualEthernetCard) { - nics.add(device); - } - } - } - - 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) { - if(device instanceof VirtualEthernetCard) { - nics.add(device); - } - } - } - - Collections.sort(nics, new Comparator() { - @Override - public int compare(VirtualDevice arg0, VirtualDevice arg1) { - int unitNumber0 = arg0.getUnitNumber() != null ? arg0.getUnitNumber().intValue() : -1; - int unitNumber1 = arg1.getUnitNumber() != null ? arg1.getUnitNumber().intValue() : -1; - if(unitNumber0 < unitNumber1) - return -1; - else if(unitNumber0 > unitNumber1) - return 1; - return 0; - } - }); - - int index = 0; - for(VirtualDevice nic : nics) { - if(((VirtualEthernetCard)nic).getDeviceInfo().getSummary().startsWith(networkNamePrefix)) - return new Pair(new Integer(index), nic); - index++; - } - return new Pair(new Integer(-1), null); - } - - 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) { - if(clz.isInstance(device)) { - returnList.add(device); - break; - } - } - } - } - - 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(); + @Deprecated + public List> getDiskDatastorePathChain(VirtualDisk disk, boolean followChain) throws Exception { + VirtualDeviceBackingInfo backingInfo = disk.getBacking(); + if(!(backingInfo instanceof VirtualDiskFlatVer2BackingInfo)) { + throw new Exception("Unsupported VirtualDeviceBackingInfo"); + } + + List> pathList = new ArrayList>(); + VirtualDiskFlatVer2BackingInfo diskBackingInfo = (VirtualDiskFlatVer2BackingInfo)backingInfo; + + if(!followChain) { + 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 + byte[] content = null; + try { + String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), diskBackingInfo.getFileName()); + content = getContext().getResourceContent(url); + 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 + // that its corresponding disk backing info is not updated correctly. therefore, we will try search + // 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("/"); + parentFileName = parentFileName.substring(fileNameStartPos + 1); + parentDiskBackingInfo.setFileName(vmxDirFile.getCompanionPath(parentFileName)); + } else { + parentDiskBackingInfo.setFileName(snapshotDirFile.getCompanionPath(parentFileName)); + } + 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()) { + if(device instanceof VirtualIDEController) { + return String.format("ide%d:%d", ((VirtualIDEController)device).getBusNumber(), theDevice.getUnitNumber()); + } else if(device instanceof VirtualSCSIController) { + return String.format("scsi%d:%d", ((VirtualSCSIController)device).getBusNumber(), theDevice.getUnitNumber()); + } else { + throw new Exception("Device controller is not supported yet"); + } + } + } + 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"); + if(devices != null && devices.length > 0) { + for(VirtualDevice device : devices) { + if(device instanceof VirtualDisk) { + deviceList.add((VirtualDisk)device); + } + } + } + + return deviceList.toArray(new VirtualDisk[0]); + } + + public VirtualDisk[] getAllIndependentDiskDevice() throws Exception { + List independentDisks = new ArrayList(); + VirtualDisk[] allDisks = getAllDiskDevice(); + if(allDisks.length > 0) { + for(VirtualDisk disk : allDisks) { + String diskMode = ""; + if(disk.getBacking() instanceof VirtualDiskFlatVer1BackingInfo) { + diskMode = ((VirtualDiskFlatVer1BackingInfo)disk.getBacking()).getDiskMode(); + } else if(disk.getBacking() instanceof VirtualDiskFlatVer2BackingInfo) { + diskMode = ((VirtualDiskFlatVer2BackingInfo)disk.getBacking()).getDiskMode(); + } else if(disk.getBacking() instanceof VirtualDiskRawDiskMappingVer1BackingInfo) { + diskMode = ((VirtualDiskRawDiskMappingVer1BackingInfo)disk.getBacking()).getDiskMode(); + } else if(disk.getBacking() instanceof VirtualDiskSparseVer1BackingInfo) { + diskMode = ((VirtualDiskSparseVer1BackingInfo)disk.getBacking()).getDiskMode(); + } 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) { + return ((VirtualIDEController)device).getKey(); + } + } + } + + 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) { + return ((VirtualIDEController)device).getKey(); + } + } + } + + 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"); + if(devices != null && devices.length > 0) { + for(VirtualDevice device : devices) { + if(device instanceof VirtualCdrom) { + return device; + } + } + } + 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) { + return ((VirtualPCIController)device).getKey(); + } + } + } + + 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) { + if(device.getControllerKey() != null && device.getControllerKey().intValue() == controllerKey) { + if(device.getUnitNumber() != null && device.getUnitNumber().intValue() > deviceNumber) { + deviceNumber = device.getUnitNumber().intValue(); + } + } + } + } + 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) { + if(device instanceof VirtualEthernetCard) { + nics.add(device); + } + } + } + + 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) { + if(device instanceof VirtualEthernetCard) { + nics.add(device); + } + } + } + + Collections.sort(nics, new Comparator() { + @Override + public int compare(VirtualDevice arg0, VirtualDevice arg1) { + int unitNumber0 = arg0.getUnitNumber() != null ? arg0.getUnitNumber().intValue() : -1; + int unitNumber1 = arg1.getUnitNumber() != null ? arg1.getUnitNumber().intValue() : -1; + if(unitNumber0 < unitNumber1) + return -1; + else if(unitNumber0 > unitNumber1) + return 1; + return 0; + } + }); + + int index = 0; + for(VirtualDevice nic : nics) { + if(((VirtualEthernetCard)nic).getDeviceInfo().getSummary().startsWith(networkNamePrefix)) + return new Pair(new Integer(index), nic); + index++; + } + return new Pair(new Integer(-1), null); + } + + 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) { + if(clz.isInstance(device)) { + returnList.add(device); + break; + } + } + } + } + + 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, - vmFileInfo.getVmPathName(), - 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)); - } else { + + ManagedObjectReference morFolder = getParentMor(); + ManagedObjectReference morPool = hostMo.getHyperHostOwnerResourcePool(); + + _context.getService().unregisterVM(_mor); + + ManagedObjectReference morTask = _context.getService().registerVM_Task( + morFolder, + vmFileInfo.getVmPathName(), + 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)); + } else { _context.waitForTaskProgressDone(morTask); if(isTemplate) { VirtualMachineMO vmNewRegistration = hostMo.findVmOnHyperHost(vmName); assert(vmNewRegistration != null); vmNewRegistration.markAsTemplate(); } - } + } } -} - +} + diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmdkFileDescriptor.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmdkFileDescriptor.java index 6ebbcc271b1..dc07d7fd10b 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmdkFileDescriptor.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmdkFileDescriptor.java @@ -10,145 +10,145 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.Properties; - -import org.apache.log4j.Logger; - -public class VmdkFileDescriptor { - private static final Logger s_logger = Logger.getLogger(VmdkFileDescriptor.class); - - private Properties _properties = new Properties(); - private String _baseFileName; - - public VmdkFileDescriptor() { - } - - public void parse(byte[] vmdkFileContent) throws IOException { - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmdkFileContent))); - String line; - while((line = in.readLine()) != null) { - // ignore empty and comment lines - line = line.trim(); - if(line.isEmpty()) - continue; - if(line.charAt(0) == '#') - continue; - - String[] tokens = line.split("="); - if(tokens.length == 2) { - String name = tokens[0].trim(); - String value = tokens[1].trim(); - if(value.charAt(0) == '\"') - value = value.substring(1, value.length() -1); - - _properties.put(name, value); - } else { - if(line.startsWith("RW")) { - int startPos = line.indexOf('\"'); - int endPos = line.lastIndexOf('\"'); - assert(startPos > 0); - assert(endPos > 0); - - _baseFileName = line.substring(startPos + 1, endPos); - } else { - s_logger.warn("Unrecognized vmdk line content: " + line); - } - } - } - } finally { - if(in != null) - in.close(); - } - } - - public String getBaseFileName() { - return _baseFileName; - } - - public String getParentFileName() { - return _properties.getProperty("parentFileNameHint"); - } - - public static byte[] changeVmdkContentBaseInfo(byte[] vmdkContent, - String baseFileName, String parentFileName) throws IOException { - - assert(vmdkContent != null); - - BufferedReader in = null; - BufferedWriter out = null; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - try { - in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmdkContent))); - out = new BufferedWriter(new OutputStreamWriter(bos)); - String line; - while((line = in.readLine()) != null) { - // ignore empty and comment lines - line = line.trim(); - if(line.isEmpty()) { - out.newLine(); - continue; - } - if(line.charAt(0) == '#') { - out.write(line); - out.newLine(); - continue; - } - - String[] tokens = line.split("="); - if(tokens.length == 2) { - String name = tokens[0].trim(); - String value = tokens[1].trim(); - if(value.charAt(0) == '\"') - value = value.substring(1, value.length() - 1); - - if(parentFileName != null && name.equals("parentFileNameHint")) { - out.write(name + "=\"" + parentFileName + "\""); - out.newLine(); - } else { - out.write(line); - out.newLine(); - } - } else { - if(line.startsWith("RW")) { - if(baseFileName != null) { - int startPos = line.indexOf('\"'); - int endPos = line.lastIndexOf('\"'); - assert(startPos > 0); - assert(endPos > 0); - - // replace it with base file name - out.write(line.substring(0, startPos + 1)); - out.write(baseFileName); - out.write(line.substring(endPos)); - out.newLine(); - } else { - out.write(line); - out.newLine(); - } - } else { - s_logger.warn("Unrecognized vmdk line content: " + line); - } - } - } - } finally { - if(in != null) - in.close(); - if(out != null) - out.close(); - } - - return bos.toByteArray(); - } -} +package com.cloud.hypervisor.vmware.mo; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.util.Properties; + +import org.apache.log4j.Logger; + +public class VmdkFileDescriptor { + private static final Logger s_logger = Logger.getLogger(VmdkFileDescriptor.class); + + private Properties _properties = new Properties(); + private String _baseFileName; + + public VmdkFileDescriptor() { + } + + public void parse(byte[] vmdkFileContent) throws IOException { + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmdkFileContent))); + String line; + while((line = in.readLine()) != null) { + // ignore empty and comment lines + line = line.trim(); + if(line.isEmpty()) + continue; + if(line.charAt(0) == '#') + continue; + + String[] tokens = line.split("="); + if(tokens.length == 2) { + String name = tokens[0].trim(); + String value = tokens[1].trim(); + if(value.charAt(0) == '\"') + value = value.substring(1, value.length() -1); + + _properties.put(name, value); + } else { + if(line.startsWith("RW")) { + int startPos = line.indexOf('\"'); + int endPos = line.lastIndexOf('\"'); + assert(startPos > 0); + assert(endPos > 0); + + _baseFileName = line.substring(startPos + 1, endPos); + } else { + s_logger.warn("Unrecognized vmdk line content: " + line); + } + } + } + } finally { + if(in != null) + in.close(); + } + } + + public String getBaseFileName() { + return _baseFileName; + } + + public String getParentFileName() { + return _properties.getProperty("parentFileNameHint"); + } + + public static byte[] changeVmdkContentBaseInfo(byte[] vmdkContent, + String baseFileName, String parentFileName) throws IOException { + + assert(vmdkContent != null); + + BufferedReader in = null; + BufferedWriter out = null; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + try { + in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmdkContent))); + out = new BufferedWriter(new OutputStreamWriter(bos)); + String line; + while((line = in.readLine()) != null) { + // ignore empty and comment lines + line = line.trim(); + if(line.isEmpty()) { + out.newLine(); + continue; + } + if(line.charAt(0) == '#') { + out.write(line); + out.newLine(); + continue; + } + + String[] tokens = line.split("="); + if(tokens.length == 2) { + String name = tokens[0].trim(); + String value = tokens[1].trim(); + if(value.charAt(0) == '\"') + value = value.substring(1, value.length() - 1); + + if(parentFileName != null && name.equals("parentFileNameHint")) { + out.write(name + "=\"" + parentFileName + "\""); + out.newLine(); + } else { + out.write(line); + out.newLine(); + } + } else { + if(line.startsWith("RW")) { + if(baseFileName != null) { + int startPos = line.indexOf('\"'); + int endPos = line.lastIndexOf('\"'); + assert(startPos > 0); + assert(endPos > 0); + + // replace it with base file name + out.write(line.substring(0, startPos + 1)); + out.write(baseFileName); + out.write(line.substring(endPos)); + out.newLine(); + } else { + out.write(line); + out.newLine(); + } + } else { + s_logger.warn("Unrecognized vmdk line content: " + line); + } + } + } + } finally { + if(in != null) + in.close(); + if(out != null) + out.close(); + } + + return bos.toByteArray(); + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java index 89398f981e1..4f39860e18f 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHost.java @@ -10,56 +10,56 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -import com.cloud.hypervisor.vmware.util.VmwareContext; -import com.vmware.vim25.ClusterDasConfigInfo; -import com.vmware.vim25.ComputeResourceSummary; -import com.vmware.vim25.ManagedObjectReference; -import com.vmware.vim25.ObjectContent; -import com.vmware.vim25.VirtualMachineConfigSpec; - -/** - * Interface to consolidate ESX(i) hosts and HA/FT clusters into a common interface used by CloudStack Hypervisor resources - */ -public interface VmwareHypervisorHost { - VmwareContext getContext(); - ManagedObjectReference getMor(); - - String getHyperHostName() throws Exception; - - ClusterDasConfigInfo getDasConfig() throws Exception; - +package com.cloud.hypervisor.vmware.mo; + +import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.vmware.vim25.ClusterDasConfigInfo; +import com.vmware.vim25.ComputeResourceSummary; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.ObjectContent; +import com.vmware.vim25.VirtualMachineConfigSpec; + +/** + * Interface to consolidate ESX(i) hosts and HA/FT clusters into a common interface used by CloudStack Hypervisor resources + */ +public interface VmwareHypervisorHost { + VmwareContext getContext(); + ManagedObjectReference getMor(); + + String getHyperHostName() throws Exception; + + ClusterDasConfigInfo getDasConfig() throws Exception; + ManagedObjectReference getHyperHostDatacenter() throws Exception; ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception; ManagedObjectReference getHyperHostCluster() throws Exception; - - boolean isHyperHostConnected() throws Exception; - String getHyperHostDefaultGateway() throws Exception; - - VirtualMachineMO findVmOnHyperHost(String name) throws Exception; - VirtualMachineMO findVmOnPeerHyperHost(String name) throws Exception; - - boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception; - boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, - String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception; - void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception; - - ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception; - ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception; - - ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress, - int poolHostPort, String poolPath, String poolUuid) throws Exception; - void unmountDatastore(String poolUuid) throws Exception; - - ManagedObjectReference findDatastore(String poolUuid) throws Exception; - - @Deprecated - ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception; - - ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception; - - VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception; - VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String esxServiceConsolePort) throws Exception; - ComputeResourceSummary getHyperHostHardwareSummary() throws Exception; -} + + boolean isHyperHostConnected() throws Exception; + String getHyperHostDefaultGateway() throws Exception; + + VirtualMachineMO findVmOnHyperHost(String name) throws Exception; + VirtualMachineMO findVmOnPeerHyperHost(String name) throws Exception; + + boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception; + boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, + String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception; + void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception; + + ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception; + ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception; + + ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress, + int poolHostPort, String poolPath, String poolUuid) throws Exception; + void unmountDatastore(String poolUuid) throws Exception; + + ManagedObjectReference findDatastore(String poolUuid) throws Exception; + + @Deprecated + ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception; + + ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception; + + VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception; + VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String esxServiceConsolePort) throws Exception; + ComputeResourceSummary getHyperHostHardwareSummary() throws Exception; +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostNetworkSummary.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostNetworkSummary.java index 1c1418ea98b..af16ad827a7 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostNetworkSummary.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostNetworkSummary.java @@ -10,37 +10,37 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -public class VmwareHypervisorHostNetworkSummary { - private String hostIp; - private String hostNetmask; - private String hostMacAddress; - - public VmwareHypervisorHostNetworkSummary() { - } - - public String getHostIp() { - return hostIp; - } - - public void setHostIp(String hostIp) { - this.hostIp = hostIp; - } - - public String getHostNetmask() { - return hostNetmask; - } - - public void setHostNetmask(String hostNetmask) { - this.hostNetmask = hostNetmask; - } - - public String getHostMacAddress() { - return hostMacAddress; - } - - public void setHostMacAddress(String hostMacAddress) { - this.hostMacAddress = hostMacAddress; - } -} +package com.cloud.hypervisor.vmware.mo; + +public class VmwareHypervisorHostNetworkSummary { + private String hostIp; + private String hostNetmask; + private String hostMacAddress; + + public VmwareHypervisorHostNetworkSummary() { + } + + public String getHostIp() { + return hostIp; + } + + public void setHostIp(String hostIp) { + this.hostIp = hostIp; + } + + public String getHostNetmask() { + return hostNetmask; + } + + public void setHostNetmask(String hostNetmask) { + this.hostNetmask = hostNetmask; + } + + public String getHostMacAddress() { + return hostMacAddress; + } + + public void setHostMacAddress(String hostMacAddress) { + this.hostMacAddress = hostMacAddress; + } +} diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostResourceSummary.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostResourceSummary.java index aaffffdd3da..bbd6a42497e 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostResourceSummary.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VmwareHypervisorHostResourceSummary.java @@ -10,37 +10,37 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.mo; - -public class VmwareHypervisorHostResourceSummary { - private long memoryBytes; - private long cpuCount; - private long cpuSpeed; - - public VmwareHypervisorHostResourceSummary() { - } - - public long getMemoryBytes() { - return memoryBytes; - } - - public void setMemoryBytes(long memoryBytes) { - this.memoryBytes = memoryBytes; - } - - public long getCpuCount() { - return cpuCount; - } - - public void setCpuCount(long cpuCount) { - this.cpuCount = cpuCount; - } - - public long getCpuSpeed() { - return cpuSpeed; - } - - public void setCpuSpeed(long cpuSpeed) { - this.cpuSpeed = cpuSpeed; - } -} +package com.cloud.hypervisor.vmware.mo; + +public class VmwareHypervisorHostResourceSummary { + private long memoryBytes; + private long cpuCount; + private long cpuSpeed; + + public VmwareHypervisorHostResourceSummary() { + } + + public long getMemoryBytes() { + return memoryBytes; + } + + public void setMemoryBytes(long memoryBytes) { + this.memoryBytes = memoryBytes; + } + + public long getCpuCount() { + return cpuCount; + } + + public void setCpuCount(long cpuCount) { + this.cpuCount = cpuCount; + } + + public long getCpuSpeed() { + return cpuSpeed; + } + + public void setCpuSpeed(long cpuSpeed) { + this.cpuSpeed = cpuSpeed; + } +} 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 73d77998626..d72e5c84265 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareContext.java @@ -10,291 +10,291 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; +package com.cloud.hypervisor.vmware.util; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +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; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSession; - -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; -import com.vmware.vim25.VimPortType; - -public class VmwareContext { - private static final Logger s_logger = Logger.getLogger(VmwareContext.class); +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; + +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; +import com.vmware.vim25.VimPortType; + +public class VmwareContext { + private static final Logger s_logger = Logger.getLogger(VmwareContext.class); private static int MAX_CONNECT_RETRY = 5; private static int CONNECT_RETRY_INTERVAL = 1000; - - private ExtendedAppUtil _appUtil; - private String _serverAddress; - - private Map _stockMap = new HashMap(); + + private ExtendedAppUtil _appUtil; + 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.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; - _serverAddress = address; - } - - public void registerStockObject(String name, Object obj) { - synchronized(_stockMap) { - _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(); - } - - public VimPortType getService() { - return getServiceConnection().getService(); - } - - public ServiceContent getServiceContent() { - return getServiceConnection().getServiceContent(); - } - - public ServiceUtil getServiceUtil() { - return _appUtil.getServiceUtil3(); - } - - public ManagedObjectReference getRootFolder() { - return getServiceContent().getRootFolder(); - } - - 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; - if(mor.getType().equalsIgnoreCase("Datacenter")) { - PropertySpec pSpec = new PropertySpec(); - pSpec.setType("ManagedEntity"); - pSpec.setPathSet(new String[] { "name" }); - - TraversalSpec dcHostFolderTraversal = new TraversalSpec(); - dcHostFolderTraversal.setType("Datacenter"); - dcHostFolderTraversal.setPath("hostFolder"); - dcHostFolderTraversal.setName("dcHostFolderTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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.setType("ManagedEntity"); - pSpec.setPathSet(new String[] { "name" }); - - TraversalSpec folderChildrenTraversal = new TraversalSpec(); - folderChildrenTraversal.setType("Folder"); - folderChildrenTraversal.setPath("childEntity"); - folderChildrenTraversal.setName("folderChildrenTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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.setType("ManagedEntity"); - pSpec.setPathSet(new String[] { "name" }); - - TraversalSpec clusterHostTraversal = new TraversalSpec(); - clusterHostTraversal.setType("ClusterComputeResource"); - clusterHostTraversal.setPath("host"); - clusterHostTraversal.setName("folderChildrenTraversal"); - - ObjectSpec oSpec = new ObjectSpec(); - oSpec.setObj(mor); - oSpec.setSkip(Boolean.TRUE); - oSpec.setSelectSet(new SelectionSpec[] { 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) { - boolean found = false; - for(ObjectContent oc : ocs) { - String name = oc.getPropSet()[0].getVal().toString(); - if(name.equalsIgnoreCase(token) || name.equalsIgnoreCase("host")) { - mor = oc.getObj(); - found = true; - if (name.equalsIgnoreCase("host")) - i--; - break; - } - } - if(!found) { - s_logger.error("Path element points to an un-existing inventory entity"); - return null; - } - } else { - s_logger.error("Path element points to an un-existing inventory entity"); - return null; - } - } - return mor; - } - - // 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"); - 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]; - int len = 0; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - in.close(); - out.close(); - } - - public void uploadFile(String urlString, String localFileFullName) throws Exception { - uploadFile(urlString, new File(localFileFullName)); + + 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.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + s_logger.error("Unexpected exception ", e); + } } - public void uploadFile(String urlString, File localFile) throws Exception { + public VmwareContext(ExtendedAppUtil appUtil, String address) { + assert(appUtil != null) : "Invalid parameter in constructing VmwareContext object"; + + _appUtil = appUtil; + _serverAddress = address; + } + + public void registerStockObject(String name, Object obj) { + synchronized(_stockMap) { + _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(); + } + + public VimPortType getService() { + return getServiceConnection().getService(); + } + + public ServiceContent getServiceContent() { + return getServiceConnection().getServiceContent(); + } + + public ServiceUtil getServiceUtil() { + return _appUtil.getServiceUtil3(); + } + + public ManagedObjectReference getRootFolder() { + return getServiceContent().getRootFolder(); + } + + 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; + if(mor.getType().equalsIgnoreCase("Datacenter")) { + PropertySpec pSpec = new PropertySpec(); + pSpec.setType("ManagedEntity"); + pSpec.setPathSet(new String[] { "name" }); + + TraversalSpec dcHostFolderTraversal = new TraversalSpec(); + dcHostFolderTraversal.setType("Datacenter"); + dcHostFolderTraversal.setPath("hostFolder"); + dcHostFolderTraversal.setName("dcHostFolderTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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.setType("ManagedEntity"); + pSpec.setPathSet(new String[] { "name" }); + + TraversalSpec folderChildrenTraversal = new TraversalSpec(); + folderChildrenTraversal.setType("Folder"); + folderChildrenTraversal.setPath("childEntity"); + folderChildrenTraversal.setName("folderChildrenTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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.setType("ManagedEntity"); + pSpec.setPathSet(new String[] { "name" }); + + TraversalSpec clusterHostTraversal = new TraversalSpec(); + clusterHostTraversal.setType("ClusterComputeResource"); + clusterHostTraversal.setPath("host"); + clusterHostTraversal.setName("folderChildrenTraversal"); + + ObjectSpec oSpec = new ObjectSpec(); + oSpec.setObj(mor); + oSpec.setSkip(Boolean.TRUE); + oSpec.setSelectSet(new SelectionSpec[] { 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) { + boolean found = false; + for(ObjectContent oc : ocs) { + String name = oc.getPropSet()[0].getVal().toString(); + if(name.equalsIgnoreCase(token) || name.equalsIgnoreCase("host")) { + mor = oc.getObj(); + found = true; + if (name.equalsIgnoreCase("host")) + i--; + break; + } + } + if(!found) { + s_logger.error("Path element points to an un-existing inventory entity"); + return null; + } + } else { + s_logger.error("Path element points to an un-existing inventory entity"); + return null; + } + } + return mor; + } + + // 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"); + 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]; + int len = 0; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.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; @@ -327,246 +327,246 @@ public class VmwareContext { br.close(); } } - - 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.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.write(buffer, 0, bytesRead); - totalBytesUpdated += bytesRead; - bos.flush(); - if(progressUpdater != null) - progressUpdater.action(new Long(totalBytesUpdated)); - } - bos.flush(); - } finally { - if(is != null) - is.close(); - if(bos != null) - bos.close(); - - conn.disconnect(); - } - } - - 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); + + 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.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.write(buffer, 0, bytesRead); + totalBytesUpdated += bytesRead; + bos.flush(); + if(progressUpdater != null) + progressUpdater.action(new Long(totalBytesUpdated)); + } + bos.flush(); + } finally { + if(is != null) + is.close(); + if(bos != null) + bos.close(); + + conn.disconnect(); + } + } + + 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.setAllowUserInteraction(true); connectWithRetry(conn); - - 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); - 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; - } - - 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; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - in.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"); - - OutputStream out = conn.getOutputStream(); - out.write(content); - out.flush(); - - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - if(s_logger.isTraceEnabled()) - s_logger.trace("Upload " + urlString + " response: " + line); - } - 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 - * - - - - - Index of Fedora-clone-test on datastore NFS datastore in datacenter cupertino - -

Index of Fedora-clone-test on datastore NFS datastore in datacenter cupertino

- - - - - - - - - - - - - - - - - - - - -
NameLast modifiedSize

Parent Directory  -
Fedora-clone-test-a2013465.hlog15-Aug-2010 00:131
Fedora-clone-test-a2013465.vswp14-Aug-2010 23:01402653184
Fedora-clone-test-flat.vmdk26-Aug-2010 18:4317179869184
Fedora-clone-test.nvram15-Aug-2010 00:138684
Fedora-clone-test.vmdk15-Aug-2010 00:13479
Fedora-clone-test.vmsd14-Aug-2010 16:590
Fedora-clone-test.vmx15-Aug-2010 00:133500
Fedora-clone-test.vmxf15-Aug-2010 00:13272
test.txt24-Aug-2010 01:0312
vmware-2.log14-Aug-2010 16:5180782
vmware-3.log14-Aug-2010 19:0758573
vmware-4.log14-Aug-2010 23:0049751
vmware-5.log15-Aug-2010 00:0464024
vmware-6.log15-Aug-2010 00:1159742
vmware-7.log15-Aug-2010 00:1359859
vmware.log15-Aug-2010 00:2347157

- - - */ - public String[] listDatastoreDirContent(String urlString) throws Exception { - List fileList = new ArrayList(); - String content = new String(getResourceContent(urlString)); - String marker = " 0) { - int beginPos = content.lastIndexOf('>', parsePos -1); - if(beginPos < 0) - beginPos = 0; - - fileList.add((content.substring(beginPos + 1, parsePos))); - parsePos += marker.length(); - } else { - break; - } - } while(parsePos > 0); - return fileList.toArray(new String[0]); - } - - public String composeDatastoreBrowseUrl(String dcName, String fullPath) { - 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); - sb.append("/folder/"); - sb.append(relativePath); - sb.append("?dcPath=").append(URLEncoder.encode(dcName)).append("&dsName="); - 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) { - return true; - } - }; - - HttpsURLConnection.setDefaultHostnameVerifier(hv); - URL url = new URL(urlString); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setAllowUserInteraction(true); - conn.setRequestProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE, cookieString); - conn.setRequestMethod(httpMethod); + + 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); + 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; + } + + 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; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.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"); + + OutputStream out = conn.getOutputStream(); + out.write(content); + out.flush(); + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + if(s_logger.isTraceEnabled()) + s_logger.trace("Upload " + urlString + " response: " + line); + } + 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 + * + + + + + Index of Fedora-clone-test on datastore NFS datastore in datacenter cupertino + +

Index of Fedora-clone-test on datastore NFS datastore in datacenter cupertino

+ + + + + + + + + + + + + + + + + + + + +
NameLast modifiedSize

Parent Directory  -
Fedora-clone-test-a2013465.hlog15-Aug-2010 00:131
Fedora-clone-test-a2013465.vswp14-Aug-2010 23:01402653184
Fedora-clone-test-flat.vmdk26-Aug-2010 18:4317179869184
Fedora-clone-test.nvram15-Aug-2010 00:138684
Fedora-clone-test.vmdk15-Aug-2010 00:13479
Fedora-clone-test.vmsd14-Aug-2010 16:590
Fedora-clone-test.vmx15-Aug-2010 00:133500
Fedora-clone-test.vmxf15-Aug-2010 00:13272
test.txt24-Aug-2010 01:0312
vmware-2.log14-Aug-2010 16:5180782
vmware-3.log14-Aug-2010 19:0758573
vmware-4.log14-Aug-2010 23:0049751
vmware-5.log15-Aug-2010 00:0464024
vmware-6.log15-Aug-2010 00:1159742
vmware-7.log15-Aug-2010 00:1359859
vmware.log15-Aug-2010 00:2347157

+ + + */ + public String[] listDatastoreDirContent(String urlString) throws Exception { + List fileList = new ArrayList(); + String content = new String(getResourceContent(urlString)); + String marker = " 0) { + int beginPos = content.lastIndexOf('>', parsePos -1); + if(beginPos < 0) + beginPos = 0; + + fileList.add((content.substring(beginPos + 1, parsePos))); + parsePos += marker.length(); + } else { + break; + } + } while(parsePos > 0); + return fileList.toArray(new String[0]); + } + + public String composeDatastoreBrowseUrl(String dcName, String fullPath) { + 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); + sb.append("/folder/"); + sb.append(relativePath); + sb.append("?dcPath=").append(URLEncoder.encode(dcName)).append("&dsName="); + 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) { + return true; + } + }; + + HttpsURLConnection.setDefaultHostnameVerifier(hv); + URL url = new URL(urlString); + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setAllowUserInteraction(true); + conn.setRequestProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE, cookieString); + conn.setRequestMethod(httpMethod); connectWithRetry(conn); - return conn; - } - - public HttpURLConnection getRawHTTPConnection(String urlString) throws Exception { - HostnameVerifier hv = new HostnameVerifier() { - public boolean verify(String urlHostName, SSLSession session) { - return true; - } - }; - - HttpsURLConnection.setDefaultHostnameVerifier(hv); - URL url = new URL(urlString); - 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; + return conn; + } + + public HttpURLConnection getRawHTTPConnection(String urlString) throws Exception { + HostnameVerifier hv = new HostnameVerifier() { + public boolean verify(String urlHostName, SSLSession session) { + return true; + } + }; + + HttpsURLConnection.setDefaultHostnameVerifier(hv); + URL url = new URL(urlString); + 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 static void connectWithRetry(HttpURLConnection conn) throws Exception { @@ -588,37 +588,37 @@ public class VmwareContext { if(!connected) throw new Exception("Unable to connect to " + conn.toString()); - } - - public void close() { - try { - _appUtil.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() { - 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) - throws java.security.cert.CertificateException { - return; - } - - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) - throws java.security.cert.CertificateException { - return; - } - } -} + } + + public void close() { + try { + _appUtil.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() { + 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) + throws java.security.cert.CertificateException { + return; + } + + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } + } +} 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 3a95b72daf9..dc4fd7eeae3 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareGuestOsMapper.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.util; - -import java.util.HashMap; -import java.util.Map; - -import com.vmware.vim25.VirtualMachineGuestOsIdentifier; - -public class VmwareGuestOsMapper { - private static Map s_mapper = new HashMap(); +package com.cloud.hypervisor.vmware.util; + +import java.util.HashMap; +import java.util.Map; + +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); @@ -33,17 +33,17 @@ public class VmwareGuestOsMapper { 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 (32-bit)", VirtualMachineGuestOsIdentifier.windows7Guest); s_mapper.put("Windows 7 (64-bit)", VirtualMachineGuestOsIdentifier.windows7_64Guest); 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 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); @@ -55,34 +55,34 @@ public class VmwareGuestOsMapper { 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(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(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(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 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 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 (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("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 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); @@ -102,7 +102,7 @@ public class VmwareGuestOsMapper { 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 (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); @@ -110,13 +110,13 @@ public class VmwareGuestOsMapper { 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(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); @@ -158,9 +158,9 @@ public class VmwareGuestOsMapper { s_mapper.put("Other (32-bit)", VirtualMachineGuestOsIdentifier.otherGuest); s_mapper.put("Other (64-bit)", VirtualMachineGuestOsIdentifier.otherGuest64); - } - - public static VirtualMachineGuestOsIdentifier getGuestOsIdentifier(String guestOsName) { - return s_mapper.get(guestOsName); - } -} + } + + 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 428b77c6673..0f717b82cc2 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareHelper.java @@ -10,62 +10,62 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.util; - -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.StringWriter; +package com.cloud.hypervisor.vmware.util; + +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.ArrayList; -import java.util.List; +import java.util.List; import java.util.Random; - -import org.apache.log4j.Logger; - -import com.cloud.hypervisor.vmware.mo.DatacenterMO; -import com.cloud.hypervisor.vmware.mo.DatastoreMO; + +import org.apache.log4j.Logger; + +import com.cloud.hypervisor.vmware.mo.DatacenterMO; +import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType; -import com.cloud.hypervisor.vmware.mo.VirtualMachineMO; -import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; -import com.cloud.utils.exception.ExceptionUtil; -import com.vmware.vim25.DynamicProperty; -import com.vmware.vim25.ManagedObjectReference; -import com.vmware.vim25.MethodFault; -import com.vmware.vim25.ObjectContent; -import com.vmware.vim25.OptionValue; -import com.vmware.vim25.ResourceAllocationInfo; -import com.vmware.vim25.VirtualCdrom; -import com.vmware.vim25.VirtualCdromIsoBackingInfo; -import com.vmware.vim25.VirtualCdromRemotePassthroughBackingInfo; -import com.vmware.vim25.VirtualDevice; -import com.vmware.vim25.VirtualDeviceBackingInfo; -import com.vmware.vim25.VirtualDeviceConnectInfo; -import com.vmware.vim25.VirtualDisk; -import com.vmware.vim25.VirtualDiskFlatVer1BackingInfo; -import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo; -import com.vmware.vim25.VirtualDiskMode; -import com.vmware.vim25.VirtualDiskRawDiskMappingVer1BackingInfo; -import com.vmware.vim25.VirtualDiskSparseVer1BackingInfo; -import com.vmware.vim25.VirtualDiskSparseVer2BackingInfo; -import com.vmware.vim25.VirtualE1000; +import com.cloud.hypervisor.vmware.mo.VirtualMachineMO; +import com.cloud.utils.Pair; +import com.cloud.utils.Ternary; +import com.cloud.utils.exception.ExceptionUtil; +import com.vmware.vim25.DynamicProperty; +import com.vmware.vim25.ManagedObjectReference; +import com.vmware.vim25.MethodFault; +import com.vmware.vim25.ObjectContent; +import com.vmware.vim25.OptionValue; +import com.vmware.vim25.ResourceAllocationInfo; +import com.vmware.vim25.VirtualCdrom; +import com.vmware.vim25.VirtualCdromIsoBackingInfo; +import com.vmware.vim25.VirtualCdromRemotePassthroughBackingInfo; +import com.vmware.vim25.VirtualDevice; +import com.vmware.vim25.VirtualDeviceBackingInfo; +import com.vmware.vim25.VirtualDeviceConnectInfo; +import com.vmware.vim25.VirtualDisk; +import com.vmware.vim25.VirtualDiskFlatVer1BackingInfo; +import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo; +import com.vmware.vim25.VirtualDiskMode; +import com.vmware.vim25.VirtualDiskRawDiskMappingVer1BackingInfo; +import com.vmware.vim25.VirtualDiskSparseVer1BackingInfo; +import com.vmware.vim25.VirtualDiskSparseVer2BackingInfo; +import com.vmware.vim25.VirtualE1000; import com.vmware.vim25.VirtualEthernetCard; -import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo; -import com.vmware.vim25.VirtualMachineConfigSpec; -import com.vmware.vim25.VirtualMachineSnapshotTree; +import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo; +import com.vmware.vim25.VirtualMachineConfigSpec; +import com.vmware.vim25.VirtualMachineSnapshotTree; import com.vmware.vim25.VirtualPCNet32; import com.vmware.vim25.VirtualVmxnet2; 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 { - + +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 : @@ -88,318 +88,318 @@ public class VmwareHelper { 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); - connectInfo.setStartConnected(connectOnStart); - nic.setAddressType("Manual"); - nic.setConnectable(connectInfo); + + VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); + nicBacking.setDeviceName(portGroupName); + nicBacking.setNetwork(morNetwork); + nic.setBacking(nicBacking); + + VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); + connectInfo.setAllowGuestControl(true); + connectInfo.setConnected(conntected); + connectInfo.setStartConnected(connectOnStart); + nic.setAddressType("Manual"); + nic.setConnectable(connectInfo); nic.setMacAddress(macAddress); - nic.setUnitNumber(deviceNumber); - nic.setKey(-contextNumber); - return nic; - } - - // vmdkDatastorePath: [datastore name] vmdkFilePath - 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.setThinProvisioned(true); - backingInfo.setEagerlyScrub(false); - backingInfo.setDatastore(morDs); - backingInfo.setFileName(vmdkDatastorePath); - 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); - disk.setCapacityInKB(sizeInMb*1024); - - VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); - 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, - 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 - // same datastore - VirtualDisk disk = new VirtualDisk(); - if(parentBacking instanceof VirtualDiskFlatVer1BackingInfo) { - VirtualDiskFlatVer1BackingInfo backingInfo = new VirtualDiskFlatVer1BackingInfo(); - backingInfo.setDiskMode(((VirtualDiskFlatVer1BackingInfo)parentBacking).getDiskMode()); - backingInfo.setDatastore(morDs); - backingInfo.setFileName(vmdkDatastorePath); - backingInfo.setParent((VirtualDiskFlatVer1BackingInfo)parentBacking); - disk.setBacking(backingInfo); - } else if(parentBacking instanceof VirtualDiskFlatVer2BackingInfo) { - VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); - backingInfo.setDiskMode(((VirtualDiskFlatVer2BackingInfo)parentBacking).getDiskMode()); - backingInfo.setDatastore(morDs); - backingInfo.setFileName(vmdkDatastorePath); - backingInfo.setParent((VirtualDiskFlatVer2BackingInfo)parentBacking); - disk.setBacking(backingInfo); - } else if(parentBacking instanceof VirtualDiskRawDiskMappingVer1BackingInfo) { - VirtualDiskRawDiskMappingVer1BackingInfo backingInfo = new VirtualDiskRawDiskMappingVer1BackingInfo(); - backingInfo.setDiskMode(((VirtualDiskRawDiskMappingVer1BackingInfo)parentBacking).getDiskMode()); - backingInfo.setDatastore(morDs); - backingInfo.setFileName(vmdkDatastorePath); - backingInfo.setParent((VirtualDiskRawDiskMappingVer1BackingInfo)parentBacking); - disk.setBacking(backingInfo); - } else if(parentBacking instanceof VirtualDiskSparseVer1BackingInfo) { - VirtualDiskSparseVer1BackingInfo backingInfo = new VirtualDiskSparseVer1BackingInfo(); - backingInfo.setDiskMode(((VirtualDiskSparseVer1BackingInfo)parentBacking).getDiskMode()); - backingInfo.setDatastore(morDs); - backingInfo.setFileName(vmdkDatastorePath); - backingInfo.setParent((VirtualDiskSparseVer1BackingInfo)parentBacking); - disk.setBacking(backingInfo); - } else if(parentBacking instanceof VirtualDiskSparseVer2BackingInfo) { - VirtualDiskSparseVer2BackingInfo backingInfo = new VirtualDiskSparseVer2BackingInfo(); - backingInfo.setDiskMode(((VirtualDiskSparseVer2BackingInfo)parentBacking).getDiskMode()); - backingInfo.setDatastore(morDs); - backingInfo.setFileName(vmdkDatastorePath); - backingInfo.setParent((VirtualDiskSparseVer2BackingInfo)parentBacking); - disk.setBacking(backingInfo); - } 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); - - VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); - connectInfo.setConnected(true); - connectInfo.setStartConnected(true); - disk.setConnectable(connectInfo); - return disk; - } - - // vmdkDatastorePath: [datastore name] vmdkFilePath - 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()); - 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; - } - - private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, - ManagedObjectReference morDs, String[] parentDatastorePathList) { - - VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); - parentBacking.setDatastore(morDs); - 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++) - nextDatastorePathList[i] = parentDatastorePathList[i + 1]; - setParentBackingInfo(parentBacking, morDs, nextDatastorePathList); - } - parentBacking.setFileName(parentDatastorePathList[0]); - - 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(); + nic.setUnitNumber(deviceNumber); + nic.setKey(-contextNumber); + return nic; + } + + // vmdkDatastorePath: [datastore name] vmdkFilePath + public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, int controllerKey, String vmdkDatastorePath, + int sizeInMb, ManagedObjectReference morDs, int deviceNumber, int contextNumber) throws Exception { + + VirtualDisk disk = new VirtualDisk(); - 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); - backingInfo.setDatastore(morDs); - cdRom.setBacking(backingInfo); - } else { - VirtualCdromRemotePassthroughBackingInfo backingInfo = new VirtualCdromRemotePassthroughBackingInfo(); - 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) { - assert(findName != null); - - ManagedObjectReference snapMor = null; - if (snapTree == null) - return snapMor; - - for (int i = 0; i < snapTree.length && snapMor == null; i++) { - VirtualMachineSnapshotTree node = snapTree[i]; - - if (node.getName().equals(findName)) { - snapMor = node.getSnapshot(); - } else { - VirtualMachineSnapshotTree[] childTree = node.getChildSnapshotList(); - snapMor = findSnapshotInTree(childTree, findName); - } - } - return snapMor; - } - - 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.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, - boolean enableVnc, String vncPassword, int vncPort, String keyboardLayout) { - + VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); + backingInfo.setDiskMode(VirtualDiskMode.persistent.toString()); + backingInfo.setThinProvisioned(true); + backingInfo.setEagerlyScrub(false); + backingInfo.setDatastore(morDs); + backingInfo.setFileName(vmdkDatastorePath); + 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); + disk.setCapacityInKB(sizeInMb*1024); + + VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); + 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, + 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 + // same datastore + VirtualDisk disk = new VirtualDisk(); + if(parentBacking instanceof VirtualDiskFlatVer1BackingInfo) { + VirtualDiskFlatVer1BackingInfo backingInfo = new VirtualDiskFlatVer1BackingInfo(); + backingInfo.setDiskMode(((VirtualDiskFlatVer1BackingInfo)parentBacking).getDiskMode()); + backingInfo.setDatastore(morDs); + backingInfo.setFileName(vmdkDatastorePath); + backingInfo.setParent((VirtualDiskFlatVer1BackingInfo)parentBacking); + disk.setBacking(backingInfo); + } else if(parentBacking instanceof VirtualDiskFlatVer2BackingInfo) { + VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo(); + backingInfo.setDiskMode(((VirtualDiskFlatVer2BackingInfo)parentBacking).getDiskMode()); + backingInfo.setDatastore(morDs); + backingInfo.setFileName(vmdkDatastorePath); + backingInfo.setParent((VirtualDiskFlatVer2BackingInfo)parentBacking); + disk.setBacking(backingInfo); + } else if(parentBacking instanceof VirtualDiskRawDiskMappingVer1BackingInfo) { + VirtualDiskRawDiskMappingVer1BackingInfo backingInfo = new VirtualDiskRawDiskMappingVer1BackingInfo(); + backingInfo.setDiskMode(((VirtualDiskRawDiskMappingVer1BackingInfo)parentBacking).getDiskMode()); + backingInfo.setDatastore(morDs); + backingInfo.setFileName(vmdkDatastorePath); + backingInfo.setParent((VirtualDiskRawDiskMappingVer1BackingInfo)parentBacking); + disk.setBacking(backingInfo); + } else if(parentBacking instanceof VirtualDiskSparseVer1BackingInfo) { + VirtualDiskSparseVer1BackingInfo backingInfo = new VirtualDiskSparseVer1BackingInfo(); + backingInfo.setDiskMode(((VirtualDiskSparseVer1BackingInfo)parentBacking).getDiskMode()); + backingInfo.setDatastore(morDs); + backingInfo.setFileName(vmdkDatastorePath); + backingInfo.setParent((VirtualDiskSparseVer1BackingInfo)parentBacking); + disk.setBacking(backingInfo); + } else if(parentBacking instanceof VirtualDiskSparseVer2BackingInfo) { + VirtualDiskSparseVer2BackingInfo backingInfo = new VirtualDiskSparseVer2BackingInfo(); + backingInfo.setDiskMode(((VirtualDiskSparseVer2BackingInfo)parentBacking).getDiskMode()); + backingInfo.setDatastore(morDs); + backingInfo.setFileName(vmdkDatastorePath); + backingInfo.setParent((VirtualDiskSparseVer2BackingInfo)parentBacking); + disk.setBacking(backingInfo); + } 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); + + VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo(); + connectInfo.setConnected(true); + connectInfo.setStartConnected(true); + disk.setConnectable(connectInfo); + return disk; + } + + // vmdkDatastorePath: [datastore name] vmdkFilePath + 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()); + 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; + } + + private static void setParentBackingInfo(VirtualDiskFlatVer2BackingInfo backingInfo, + ManagedObjectReference morDs, String[] parentDatastorePathList) { + + VirtualDiskFlatVer2BackingInfo parentBacking = new VirtualDiskFlatVer2BackingInfo(); + parentBacking.setDatastore(morDs); + 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++) + nextDatastorePathList[i] = parentDatastorePathList[i + 1]; + setParentBackingInfo(parentBacking, morDs, nextDatastorePathList); + } + parentBacking.setFileName(parentDatastorePathList[0]); + + 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.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); + backingInfo.setDatastore(morDs); + cdRom.setBacking(backingInfo); + } else { + VirtualCdromRemotePassthroughBackingInfo backingInfo = new VirtualCdromRemotePassthroughBackingInfo(); + 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) { + assert(findName != null); + + ManagedObjectReference snapMor = null; + if (snapTree == null) + return snapMor; + + for (int i = 0; i < snapTree.length && snapMor == null; i++) { + VirtualMachineSnapshotTree node = snapTree[i]; + + if (node.getName().equals(findName)) { + snapMor = node.getSnapshot(); + } else { + VirtualMachineSnapshotTree[] childTree = node.getChildSnapshotList(); + snapMor = findSnapshotInTree(childTree, findName); + } + } + return snapMor; + } + + 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.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, + 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"); + + 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) { @@ -407,18 +407,18 @@ public class VmwareHelper { 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(); + + 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); } else { @@ -426,75 +426,75 @@ 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(); - - 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); - } - - 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); - } - - 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(); - } - - return ExceptionUtil.toString(e, printStack); + 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(); + + 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); + } + + 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); + } + + 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(); + } + + return ExceptionUtil.toString(e, printStack); } public static VirtualMachineMO pickOneVmOnRunningHost(List vmList, boolean bFirstFit) throws Exception { @@ -515,4 +515,4 @@ public class VmwareHelper { Random random = new Random(); return candidates.get(random.nextInt(candidates.size())); } -} +}